Compare commits
1 commit
main
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a4a5a20f5 |
41 changed files with 951 additions and 3385 deletions
|
|
@ -1,48 +0,0 @@
|
|||
module.exports = {
|
||||
env: {
|
||||
node: true,
|
||||
es2021: true,
|
||||
es6: true,
|
||||
browser: true, // Added for epic-games.js which uses window and navigator
|
||||
},
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
],
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': ['warn', {
|
||||
varsIgnorePattern: '^_',
|
||||
argsIgnorePattern: '^_',
|
||||
}],
|
||||
'no-undef': 'error',
|
||||
'@stylistic/js/comma-dangle': ['error', 'always-multiline'],
|
||||
'@stylistic/js/arrow-parens': ['error', 'as-needed'],
|
||||
},
|
||||
plugins: [
|
||||
'@stylistic/js',
|
||||
],
|
||||
globals: {
|
||||
screenshot: 'readonly',
|
||||
cfg: 'readonly',
|
||||
URL_CLAIM: 'readonly',
|
||||
COOKIES_PATH: 'readonly',
|
||||
BEARER_TOKEN_NAME: 'readonly',
|
||||
notify: 'readonly',
|
||||
authenticator: 'readonly',
|
||||
prompt: 'readonly',
|
||||
html_game_list: 'readonly',
|
||||
datetime: 'readonly',
|
||||
filenamify: 'readonly',
|
||||
handleSIGINT: 'readonly',
|
||||
stealth: 'readonly',
|
||||
jsonDb: 'readonly',
|
||||
delay: 'readonly',
|
||||
dataDir: 'readonly',
|
||||
resolve: 'readonly',
|
||||
window: 'readonly', // Added for epic-games.js
|
||||
navigator: 'readonly', // Added for epic-games.js
|
||||
},
|
||||
};
|
||||
|
|
@ -1,136 +0,0 @@
|
|||
name: build-and-push
|
||||
#
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
|
||||
env:
|
||||
IMAGE_TAG: ${{ github.ref == 'refs/heads/dev' && 'dev' || 'latest' }}
|
||||
REPO_URL: https://git.sky-net.it
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: self-hosted
|
||||
container:
|
||||
image: node:20-alpine
|
||||
steps:
|
||||
- name: Manual Git Checkout
|
||||
run: |
|
||||
apk add --no-cache git
|
||||
git init
|
||||
git remote add origin ${{ env.REPO_URL }}/${{ github.repository }}.git
|
||||
git fetch --depth 1 origin ${{ github.ref }}
|
||||
git checkout FETCH_HEAD
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Run ESLint
|
||||
run: npm run lint
|
||||
|
||||
sonar:
|
||||
needs: lint
|
||||
runs-on: self-hosted
|
||||
container:
|
||||
image: node:20-alpine
|
||||
steps:
|
||||
- name: Manual Git Checkout and Prepare
|
||||
run: |
|
||||
apk add --no-cache git curl bash
|
||||
git init
|
||||
git remote add origin ${{ env.REPO_URL }}/${{ github.repository }}.git
|
||||
git fetch --depth 1 origin ${{ github.ref }}
|
||||
git checkout FETCH_HEAD
|
||||
|
||||
- name: Install Java and Sonar Scanner
|
||||
run: |
|
||||
apk add --no-cache nodejs npm curl openjdk17-jre unzip
|
||||
curl -sSLo /tmp/sonar-scanner-cli.zip https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-6.2.1.4610.zip
|
||||
unzip -q /tmp/sonar-scanner-cli.zip -d /opt
|
||||
rm /tmp/sonar-scanner-cli.zip
|
||||
ls -la /opt/
|
||||
ln -sf /opt/sonar-scanner-6.2.1.4610/bin/sonar-scanner /usr/local/bin/sonar-scanner
|
||||
which sonar-scanner
|
||||
|
||||
- name: SonarQube Scan
|
||||
env:
|
||||
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
SONAR_PROJECT_KEY: ${{ secrets.SONAR_PROJECT_KEY }}
|
||||
run: |
|
||||
WORKDIR=${GITHUB_WORKSPACE:-$PWD}
|
||||
HOST_URL=${SONAR_HOST_URL:?SONAR_HOST_URL secret not set}
|
||||
BRANCH_NAME=${GITHUB_REF#refs/heads/}
|
||||
PROJECT_KEY=${SONAR_PROJECT_KEY:-}
|
||||
if [ -z "$PROJECT_KEY" ] && [ -f sonar-project.properties ]; then
|
||||
PROJECT_KEY=$(grep -E '^sonar.projectKey=' sonar-project.properties | cut -d= -f2 | tr -d '\r')
|
||||
fi
|
||||
if [ -z "$PROJECT_KEY" ]; then
|
||||
echo "SONAR_PROJECT_KEY secret not set and no sonar-project.properties entry found" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Sonar project key: $PROJECT_KEY"
|
||||
echo "Listing workspace:"
|
||||
ls -la
|
||||
echo "Sample files:"
|
||||
find . -maxdepth 2 -type f | head -n 20
|
||||
echo "Running local sonar-scanner..."
|
||||
echo "SonarQube URL: $HOST_URL"
|
||||
sonar-scanner \
|
||||
-Dsonar.host.url="$HOST_URL" \
|
||||
-Dsonar.token="$SONAR_TOKEN" \
|
||||
-Dsonar.projectKey="$PROJECT_KEY" \
|
||||
-Dsonar.sources=. \
|
||||
-Dsonar.scm.disabled=true \
|
||||
-Dsonar.projectBaseDir="$WORKDIR" \
|
||||
-Dsonar.branch.name="$BRANCH_NAME" 2>/dev/null || \
|
||||
sonar-scanner \
|
||||
-Dsonar.host.url="$HOST_URL" \
|
||||
-Dsonar.token="$SONAR_TOKEN" \
|
||||
-Dsonar.projectKey="$PROJECT_KEY" \
|
||||
-Dsonar.sources=. \
|
||||
-Dsonar.scm.disabled=true \
|
||||
-Dsonar.projectBaseDir="$WORKDIR"
|
||||
|
||||
docker:
|
||||
needs: [lint, sonar]
|
||||
runs-on: self-hosted
|
||||
container:
|
||||
image: node:20-alpine
|
||||
steps:
|
||||
- name: Network Debugging
|
||||
run: |
|
||||
apk add --no-cache iputils bind-tools
|
||||
cat /etc/resolv.conf
|
||||
cat /etc/hosts
|
||||
ping -c 4 127.0.0.1
|
||||
getent hosts 127.0.0.1
|
||||
|
||||
- name: Manual Git Checkout
|
||||
run: |
|
||||
apk add --no-cache git
|
||||
git init
|
||||
git remote add origin ${{ env.REPO_URL }}/${{ github.repository }}.git
|
||||
git fetch --depth 1 origin ${{ github.ref }}
|
||||
git checkout FETCH_HEAD
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
run: |
|
||||
apk add --no-cache docker-cli docker-cli-compose curl
|
||||
mkdir -p ~/.docker/cli-plugins
|
||||
curl -SL https://github.com/docker/buildx/releases/download/v0.14.1/buildx-v0.14.1.linux-amd64 -o ~/.docker/cli-plugins/docker-buildx
|
||||
chmod +x ~/.docker/cli-plugins/docker-buildx
|
||||
|
||||
- name: Login to registry
|
||||
run: echo "${{ secrets.REG_TOKEN }}" | docker login "${{ secrets.REGISTRY }}" -u "${{ secrets.REG_USER }}" --password-stdin
|
||||
|
||||
- name: Build image
|
||||
run: |
|
||||
docker buildx build --load \
|
||||
-t "${{ secrets.REGISTRY_IMAGE }}:${{ env.IMAGE_TAG }}" .
|
||||
|
||||
- name: Push image
|
||||
run: |
|
||||
docker push "${{ secrets.REGISTRY_IMAGE }}:${{ env.IMAGE_TAG }}"
|
||||
13
.github/FUNDING.yml
vendored
Normal file
13
.github/FUNDING.yml
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# These are supported funding model platforms
|
||||
|
||||
github: vogler # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: fgc # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: vogler # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: vogler # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
custom: ["https://www.buymeacoffee.com/vogler", "https://paypal.me/voglerr"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
28
.github/dependabot.yml
vendored
Normal file
28
.github/dependabot.yml
vendored
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
# commit-message:
|
||||
# prefix: "npm"
|
||||
# include: "scope"
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
# commit-message:
|
||||
# prefix: "docker"
|
||||
# include: "scope"
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
# commit-message:
|
||||
# prefix: "github-actions"
|
||||
# include: "scope"
|
||||
7
.github/renovate.json
vendored
Normal file
7
.github/renovate.json
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"enabled": false,
|
||||
"extends": [
|
||||
"config:recommended"
|
||||
]
|
||||
}
|
||||
72
.github/workflows/docker.yml
vendored
Normal file
72
.github/workflows/docker.yml
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
name: Build and push Docker image (amd64, arm64 to hub.docker.com and ghcr.io)
|
||||
|
||||
on:
|
||||
workflow_dispatch: # allows manual trigger
|
||||
push: # push on branch
|
||||
branches: [main, dev]
|
||||
paths: # ignore changes to .md files
|
||||
- '**'
|
||||
- '!*.md'
|
||||
# - '!.github/**'
|
||||
pull_request: # runs when opened/reopned or when the head branch is updated
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
env:
|
||||
BRANCH: ${{ github.head_ref || github.ref_name }} # head_ref/base_ref are only set for PRs, for branches ref_name will be used
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
-
|
||||
name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
-
|
||||
name: Set environment variables
|
||||
run: |
|
||||
echo "NOW=$(date -R)" >> $GITHUB_ENV # date -Iseconds; date +'%Y-%m-%dT%H:%M:%S'
|
||||
if [[ "$BRANCH" == "main" ]]; then
|
||||
echo "IMAGE_TAG=latest" >> $GITHUB_ENV
|
||||
else
|
||||
echo "IMAGE_TAG=$BRANCH" >> $GITHUB_ENV
|
||||
fi
|
||||
-
|
||||
name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
-
|
||||
name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
-
|
||||
name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
# if: ${{ secrets.DOCKERHUB_USERNAME != '' && secrets.DOCKERHUB_TOKEN != '' }} # does not work: Unrecognized named-value: 'secrets' - https://www.cloudtruth.com/blog/skipping-jobs-in-github-actions-when-secrets-are-unavailable-securely-inject-configuration-secrets-into-github
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
-
|
||||
name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }} # actor is user that opened PR, was repository_owner before
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
-
|
||||
name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
if: ${{ env.IMAGE_TAG != '' }}
|
||||
with:
|
||||
context: .
|
||||
push: ${{ secrets.DOCKERHUB_USERNAME != '' }}
|
||||
build-args: |
|
||||
COMMIT=${{ github.sha }}
|
||||
BRANCH=${{ env.BRANCH }}
|
||||
NOW=${{ env.NOW }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: |
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/free-games-claimer:${{env.IMAGE_TAG}}
|
||||
ghcr.io/${{ github.actor }}/free-games-claimer:${{env.IMAGE_TAG}}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
36
.github/workflows/lint.yml
vendored
Normal file
36
.github/workflows/lint.yml
vendored
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# https://github.com/marketplace/actions/super-linter#get-started
|
||||
name: Lint
|
||||
|
||||
on: # yamllint disable-line rule:truthy
|
||||
push: null
|
||||
pull_request: null
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
# To report GitHub Actions status checks
|
||||
statuses: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# super-linter needs the full git history to get the
|
||||
# list of files that changed across commits
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Super-linter
|
||||
uses: super-linter/super-linter/slim@v7.4.0 # x-release-please-version
|
||||
# TODO need to create problem matchers for each linter? https://github.com/rhysd/actionlint/blob/v1.7.7/docs/usage.md#problem-matchers
|
||||
env:
|
||||
# To report GitHub Actions status checks
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# TODO automatically fix linting issues and commit them for PRs
|
||||
# fix-lint-issues: # https://github.com/marketplace/actions/super-linter#github-actions-workflow-example-pull-request
|
||||
42
.github/workflows/sonar.yml
vendored
Normal file
42
.github/workflows/sonar.yml
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
name: Sonar
|
||||
|
||||
on:
|
||||
# Trigger analysis when pushing in main or pull requests, and when creating a pull request.
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sonarcloud:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
-
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# Disabling shallow clone is recommended for improving relevancy of reporting. Otherwise sonarcloud will show a warning.
|
||||
fetch-depth: 0
|
||||
-
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
cache: 'npm'
|
||||
-
|
||||
name: Install dev dependencies which includde ESLint + plugins
|
||||
run: npm install --only=dev
|
||||
-
|
||||
name: Run ESLint
|
||||
continue-on-error: true
|
||||
run: npx eslint . -f json -o eslint_report.json
|
||||
-
|
||||
name: Fix ESLint paths
|
||||
run: sed -i 's+/home/runner/work/free-games-claimer/free-games-claimer+/github/workspace+g' eslint_report.json
|
||||
-
|
||||
name: SonarCloud Scan
|
||||
uses: sonarsource/sonarcloud-github-action@master
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,4 +1,3 @@
|
|||
node_modules/
|
||||
data/
|
||||
*.env
|
||||
.continue
|
||||
|
|
|
|||
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
|
|
@ -1,4 +1,3 @@
|
|||
### eslint style
|
||||
{
|
||||
// https://eslint.style/guide/faq#vs-code
|
||||
"editor.formatOnSave": true,
|
||||
|
|
|
|||
30
Dockerfile
30
Dockerfile
|
|
@ -23,6 +23,8 @@ RUN apt-get update \
|
|||
novnc websockify \
|
||||
dos2unix \
|
||||
python3-pip \
|
||||
# && npx playwright install-deps firefox \
|
||||
&& apt-get install --no-install-recommends -y \
|
||||
libgtk-3-0 \
|
||||
libasound2 \
|
||||
libxcomposite1 \
|
||||
|
|
@ -34,9 +36,6 @@ RUN apt-get update \
|
|||
libgdk-pixbuf-2.0-0 \
|
||||
libdbus-glib-1-2 \
|
||||
libxcursor1 \
|
||||
libnss3 \
|
||||
libnspr4 \
|
||||
libgbm1 \
|
||||
&& apt-get autoremove -y \
|
||||
&& apt-get clean \
|
||||
&& rm -rf \
|
||||
|
|
@ -44,10 +43,13 @@ RUN apt-get update \
|
|||
/usr/share/doc/* \
|
||||
/var/cache/* \
|
||||
/var/lib/apt/lists/* \
|
||||
/var/tmp/* \
|
||||
&& useradd -ms /bin/bash fgc \
|
||||
&& ln -s /usr/share/novnc/vnc_auto.html /usr/share/novnc/index.html \
|
||||
&& pip install apprise
|
||||
/var/tmp/*
|
||||
|
||||
# RUN node --version
|
||||
# RUN npm --version
|
||||
|
||||
RUN ln -s /usr/share/novnc/vnc_auto.html /usr/share/novnc/index.html
|
||||
RUN pip install apprise
|
||||
|
||||
WORKDIR /fgc
|
||||
COPY package*.json ./
|
||||
|
|
@ -59,15 +61,10 @@ RUN npm install
|
|||
# From 1.38 Playwright will no longer install browser automatically for playwright, but apparently still for playwright-firefox: https://github.com/microsoft/playwright/releases/tag/v1.38.0
|
||||
# RUN npx playwright install firefox
|
||||
|
||||
# Only copy the files we actually need in the image to avoid accidentally adding secrets.
|
||||
COPY *.js ./
|
||||
COPY eslint.config.js jsconfig.json sonar-project.properties ./
|
||||
COPY src ./src
|
||||
COPY test ./test
|
||||
COPY docker-entrypoint.sh ./
|
||||
COPY . .
|
||||
|
||||
# Shell scripts need Linux line endings. On Windows, git might be configured to check out dos/CRLF line endings, so we convert them for those people in case they want to build the image. They could also use --config core.autocrlf=input
|
||||
RUN dos2unix ./*.sh && chmod +x ./*.sh && chown -R fgc:fgc /fgc
|
||||
RUN dos2unix ./*.sh && chmod +x ./*.sh
|
||||
COPY docker-entrypoint.sh /usr/local/bin/
|
||||
|
||||
ARG COMMIT=""
|
||||
|
|
@ -90,9 +87,8 @@ LABEL org.opencontainers.image.title="free-games-claimer" \
|
|||
# Configure VNC via environment variables:
|
||||
ENV VNC_PORT 5900
|
||||
ENV NOVNC_PORT 6080
|
||||
# Ports are not exposed by default; publish explicitly with -p when you really need GUI access.
|
||||
# EXPOSE 5900
|
||||
# EXPOSE 6080
|
||||
EXPOSE 5900
|
||||
EXPOSE 6080
|
||||
|
||||
# Configure Xvfb via environment variables:
|
||||
ENV WIDTH 1920
|
||||
|
|
|
|||
|
|
@ -1,86 +0,0 @@
|
|||
# OAuth Device Flow funktioniert NICHT mit öffentlichen Credentials
|
||||
|
||||
## Problem
|
||||
|
||||
Epic Games OAuth Device Flow erfordert **gültige Client Credentials** die NICHT öffentlich verfügbar sind.
|
||||
|
||||
Fehler:
|
||||
```
|
||||
errors.com.epicgames.account.invalid_client_credentials
|
||||
Sorry the client credentials you are using are invalid
|
||||
```
|
||||
|
||||
## Warum es nicht funktioniert
|
||||
|
||||
1. **Device Auth Client ID/Secret** sind bei Epic Games **nicht öffentlich**
|
||||
2. Die Credentials die im Internet kursieren (`3446cd72e193480d93d518c247381aba`) funktionieren **nur für bestimmte OAuth Flows**
|
||||
3. **Client Credentials Flow** (`grant_type=client_credentials`) ist für **Server-zu-Server** Kommunikation und erfordert registrierte App
|
||||
|
||||
## claabs/epicgames-freegames-node Lösung
|
||||
|
||||
Das claabs Projekt verwendet:
|
||||
- **Eigene OAuth App Registration** bei Epic Games
|
||||
- ODER: **Reverse-engineered Credentials** aus dem Epic Games Launcher
|
||||
- Diese sind **nicht im Code** sondern in der Config-Datei
|
||||
|
||||
## Unsere Lösung
|
||||
|
||||
Da wir keine gültigen Device Auth Credentials haben:
|
||||
|
||||
### Option 1: Puppeteer mit besserem Stealth (Empfohlen)
|
||||
|
||||
Verwende `puppeteer-extra-plugin-stealth` mit optimierten Einstellungen:
|
||||
|
||||
```javascript
|
||||
import puppeteer from 'puppeteer-extra';
|
||||
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
|
||||
|
||||
puppeteer.use(StealthPlugin({
|
||||
enabledEvasions: [
|
||||
'chrome.app',
|
||||
'chrome.csi',
|
||||
'chrome.loadTimes',
|
||||
'chrome.runtime',
|
||||
'iframe.contentWindow',
|
||||
'media.codecs',
|
||||
'navigator.hardwareConcurrency',
|
||||
'navigator.languages',
|
||||
'navigator.permissions',
|
||||
'navigator.plugins',
|
||||
'navigator.webdriver',
|
||||
'sourceurl',
|
||||
'user-agent-override',
|
||||
'webgl.vendor',
|
||||
'window.outerdimensions',
|
||||
],
|
||||
}));
|
||||
```
|
||||
|
||||
### Option 2: FlareSolverr für Cloudflare
|
||||
|
||||
FlareSolverr kann Cloudflare Challenges automatisch lösen:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
flaresolverr:
|
||||
image: ghcr.io/flaresolverr/flaresolverr:latest
|
||||
ports:
|
||||
- "8191:8191"
|
||||
environment:
|
||||
- LOG_LEVEL=info
|
||||
- CAPTCHA_SOLVER=none
|
||||
```
|
||||
|
||||
### Option 3: Manuelles Login mit Cookie-Export
|
||||
|
||||
1. Einmal im Browser manuell einloggen
|
||||
2. Cookies exportieren
|
||||
3. Cookies für Automation verwenden
|
||||
|
||||
## Fazit
|
||||
|
||||
**OAuth Device Flow ist keine Option** ohne:
|
||||
- Eigene Epic Games Developer App Registration, ODER
|
||||
- Gültige Launcher Credentials (die sich ändern können)
|
||||
|
||||
**Bester Weg:** Browser-Automation mit verbessertem Stealth + FlareSolverr
|
||||
355
README.md
355
README.md
|
|
@ -1,159 +1,224 @@
|
|||
Free Games Claimer (Fork)
|
||||
==========================
|
||||
<p align="center">
|
||||
<img alt="logo-free-games-claimer" src="https://user-images.githubusercontent.com/493741/214588518-a4c89998-127e-4a8c-9b1e-ee4a9d075715.png" />
|
||||
</p>
|
||||
|
||||
[](https://sonata.cyber77.de/dashboard?id=free-games-claimer)
|
||||
- Optional notifications: `pip install apprise`
|
||||
Automates claiming of free games for:
|
||||
- Amazon Luna Gaming / Luna claims (including external stores like GOG, Epic Games, Legacy Games )
|
||||
- GOG giveaways
|
||||
- Optional extras: Steam stats, AliExpress dailies (not implemated yet)
|
||||
-p 6080:6080 \
|
||||
Requirements
|
||||
------------
|
||||
- Docker or Podman (recommended), or Node.js ≥ 20 for local runs
|
||||
- Optional notifications: `pip install apprise`
|
||||
- Playwright dependencies are baked into the container; locally, `npm install` downloads Firefox.
|
||||
[](https://sonarcloud.io/project/overview?id=vogler_free-games-claimer)
|
||||
# free-games-claimer
|
||||
|
||||
Quickstart (Docker Run)
|
||||
-----------------------
|
||||
Claims free games periodically on
|
||||
- <img src="https://github.com/user-attachments/assets/82e9e9bf-b6ac-4f20-91db-36d2c8429cb6" width="32" align="middle" /> [Epic Games Store](https://www.epicgames.com/store/free-games)
|
||||
- <img src="https://github.com/user-attachments/assets/7627a108-20c6-4525-a1d8-5d221ee89d6e" width="32" align="middle" /> [Amazon Prime Gaming](https://gaming.amazon.com)
|
||||
- <img src="https://github.com/user-attachments/assets/49040b50-ee14-4439-8e3c-e93cafd7c3a5" width="32" align="middle" /> [GOG](https://www.gog.com)
|
||||
- <img src="https://github.com/user-attachments/assets/3582444b-f23b-448d-bf31-01668cd0313a" width="32" align="middle" /> [Unreal Engine (Assets)](https://www.unrealengine.com/marketplace/en-US/assets?count=20&sortBy=effectiveDate&sortDir=DESC&start=0&tag=4910) ([experimental](https://github.com/vogler/free-games-claimer/issues/44), same login as Epic Games)
|
||||
<!-- - <img src="https://www.freepnglogos.com/uploads/xbox-logo-picture-png-14.png" width="32"/> [Xbox Live Games with Gold](https://www.xbox.com/en-US/live/gold#gameswithgold) ([experimental](https://github.com/vogler/free-games-claimer/issues/19)) -->
|
||||
|
||||
Pull requests welcome :)
|
||||
|
||||

|
||||
|
||||
_Works on Windows/macOS/Linux._
|
||||
|
||||
Raspberry Pi (3, 4, Zero 2): [requires 64-bit OS](https://github.com/vogler/free-games-claimer/issues/3) like Raspberry Pi OS or Ubuntu (Raspbian won't work since it's 32-bit).
|
||||
|
||||
## How to run
|
||||
Easy option: [install Docker](https://docs.docker.com/get-docker/) (or [podman](https://podman-desktop.io/)) and run this command in a terminal:
|
||||
```
|
||||
docker run --rm -it \
|
||||
-p 6080:6080 \
|
||||
-v fgc-data:/fgc/data \
|
||||
-v fgc-browser:/home/fgc/.cache/browser \
|
||||
-v fgc-playwright:/home/fgc/.cache/ms-playwright \
|
||||
-e SHOW=1 \
|
||||
git.sky-net.it/nocci/free-games-claimer:dev \
|
||||
bash -c "node prime-gaming; node gog; ./keep-alive.sh"
|
||||
docker run --rm -it -p 6080:6080 -v fgc:/fgc/data --pull=always ghcr.io/vogler/free-games-claimer
|
||||
```
|
||||
- Ports 6080/5900: noVNC/VNC (only needed with `SHOW=1`)
|
||||
- Volumes persist profile + Playwright-Browser, damit Logins/Downloads bleiben.
|
||||
|
||||
Docker Compose Example (persistent volumes)
|
||||
-------------------------------------------
|
||||
```yaml
|
||||
services:
|
||||
free-games-claimer:
|
||||
image: git.sky-net.it/nocci/free-games-claimer:dev
|
||||
container_name: fgc
|
||||
environment:
|
||||
- SHOW=1 # show browser via VNC/noVNC
|
||||
# - PG_EMAIL=...
|
||||
# - PG_PASSWORD=...
|
||||
# - PG_OTPKEY=...
|
||||
- BROWSER_DIR=/fgc/data/browser
|
||||
- LOGIN_VISIBLE_TIMEOUT=20 # optional: faster login detection
|
||||
- KEEP_ALIVE_SECONDS=86400 # optional: keep container alive after runs
|
||||
volumes:
|
||||
- fgc-data:/fgc/data
|
||||
- fgc-browser:/home/fgc/.cache/browser
|
||||
- fgc-playwright:/home/fgc/.cache/ms-playwright
|
||||
ports:
|
||||
- "6080:6080" # noVNC
|
||||
# - "5900:5900" # VNC optional
|
||||
command: bash -c "node prime-gaming; node gog; ./keep-alive.sh"
|
||||
volumes:
|
||||
fgc-data:
|
||||
fgc-browser:
|
||||
fgc-playwright:
|
||||
```
|
||||
Hinweis: Das Image läuft auf `dev`; bei Bedarf `:latest` wählen.
|
||||
_This currently gives you a captcha challenge for epic-games. Until [issue #183](https://github.com/vogler/free-games-claimer/issues/183) is fixed, it is recommended to just run `node epic-games` without docker (see below)._
|
||||
|
||||
Configuration (Environment Variables)
|
||||
-------------------------------------
|
||||
Common options:
|
||||
- `SHOW=0/1` (0 = headless, 1 = UI)
|
||||
- `WIDTH`, `HEIGHT` (browser size)
|
||||
- `TIMEOUT`, `LOGIN_TIMEOUT` (seconds)
|
||||
- Epic: `EG_MODE=legacy|new` (legacy Playwright flow or neuer API-getriebener Claimer), `EG_PARENTALPIN`, `EG_EMAIL`, `EG_PASSWORD`, `EG_OTPKEY`
|
||||
- Epic (new mode): Cookies werden unter `data/browser/epic-cookies.json` persistiert; OAuth Device Code Flow benötigt ggf. einmalige Freigabe im Browser.
|
||||
- Falls Device-Code-Endpunkt nicht erreichbar ist (404/Bad Request), fällt der neue Modus automatisch auf manuellen Browser-Login zurück.
|
||||
- Login: `EMAIL`, `PASSWORD` global; per store `EG_EMAIL`, `EG_PASSWORD`, `EG_OTPKEY`, `PG_EMAIL`, `PG_PASSWORD`, `PG_OTPKEY`, `GOG_EMAIL`, `GOG_PASSWORD`
|
||||
- Prime Gaming: `PG_REDEEM=1` (auto-redeem keys, experimental), `PG_CLAIMDLC=1`, `PG_TIMELEFT=<days>` to skip long-remaining offers
|
||||
- Screenshots: `SCREENSHOTS_DIR` (default `data/screenshots`)
|
||||
- Notifications: `NOTIFY='...'` (Apprise URL), optional `NOTIFY_TITLE`
|
||||
- Browser profile: `BROWSER_DIR` (default `data/browser`)
|
||||
- Recording: `RECORD=1` to save videos/HAR to `data/record/`
|
||||
- Debugging: `DEBUG=1` (opens Playwright inspector), `DEBUG_NETWORK=1` (logs requests), `TIME=1` (prints timings)
|
||||
- Dry run / Interaction: `DRYRUN=1` (do not claim), `INTERACTIVE=1` (ask before claiming), `HEADLESS` is derived from `SHOW`/`DEBUG`
|
||||
- Directories: `SCREENSHOTS_DIR`, `BROWSER_DIR`, `DATA_DIR` (prefix for data; default under `data/`)
|
||||
- VNC/noVNC: `VNC_PASSWORD` (for Docker entrypoint), `NOVNC_PORT`/`VNC_PORT` (Docker)
|
||||
- General timeouts: `TIMEOUT` (per action), `LOGIN_TIMEOUT` (extra time for login)
|
||||
- Login detection: `LOGIN_VISIBLE_TIMEOUT` (ms) to abort sooner when login buttons not present
|
||||
- Keep-alive: `KEEP_ALIVE_SECONDS` (default 86400) for `keep-alive.sh`
|
||||
- Repo banner: `REPO_URL` for log output
|
||||
This will run `node epic-games; node prime-gaming; node gog` - if you only want to claim games for one of the stores, you can override the default command by appending e.g. `node epic-games` at the end of the `docker run` command, or if you want several `bash -c "node epic-games.js; node gog.js"`.
|
||||
Data (including json files with claimed games, codes to redeem, screenshots) is stored in the Docker volume `fgc`.
|
||||
|
||||
You can place a `data/config.env`; it is loaded via dotenv and is overridden by explicitly set environment variables.
|
||||
<details>
|
||||
<summary>I want to run without Docker or develop locally.</summary>
|
||||
|
||||
Local Run Without Docker
|
||||
------------------------
|
||||
```
|
||||
npm install
|
||||
SHOW=0 PG_EMAIL=... PG_PASSWORD=... PG_OTPKEY=... node prime-gaming.js
|
||||
```
|
||||
- Playwright downloads Firefox to `~/.cache/ms-playwright`.
|
||||
- Use `SHOW=1` for a visible browser (requires GUI/Xvfb).
|
||||
1. [Install Node.js](https://nodejs.org/en/download)
|
||||
2. Clone/download this repository and `cd` into it in a terminal
|
||||
3. Run `npm install`
|
||||
4. Run `pip install apprise` (or use [pipx](https://github.com/pypa/pipx) if you have [problems](https://stackoverflow.com/questions/75608323/how-do-i-solve-error-externally-managed-environment-every-time-i-use-pip-3)) to install [apprise](https://github.com/caronc/apprise) if you want notifications
|
||||
5. To get updates: `git pull; npm install`
|
||||
6. Run `node epic-games`, `node prime-gaming`, `node gog`...
|
||||
|
||||
Persistence & Outputs
|
||||
---------------------
|
||||
- Data/status: `data/*.json` (per store)
|
||||
- Browser profile: `data/browser`
|
||||
- Screenshots: `data/screenshots/<store>/`
|
||||
- Optional videos/HAR: `RECORD=1` → `data/record/`
|
||||
During `npm install` Playwright will download its Firefox to a cache in home ([doc](https://playwright.dev/docs/browsers#managing-browser-binaries)).
|
||||
If you are missing some dependencies for the browser on your system, you can use `sudo npx playwright install firefox --with-deps`.
|
||||
|
||||
Tip: For captchas or first-time login, run with `SHOW=1` and log in once; cookies stay in the profile. Notifications via `NOTIFY` help surface errors (e.g., captcha, login).
|
||||
If you don't want to use Docker for quasi-headless mode, you could run inside a virtual machine, on a server, or you wake your PC at night to avoid being interrupted.
|
||||
</details>
|
||||
|
||||
## Usage
|
||||
All scripts start an automated Firefox instance, either with the browser GUI shown or hidden (*headless mode*). By default, you won't see any browser open on your host system.
|
||||
|
||||
- When running inside Docker, the browser will be shown only inside the container. You can open http://localhost:6080 to interact with the browser running inside the container via noVNC (or use other VNC clients on port 5900).
|
||||
- When running the scripts outside of Docker, the browser will be hidden by default; you can use `SHOW=1 ...` to show the UI (see options below).
|
||||
|
||||
When running the first time, you have to login for each store you want to claim games on.
|
||||
You can login indirectly via the terminal or directly in the browser. The scripts will wait until you are successfully logged in.
|
||||
|
||||
There will be prompts in the terminal asking you to enter email, password, and afterwards some OTP (one time password / security code) if you have 2FA/MFA (two-/multi-factor authentication) enabled. If you want to login yourself via the browser, you can press escape in the terminal to skip the prompts.
|
||||
|
||||
After login, the script will continue claiming the current games. If it still waits after you are already logged in, you can restart it (and open an issue). If you run the scripts regularly, you should not have to login again.
|
||||
|
||||
### Configuration / Options
|
||||
Options are set via [environment variables](https://kinsta.com/knowledgebase/what-is-an-environment-variable/) which allow for flexible configuration.
|
||||
|
||||
TODO: ~~On the first run, the script will guide you through configuration and save all settings to `data/config.env`. You can edit this file directly or run `node fgc config` to run the configuration assistant again.~~
|
||||
|
||||
Available options/variables and their default values:
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------------- |--------- |------------------------------------------------------------------------ |
|
||||
| SHOW | 1 | Show browser if 1. Default for Docker, not shown when running outside. |
|
||||
| WIDTH | 1280 | Width of the opened browser (and of screen for VNC in Docker). |
|
||||
| HEIGHT | 1280 | Height of the opened browser (and of screen for VNC in Docker). |
|
||||
| VNC_PASSWORD | | VNC password for Docker. No password used by default! |
|
||||
| NOTIFY | | Notification services to use (Pushover, Slack, Telegram...), see below. [Apprise](https://github.com/caronc/apprise) |
|
||||
| NOTIFY_TITLE | | Optional title for notifications, e.g. for Pushover. |
|
||||
| BROWSER_DIR | data/browser | Directory for browser profile, e.g. for multiple accounts. |
|
||||
| TIMEOUT | 60 | Timeout for any page action. Should be fine even on slow machines. |
|
||||
| LOGIN_TIMEOUT | 180 | Timeout for login in seconds. Will wait twice (prompt + manual login). |
|
||||
| EMAIL | | Default email for any login. |
|
||||
| PASSWORD | | Default password for any login. |
|
||||
| EG_EMAIL | | Epic Games email for login. Overrides EMAIL. |
|
||||
| EG_PASSWORD | | Epic Games password for login. Overrides PASSWORD. |
|
||||
| EG_OTPKEY | | Epic Games MFA OTP key. |
|
||||
| EG_PARENTALPIN | | Epic Games Parental Controls PIN. |
|
||||
| PG_EMAIL | | Prime Gaming email for login. Overrides EMAIL. |
|
||||
| PG_PASSWORD | | Prime Gaming password for login. Overrides PASSWORD. |
|
||||
| PG_OTPKEY | | Prime Gaming MFA OTP key. |
|
||||
| PG_REDEEM | 0 | Prime Gaming: try to redeem keys on external stores ([experimental](https://github.com/vogler/free-games-claimer/issues/5)). |
|
||||
| PG_CLAIMDLC | 0 | Prime Gaming: try to claim DLCs ([experimental](https://github.com/vogler/free-games-claimer/issues/55)). |
|
||||
| GOG_EMAIL | | GOG email for login. Overrides EMAIL. |
|
||||
| GOG_PASSWORD | | GOG password for login. Overrides PASSWORD. |
|
||||
| GOG_NEWSLETTER | 0 | Do not unsubscribe from newsletter after claiming a game if 1. |
|
||||
| LG_EMAIL | | Legacy Games: email to use for redeeming (if not set, defaults to PG_EMAIL) |
|
||||
|
||||
See `src/config.js` for all options.
|
||||
|
||||
#### How to set options
|
||||
You can add options directly in the command or put them in a file to load.
|
||||
|
||||
##### Docker
|
||||
You can pass variables using `-e VAR=VAL`, for example `docker run -e EMAIL=foo@bar.baz -e NOTIFY='tgram://bottoken/ChatID' ...` or using `--env-file fgc.env` where `fgc.env` is a file on your host system (see [docs](https://docs.docker.com/engine/reference/commandline/run/#env)). You can also `docker cp` your configuration file to `/fgc/data/config.env` in the `fgc` volume to store it with the rest of the data instead of on the host ([example](https://github.com/moby/moby/issues/25245#issuecomment-365980572)).
|
||||
If you are using [docker compose](https://docs.docker.com/compose/environment-variables/) (or Portainer etc.), you can put options in the `environment:` section.
|
||||
|
||||
##### Without Docker
|
||||
On Linux/macOS you can prefix the variables you want to set, for example `EMAIL=foo@bar.baz SHOW=1 node epic-games` will show the browser and skip asking you for your login email. On Windows you have to use `set`, [example](https://github.com/vogler/free-games-claimer/issues/314).
|
||||
You can also put options in `data/config.env` which will be loaded by [dotenv](https://github.com/motdotla/dotenv).
|
||||
|
||||
### Notifications
|
||||
The scripts will try to send notifications for successfully claimed games and any errors like needing to log in or encountered captchas (should not happen).
|
||||
|
||||
[apprise](https://github.com/caronc/apprise) is used for notifications and offers many services including Pushover, Slack, Telegram, SMS, Email, desktop and custom notifications.
|
||||
You just need to set `NOTIFY` to the notification services you want to use, e.g. `NOTIFY='mailto://myemail:mypass@gmail.com' 'pbul://o.gn5kj6nfhv736I7jC3cj3QLRiyhgl98b'` - refer to their list of services and [examples](https://github.com/caronc/apprise#command-line-usage).
|
||||
|
||||
### Automatic login, two-factor authentication
|
||||
If you set the options for email, password and OTP key, there will be no prompts and logins should happen automatically. This is optional since all stores should stay logged in since cookies are refreshed.
|
||||
To get the OTP key, it is easiest to follow the store's guide for adding an authenticator app. You should also scan the shown QR code with your favorite app to have an alternative method for 2FA.
|
||||
|
||||
- **Epic Games**: visit [password & security](https://www.epicgames.com/account/password), enable 'third-party authenticator app', copy the 'Manual Entry Key' and use it to set `EG_OTPKEY`.
|
||||
- **Prime Gaming**: visit Amazon 'Your Account › Login & security', 2-step verification › Manage › Add new app › Can't scan the barcode, copy the bold key and use it to set `PG_OTPKEY`
|
||||
- **GOG**: only offers OTP via email
|
||||
<!-- - **Xbox**: visit [additional security](https://account.live.com/proofs/manage/additional) > Add a new way to sign in or verify > Use an app > Set up a different Authenticator app > I can't scan the bar code > copy the bold key and use it to set `XBOX_OTPKEY` -->
|
||||
|
||||
Beware that storing passwords and OTP keys as clear text may be a security risk. Use a unique/generated password! TODO: maybe at least offer to base64 encode for storage.
|
||||
|
||||
### Epic Games Store
|
||||
Run `node epic-games` (locally or in Docker).
|
||||
|
||||
### Amazon Prime Gaming
|
||||
Run `node prime-gaming` (locally or in Docker).
|
||||
|
||||
Claiming the Amazon Games works out-of-the-box, however, for games on external stores you need to either link your account or redeem a key.
|
||||
|
||||
- Stores that require account linking: Epic Games, Battle.net, Origin.
|
||||
- Stores that require redeeming a key: GOG.com, Microsoft Games, Legacy Games.
|
||||
|
||||
Keys and URLs are printed to the console, included in notifications and saved in `data/prime-gaming.json`. A screenshot of the page with the key is also saved to `data/screenshots`.
|
||||
[TODO](https://github.com/vogler/free-games-claimer/issues/5): ~~redeem keys on external stores.~~
|
||||
|
||||
<!-- ### Xbox Games With Gold -->
|
||||
<!-- Run `node xbox` (locally or in docker). -->
|
||||
|
||||
### Run periodically
|
||||
#### How often?
|
||||
Epic Games usually has two free games *every week*, before Christmas every day.
|
||||
Prime Gaming has new games *every month* or more often during Prime days.
|
||||
GOG usually has one new game every couples of weeks.
|
||||
Unreal Engine has new assets to claim *every first Tuesday of a month*.
|
||||
<!-- Xbox usually has two games *every month*. -->
|
||||
|
||||
It is safe to run the scripts every day.
|
||||
|
||||
#### How to schedule?
|
||||
The container/scripts will claim currently available games and then exit.
|
||||
If you want it to run regularly, you have to schedule the runs yourself:
|
||||
|
||||
- Linux/macOS: `crontab -e` ([example](https://github.com/vogler/free-games-claimer/discussions/56))
|
||||
- macOS: [launchd](https://stackoverflow.com/questions/132955/how-do-i-set-a-task-to-run-every-so-often)
|
||||
- Windows: [task scheduler](https://active-directory-wp.com/docs/Usage/How_to_add_a_cron_job_on_Windows/Scheduled_tasks_and_cron_jobs_on_Windows/index.html) ([example](https://github.com/vogler/free-games-claimer/wiki/%5BHowTo%5D-Schedule-runs-on-Windows)), [other options](https://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron), or just put the command in a `.bat` file in Autostart if you restart often...
|
||||
- any OS: use a process manager like [pm2](https://pm2.keymetrics.io/docs/usage/restart-strategies/)
|
||||
- Docker Compose `command: bash -c "node epic-games; node prime-gaming; node gog; echo sleeping; sleep 1d"` additionally add `restart: unless-stopped` to it.
|
||||
|
||||
TODO: ~~add some server-mode where the script just keeps running and claims games e.g. every day.~~
|
||||
|
||||
### Problems?
|
||||
|
||||
Check the open [issues](https://github.com/vogler/free-games-claimer/issues) and comment there or open a new issue.
|
||||
|
||||
If you're a developer, you can use `PWDEBUG=1 ...` to [inspect](https://playwright.dev/docs/inspector) which opens a debugger where you can step through the script.
|
||||
|
||||
|
||||
## History/DevLog
|
||||
<details>
|
||||
<summary>Click to expand</summary>
|
||||
|
||||
Tried [epicgames-freebies-claimer](https://github.com/Revadike/epicgames-freebies-claimer), but had problems since epicgames introduced hcaptcha (see [issue](https://github.com/Revadike/epicgames-freebies-claimer/issues/172)).
|
||||
|
||||
Played around with puppeteer before, now trying newer https://playwright.dev which is pretty similar.
|
||||
Playwright Inspector and `codegen` to generate scripts are nice, but failed to generate the right code for clicking a button in an iframe.
|
||||
|
||||
Added [main.spec.ts](https://github.com/vogler/epicgames-claimer/commit/e5ce7916ab6329cfc7134677c4d89c2b3fa3ba97#diff-d18d03e9c407a20e05fbf03cbd6f9299857740544fb6b50d6a70b9c6fbc35831) which was the test script generated by `npx playwright codegen` with manual fix for clicking buttons in the created iframe. Can be executed by `npx playwright test`. The test runner has options `--debug` and `--timeout` and can execute typescript which is nice. However, this only worked up to the button 'I Agree', and then showed an hcaptcha.
|
||||
|
||||
Added [main.captcha.js](https://github.com/vogler/epicgames-claimer/commit/e5ce7916ab6329cfc7134677c4d89c2b3fa3ba97#diff-d18d03e9c407a20e05fbf03cbd6f9299857740544fb6b50d6a70b9c6fbc35831) which uses beta of `playwright-extra@next` and `@extra/recaptcha@next` (from [comment on puppeteer-extra](https://github.com/berstend/puppeteer-extra/pull/303#issuecomment-775277480)).
|
||||
However, `playwright-extra` seems to be old and missing `:has-text` selector (fixed [here](https://github.com/vogler/epicgames-claimer/commit/ba97a0e840b65f4476cca18e28d8461b0c703420)) and `page.frameLocator`, so the script did not run without adjustments.
|
||||
Also, solving via [2captcha](https://2captcha.com?from=13225256) is a paid service which takes time and may be unreliable.
|
||||
<!-- Alternative: https://anti-captcha.com -->
|
||||
|
||||
Added [main.stealth.js](https://github.com/vogler/epicgames-claimer/commit/64d0ba8ce71baec3947d1b64acd567befcb39340#diff-f70d3bd29df4a343f11062a97063953173491ce30fe34f69a0fc52517adbf342) which uses the stealth plugin without `playwright-extra` wrapper but up-to-date `playwright` (from [comment](https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212)).
|
||||
The listed evasions are enough to not show an hcaptcha. Script claimed game successfully in non-headless mode.
|
||||
|
||||
Removed `main.captcha.js`.
|
||||
Using Playwright Test (`main.spec.ts`) instead of Library (`main.stealth.js`) has the advantage of free CLI like `--debug` and `--timeout`.
|
||||
<!-- TODO: check if stealth plugin can be setup with `contextOptions` ([doc](https://playwright.dev/docs/test-configuration#more-browser-and-context-options)). -->
|
||||
|
||||
Button selectors should preferably use text in order to be more stable against changes in the DOM.
|
||||
|
||||
Renamed repository from epicgames-claimer to free-games-claimer since a script for Amazon Prime Gaming was also added. Removed all old scripts in favor of just `epic-games.js` and `prime-gaming.js`.
|
||||
|
||||
epic games: `headless` mode gets hcaptcha challenge. More details/references in [issue](https://github.com/vogler/free-games-claimer/issues/2).
|
||||
|
||||
https://github.com/vogler/free-games-claimer/pull/11 introduced a Dockerfile for running non-headless inside the container via xvfb which makes it headless for the host running the container.
|
||||
|
||||
v1.0 Standalone scripts node epic-games and node prime-gaming using Chromium.
|
||||
|
||||
Changed to Firefox for all scripts since Chromium led to captchas. Claiming then also worked in headless mode without Docker.
|
||||
|
||||
Added options via env vars, configurable in `data/config.env`.
|
||||
|
||||
Added OTP generation via otplib for automatic login, even with 2FA.
|
||||
|
||||
Added notifications via [apprise](https://github.com/caronc/apprise).
|
||||
</details>
|
||||
|
||||
[](https://star-history.com/#vogler/free-games-claimer&Date)
|
||||
<!-- [](https://starchart.cc/vogler/free-games-claimer) -->
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 📖 Complete Setup Guide
|
||||
|
||||
For detailed setup instructions, see **[SETUP.md](SETUP.md)**.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Cloudflare / "Incorrect response" Error (Epic Games)
|
||||
|
||||
If you see **"Incorrect response. Please refresh the page."** or repeated "word word" text on the login page, Cloudflare is blocking the automated browser.
|
||||
|
||||
**Solution 1: Use Docker Compose (recommended)**
|
||||
|
||||
The included `docker-compose.yml` has FlareSolverr pre-configured:
|
||||
|
||||
```bash
|
||||
docker compose up
|
||||
```
|
||||
|
||||
**Solution 2: Manual login with persistent cookies**
|
||||
|
||||
```bash
|
||||
docker run --rm -it \
|
||||
-p 6080:6080 \
|
||||
-v fgc-data:/fgc/data \
|
||||
-v fgc-browser:/home/fgc/.cache/browser \
|
||||
-e SHOW=1 \
|
||||
-e EG_MODE=new \
|
||||
git.sky-net.it/nocci/free-games-claimer:dev \
|
||||
node epic-games
|
||||
```
|
||||
|
||||
Then open `http://localhost:6080`, log in manually. Cookies are saved for subsequent runs.
|
||||
|
||||
**Solution 3: Disable strict Firefox privacy settings**
|
||||
|
||||
The entrypoint now creates a `user.js` with Cloudflare-friendly settings. If you still have issues, delete the browser profile to regenerate it:
|
||||
|
||||
```bash
|
||||
docker volume rm fgc-browser
|
||||
```
|
||||
|
||||
### Common Issues
|
||||
|
||||
| Error | Cause | Fix |
|
||||
|-------|-------|-----|
|
||||
| "Incorrect response" | Cloudflare bot detection | Use FlareSolverr or manual login |
|
||||
| Captcha loop | IP flagged | Wait, change IP, or use FlareSolverr |
|
||||
| "Not signed in" timeout | Login expired | Run with `SHOW=1` and re-login |
|
||||
| Repeated "word" text | Cloudflare fingerprinting | See Cloudflare solutions above |
|
||||
Logo with smaller aspect ratio (for Telegram bot etc.): 👾 - [emojipedia](https://emojipedia.org/alien-monster/)
|
||||
|
||||

|
||||
|
|
|
|||
350
SETUP.md
350
SETUP.md
|
|
@ -1,350 +0,0 @@
|
|||
# Epic Games Free Games Claimer - Setup Guide
|
||||
|
||||
## 🚀 Quick Start (Docker Compose)
|
||||
|
||||
### Voraussetzungen
|
||||
|
||||
- Docker & Docker Compose
|
||||
- Epic Games Account (Email, Passwort, optional 2FA)
|
||||
|
||||
### 1. docker-compose.yml erstellen
|
||||
|
||||
```yaml
|
||||
services:
|
||||
# FlareSolverr für Cloudflare Bypass
|
||||
flaresolverr:
|
||||
image: ghcr.io/flaresolverr/flaresolverr:latest
|
||||
container_name: flaresolverr
|
||||
ports:
|
||||
- "8191:8191"
|
||||
environment:
|
||||
- LOG_LEVEL=info
|
||||
- LOG_HTML=false
|
||||
- CAPTCHA_SOLVER=none
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- fgc-network
|
||||
|
||||
# Free Games Claimer
|
||||
free-games-claimer:
|
||||
image: git.sky-net.it/nocci/free-games-claimer:latest
|
||||
# ODER: build: . # Selbst bauen für neueste Version
|
||||
container_name: fgc
|
||||
ports:
|
||||
- "6080:6080" # noVNC (Web-Browser für Login)
|
||||
# - "5900:5900" # VNC (optional)
|
||||
volumes:
|
||||
- fgc-data:/fgc/data
|
||||
- fgc-browser:/home/fgc/.cache/browser
|
||||
- fgc-playwright:/home/fgc/.cache/ms-playwright
|
||||
environment:
|
||||
# Epic Games Login
|
||||
- EG_EMAIL=deine@email.com
|
||||
- EG_PASSWORD=dein_passwort
|
||||
- EG_OTPKEY= # Optional: 2FA Secret (Base32)
|
||||
|
||||
# Login-Modus
|
||||
- EG_MODE=new # "new" für API-Modus, "legacy" für Browser
|
||||
|
||||
# FlareSolverr Integration
|
||||
- FLARESOLVERR_URL=http://flaresolverr:8191/v1
|
||||
|
||||
# Browser-Einstellungen
|
||||
- SHOW=0 # 0=headless, 1=visible (für Debugging)
|
||||
- WIDTH=1920
|
||||
- HEIGHT=1080
|
||||
|
||||
# Timeouts
|
||||
- TIMEOUT=60 # Standard-Timeout in Sekunden
|
||||
- LOGIN_TIMEOUT=180 # Login-Timeout (länger für Captchas)
|
||||
|
||||
# Optional: Notifications
|
||||
# - NOTIFY=apprise://...
|
||||
|
||||
# Keep-Alive (Container läuft weiter nach Durchlauf)
|
||||
- KEEP_ALIVE_SECONDS=86400
|
||||
networks:
|
||||
- fgc-network
|
||||
depends_on:
|
||||
- flaresolverr
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
fgc-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
fgc-data:
|
||||
fgc-browser:
|
||||
fgc-playwright:
|
||||
```
|
||||
|
||||
### 2. Environment-Variablen setzen
|
||||
|
||||
**WICHTIG:** Ersetze die Platzhalter:
|
||||
|
||||
```bash
|
||||
# .env Datei erstellen (nicht versionieren!)
|
||||
cat > .env << EOF
|
||||
EG_EMAIL=deine@email.com
|
||||
EG_PASSWORD=dein_passwort
|
||||
EG_OTPKEY= # Optional, wenn 2FA aktiv
|
||||
NOTIFY= # Optional, für Benachrichtigungen
|
||||
EOF
|
||||
```
|
||||
|
||||
### 3. Starten
|
||||
|
||||
```bash
|
||||
# Container starten
|
||||
docker compose up -d
|
||||
|
||||
# Logs ansehen
|
||||
docker compose logs -f fgc
|
||||
|
||||
# Container stoppen
|
||||
docker compose down
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Erster Login (WICHTIG!)
|
||||
|
||||
### Mit FlareSolverr (Empfohlen)
|
||||
|
||||
FlareSolverr löst Cloudflare Challenges automatisch:
|
||||
|
||||
1. Container starten (FlareSolverr läuft mit)
|
||||
2. Erster Login wird automatisch versucht
|
||||
3. Falls Captcha: FlareSolverr versucht es zu lösen
|
||||
4. Nach Erfolg: Tokens werden gespeichert
|
||||
|
||||
### Ohne FlareSolverr (Manuell)
|
||||
|
||||
Falls Cloudflare Captchas nicht automatisch lösbar sind:
|
||||
|
||||
```bash
|
||||
# Container mit visible Browser starten
|
||||
docker compose up -d
|
||||
|
||||
# noVNC im Browser öffnen
|
||||
http://localhost:6080
|
||||
|
||||
# Manuell bei Epic Games einloggen
|
||||
# Cookies/Tokens werden automatisch gespeichert!
|
||||
```
|
||||
|
||||
**Beim nächsten Start:** Kein Login nötig (gespeicherte Session)!
|
||||
|
||||
---
|
||||
|
||||
## 📋 Environment-Variablen
|
||||
|
||||
### Epic Games Login
|
||||
|
||||
| Variable | Beschreibung | Beispiel |
|
||||
|----------|-------------|----------|
|
||||
| `EG_EMAIL` | Epic Games Account Email | `user@example.com` |
|
||||
| `EG_PASSWORD` | Epic Games Passwort | `secret123` |
|
||||
| `EG_OTPKEY` | 2FA Secret (Base32) | `JBSWY3DPEHPK3PXP` |
|
||||
| `EG_PARENTALPIN` | Parental Control PIN | `1234` |
|
||||
|
||||
### Login-Modus
|
||||
|
||||
| Variable | Beschreibung | Werte |
|
||||
|----------|-------------|-------|
|
||||
| `EG_MODE` | Login-Methode | `new` (API), `legacy` (Browser) |
|
||||
|
||||
### Browser & Display
|
||||
|
||||
| Variable | Beschreibung | Default |
|
||||
|----------|-------------|---------|
|
||||
| `SHOW` | Visible Browser | `0` (headless) |
|
||||
| `WIDTH` | Browser Breite | `1920` |
|
||||
| `HEIGHT` | Browser Höhe | `1080` |
|
||||
| `BROWSER_DIR` | Browser Profil Pfad | `/fgc/data/browser` |
|
||||
|
||||
### Timeouts
|
||||
|
||||
| Variable | Beschreibung | Default |
|
||||
|----------|-------------|---------|
|
||||
| `TIMEOUT` | Standard-Timeout (Sekunden) | `60` |
|
||||
| `LOGIN_TIMEOUT` | Login-Timeout (Sekunden) | `180` |
|
||||
| `LOGIN_VISIBLE_TIMEOUT` | Login Button Detection (ms) | `20000` |
|
||||
|
||||
### FlareSolverr
|
||||
|
||||
| Variable | Beschreibung | Default |
|
||||
|----------|-------------|---------|
|
||||
| `FLARESOLVERR_URL` | FlareSolverr API URL | `http://flaresolverr:8191/v1` |
|
||||
|
||||
### Notifications
|
||||
|
||||
| Variable | Beschreibung | Beispiel |
|
||||
|----------|-------------|----------|
|
||||
| `NOTIFY` | Apprise Notification URL | `tgram://...` |
|
||||
| `NOTIFY_TITLE` | Notification Titel | `Free Games Claimer` |
|
||||
|
||||
### Debugging
|
||||
|
||||
| Variable | Beschreibung | Default |
|
||||
|----------|-------------|---------|
|
||||
| `DEBUG` | Playwright Inspector | `0` |
|
||||
| `DEBUG_NETWORK` | Log Network Requests | `0` |
|
||||
| `DRYRUN` | Nicht wirklich claimen | `0` |
|
||||
| `TIME` | Timing-Informationen | `0` |
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Troubleshooting
|
||||
|
||||
### Cloudflare / Captcha Probleme
|
||||
|
||||
**Symptom:** "Incorrect response" oder Captcha-Schleife
|
||||
|
||||
**Lösung 1: FlareSolverr prüfen**
|
||||
```bash
|
||||
docker compose logs flaresolverr
|
||||
# Sollte "Serving on http://0.0.0.0:8191" zeigen
|
||||
```
|
||||
|
||||
**Lösung 2: Manuelles Login**
|
||||
```bash
|
||||
# noVNC öffnen
|
||||
http://localhost:6080
|
||||
|
||||
# Einmal manuell einloggen
|
||||
# Cookies bleiben gespeichert!
|
||||
```
|
||||
|
||||
**Lösung 3: Browser-Profil resetten**
|
||||
```bash
|
||||
docker volume rm fgc-browser
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### Login schlägt fehl
|
||||
|
||||
**Symptom:** "Login failed" oder Timeout
|
||||
|
||||
**Lösung:**
|
||||
1. Email/Passwort prüfen
|
||||
2. 2FA: EG_OTPKEY korrekt setzen
|
||||
3. Mit `SHOW=1` debuggen
|
||||
|
||||
### Container startet nicht
|
||||
|
||||
**Symptom:** Exit Code 1 oder hängt
|
||||
|
||||
**Logs prüfen:**
|
||||
```bash
|
||||
docker compose logs fgc
|
||||
```
|
||||
|
||||
**Volumes prüfen:**
|
||||
```bash
|
||||
docker volume ls | grep fgc
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 2FA / OTP einrichten
|
||||
|
||||
### Epic Games 2FA Secret auslesen
|
||||
|
||||
1. Epic Games Website → Account → Passwort & Sicherheit
|
||||
2. Zwei-Faktor-Authentifizierung → Authentifizierungs-App
|
||||
3. **NICHT** QR-Code scannen, sondern "Manuell eingeben" wählen
|
||||
4. Secret kopieren (Base32, z.B. `JBSWY3DPEHPK3PXP`)
|
||||
|
||||
### In docker-compose.yml
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
- EG_OTPKEY=JBSWY3DPEHPK3PXP # Dein Secret hier
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Updates
|
||||
|
||||
### Image Update
|
||||
|
||||
```bash
|
||||
# Aktuellen Container stoppen
|
||||
docker compose down
|
||||
|
||||
# Neues Image pullen
|
||||
docker compose pull
|
||||
|
||||
# Neu starten
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### Selbst bauen (neueste Version)
|
||||
|
||||
```bash
|
||||
# In docker-compose.yml: build: . statt image: ...
|
||||
cd /path/to/free-games-claimer
|
||||
docker compose build --no-cache
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📁 Volumes (Persistenz)
|
||||
|
||||
| Volume | Inhalt | Wichtig |
|
||||
|--------|--------|---------|
|
||||
| `fgc-data` | JSON-Datenbank, Screenshots | ✅ Claim-Status |
|
||||
| `fgc-browser` | Browser-Profil, Cookies | ✅ Login-Session |
|
||||
| `fgc-playwright` | Playwright Browser | ⚡ Schnellere Starts |
|
||||
|
||||
**Backup:**
|
||||
```bash
|
||||
# Alle Volumes sichern
|
||||
docker run --rm -v fgc-data:/data -v $(pwd)/backup:/backup alpine tar czf /backup/fgc-data.tar.gz -C /data .
|
||||
```
|
||||
|
||||
**Restore:**
|
||||
```bash
|
||||
docker run --rm -v fgc-data:/data -v $(pwd)/backup:/backup alpine tar xzf /backup/fgc-data.tar.gz -C /data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Nächste Schritte
|
||||
|
||||
1. **Einrichten:** docker-compose.yml anpassen
|
||||
2. **Starten:** `docker compose up -d`
|
||||
3. **Erster Login:** noVNC oder mit FlareSolverr
|
||||
4. **Automatisieren:** Cron-Job für regelmäßige Ausführung
|
||||
|
||||
### Cron-Job Beispiel (alle 6 Stunden)
|
||||
|
||||
```yaml
|
||||
# In docker-compose.yml
|
||||
command: >
|
||||
bash -c "
|
||||
node epic-games &&
|
||||
node gog &&
|
||||
sleep 86400
|
||||
"
|
||||
```
|
||||
|
||||
Oder mit Host-Cron:
|
||||
```bash
|
||||
# Host-Cron bearbeiten
|
||||
crontab -e
|
||||
|
||||
# Alle 6 Stunden
|
||||
0 */6 * * * docker compose -f /path/to/docker-compose.yml up --rm free-games-claimer
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🆘 Support
|
||||
|
||||
- **Issues:** https://git.sky-net.it/nocci/free-games-claimer/issues
|
||||
- **Dokumentation:** README.md im Repository
|
||||
- **FlareSolverr:** https://github.com/FlareSolverr/FlareSolverr
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||
import { datetime, filenamify, prompt, handleSIGINT } from './src/util.js';
|
||||
import { datetime, filenamify, prompt, handleSIGINT, stealth } from './src/util.js';
|
||||
import { cfg } from './src/config.js';
|
||||
|
||||
// using https://github.com/apify/fingerprint-suite worked, but has no launchPersistentContext...
|
||||
|
|
@ -8,12 +8,13 @@ import { FingerprintInjector } from 'fingerprint-injector';
|
|||
import { FingerprintGenerator } from 'fingerprint-generator';
|
||||
|
||||
const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({
|
||||
devices: ['mobile'],
|
||||
operatingSystems: ['android'],
|
||||
devices: ["mobile"],
|
||||
operatingSystems: ["android"],
|
||||
});
|
||||
|
||||
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||
headless: cfg.headless,
|
||||
// viewport: { width: cfg.width, height: cfg.height },
|
||||
locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL
|
||||
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined, // will record a .webm video for each page navigated; without size, video would be scaled down to fit 800x800
|
||||
recordHar: cfg.record ? { path: `data/record/aliexpress-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools
|
||||
|
|
@ -28,19 +29,23 @@ const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
|||
},
|
||||
});
|
||||
handleSIGINT(context);
|
||||
// await stealth(context);
|
||||
await new FingerprintInjector().attachFingerprintToPlaywright(context, { fingerprint, headers });
|
||||
|
||||
context.setDefaultTimeout(cfg.debug ? 0 : cfg.timeout);
|
||||
|
||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||
|
||||
const auth = async url => {
|
||||
const auth = async (url) => {
|
||||
console.log('auth', url);
|
||||
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||
// redirects to https://login.aliexpress.com/?return_url=https%3A%2F%2Fwww.aliexpress.com%2Fp%2Fcoin-pc-index%2Findex.html
|
||||
await Promise.any([page.waitForURL(url => url.includes('login.aliexpress.com')).then(async () => {
|
||||
await Promise.any([page.waitForURL(/.*login\.aliexpress.com.*/).then(async () => {
|
||||
// manual login
|
||||
console.error('Not logged in! Will wait for 120s for you to login...');
|
||||
page.locator('span:has-text("Switch account")').click().catch(() => {}); // sometimes no longer logged in, but previous user/email is pre-selected -> in this case we want to go back to the classic login
|
||||
// await page.waitForTimeout(120*1000);
|
||||
// or try automated
|
||||
page.locator('span:has-text("Switch account")').click().catch(_ => {}); // sometimes no longer logged in, but previous user/email is pre-selected -> in this case we want to go back to the classic login
|
||||
const login = page.locator('.login-container');
|
||||
const email = cfg.ae_email || await prompt({ message: 'Enter email' });
|
||||
const emailInput = login.locator('input[label="Email or phone number"]');
|
||||
|
|
@ -53,10 +58,14 @@ const auth = async url => {
|
|||
await login.locator('input[label="Password"]').fill(password);
|
||||
await login.locator('button:has-text("Sign in")').click();
|
||||
const error = login.locator('.error-text');
|
||||
error.waitFor().then(async () => console.error('Login error:', await error.innerText()));
|
||||
error.waitFor().then(async _ => console.error('Login error:', await error.innerText()));
|
||||
await page.waitForURL(url);
|
||||
page.getByRole('button', { name: 'Accept cookies' }).click().then(() => console.log('Accepted cookies')).catch(() => { });
|
||||
}), page.locator('#nav-user-account').waitFor()]).catch(() => {});
|
||||
// await page.addLocatorHandler(page.getByRole('button', { name: 'Accept cookies' }), btn => btn.click());
|
||||
page.getByRole('button', { name: 'Accept cookies' }).click().then(_ => console.log('Accepted cookies')).catch(_ => { });
|
||||
}), page.locator('#nav-user-account').waitFor()]).catch(_ => {});
|
||||
|
||||
// await page.locator('#nav-user-account').hover();
|
||||
// console.log('Logged in as:', await page.locator('.welcome-name').innerText());
|
||||
};
|
||||
|
||||
// copied URLs from AliExpress app on tablet which has menu for the used webview
|
||||
|
|
@ -71,8 +80,8 @@ const urls = {
|
|||
merge: 'https://m.aliexpress.com/p/merge-market/index.html',
|
||||
};
|
||||
|
||||
|
||||
const coins = async () => {
|
||||
// await auth(urls.coins);
|
||||
await Promise.any([page.locator('.checkin-button').click(), page.locator('.addcoin').waitFor()]);
|
||||
console.log('Coins:', await page.locator('.mycoin-content-right-money').innerText());
|
||||
console.log('Streak:', await page.locator('.title-box').innerText());
|
||||
|
|
@ -95,15 +104,17 @@ const merge = async () => {
|
|||
await page.pause();
|
||||
};
|
||||
|
||||
|
||||
try {
|
||||
// await coins();
|
||||
await [
|
||||
// coins,
|
||||
// grow,
|
||||
// gogo,
|
||||
// euro,
|
||||
merge,
|
||||
].reduce((a, f) => a.then(async () => {
|
||||
await auth(urls[f.name]);
|
||||
await f();
|
||||
console.log();
|
||||
}), Promise.resolve());
|
||||
].reduce((a, f) => a.then(async _ => { await auth(urls[f.name]); await f(); console.log() }), Promise.resolve());
|
||||
|
||||
// await page.pause();
|
||||
} catch (error) {
|
||||
process.exitCode ||= 1;
|
||||
console.error('--- Exception:');
|
||||
|
|
|
|||
|
|
@ -1,18 +1,5 @@
|
|||
# start with `docker compose up`
|
||||
services:
|
||||
flaresolverr:
|
||||
container_name: flaresolverr
|
||||
image: flaresolverr/flaresolverr:latest
|
||||
ports:
|
||||
- "8191:8191"
|
||||
environment:
|
||||
- LOG_LEVEL=info
|
||||
- LOG_HTML=false
|
||||
- CAPTCHA_SOLVER=none
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- fgc-network
|
||||
|
||||
free-games-claimer:
|
||||
container_name: fgc # is printed in front of every output line
|
||||
image: ghcr.io/vogler/free-games-claimer # otherwise image name will be free-games-claimer-free-games-claimer
|
||||
|
|
@ -23,20 +10,6 @@ services:
|
|||
volumes:
|
||||
- fgc:/fgc/data
|
||||
# command: bash -c "node epic-games; node gog"
|
||||
command: node epic-games
|
||||
environment:
|
||||
# - EMAIL=foo@bar.org
|
||||
# - NOTIFY='tgram://...'
|
||||
- EG_MODE=new
|
||||
- FLARESOLVERR_URL=http://flaresolverr:8191/v1
|
||||
networks:
|
||||
- fgc-network
|
||||
depends_on:
|
||||
- flaresolverr
|
||||
|
||||
networks:
|
||||
fgc-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
fgc:
|
||||
|
|
|
|||
|
|
@ -2,77 +2,33 @@
|
|||
|
||||
set -eo pipefail # exit on error, error on any fail in pipe (not just last cmd); add -x to print each cmd; see gist bash_strict_mode.md
|
||||
|
||||
REPO_URL=${REPO_URL:-https://git.sky-net.it/nocci/free-games-claimer}
|
||||
if [ -n "$COMMIT" ]; then
|
||||
echo "Version: ${REPO_URL}/tree/${COMMIT}"
|
||||
else
|
||||
echo "Version: ${REPO_URL}"
|
||||
fi
|
||||
[ -n "$BRANCH" ] && [ "$BRANCH" != "main" ] && echo "Branch: ${BRANCH}"
|
||||
echo "Version: https://github.com/vogler/free-games-claimer/tree/${COMMIT}"
|
||||
[ ! -z $BRANCH ] && [ $BRANCH != "main" ] && echo "Branch: ${BRANCH}"
|
||||
echo "Build: $NOW"
|
||||
|
||||
# Ensure writable data dir for fgc when host bind-mount is owned by root.
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
chown -R 1000:1000 /fgc/data 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Remove chromium profile lock.
|
||||
# When running in docker and then killing it, on the next run chromium displayed a dialog to unlock the profile which made the script time out.
|
||||
# Maybe due to changed hostname of container or due to how the docker container kills playwright - didn't check.
|
||||
# https://bugs.chromium.org/p/chromium/issues/detail?id=367048
|
||||
rm -f /fgc/data/browser/SingletonLock 2>/dev/null || true
|
||||
rm -f /fgc/data/browser/SingletonLock
|
||||
|
||||
# Firefox profile directory (persistent if writable; fallback to cache when bind-mount is read-only).
|
||||
BROWSER_DIR=/fgc/data/browser
|
||||
mkdir -p "$BROWSER_DIR" 2>/dev/null || true
|
||||
if [ ! -w "$BROWSER_DIR" ]; then
|
||||
echo "Warning: $BROWSER_DIR not writable; using fallback profile at /home/fgc/.cache/browser"
|
||||
BROWSER_DIR=/home/fgc/.cache/browser
|
||||
mkdir -p "$BROWSER_DIR" 2>/dev/null || true
|
||||
chown 1000:1000 "$BROWSER_DIR" 2>/dev/null || true
|
||||
fi
|
||||
if [ ! -w "$BROWSER_DIR" ]; then
|
||||
echo "Warning: $BROWSER_DIR not writable; using temp profile at /tmp/browser"
|
||||
BROWSER_DIR=/tmp/browser
|
||||
mkdir -p "$BROWSER_DIR"
|
||||
chmod 777 "$BROWSER_DIR" 2>/dev/null || true
|
||||
fi
|
||||
# clean up stale firefox locks that can trigger "already running"
|
||||
rm -f "$BROWSER_DIR"/parent.lock "$BROWSER_DIR"/lock "$BROWSER_DIR"/.parentlock 2>/dev/null || true
|
||||
# Firefox preferences are stored in $BROWSER_DIR/pref.js and can be overridden by a file user.js
|
||||
# Since this file has to be in the volume (data/browser), we can't do this in Dockerfile.
|
||||
mkdir -p /fgc/data/browser
|
||||
# fix for 'Incorrect response' after solving a captcha correctly - https://github.com/vogler/free-games-claimer/issues/261#issuecomment-1868385830
|
||||
# Only write the prefs file when the volume is writable (container runs as non-root).
|
||||
if [ -w "$BROWSER_DIR" ] && { [ ! -e "$BROWSER_DIR/user.js" ] || [ -w "$BROWSER_DIR/user.js" ] || rm -f "$BROWSER_DIR/user.js" 2>/dev/null; }; then
|
||||
cat << 'EOT' > "$BROWSER_DIR/user.js"
|
||||
// Anti-fingerprinting settings for Cloudflare bypass
|
||||
user_pref("privacy.resistFingerprinting", false); // Can trigger Cloudflare
|
||||
user_pref("privacy.resistFingerprinting.letterboxing", false);
|
||||
user_pref("browser.contentblocking.category", "standard");
|
||||
user_pref("webgl.disabled", false); // WebGL needed for some bot detection
|
||||
user_pref("webgl.enable-webgl2", true);
|
||||
user_pref("javascript.use_us_english_locale", true);
|
||||
user_pref("intl.accept_languages", "en-US,en");
|
||||
user_pref("privacy.trackingprotection.enabled", false); // Can interfere with Cloudflare
|
||||
user_pref("network.http.referer.default_policy", 2);
|
||||
user_pref("network.http.referer.XOriginPolicy", 0);
|
||||
# echo 'user_pref("privacy.resistFingerprinting", true);' > /fgc/data/browser/user.js
|
||||
cat << EOT > /fgc/data/browser/user.js
|
||||
user_pref("privacy.resistFingerprinting", true);
|
||||
// user_pref("privacy.resistFingerprinting.letterboxing", true);
|
||||
// user_pref("browser.contentblocking.category", "strict");
|
||||
// user_pref("webgl.disabled", true);
|
||||
EOT
|
||||
else
|
||||
echo "Warning: $BROWSER_DIR not writable; skipping user.js creation."
|
||||
fi
|
||||
export BROWSER_DIR
|
||||
# TODO disable session restore message?
|
||||
|
||||
# Remove X server display lock, fix for `docker compose up` which reuses container which made it fail after initial run, https://github.com/vogler/free-games-claimer/issues/31
|
||||
# echo $DISPLAY
|
||||
# ls -l /tmp/.X11-unix/
|
||||
rm -f /tmp/.X11-lock
|
||||
|
||||
# Ensure X11 socket dir exists with sane ownership/permissions.
|
||||
mkdir -p /tmp/.X11-unix
|
||||
if [ "$(stat -c %U /tmp/.X11-unix 2>/dev/null)" != "root" ]; then
|
||||
chown root:root /tmp/.X11-unix 2>/dev/null || chmod 1777 /tmp/.X11-unix
|
||||
fi
|
||||
rm -f /tmp/.X1-lock
|
||||
|
||||
# 6000+SERVERNUM is the TCP port Xvfb is listening on:
|
||||
# SERVERNUM=$(echo "$DISPLAY" | sed 's/:\([0-9][0-9]*\).*/\1/')
|
||||
|
|
@ -96,11 +52,4 @@ echo "VNC is running on port $VNC_PORT ($pwt)"
|
|||
websockify -D --web "/usr/share/novnc/" $NOVNC_PORT "localhost:$VNC_PORT" 2>/dev/null 1>&2 &
|
||||
echo "noVNC (VNC via browser) is running on http://localhost:$NOVNC_PORT"
|
||||
echo
|
||||
|
||||
# Ensure Playwright browsers are available (chromium + firefox).
|
||||
if [ ! -x /home/fgc/.cache/ms-playwright/firefox-1482/firefox/firefox ] || ! ls /home/fgc/.cache/ms-playwright/chromium-*/*/chrome >/dev/null 2>&1; then
|
||||
echo "Playwright browsers missing; installing..."
|
||||
npx playwright install chromium firefox || echo "Warning: failed to install Playwright browsers" >&2
|
||||
fi
|
||||
|
||||
exec tini -g -- "$@" # https://github.com/krallin/tini/issues/8 node/playwright respond to signals like ctrl-c, but unsure about zombie processes
|
||||
|
|
|
|||
|
|
@ -1,447 +0,0 @@
|
|||
import { firefox } from 'playwright-firefox';
|
||||
import { authenticator } from 'otplib';
|
||||
import path from 'node:path';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import {
|
||||
jsonDb,
|
||||
datetime,
|
||||
stealth,
|
||||
filenamify,
|
||||
prompt,
|
||||
notify,
|
||||
html_game_list,
|
||||
handleSIGINT,
|
||||
} from './src/util.js';
|
||||
import { cfg } from './src/config.js';
|
||||
import { FREE_GAMES_PROMOTIONS_ENDPOINT, STORE_HOMEPAGE_EN, EPIC_PURCHASE_ENDPOINT, ID_LOGIN_ENDPOINT } from './src/constants.js';
|
||||
import { setPuppeteerCookies } from './src/cookie.js';
|
||||
import { getAccountAuth, setAccountAuth } from './src/device-auths.js';
|
||||
import { solveCloudflare, isCloudflareChallenge } from './src/cloudflare.js';
|
||||
import logger from './src/logger.js';
|
||||
|
||||
const L = logger.child({ module: 'epic-claimer-new' });
|
||||
|
||||
// Fetch Free Games from API using page.evaluate (browser context)
|
||||
const fetchFreeGamesAPI = async page => {
|
||||
const response = await page.evaluate(async () => {
|
||||
const resp = await fetch(FREE_GAMES_PROMOTIONS_ENDPOINT + '?locale=en-US&country=US&allowCountries=US,DE,AT,CH,GB');
|
||||
return await resp.json();
|
||||
});
|
||||
|
||||
return response?.Catalog?.searchStore?.elements
|
||||
?.filter(g => g.promotions?.promotionalOffers?.[0])
|
||||
?.map(g => {
|
||||
const offer = g.promotions.promotionalOffers[0].promotionalOffers[0];
|
||||
const mapping = g.catalogNs?.mappings?.[0];
|
||||
return {
|
||||
title: g.title,
|
||||
namespace: mapping?.id || g.productSlug,
|
||||
pageSlug: mapping?.pageSlug || g.urlSlug,
|
||||
offerId: offer?.offerId,
|
||||
};
|
||||
}) || [];
|
||||
};
|
||||
|
||||
const URL_CLAIM = 'https://store.epicgames.com/en-US/free-games';
|
||||
const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM;
|
||||
const COOKIES_PATH = path.resolve(cfg.dir.browser, 'epic-cookies.json');
|
||||
|
||||
// Claim game function
|
||||
const claimGame = async (page, game) => {
|
||||
const purchaseUrl = `https://store.epicgames.com/${game.pageSlug}`;
|
||||
console.log(`🎮 ${game.title} → ${purchaseUrl}`);
|
||||
const notify_game = { title: game.title, url: purchaseUrl, status: 'failed' };
|
||||
|
||||
await page.goto(purchaseUrl, { waitUntil: 'networkidle' });
|
||||
|
||||
const purchaseBtn = page.locator('button[data-testid="purchase-cta-button"]').first();
|
||||
await purchaseBtn.waitFor({ timeout: cfg.timeout });
|
||||
const btnText = (await purchaseBtn.textContent() || '').toLowerCase();
|
||||
|
||||
if (btnText.includes('library') || btnText.includes('owned')) {
|
||||
notify_game.status = 'existed';
|
||||
return notify_game;
|
||||
}
|
||||
if (cfg.dryrun) {
|
||||
notify_game.status = 'skipped';
|
||||
return notify_game;
|
||||
}
|
||||
|
||||
await purchaseBtn.click({ delay: 50 });
|
||||
|
||||
try {
|
||||
await page.waitForSelector('#webPurchaseContainer iframe', { timeout: 15000 });
|
||||
const iframe = page.frameLocator('#webPurchaseContainer iframe');
|
||||
|
||||
if (cfg.eg_parentalpin) {
|
||||
try {
|
||||
await iframe.locator('.payment-pin-code').waitFor({ timeout: 10000 });
|
||||
await iframe.locator('input.payment-pin-code__input').first().pressSequentially(cfg.eg_parentalpin);
|
||||
await iframe.locator('button:has-text("Continue")').click({ delay: 11 });
|
||||
} catch {
|
||||
// no PIN needed
|
||||
}
|
||||
}
|
||||
|
||||
await iframe.locator('button:has-text("Place Order"):not(:has(.payment-loading--loading))').click({ delay: 11 });
|
||||
try {
|
||||
await iframe.locator('button:has-text("I Accept")').click({ timeout: 5000 });
|
||||
} catch {
|
||||
// not required
|
||||
}
|
||||
await page.locator('text=Thanks for your order!').waitFor({ state: 'attached', timeout: cfg.timeout });
|
||||
notify_game.status = 'claimed';
|
||||
} catch (e) {
|
||||
notify_game.status = 'failed';
|
||||
const screenshotPath = path.resolve(cfg.dir.screenshots, 'epic-games', 'failed', `${game.offerId || game.pageSlug}_${filenamify(datetime())}.png`);
|
||||
await page.screenshot({ path: screenshotPath, fullPage: true }).catch(() => { });
|
||||
console.error(' Failed to claim:', e.message);
|
||||
}
|
||||
|
||||
return notify_game;
|
||||
};
|
||||
|
||||
// Check if logged in
|
||||
const isLoggedIn = async page => {
|
||||
try {
|
||||
// Wait for egs-navigation element to be present
|
||||
await page.locator('egs-navigation').waitFor({ state: 'attached', timeout: 5000 });
|
||||
const attr = await page.locator('egs-navigation').getAttribute('isloggedin');
|
||||
const isLogged = attr === 'true';
|
||||
L.trace({ isLogged, attr }, 'Login status check');
|
||||
return isLogged;
|
||||
} catch (err) {
|
||||
L.trace({ err: err.message }, 'Login status check failed');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Browser-based login with FlareSolverr support
|
||||
const attemptBrowserLogin = async (page, context) => {
|
||||
if (!cfg.eg_email || !cfg.eg_password) {
|
||||
L.warn('No email/password configured');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
L.info({ email: cfg.eg_email }, 'Attempting browser login');
|
||||
console.log('📝 Logging in with email/password...');
|
||||
|
||||
await page.goto(URL_LOGIN, {
|
||||
waitUntil: 'domcontentloaded',
|
||||
timeout: cfg.login_timeout,
|
||||
});
|
||||
|
||||
// Check for Cloudflare and solve if needed
|
||||
await page.waitForTimeout(2000); // Let page stabilize
|
||||
|
||||
try {
|
||||
if (await isCloudflareChallenge(page)) {
|
||||
L.warn('Cloudflare challenge detected during login');
|
||||
console.log('☁️ Cloudflare detected, attempting to solve...');
|
||||
|
||||
if (cfg.flaresolverr_url) {
|
||||
const solution = await solveCloudflare(page, URL_LOGIN);
|
||||
if (solution) {
|
||||
console.log('✅ Cloudflare solved by FlareSolverr');
|
||||
await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' });
|
||||
} else {
|
||||
console.log('⚠️ FlareSolverr failed, may need manual solve');
|
||||
}
|
||||
} else {
|
||||
console.log('⚠️ FlareSolverr not configured, may need manual solve');
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
L.warn({ err: err.message }, 'Cloudflare check failed');
|
||||
}
|
||||
|
||||
const emailField = page.locator('input[name="email"], input#email, input[aria-label="Sign in with email"]').first();
|
||||
const passwordField = page.locator('input[name="password"], input#password').first();
|
||||
const continueBtn = page.locator('button:has-text("Continue"), button#continue, button[type="submit"]').first();
|
||||
|
||||
// Step 1: Email + continue
|
||||
if (await emailField.count() > 0) {
|
||||
await emailField.fill(cfg.eg_email);
|
||||
await continueBtn.click();
|
||||
await page.waitForTimeout(1000);
|
||||
}
|
||||
|
||||
// Step 2: Password + submit
|
||||
try {
|
||||
await passwordField.waitFor({ timeout: cfg.login_visible_timeout });
|
||||
await passwordField.fill(cfg.eg_password);
|
||||
|
||||
const rememberMe = page.locator('input[name="rememberMe"], #rememberMe').first();
|
||||
if (await rememberMe.count() > 0) await rememberMe.check();
|
||||
await continueBtn.click();
|
||||
} catch (err) {
|
||||
L.warn({ err: err.message }, 'Password field not found, may already be logged in');
|
||||
return await isLoggedIn(page);
|
||||
}
|
||||
|
||||
// MFA step
|
||||
try {
|
||||
await page.waitForURL('**/id/login/mfa**', { timeout: 15000 });
|
||||
console.log('🔐 2FA detected');
|
||||
|
||||
const otp = cfg.eg_otpkey
|
||||
? authenticator.generate(cfg.eg_otpkey)
|
||||
: await prompt({
|
||||
type: 'text',
|
||||
message: 'Enter two-factor sign in code',
|
||||
validate: n => n.toString().length === 6 || 'The code must be 6 digits!',
|
||||
});
|
||||
|
||||
const codeInputs = page.locator('input[name^="code-input"]');
|
||||
if (await codeInputs.count() > 0) {
|
||||
const digits = otp.toString().split('');
|
||||
for (let i = 0; i < digits.length; i++) {
|
||||
const input = codeInputs.nth(i);
|
||||
await input.fill(digits[i]);
|
||||
}
|
||||
} else {
|
||||
await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString());
|
||||
}
|
||||
await continueBtn.click();
|
||||
} catch {
|
||||
// No MFA required
|
||||
L.trace('No MFA required');
|
||||
}
|
||||
|
||||
// Wait for successful login
|
||||
try {
|
||||
L.trace('Waiting for navigation to free-games page');
|
||||
await page.waitForURL('**/free-games**', { timeout: cfg.login_timeout });
|
||||
|
||||
// Give page time to fully load and egs-navigation to update
|
||||
L.trace('Waiting for page to stabilize');
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
// Check multiple times to ensure stable login state
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const logged = await isLoggedIn(page);
|
||||
if (logged) {
|
||||
L.info('Login confirmed');
|
||||
return true;
|
||||
}
|
||||
L.trace({ attempt: i + 1 }, 'Login not yet confirmed, retrying');
|
||||
await page.waitForTimeout(2000);
|
||||
}
|
||||
|
||||
L.warn('Login URL reached but login status not confirmed');
|
||||
return false;
|
||||
} catch (err) {
|
||||
L.warn({ err: err.message }, 'Login URL timeout, checking if logged in anyway');
|
||||
await page.waitForTimeout(3000);
|
||||
return await isLoggedIn(page);
|
||||
}
|
||||
} catch (err) {
|
||||
L.error({ err }, 'Browser login failed');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure user is logged in
|
||||
const ensureLoggedIn = async (page, context) => {
|
||||
L.info('Checking login status');
|
||||
|
||||
// Check if already logged in (from saved cookies)
|
||||
if (await isLoggedIn(page)) {
|
||||
const displayName = await page.locator('egs-navigation').getAttribute('displayname');
|
||||
L.info({ user: displayName }, 'Already logged in (from cookies)');
|
||||
console.log(`✅ Already signed in as ${displayName}`);
|
||||
return displayName;
|
||||
}
|
||||
|
||||
L.info('Not logged in, attempting login');
|
||||
console.log('📝 Not logged in, starting login process...');
|
||||
|
||||
// Try browser login with email/password
|
||||
const logged = await attemptBrowserLogin(page, context);
|
||||
|
||||
if (!logged) {
|
||||
L.error('Browser login failed');
|
||||
console.log('❌ Automatic login failed.');
|
||||
|
||||
// If headless, we can't do manual login
|
||||
if (cfg.headless) {
|
||||
const msg = 'Login failed in headless mode. Run with SHOW=1 to login manually via noVNC.';
|
||||
console.error(msg);
|
||||
await notify(`epic-games: ${msg}`);
|
||||
throw new Error('Login failed, headless mode');
|
||||
}
|
||||
|
||||
// Wait for manual login in visible browser
|
||||
console.log('⏳ Waiting for manual login in browser...');
|
||||
console.log(` Open noVNC at: http://localhost:${cfg.novnc_port || '6080'}`);
|
||||
await notify(
|
||||
'epic-games: Manual login required!<br>' +
|
||||
`Open noVNC: <a href="http://localhost:${cfg.novnc_port || '6080'}">http://localhost:${cfg.novnc_port || '6080'}</a><br>` +
|
||||
`Login timeout: ${cfg.login_timeout / 1000}s`,
|
||||
);
|
||||
|
||||
const maxWait = cfg.login_timeout;
|
||||
const checkInterval = 5000;
|
||||
let waited = 0;
|
||||
let loginConfirmed = false;
|
||||
|
||||
while (waited < maxWait) {
|
||||
await page.waitForTimeout(checkInterval);
|
||||
waited += checkInterval;
|
||||
|
||||
// Check multiple times for stable state
|
||||
for (let i = 0; i < 2; i++) {
|
||||
if (await isLoggedIn(page)) {
|
||||
// Confirm it's stable
|
||||
await page.waitForTimeout(2000);
|
||||
if (await isLoggedIn(page)) {
|
||||
loginConfirmed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (loginConfirmed) {
|
||||
L.info('Manual login detected and confirmed');
|
||||
console.log('✅ Manual login detected!');
|
||||
break;
|
||||
}
|
||||
|
||||
// Progress update every 30 seconds
|
||||
if (waited % 30000 === 0) {
|
||||
const remaining = Math.round((maxWait - waited) / 1000);
|
||||
console.log(` Still waiting... ${remaining}s remaining`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!loginConfirmed && !await isLoggedIn(page)) {
|
||||
throw new Error('Manual login did not complete within timeout');
|
||||
}
|
||||
}
|
||||
|
||||
const displayName = await page.locator('egs-navigation').getAttribute('displayname');
|
||||
L.info({ user: displayName }, 'Successfully logged in');
|
||||
console.log(`✅ Signed in as ${displayName}`);
|
||||
|
||||
return displayName;
|
||||
};
|
||||
|
||||
// Save cookies to file
|
||||
const saveCookies = async context => {
|
||||
try {
|
||||
const cookies = await context.cookies();
|
||||
writeFileSync(COOKIES_PATH, JSON.stringify(cookies, null, 2));
|
||||
L.trace({ cookieCount: cookies.length }, 'Cookies saved');
|
||||
} catch (err) {
|
||||
L.warn({ err: err.message }, 'Failed to save cookies');
|
||||
}
|
||||
};
|
||||
|
||||
// Load cookies from file
|
||||
const loadCookies = async context => {
|
||||
if (!existsSync(COOKIES_PATH)) {
|
||||
L.trace('No saved cookies found');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const cookies = JSON.parse(readFileSync(COOKIES_PATH, 'utf8'));
|
||||
await context.addCookies(cookies);
|
||||
L.info({ cookieCount: cookies.length }, 'Loaded saved cookies');
|
||||
console.log('✅ Loaded saved cookies');
|
||||
return true;
|
||||
} catch (err) {
|
||||
L.warn({ err: err.message }, 'Failed to load cookies');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Main function to claim Epic Games
|
||||
export const claimEpicGamesNew = async () => {
|
||||
console.log('🚀 Starting Epic Games claimer (new mode)');
|
||||
const db = await jsonDb('epic-games.json', {});
|
||||
const notify_games = [];
|
||||
|
||||
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||
headless: cfg.headless,
|
||||
viewport: { width: cfg.width, height: cfg.height },
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0',
|
||||
locale: 'en-US',
|
||||
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined,
|
||||
recordHar: cfg.record ? { path: `data/record/eg-${filenamify(datetime())}.har` } : undefined,
|
||||
handleSIGINT: false,
|
||||
});
|
||||
handleSIGINT(context);
|
||||
await stealth(context);
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
|
||||
const page = context.pages().length ? context.pages()[0] : await context.newPage();
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height });
|
||||
|
||||
let user;
|
||||
|
||||
try {
|
||||
// Load saved cookies
|
||||
await loadCookies(context);
|
||||
|
||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
|
||||
|
||||
// Ensure logged in
|
||||
user = await ensureLoggedIn(page, context);
|
||||
db.data[user] ||= {};
|
||||
|
||||
// Fetch free games
|
||||
const freeGames = await fetchFreeGamesAPI(page);
|
||||
console.log('🎮 Free games available:', freeGames.length);
|
||||
if (freeGames.length > 0) {
|
||||
console.log(' ' + freeGames.map(g => g.title).join(', '));
|
||||
}
|
||||
|
||||
// Claim each game
|
||||
for (const game of freeGames) {
|
||||
if (cfg.time) console.time('claim game');
|
||||
|
||||
const result = await claimGame(page, game);
|
||||
notify_games.push(result);
|
||||
|
||||
db.data[user][game.offerId || game.pageSlug] = {
|
||||
title: game.title,
|
||||
time: datetime(),
|
||||
url: `https://store.epicgames.com/${game.pageSlug}`,
|
||||
status: result.status,
|
||||
};
|
||||
|
||||
if (cfg.time) console.timeEnd('claim game');
|
||||
}
|
||||
|
||||
// Save cookies for next run
|
||||
await saveCookies(context);
|
||||
|
||||
console.log('✅ Epic Games claimer completed');
|
||||
} catch (error) {
|
||||
process.exitCode ||= 1;
|
||||
console.error('--- Exception:');
|
||||
console.error(error);
|
||||
if (error.message && process.exitCode !== 130) {
|
||||
notify(`epic-games (new) failed: ${error.message.split('\n')[0]}`);
|
||||
}
|
||||
} finally {
|
||||
await db.write();
|
||||
|
||||
// Send notification if games were claimed or failed
|
||||
if (notify_games.filter(g => g.status === 'claimed' || g.status === 'failed').length) {
|
||||
notify(`epic-games (${user || 'unknown'}):<br>${html_game_list(notify_games)}`);
|
||||
}
|
||||
|
||||
if (cfg.debug && context) {
|
||||
console.log('Cookies:', JSON.stringify(await context.cookies(), null, 2));
|
||||
}
|
||||
|
||||
if (page.video()) {
|
||||
console.log('Recorded video:', await page.video().path());
|
||||
}
|
||||
|
||||
await context.close();
|
||||
}
|
||||
};
|
||||
470
epic-games.js
470
epic-games.js
|
|
@ -1,26 +1,17 @@
|
|||
import { firefox } from 'playwright-firefox';
|
||||
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||
import { authenticator } from 'otplib';
|
||||
import chalk from 'chalk';
|
||||
import path from 'node:path';
|
||||
import { existsSync, writeFileSync, appendFileSync } from 'node:fs';
|
||||
import { jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js';
|
||||
import path from 'path';
|
||||
import { existsSync, writeFileSync, appendFileSync } from 'fs';
|
||||
import { resolve, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js';
|
||||
import { cfg } from './src/config.js';
|
||||
import { EPIC_CLIENT_ID, GRAPHQL_ENDPOINT, FREE_GAMES_PROMOTIONS_ENDPOINT, STORE_HOMEPAGE_EN, EPIC_PURCHASE_ENDPOINT, ID_LOGIN_ENDPOINT } from './src/constants.js';
|
||||
import { setPuppeteerCookies } from './src/cookie.js';
|
||||
import { getAccountAuth, setAccountAuth } from './src/device-auths.js';
|
||||
|
||||
const screenshot = (...a) => path.resolve(cfg.dir.screenshots, 'epic-games', ...a);
|
||||
const screenshot = (...a) => resolve(cfg.dir.screenshots, 'epic-games', ...a);
|
||||
|
||||
const URL_CLAIM = 'https://store.epicgames.com/en-US/free-games';
|
||||
const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM;
|
||||
|
||||
console.log(datetime(), 'started checking epic-games (GraphQL API mode)');
|
||||
|
||||
if (cfg.eg_mode === 'new') {
|
||||
const { claimEpicGamesNew } = await import('./epic-claimer-new.js');
|
||||
await claimEpicGamesNew();
|
||||
process.exit(0);
|
||||
}
|
||||
console.log(datetime(), 'started checking epic-games');
|
||||
|
||||
const db = await jsonDb('epic-games.json', {});
|
||||
|
||||
|
|
@ -29,7 +20,7 @@ if (cfg.time) console.time('startup');
|
|||
const browserPrefs = path.join(cfg.dir.browser, 'prefs.js');
|
||||
if (existsSync(browserPrefs)) {
|
||||
console.log('Adding webgl.disabled to', browserPrefs);
|
||||
appendFileSync(browserPrefs, 'user_pref("webgl.disabled", true);');
|
||||
appendFileSync(browserPrefs, 'user_pref("webgl.disabled", true);'); // apparently Firefox removes duplicates (and sorts), so no problem appending every time
|
||||
} else {
|
||||
console.log(browserPrefs, 'does not exist yet, will patch it on next run. Restart the script if you get a captcha.');
|
||||
}
|
||||
|
|
@ -38,36 +29,34 @@ if (existsSync(browserPrefs)) {
|
|||
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||
headless: cfg.headless,
|
||||
viewport: { width: cfg.width, height: cfg.height },
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0',
|
||||
locale: 'en-US',
|
||||
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined,
|
||||
recordHar: cfg.record ? { path: `data/record/eg-${filenamify(datetime())}.har` } : undefined,
|
||||
handleSIGINT: false,
|
||||
args: [],
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0', // see replace of Headless in util.newStealthContext. TODO Windows UA enough to avoid 'device not supported'? update if browser is updated?
|
||||
// userAgent firefox (macOS): Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:106.0) Gecko/20100101 Firefox/106.0
|
||||
// userAgent firefox (docker): Mozilla/5.0 (X11; Linux aarch64; rv:109.0) Gecko/20100101 Firefox/115.0
|
||||
locale: 'en-US', // ignore OS locale to be sure to have english text for locators
|
||||
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined, // will record a .webm video for each page navigated; without size, video would be scaled down to fit 800x800
|
||||
recordHar: cfg.record ? { path: `data/record/eg-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools
|
||||
handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved
|
||||
// user settings for firefox have to be put in $BROWSER_DIR/user.js
|
||||
args: [ // https://wiki.mozilla.org/Firefox/CommandLineOptions
|
||||
// '-kiosk',
|
||||
],
|
||||
});
|
||||
|
||||
handleSIGINT(context);
|
||||
|
||||
// Without stealth plugin, the website shows an hcaptcha on login with username/password and in the last step of claiming a game. It may have other heuristics like unsuccessful logins as well. After <6h (TBD) it resets to no captcha again. Getting a new IP also resets.
|
||||
await stealth(context);
|
||||
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
|
||||
const page = context.pages().length ? context.pages()[0] : await context.newPage();
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height });
|
||||
|
||||
// some debug info about the page
|
||||
if (cfg.debug) {
|
||||
const debugInfo = await page.evaluate(() => {
|
||||
const { width, height, availWidth, availHeight } = window.screen;
|
||||
return {
|
||||
screen: { width, height, availWidth, availHeight },
|
||||
userAgent: navigator.userAgent,
|
||||
};
|
||||
});
|
||||
console.debug(debugInfo);
|
||||
}
|
||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||
|
||||
// some debug info about the page (screen dimensions, user agent, platform)
|
||||
// eslint-disable-next-line no-undef
|
||||
if (cfg.debug) console.debug(await page.evaluate(() => [(({ width, height, availWidth, availHeight }) => ({ width, height, availWidth, availHeight }))(window.screen), navigator.userAgent, navigator.platform, navigator.vendor])); // deconstruct screen needed since `window.screen` prints {}, `window.screen.toString()` '[object Screen]', and can't use some pick function without defining it on `page`
|
||||
if (cfg.debug_network) {
|
||||
// const filter = _ => true;
|
||||
const filter = r => r.url().includes('store.epicgames.com');
|
||||
page.on('request', request => filter(request) && console.log('>>', request.method(), request.url()));
|
||||
page.on('response', response => filter(response) && console.log('<<', response.status(), response.url()));
|
||||
|
|
@ -76,254 +65,107 @@ if (cfg.debug_network) {
|
|||
const notify_games = [];
|
||||
let user;
|
||||
|
||||
// Generate login redirect URL
|
||||
const generateLoginRedirect = redirectUrl => {
|
||||
const loginRedirectUrl = new URL(ID_LOGIN_ENDPOINT);
|
||||
loginRedirectUrl.searchParams.set('noHostRedirect', 'true');
|
||||
loginRedirectUrl.searchParams.set('redirectUrl', redirectUrl);
|
||||
loginRedirectUrl.searchParams.set('client_id', EPIC_CLIENT_ID);
|
||||
return loginRedirectUrl.toString();
|
||||
};
|
||||
|
||||
// Generate checkout URL with login redirect
|
||||
const generateCheckoutUrl = offers => {
|
||||
const offersParams = offers
|
||||
.map(offer => `&offers=1-${offer.offerNamespace}-${offer.offerId}`)
|
||||
.join('');
|
||||
const checkoutUrl = `${EPIC_PURCHASE_ENDPOINT}?highlightColor=0078f2${offersParams}&orderId&purchaseToken&showNavigation=true`;
|
||||
return generateLoginRedirect(checkoutUrl);
|
||||
};
|
||||
|
||||
// Get free games from promotions API (weekly free games)
|
||||
const getFreeGamesFromPromotions = async () => {
|
||||
const response = await page.evaluate(async () => {
|
||||
const resp = await fetch(FREE_GAMES_PROMOTIONS_ENDPOINT + '?locale=en-US&country=US&allowCountries=US');
|
||||
return await resp.json();
|
||||
});
|
||||
|
||||
const nowDate = new Date();
|
||||
const elements = response.data?.Catalog?.searchStore?.elements || [];
|
||||
|
||||
return elements.filter(offer => {
|
||||
if (!offer.promotions) return false;
|
||||
|
||||
return offer.promotions.promotionalOffers.some(innerOffers => innerOffers.promotionalOffers.some(pOffer => {
|
||||
const startDate = new Date(pOffer.startDate);
|
||||
const endDate = new Date(pOffer.endDate);
|
||||
const isFree = pOffer.discountSetting?.discountPercentage === 0;
|
||||
return startDate <= nowDate && nowDate <= endDate && isFree;
|
||||
}));
|
||||
}).map(game => ({
|
||||
offerId: game.id,
|
||||
offerNamespace: game.namespace,
|
||||
productName: game.title,
|
||||
productSlug: game.productSlug || game.urlSlug,
|
||||
}));
|
||||
};
|
||||
|
||||
// Get all free games
|
||||
const getAllFreeGames = async () => {
|
||||
try {
|
||||
const weeklyGames = await getFreeGamesFromPromotions();
|
||||
console.log('Found', weeklyGames.length, 'weekly free games');
|
||||
return weeklyGames;
|
||||
} catch (e) {
|
||||
console.error('Failed to get weekly free games:', e.message);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// Login with device auth - attempts to use stored auth token
|
||||
const loginWithDeviceAuth = async () => {
|
||||
const deviceAuth = await getAccountAuth(cfg.eg_email || 'default');
|
||||
|
||||
if (deviceAuth && deviceAuth.access_token) {
|
||||
console.log('Using stored device auth');
|
||||
|
||||
// Set the bearer token cookie for authentication
|
||||
/** @type {import('playwright-firefox').Cookie} */
|
||||
const bearerCookie = {
|
||||
name: 'EPIC_BEARER_TOKEN',
|
||||
value: deviceAuth.access_token,
|
||||
expires: new Date(deviceAuth.expires_at).getTime() / 1000,
|
||||
domain: '.epicgames.com',
|
||||
path: '/',
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'Lax',
|
||||
};
|
||||
|
||||
await context.addCookies([bearerCookie]);
|
||||
|
||||
// Visit store to get session cookies
|
||||
await page.goto(STORE_HOMEPAGE_EN, { waitUntil: 'networkidle' });
|
||||
|
||||
// Check if login worked
|
||||
const isLoggedIn = await page.locator('egs-navigation').getAttribute('isloggedin') === 'true';
|
||||
if (isLoggedIn) {
|
||||
console.log('Successfully logged in with device auth');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
// Save device auth
|
||||
const saveDeviceAuth = async (accessToken, refreshToken, expiresAt) => {
|
||||
const deviceAuth = {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
expires_at: expiresAt,
|
||||
expires_in: 86400,
|
||||
token_type: 'bearer',
|
||||
account_id: 'unknown',
|
||||
client_id: EPIC_CLIENT_ID,
|
||||
internal_client: true,
|
||||
client_service: 'account',
|
||||
displayName: 'User',
|
||||
app: 'epic-games',
|
||||
in_app_id: 'unknown',
|
||||
product_id: 'unknown',
|
||||
refresh_expires: 604800,
|
||||
refresh_expires_at: new Date(Date.now() + 604800000).toISOString(),
|
||||
application_id: 'unknown',
|
||||
};
|
||||
|
||||
await setAccountAuth(cfg.eg_email || 'default', deviceAuth);
|
||||
console.log('Device auth saved');
|
||||
};
|
||||
|
||||
try {
|
||||
await context.addCookies([
|
||||
{ name: 'OptanonAlertBoxClosed', value: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), domain: '.epicgames.com', path: '/' },
|
||||
{ name: 'HasAcceptedAgeGates', value: 'USK:9007199254740991,general:18,EPIC SUGGESTED RATING:18', domain: 'store.epicgames.com', path: '/' },
|
||||
{ name: 'OptanonAlertBoxClosed', value: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), domain: '.epicgames.com', path: '/' }, // Accept cookies to get rid of banner to save space on screen. Set accept time to 5 days ago.
|
||||
{ name: 'HasAcceptedAgeGates', value: 'USK:9007199254740991,general:18,EPIC SUGGESTED RATING:18', domain: 'store.epicgames.com', path: '/' }, // gets rid of 'To continue, please provide your date of birth', https://github.com/vogler/free-games-claimer/issues/275, USK number doesn't seem to matter, cookie from 'Fallout 3: Game of the Year Edition'
|
||||
]);
|
||||
|
||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
|
||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // 'domcontentloaded' faster than default 'load' https://playwright.dev/docs/api/class-page#page-goto
|
||||
|
||||
if (cfg.time) console.timeEnd('startup');
|
||||
if (cfg.time) console.time('login');
|
||||
|
||||
// Try device auth first
|
||||
await loginWithDeviceAuth();
|
||||
// page.click('button:has-text("Accept All Cookies")').catch(_ => { }); // Not needed anymore since we set the cookie above. Clicking this did not always work since the message was animated in too slowly.
|
||||
|
||||
// If device auth failed, try regular login
|
||||
while (await page.locator('egs-navigation').getAttribute('isloggedin') != 'true') {
|
||||
console.error('Not signed in. Please login in the browser or here in the terminal.');
|
||||
console.error('Not signed in anymore. Please login in the browser or here in the terminal.');
|
||||
if (cfg.novnc_port) console.info(`Open http://localhost:${cfg.novnc_port} to login inside the docker container.`);
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout);
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
|
||||
console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`);
|
||||
await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' });
|
||||
|
||||
if (cfg.eg_email && cfg.eg_password) console.info('Using email and password from environment.');
|
||||
else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).');
|
||||
|
||||
const notifyBrowserLogin = async () => {
|
||||
console.log('Waiting for you to login in the browser.');
|
||||
await notify('epic-games: no longer signed in and not enough options set for automatic login.');
|
||||
if (cfg.headless) {
|
||||
console.log('Run `SHOW=1 node epic-games` to login in the opened browser.');
|
||||
await context.close();
|
||||
await context.close(); // finishes potential recording
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
const hasCaptcha = await page.locator('.h_captcha_challenge iframe').count() > 0 || await page.locator('text=Incorrect response').count() > 0;
|
||||
if (hasCaptcha) {
|
||||
console.warn('Captcha/Incorrect response detected. Please solve manually in the browser.');
|
||||
await notify('epic-games: captcha encountered; please solve manually in browser.');
|
||||
await page.waitForTimeout(cfg.login_timeout);
|
||||
continue;
|
||||
}
|
||||
|
||||
const email = cfg.eg_email || await prompt({ message: 'Enter email' });
|
||||
if (email) {
|
||||
if (!email) await notifyBrowserLogin();
|
||||
else {
|
||||
// await page.click('text=Sign in with Epic Games');
|
||||
page.waitForSelector('.h_captcha_challenge iframe').then(async () => {
|
||||
console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
|
||||
await notify('epic-games: got captcha during login. Please check.');
|
||||
}).catch(_ => { });
|
||||
page.waitForSelector('p:has-text("Incorrect response.")').then(async () => {
|
||||
console.error('Incorrect response for captcha!');
|
||||
}).catch(_ => { });
|
||||
await page.fill('#email', email);
|
||||
const password = cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' });
|
||||
if (password) {
|
||||
// await page.click('button[type="submit"]'); login was split in two steps for some time, now email and password are on the same form again
|
||||
const password = email && (cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||
if (!password) await notifyBrowserLogin();
|
||||
else {
|
||||
await page.fill('#password', password);
|
||||
await page.click('button[type="submit"]');
|
||||
} else await notifyBrowserLogin();
|
||||
|
||||
}
|
||||
const error = page.locator('#form-error-message');
|
||||
const watchLoginError = async () => {
|
||||
try {
|
||||
await error.waitFor({ timeout: 15000 });
|
||||
error.waitFor().then(async () => {
|
||||
console.error('Login error:', await error.innerText());
|
||||
console.log('Please login in the browser!');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const watchMfaStep = async () => {
|
||||
try {
|
||||
await page.waitForURL('**/id/login/mfa**', { timeout: cfg.login_timeout });
|
||||
console.log('Enter the security code to continue');
|
||||
const otp = cfg.eg_otpkey && authenticator.generate(cfg.eg_otpkey) || await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!' });
|
||||
}).catch(_ => { });
|
||||
// handle MFA, but don't await it
|
||||
page.waitForURL('**/id/login/mfa**').then(async () => {
|
||||
console.log('Enter the security code to continue - This appears to be a new device, browser or location. A security code has been sent to your email address at ...');
|
||||
// TODO locator for text (email or app?)
|
||||
const otp = cfg.eg_otpkey && authenticator.generate(cfg.eg_otpkey) || await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||
await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString());
|
||||
await page.click('button[type="submit"]');
|
||||
} catch {
|
||||
return;
|
||||
}).catch(_ => { });
|
||||
}
|
||||
};
|
||||
|
||||
watchLoginError();
|
||||
watchMfaStep();
|
||||
} else await notifyBrowserLogin();
|
||||
|
||||
await page.waitForURL(URL_CLAIM);
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
}
|
||||
|
||||
user = await page.locator('egs-navigation').getAttribute('displayname');
|
||||
user = await page.locator('egs-navigation').getAttribute('displayname'); // 'null' if !isloggedin
|
||||
console.log(`Signed in as ${user}`);
|
||||
db.data[user] ||= {};
|
||||
|
||||
if (cfg.time) console.timeEnd('login');
|
||||
if (cfg.time) console.time('claim all games');
|
||||
|
||||
// Get free games
|
||||
const freeGames = await getAllFreeGames();
|
||||
console.log('Free games:', freeGames.map(g => g.productName));
|
||||
|
||||
// Generate checkout link for all free games (available for all games)
|
||||
const checkoutUrl = freeGames.length > 0 ? generateCheckoutUrl(freeGames) : null;
|
||||
if (checkoutUrl) {
|
||||
console.log('Generated checkout URL:', checkoutUrl);
|
||||
|
||||
// Send notification with checkout link
|
||||
await notify(`epic-games (${user}):<br>Free games available!<br>Click here to claim: <a href="${checkoutUrl}">${checkoutUrl}</a>`);
|
||||
}
|
||||
|
||||
// Also save to database for reference
|
||||
freeGames.forEach(game => {
|
||||
const purchaseUrl = `https://store.epicgames.com/${game.productSlug}`;
|
||||
db.data[user][game.offerId] ||= {
|
||||
title: game.productName,
|
||||
time: datetime(),
|
||||
url: purchaseUrl,
|
||||
checkoutUrl: checkoutUrl || purchaseUrl,
|
||||
};
|
||||
// Detect free games
|
||||
const game_loc = page.locator('a:has(span:text-is("Free Now"))');
|
||||
await game_loc.last().waitFor().catch(_ => {
|
||||
// rarely there are no free games available -> catch Timeout
|
||||
// TODO would be better to wait for alternative like 'coming soon' instead of waiting for timeout
|
||||
// see https://github.com/vogler/free-games-claimer/issues/210#issuecomment-1727420943
|
||||
console.error('Seems like currently there are no free games available in your region...');
|
||||
// urls below should then be an empty list
|
||||
});
|
||||
// clicking on `game_sel` sometimes led to a 404, see https://github.com/vogler/free-games-claimer/issues/25
|
||||
// debug showed that in those cases the href was still correct, so we `goto` the urls instead of clicking.
|
||||
// Alternative: parse the json loaded to build the page https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions
|
||||
// i.e. filter data.Catalog.searchStore.elements for .promotions.promotionalOffers being set and build URL with .catalogNs.mappings[0].pageSlug or .urlSlug if not set to some wrong id like it was the case for spirit-of-the-north-f58a66 - this is also what's done here: https://github.com/claabs/epicgames-freegames-node/blob/938a9653ffd08b8284ea32cf01ac8727d25c5d4c/src/puppet/free-games.ts#L138-L213
|
||||
const urlSlugs = await Promise.all((await game_loc.elementHandles()).map(a => a.getAttribute('href')));
|
||||
const urls = urlSlugs.map(s => 'https://store.epicgames.com' + s);
|
||||
console.log('Free games:', urls);
|
||||
|
||||
// Claim each game individually (for detailed tracking)
|
||||
for (const game of freeGames) {
|
||||
for (const url of urls) {
|
||||
if (cfg.time) console.time('claim game');
|
||||
|
||||
const purchaseUrl = `https://store.epicgames.com/${game.productSlug}`;
|
||||
await page.goto(purchaseUrl);
|
||||
|
||||
const purchaseBtn = page.locator('button[data-testid="purchase-cta-button"]').first();
|
||||
await page.goto(url); // , { waitUntil: 'domcontentloaded' });
|
||||
const purchaseBtn = page.locator('button[data-testid="purchase-cta-button"] >> :has-text("e"), :has-text("i")').first(); // when loading, the button text is empty -> need to wait for some text {'get', 'in library', 'requires base game'} -> just wait for e or i to not be too specific; :text-matches("\w+") somehow didn't work - https://github.com/vogler/free-games-claimer/issues/375
|
||||
await purchaseBtn.waitFor();
|
||||
const btnText = (await purchaseBtn.innerText()).toLowerCase();
|
||||
const btnText = (await purchaseBtn.innerText()).toLowerCase(); // barrier to block until page is loaded
|
||||
|
||||
// click Continue if 'This game contains mature content recommended only for ages 18+'
|
||||
if (await page.locator('button:has-text("Continue")').count() > 0) {
|
||||
console.log(' This game contains mature content recommended only for ages 18+');
|
||||
if (await page.locator('[data-testid="AgeSelect"]').count()) {
|
||||
console.error(' Got "To continue, please provide your date of birth"');
|
||||
console.error(' Got "To continue, please provide your date of birth" - This shouldn\'t happen due to cookie set above. Please report to https://github.com/vogler/free-games-claimer/issues/275');
|
||||
await page.locator('#month_toggle').click();
|
||||
await page.locator('#month_menu li:has-text("01")').click();
|
||||
await page.locator('#day_toggle').click();
|
||||
|
|
@ -336,67 +178,81 @@ try {
|
|||
}
|
||||
|
||||
let title;
|
||||
let bundle_includes;
|
||||
if (await page.locator('span:text-is("About Bundle")').count()) {
|
||||
title = (await page.locator('span:has-text("Buy"):left-of([data-testid="purchase-cta-button"])').first().innerText()).replace('Buy ', '');
|
||||
// h1 first didn't exist for bundles but now it does... However h1 would e.g. be 'Fallout® Classic Collection' instead of 'Fallout Classic Collection'
|
||||
try {
|
||||
bundle_includes = await Promise.all((await page.locator('.product-card-top-row h5').all()).map(b => b.innerText()));
|
||||
} catch (e) {
|
||||
console.error('Failed to get "Bundle Includes":', e);
|
||||
}
|
||||
} else {
|
||||
title = await page.locator('h1').first().innerText();
|
||||
}
|
||||
|
||||
const existedInDb = db.data[user][game.offerId];
|
||||
db.data[user][game.offerId] ||= { title, time: datetime(), url: purchaseUrl, checkoutUrl: checkoutUrl };
|
||||
const game_id = page.url().split('/').pop();
|
||||
const existedInDb = db.data[user][game_id];
|
||||
db.data[user][game_id] ||= { title, time: datetime(), url: page.url() }; // this will be set on the initial run only!
|
||||
console.log('Current free game:', chalk.blue(title));
|
||||
if (bundle_includes) console.log(' This bundle includes:', bundle_includes);
|
||||
const notify_game = { title, url, status: 'failed' };
|
||||
notify_games.push(notify_game); // status is updated below
|
||||
|
||||
const notify_game = { title, url: purchaseUrl, status: 'failed' };
|
||||
notify_games.push(notify_game);
|
||||
|
||||
if (btnText == 'in library' || btnText == 'owned') {
|
||||
if (btnText == 'in library') {
|
||||
console.log(' Already in library! Nothing to claim.');
|
||||
if (!existedInDb) await notify(`Game already in library: ${purchaseUrl}`);
|
||||
if (!existedInDb) await notify(`Game already in library: ${url}`);
|
||||
notify_game.status = 'existed';
|
||||
db.data[user][game.offerId].status ||= 'existed';
|
||||
if (db.data[user][game.offerId].status.startsWith('failed')) db.data[user][game.offerId].status = 'manual';
|
||||
db.data[user][game_id].status ||= 'existed'; // does not overwrite claimed or failed
|
||||
if (db.data[user][game_id].status.startsWith('failed')) db.data[user][game_id].status = 'manual'; // was failed but now it's claimed
|
||||
} else if (btnText == 'requires base game') {
|
||||
console.log(' Requires base game! Nothing to claim.');
|
||||
notify_game.status = 'requires base game';
|
||||
db.data[user][game.offerId].status ||= 'failed:requires-base-game';
|
||||
} else {
|
||||
db.data[user][game_id].status ||= 'failed:requires-base-game';
|
||||
// TODO claim base game if it is free
|
||||
const baseUrl = 'https://store.epicgames.com' + await page.locator('a:has-text("Overview")').getAttribute('href');
|
||||
console.log(' Base game:', baseUrl);
|
||||
// await page.click('a:has-text("Overview")');
|
||||
// TODO handle this via function call for base game above since this will never terminate if DRYRUN=1
|
||||
urls.push(baseUrl); // add base game to the list of games to claim
|
||||
urls.push(url); // add add-on itself again
|
||||
} else { // GET
|
||||
console.log(' Not in library yet! Click', btnText);
|
||||
await purchaseBtn.click({ delay: 11 });
|
||||
await purchaseBtn.click({ delay: 11 }); // got stuck here without delay (or mouse move), see #75, 1ms was also enough
|
||||
|
||||
// Accept EULA if shown
|
||||
try {
|
||||
await page.locator(':has-text("end user license agreement")').waitFor({ timeout: 10000 });
|
||||
console.log(' Accept End User License Agreement');
|
||||
await page.locator('input#agree').check();
|
||||
// click Continue if 'Device not supported. This product is not compatible with your current device.' - avoided by Windows userAgent?
|
||||
page.click('button:has-text("Continue")').catch(_ => { }); // needed since change from Chromium to Firefox?
|
||||
|
||||
// click 'Yes, buy now' if 'This edition contains something you already have. Still interested?'
|
||||
page.click('button:has-text("Yes, buy now")').catch(_ => { });
|
||||
|
||||
// Accept End User License Agreement (only needed once)
|
||||
page.locator(':has-text("end user license agreement")').waitFor().then(async () => {
|
||||
console.log(' Accept End User License Agreement (only needed once)');
|
||||
console.log(page.innerHTML);
|
||||
console.log('Please report the HTML above here: https://github.com/vogler/free-games-claimer/issues/371');
|
||||
await page.locator('input#agree').check(); // TODO Bundle: got stuck here; likely unrelated to bundle and locator just changed: https://github.com/vogler/free-games-claimer/issues/371
|
||||
await page.locator('button:has-text("Accept")').click();
|
||||
} catch {
|
||||
// EULA not shown
|
||||
}
|
||||
}).catch(_ => { });
|
||||
|
||||
await page.waitForSelector('#webPurchaseContainer iframe');
|
||||
// it then creates an iframe for the purchase
|
||||
await page.waitForSelector('#webPurchaseContainer iframe'); // TODO needed?
|
||||
const iframe = page.frameLocator('#webPurchaseContainer iframe');
|
||||
|
||||
// skip game if unavailable in region, https://github.com/vogler/free-games-claimer/issues/46 TODO check games for account's region
|
||||
if (await iframe.locator(':has-text("unavailable in your region")').count() > 0) {
|
||||
console.error(' This product is unavailable in your region!');
|
||||
db.data[user][game.offerId].status = notify_game.status = 'unavailable-in-region';
|
||||
db.data[user][game_id].status = notify_game.status = 'unavailable-in-region';
|
||||
if (cfg.time) console.timeEnd('claim game');
|
||||
continue;
|
||||
}
|
||||
|
||||
const enterParentalPinIfNeeded = async () => {
|
||||
try {
|
||||
await iframe.locator('.payment-pin-code').waitFor({ timeout: 10000 });
|
||||
iframe.locator('.payment-pin-code').waitFor().then(async () => {
|
||||
if (!cfg.eg_parentalpin) {
|
||||
console.error(' EG_PARENTALPIN not set. Need to enter Parental Control PIN manually.');
|
||||
notify('epic-games: EG_PARENTALPIN not set. Need to enter Parental Control PIN manually.');
|
||||
}
|
||||
await iframe.locator('input.payment-pin-code__input').first().pressSequentially(cfg.eg_parentalpin);
|
||||
await iframe.locator('button:has-text("Continue")').click({ delay: 11 });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
};
|
||||
enterParentalPinIfNeeded();
|
||||
}).catch(_ => { });
|
||||
|
||||
if (cfg.debug) await page.pause();
|
||||
if (cfg.dryrun) {
|
||||
|
|
@ -406,77 +262,63 @@ try {
|
|||
continue;
|
||||
}
|
||||
|
||||
// Playwright clicked before button was ready to handle event, https://github.com/vogler/free-games-claimer/issues/84#issuecomment-1474346591
|
||||
await iframe.locator('button:has-text("Place Order"):not(:has(.payment-loading--loading))').click({ delay: 11 });
|
||||
|
||||
// I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872
|
||||
const btnAgree = iframe.locator('button:has-text("I Accept")');
|
||||
btnAgree.waitFor().then(() => btnAgree.click()).catch(_ => { }); // EU: wait for and click 'I Agree'
|
||||
try {
|
||||
await btnAgree.waitFor({ timeout: 10000 });
|
||||
await btnAgree.click();
|
||||
} catch {
|
||||
// EU: wait for and click 'I Agree'
|
||||
}
|
||||
|
||||
try {
|
||||
await page.locator('text=Thanks for your order!').waitFor({ state: 'attached' });
|
||||
db.data[user][game.offerId].status = 'claimed';
|
||||
db.data[user][game.offerId].time = datetime();
|
||||
// context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s?
|
||||
const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe');
|
||||
captcha.waitFor().then(async () => { // don't await, since element may not be shown
|
||||
// console.info(' Got hcaptcha challenge! NopeCHA extension will likely solve it.')
|
||||
console.error(' Got hcaptcha challenge! Lost trust due to too many login attempts? You can solve the captcha in the browser or get a new IP address.');
|
||||
// await notify(`epic-games: got captcha challenge right before claim of <a href="${url}">${title}</a>. Use VNC to solve it manually.`); // TODO not all apprise services understand HTML: https://github.com/vogler/free-games-claimer/pull/417
|
||||
await notify(`epic-games: got captcha challenge for.\nGame link: ${url}`);
|
||||
// TODO could even create purchase URL, see https://github.com/vogler/free-games-claimer/pull/130
|
||||
// await page.waitForTimeout(2000);
|
||||
// const p = path.resolve(cfg.dir.screenshots, 'epic-games', 'captcha', `${filenamify(datetime())}.png`);
|
||||
// await captcha.screenshot({ path: p });
|
||||
// console.info(' Saved a screenshot of hcaptcha challenge to', p);
|
||||
// console.error(' Got hcaptcha challenge. To avoid it, get a link from https://www.hcaptcha.com/accessibility'); // TODO save this link in config and visit it daily to set accessibility cookie to avoid captcha challenge?
|
||||
}).catch(_ => { }); // may time out if not shown
|
||||
iframe.locator('.payment__errors:has-text("Failed to challenge captcha, please try again later.")').waitFor().then(async () => {
|
||||
console.error(' Failed to challenge captcha, please try again later.');
|
||||
await notify('epic-games: failed to challenge captcha. Please check.');
|
||||
}).catch(_ => { });
|
||||
await page.locator('text=Thanks for your order!').waitFor({ state: 'attached' }); // TODO Bundle: got stuck here, but normal game now as well
|
||||
db.data[user][game_id].status = 'claimed';
|
||||
db.data[user][game_id].time = datetime(); // claimed time overwrites failed/dryrun time
|
||||
console.log(' Claimed successfully!');
|
||||
|
||||
// Save device auth if we got a new token
|
||||
const cookies = await context.cookies();
|
||||
const bearerCookie = cookies.find(c => c.name === 'EPIC_BEARER_TOKEN');
|
||||
if (bearerCookie?.value) {
|
||||
await saveDeviceAuth(bearerCookie.value, 'refresh_token_placeholder', new Date(Date.now() + 86400000).toISOString());
|
||||
}
|
||||
// context.setDefaultTimeout(cfg.timeout);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
// console.error(' Failed to claim! Try again if NopeCHA timed out. Click the extension to see if you ran out of credits (refill after 24h). To avoid captchas try to get a new IP or set a cookie from https://www.hcaptcha.com/accessibility');
|
||||
console.error(' Failed to claim! To avoid captchas try to get a new IP address.');
|
||||
const p = screenshot('failed', `${game.offerId}_${filenamify(datetime())}.png`);
|
||||
const p = screenshot('failed', `${game_id}_${filenamify(datetime())}.png`);
|
||||
await page.screenshot({ path: p, fullPage: true });
|
||||
db.data[user][game.offerId].status = 'failed';
|
||||
db.data[user][game_id].status = 'failed';
|
||||
}
|
||||
notify_game.status = db.data[user][game.offerId].status;
|
||||
notify_game.status = db.data[user][game_id].status; // claimed or failed
|
||||
|
||||
const p = screenshot(`${game.offerId}.png`);
|
||||
if (!existsSync(p)) await page.screenshot({ path: p, fullPage: false });
|
||||
const p = screenshot(`${game_id}.png`);
|
||||
if (!existsSync(p)) await page.screenshot({ path: p, fullPage: false }); // fullPage is quite long...
|
||||
}
|
||||
|
||||
if (cfg.time) console.timeEnd('claim game');
|
||||
}
|
||||
|
||||
if (cfg.time) console.timeEnd('claim all games');
|
||||
} catch (error) {
|
||||
process.exitCode ||= 1;
|
||||
console.error('--- Exception:');
|
||||
console.error(error);
|
||||
console.error(error); // .toString()?
|
||||
if (error.message && process.exitCode != 130) notify(`epic-games failed: ${error.message.split('\n')[0]}`);
|
||||
} finally {
|
||||
await db.write();
|
||||
|
||||
// Save cookies
|
||||
const cookies = await context.cookies();
|
||||
// Convert cookies to EpicCookie format for setPuppeteerCookies
|
||||
const epicCookies = cookies.map(c => ({
|
||||
domain: c.domain,
|
||||
hostOnly: !c.domain.startsWith('.'),
|
||||
httpOnly: c.httpOnly,
|
||||
name: c.name,
|
||||
path: c.path,
|
||||
sameSite: c.sameSite === 'Lax' ? 'no_restriction' : 'unspecified',
|
||||
secure: c.secure,
|
||||
session: !c.expires,
|
||||
storeId: '0',
|
||||
value: c.value,
|
||||
id: 0,
|
||||
expirationDate: c.expires ? Math.floor(c.expires) : undefined,
|
||||
}));
|
||||
await setPuppeteerCookies(cfg.eg_email || 'default', epicCookies);
|
||||
|
||||
if (notify_games.filter(g => g.status == 'claimed' || g.status == 'failed').length) {
|
||||
await db.write(); // write out json db
|
||||
if (notify_games.filter(g => g.status == 'claimed' || g.status == 'failed').length) { // don't notify if all have status 'existed', 'manual', 'requires base game', 'unavailable-in-region', 'skipped'
|
||||
notify(`epic-games (${user}):<br>${html_game_list(notify_games)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (cfg.debug) writeFileSync(path.resolve(cfg.dir.browser, 'cookies.json'), JSON.stringify(await context.cookies()));
|
||||
if (page.video()) console.log('Recorded video:', await page.video().path());
|
||||
await context.close();
|
||||
|
|
|
|||
|
|
@ -9,32 +9,13 @@ export default [
|
|||
// object with just `ignores` applies to all configuration objects
|
||||
// had `ln -s .gitignore .eslintignore` before, but .eslintignore no longer supported
|
||||
{
|
||||
ignores: ['data/**', 'node_modules/**', '.git/**'],
|
||||
ignores: ['data/**'],
|
||||
},
|
||||
js.configs.recommended,
|
||||
js.configs.recommended, // TODO still needed?
|
||||
{
|
||||
// files: ['*.js'],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
screenshot: 'readonly',
|
||||
cfg: 'readonly',
|
||||
URL_CLAIM: 'readonly',
|
||||
COOKIES_PATH: 'readonly',
|
||||
BEARER_TOKEN_NAME: 'readonly',
|
||||
notify: 'readonly',
|
||||
authenticator: 'readonly',
|
||||
prompt: 'readonly',
|
||||
html_game_list: 'readonly',
|
||||
datetime: 'readonly',
|
||||
filenamify: 'readonly',
|
||||
handleSIGINT: 'readonly',
|
||||
stealth: 'readonly',
|
||||
jsonDb: 'readonly',
|
||||
delay: 'readonly',
|
||||
dataDir: 'readonly',
|
||||
resolve: 'readonly',
|
||||
},
|
||||
globals: globals.node,
|
||||
},
|
||||
plugins: {
|
||||
'@stylistic/js': stylistic,
|
||||
|
|
@ -92,36 +73,4 @@ export default [
|
|||
'@stylistic/js/wrap-regex': 'error',
|
||||
},
|
||||
},
|
||||
// JavaScript files configuration
|
||||
{
|
||||
files: ['*.js'],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
screenshot: 'readonly',
|
||||
cfg: 'readonly',
|
||||
URL_CLAIM: 'readonly',
|
||||
COOKIES_PATH: 'readonly',
|
||||
BEARER_TOKEN_NAME: 'readonly',
|
||||
notify: 'readonly',
|
||||
authenticator: 'readonly',
|
||||
prompt: 'readonly',
|
||||
html_game_list: 'readonly',
|
||||
datetime: 'readonly',
|
||||
filenamify: 'readonly',
|
||||
handleSIGINT: 'readonly',
|
||||
stealth: 'readonly',
|
||||
jsonDb: 'readonly',
|
||||
delay: 'readonly',
|
||||
dataDir: 'readonly',
|
||||
resolve: 'readonly',
|
||||
window: 'readonly',
|
||||
navigator: 'readonly',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': 'off',
|
||||
'prefer-const': 'off',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
|
|
|||
54
gog.js
54
gog.js
|
|
@ -31,7 +31,8 @@ handleSIGINT(context);
|
|||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
|
||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
||||
|
||||
const notify_games = [];
|
||||
let user;
|
||||
|
|
@ -41,16 +42,14 @@ try {
|
|||
|
||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
||||
|
||||
// page.click('#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll').catch(_ => { }); // does not work reliably, solved by setting CookieConsent above
|
||||
const signIn = page.locator('a:has-text("Sign in")').first();
|
||||
await Promise.any([
|
||||
signIn.waitFor({ timeout: cfg.login_visible_timeout }),
|
||||
page.waitForSelector('#menuUsername', { timeout: cfg.login_visible_timeout }),
|
||||
]).catch(() => {});
|
||||
await Promise.any([signIn.waitFor(), page.waitForSelector('#menuUsername')]);
|
||||
while (await signIn.isVisible()) {
|
||||
console.error('Not signed in anymore.');
|
||||
await signIn.click();
|
||||
// it then creates an iframe for the login
|
||||
await page.waitForSelector('#GalaxyAccountsFrameContainer iframe');
|
||||
await page.waitForSelector('#GalaxyAccountsFrameContainer iframe'); // TODO needed?
|
||||
const iframe = page.frameLocator('#GalaxyAccountsFrameContainer iframe');
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
|
||||
console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`);
|
||||
|
|
@ -59,38 +58,26 @@ try {
|
|||
const email = cfg.gog_email || await prompt({ message: 'Enter email' });
|
||||
const password = email && (cfg.gog_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||
if (email && password) {
|
||||
try {
|
||||
await iframe.locator('a[href="/logout"]').click(); // Click 'Change account' (email from previous login is set in some cookie)
|
||||
} catch {
|
||||
// link not present, continue with login flow
|
||||
}
|
||||
iframe.locator('a[href="/logout"]').click().catch(_ => { }); // Click 'Change account' (email from previous login is set in some cookie)
|
||||
await iframe.locator('#login_username').fill(email);
|
||||
await iframe.locator('#login_password').fill(password);
|
||||
await iframe.locator('#login_login').click();
|
||||
const handleTwoFactor = async () => {
|
||||
try {
|
||||
await iframe.locator('form[name=second_step_authentication]').waitFor({ timeout: 15000 });
|
||||
// handle MFA, but don't await it
|
||||
iframe.locator('form[name=second_step_authentication]').waitFor().then(async () => {
|
||||
console.log('Two-Step Verification - Enter security code');
|
||||
console.log(await iframe.locator('.form__description').innerText());
|
||||
const otp = await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 4 || 'The code must be 4 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||
await iframe.locator('#second_step_authentication_token_letter_1').pressSequentially(otp.toString(), { delay: 10 });
|
||||
await iframe.locator('#second_step_authentication_send').click();
|
||||
await page.waitForTimeout(1000);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
};
|
||||
const watchInvalidCaptcha = async () => {
|
||||
try {
|
||||
await iframe.locator('text=Invalid captcha').waitFor({ timeout: 15000 });
|
||||
await page.waitForTimeout(1000); // TODO still needed with wait for username below?
|
||||
}).catch(_ => { });
|
||||
// iframe.locator('iframe[title=reCAPTCHA]').waitFor().then(() => {
|
||||
// iframe.locator('.g-recaptcha').waitFor().then(() => {
|
||||
iframe.locator('text=Invalid captcha').waitFor().then(() => {
|
||||
console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
|
||||
notify('gog: got captcha during login. Please check.');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
};
|
||||
handleTwoFactor();
|
||||
watchInvalidCaptcha();
|
||||
// TODO solve reCAPTCHA?
|
||||
}).catch(_ => { });
|
||||
await page.waitForSelector('#menuUsername');
|
||||
} else {
|
||||
console.log('Waiting for you to login in the browser.');
|
||||
|
|
@ -109,8 +96,9 @@ try {
|
|||
db.data[user] ||= {};
|
||||
|
||||
const banner = page.locator('#giveaway');
|
||||
const hasGiveaway = await banner.count();
|
||||
if (hasGiveaway) {
|
||||
if (!await banner.count()) {
|
||||
console.log('Currently no free giveaway!');
|
||||
} else {
|
||||
const text = await page.locator('.giveaway__content-header').innerText();
|
||||
const match_all = text.match(/Claim (.*) and don't miss the|Success! (.*) was added to/);
|
||||
const title = match_all[1] ? match_all[1] : match_all[2];
|
||||
|
|
@ -118,9 +106,11 @@ try {
|
|||
console.log(`Current free game: ${chalk.blue(title)} - ${url}`);
|
||||
db.data[user][title] ||= { title, time: datetime(), url };
|
||||
if (cfg.dryrun) process.exit(1);
|
||||
// await page.locator('#giveaway:not(.is-loading)').waitFor(); // otherwise screenshot is sometimes with loading indicator instead of game title; #TODO fix, skipped due to timeout, see #240
|
||||
await banner.screenshot({ path: screenshot(`${filenamify(title)}.png`) }); // overwrites every time - only keep first?
|
||||
|
||||
// instead of clicking the button, visit the auto-claim URL which gives a JSON response
|
||||
// await banner.getByRole('button', { name: 'Add to library' }).click();
|
||||
// instead of clicking the button, we visit the auto-claim URL which gives as a JSON response which is easier than checking the state of a button
|
||||
await page.goto('https://www.gog.com/giveaway/claim');
|
||||
const response = await page.innerText('body');
|
||||
// console.log(response);
|
||||
|
|
@ -151,8 +141,6 @@ try {
|
|||
await page.locator('li:has-text("Marketing communications through Trusted Partners") label').uncheck();
|
||||
await page.locator('li:has-text("Promotions and hot deals") label').uncheck();
|
||||
}
|
||||
} else {
|
||||
console.log('Currently no free giveaway!');
|
||||
}
|
||||
} catch (error) {
|
||||
process.exitCode ||= 1;
|
||||
|
|
|
|||
|
|
@ -1,11 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
sleep_for=${KEEP_ALIVE_SECONDS:-86400}
|
||||
echo "Keeping container alive (interval ${sleep_for}s). Press Ctrl+C to stop."
|
||||
|
||||
trap 'exit 0' TERM INT
|
||||
while true; do
|
||||
sleep "$sleep_for" &
|
||||
wait $!
|
||||
done
|
||||
420
package-lock.json
generated
420
package-lock.json
generated
|
|
@ -9,7 +9,6 @@
|
|||
"version": "1.4.0",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"axios": "^1.7.9",
|
||||
"chalk": "^5.4.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"dotenv": "^16.5.0",
|
||||
|
|
@ -18,15 +17,11 @@
|
|||
"lowdb": "^7.0.1",
|
||||
"otplib": "^12.0.1",
|
||||
"playwright-firefox": "^1.52.0",
|
||||
"puppeteer-extra-plugin-stealth": "^2.11.2",
|
||||
"tough-cookie": "^4.1.4"
|
||||
"puppeteer-extra-plugin-stealth": "^2.11.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.26.0",
|
||||
"@stylistic/eslint-plugin-js": "^4.2.0",
|
||||
"eslint": "^9.26.0",
|
||||
"globals": "^15.14.0",
|
||||
"typescript": "^5.9.3"
|
||||
"eslint": "^9.26.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=17"
|
||||
|
|
@ -127,19 +122,6 @@
|
|||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/eslintrc/node_modules/globals": {
|
||||
"version": "14.0.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
|
||||
"integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/js": {
|
||||
"version": "9.26.0",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.26.0.tgz",
|
||||
|
|
@ -464,23 +446,6 @@
|
|||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.13.2.tgz",
|
||||
"integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.4",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
|
|
@ -562,6 +527,7 @@
|
|||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
|
|
@ -662,18 +628,6 @@
|
|||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"delayed-stream": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
|
|
@ -798,15 +752,6 @@
|
|||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
|
|
@ -848,6 +793,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
|
|
@ -897,6 +843,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
|
|
@ -906,6 +853,7 @@
|
|||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
|
|
@ -915,6 +863,7 @@
|
|||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
|
||||
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0"
|
||||
|
|
@ -923,21 +872,6 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-set-tostringtag": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.6",
|
||||
"has-tostringtag": "^1.0.2",
|
||||
"hasown": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||
|
|
@ -1391,26 +1325,6 @@
|
|||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/follow-redirects": {
|
||||
"version": "1.15.11",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
|
||||
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/RubenVerborgh"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"debug": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/for-in": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz",
|
||||
|
|
@ -1432,43 +1346,6 @@
|
|||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/form-data": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
|
||||
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
"es-set-tostringtag": "^2.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"mime-types": "^2.1.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/form-data/node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/form-data/node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/forwarded": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||
|
|
@ -1513,6 +1390,7 @@
|
|||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
|
|
@ -1532,6 +1410,7 @@
|
|||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
|
|
@ -1556,6 +1435,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
|
|
@ -1599,9 +1479,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/globals": {
|
||||
"version": "15.15.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz",
|
||||
"integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==",
|
||||
"version": "14.0.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
|
||||
"integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
|
|
@ -1615,6 +1495,7 @@
|
|||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
|
|
@ -1642,6 +1523,7 @@
|
|||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
|
|
@ -1650,25 +1532,11 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-tostringtag": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-symbols": "^1.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
|
|
@ -1999,6 +1867,7 @@
|
|||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
|
|
@ -2372,28 +2241,11 @@
|
|||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/psl": {
|
||||
"version": "1.15.0",
|
||||
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
|
||||
"integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"punycode": "^2.3.1"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/lupomontero"
|
||||
}
|
||||
},
|
||||
"node_modules/punycode": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
|
|
@ -2521,12 +2373,6 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/querystringify": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
|
||||
"integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
|
|
@ -2553,12 +2399,6 @@
|
|||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/requires-port": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
|
||||
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/resolve-from": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
|
||||
|
|
@ -2883,30 +2723,6 @@
|
|||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/tough-cookie": {
|
||||
"version": "4.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz",
|
||||
"integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"psl": "^1.1.33",
|
||||
"punycode": "^2.1.1",
|
||||
"universalify": "^0.2.0",
|
||||
"url-parse": "^1.5.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/tough-cookie/node_modules/universalify": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz",
|
||||
"integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
|
|
@ -2940,20 +2756,6 @@
|
|||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/universalify": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
||||
|
|
@ -3013,16 +2815,6 @@
|
|||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/url-parse": {
|
||||
"version": "1.5.10",
|
||||
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
|
||||
"integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"querystringify": "^2.1.1",
|
||||
"requires-port": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vali-date": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/vali-date/-/vali-date-1.0.0.tgz",
|
||||
|
|
@ -3158,14 +2950,6 @@
|
|||
"js-yaml": "^4.1.0",
|
||||
"minimatch": "^3.1.2",
|
||||
"strip-json-comments": "^3.1.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"globals": {
|
||||
"version": "14.0.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
|
||||
"integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"@eslint/js": {
|
||||
|
|
@ -3396,21 +3180,6 @@
|
|||
"resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz",
|
||||
"integrity": "sha512-sKpyeERZ02v1FeCZT8lrfJq5u6goHCtpTAzPwJYe7c8SPFOboNjNg1vz2L4VTn9T4PQxEx13TbXLmYUcS6Ug7Q=="
|
||||
},
|
||||
"asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
|
||||
},
|
||||
"axios": {
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.13.2.tgz",
|
||||
"integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==",
|
||||
"requires": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.4",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"balanced-match": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
|
|
@ -3463,6 +3232,7 @@
|
|||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
|
|
@ -3520,14 +3290,6 @@
|
|||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"dev": true
|
||||
},
|
||||
"combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||
"requires": {
|
||||
"delayed-stream": "~1.0.0"
|
||||
}
|
||||
},
|
||||
"concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
|
|
@ -3607,11 +3369,6 @@
|
|||
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
|
||||
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="
|
||||
},
|
||||
"delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="
|
||||
},
|
||||
"depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
|
|
@ -3635,6 +3392,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
|
|
@ -3670,32 +3428,24 @@
|
|||
"es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"dev": true
|
||||
},
|
||||
"es-errors": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"dev": true
|
||||
},
|
||||
"es-object-atoms": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
|
||||
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"es-errors": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"es-set-tostringtag": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||
"requires": {
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.6",
|
||||
"has-tostringtag": "^1.0.2",
|
||||
"hasown": "^2.0.2"
|
||||
}
|
||||
},
|
||||
"escalade": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||
|
|
@ -3996,11 +3746,6 @@
|
|||
"integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==",
|
||||
"dev": true
|
||||
},
|
||||
"follow-redirects": {
|
||||
"version": "1.15.11",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
|
||||
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="
|
||||
},
|
||||
"for-in": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz",
|
||||
|
|
@ -4014,33 +3759,6 @@
|
|||
"for-in": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"form-data": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
|
||||
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
|
||||
"requires": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
"es-set-tostringtag": "^2.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"mime-types": "^2.1.12"
|
||||
},
|
||||
"dependencies": {
|
||||
"mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="
|
||||
},
|
||||
"mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"requires": {
|
||||
"mime-db": "1.52.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"forwarded": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||
|
|
@ -4071,7 +3789,8 @@
|
|||
"function-bind": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="
|
||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||
"dev": true
|
||||
},
|
||||
"generative-bayesian-network": {
|
||||
"version": "2.1.66",
|
||||
|
|
@ -4086,6 +3805,7 @@
|
|||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
|
|
@ -4103,6 +3823,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
|
|
@ -4131,15 +3852,16 @@
|
|||
}
|
||||
},
|
||||
"globals": {
|
||||
"version": "15.15.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz",
|
||||
"integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==",
|
||||
"version": "14.0.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
|
||||
"integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
|
||||
"dev": true
|
||||
},
|
||||
"gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"dev": true
|
||||
},
|
||||
"graceful-fs": {
|
||||
"version": "4.2.11",
|
||||
|
|
@ -4155,20 +3877,14 @@
|
|||
"has-symbols": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="
|
||||
},
|
||||
"has-tostringtag": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||
"requires": {
|
||||
"has-symbols": "^1.0.3"
|
||||
}
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"dev": true
|
||||
},
|
||||
"hasown": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"function-bind": "^1.1.2"
|
||||
}
|
||||
|
|
@ -4401,7 +4117,8 @@
|
|||
"math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"dev": true
|
||||
},
|
||||
"media-typer": {
|
||||
"version": "1.1.0",
|
||||
|
|
@ -4646,23 +4363,11 @@
|
|||
"ipaddr.js": "1.9.1"
|
||||
}
|
||||
},
|
||||
"proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
|
||||
},
|
||||
"psl": {
|
||||
"version": "1.15.0",
|
||||
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
|
||||
"integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==",
|
||||
"requires": {
|
||||
"punycode": "^2.3.1"
|
||||
}
|
||||
},
|
||||
"punycode": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true
|
||||
},
|
||||
"puppeteer-extra-plugin": {
|
||||
"version": "3.2.3",
|
||||
|
|
@ -4715,11 +4420,6 @@
|
|||
"side-channel": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"querystringify": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
|
||||
"integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ=="
|
||||
},
|
||||
"range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
|
|
@ -4738,11 +4438,6 @@
|
|||
"unpipe": "1.0.0"
|
||||
}
|
||||
},
|
||||
"requires-port": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
|
||||
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ=="
|
||||
},
|
||||
"resolve-from": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
|
||||
|
|
@ -4951,24 +4646,6 @@
|
|||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
||||
"dev": true
|
||||
},
|
||||
"tough-cookie": {
|
||||
"version": "4.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz",
|
||||
"integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==",
|
||||
"requires": {
|
||||
"psl": "^1.1.33",
|
||||
"punycode": "^2.1.1",
|
||||
"universalify": "^0.2.0",
|
||||
"url-parse": "^1.5.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"universalify": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz",
|
||||
"integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg=="
|
||||
}
|
||||
}
|
||||
},
|
||||
"tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
|
|
@ -4994,12 +4671,6 @@
|
|||
"mime-types": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true
|
||||
},
|
||||
"universalify": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
||||
|
|
@ -5029,15 +4700,6 @@
|
|||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"url-parse": {
|
||||
"version": "1.5.10",
|
||||
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
|
||||
"integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
|
||||
"requires": {
|
||||
"querystringify": "^2.1.1",
|
||||
"requires-port": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"vali-date": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/vali-date/-/vali-date-1.0.0.tgz",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@
|
|||
"node": ">=17"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.7.9",
|
||||
"chalk": "^5.4.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"dotenv": "^16.5.0",
|
||||
|
|
@ -29,14 +28,10 @@
|
|||
"lowdb": "^7.0.1",
|
||||
"otplib": "^12.0.1",
|
||||
"playwright-firefox": "^1.52.0",
|
||||
"puppeteer-extra-plugin-stealth": "^2.11.2",
|
||||
"tough-cookie": "^4.1.4"
|
||||
"puppeteer-extra-plugin-stealth": "^2.11.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.26.0",
|
||||
"globals": "^15.14.0",
|
||||
"@stylistic/eslint-plugin-js": "^4.2.0",
|
||||
"eslint": "^9.26.0",
|
||||
"typescript": "^5.9.3"
|
||||
"eslint": "^9.26.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
491
prime-gaming.js
491
prime-gaming.js
|
|
@ -6,7 +6,8 @@ import { cfg } from './src/config.js';
|
|||
|
||||
const screenshot = (...a) => resolve(cfg.dir.screenshots, 'prime-gaming', ...a);
|
||||
|
||||
const URL_CLAIM = 'https://luna.amazon.com/claims/home';
|
||||
// const URL_LOGIN = 'https://www.amazon.de/ap/signin'; // wrong. needs some session args to be valid?
|
||||
const URL_CLAIM = 'https://gaming.amazon.com/home';
|
||||
|
||||
console.log(datetime(), 'started checking prime-gaming');
|
||||
|
||||
|
|
@ -24,100 +25,24 @@ const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
|||
|
||||
handleSIGINT(context);
|
||||
|
||||
// TODO test if needed
|
||||
await stealth(context);
|
||||
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
|
||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
||||
|
||||
const notify_games = [];
|
||||
let user;
|
||||
|
||||
const handleMFA = async p => {
|
||||
const otpField = p.locator('#auth-mfa-otpcode, input[name=otpCode]');
|
||||
if (!await otpField.count()) return false;
|
||||
console.log('Two-Step Verification - enter the One Time Password (OTP), e.g. generated by your Authenticator App');
|
||||
await p.locator('#auth-mfa-remember-device, [name=rememberDevice]').check().catch(() => {});
|
||||
const otp = cfg.pg_otpkey && authenticator.generate(cfg.pg_otpkey) || await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||
await otpField.first().pressSequentially(otp.toString());
|
||||
await p.locator('input[type="submit"], button[type="submit"]').first().click();
|
||||
return true;
|
||||
};
|
||||
|
||||
const waitForSignedInOrMFA = async p => {
|
||||
const otpLocator = p.locator('#auth-mfa-otpcode, input[name=otpCode]');
|
||||
const waitSignedIn = p.waitForURL('**/claims/**signedIn=true', { timeout: cfg.login_timeout }).then(() => true).catch(() => false);
|
||||
const waitMFA = (async () => {
|
||||
try {
|
||||
await otpLocator.waitFor({ timeout: cfg.login_timeout });
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
await handleMFA(p);
|
||||
try {
|
||||
await p.waitForURL('**/claims/**signedIn=true', { timeout: cfg.login_timeout });
|
||||
} catch {
|
||||
// if it still fails, caller will handle via timeout
|
||||
}
|
||||
return true;
|
||||
})();
|
||||
await Promise.race([waitSignedIn, waitMFA]);
|
||||
};
|
||||
|
||||
try {
|
||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
||||
const handleDirectLoginPage = async () => {
|
||||
if (!page.url().includes('/ap/signin')) return false;
|
||||
console.log('On Amazon login page (redirect). Trying to sign in automatically.');
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout);
|
||||
const email = cfg.pg_email || await prompt({ message: 'Enter email' });
|
||||
const password = email && (cfg.pg_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||
if (email && password) {
|
||||
await page.fill('[name=email]', email);
|
||||
await page.click('input[type="submit"]');
|
||||
await page.fill('[name=password]', password);
|
||||
await page.click('input[type="submit"]');
|
||||
await waitForSignedInOrMFA(page);
|
||||
try {
|
||||
await page.waitForURL('**/ap/signin**');
|
||||
const error = await page.locator('.a-alert-content').first().innerText();
|
||||
if (error.trim().length) {
|
||||
console.error('Login error:', error);
|
||||
await notify(`prime-gaming: login: ${error}`);
|
||||
await context.close(); // finishes potential recording
|
||||
process.exit(1);
|
||||
}
|
||||
} catch {
|
||||
// if navigation succeeded, continue
|
||||
}
|
||||
await page.waitForURL(/luna\.amazon\.com\/claims\/.*signedIn=true/);
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
return true;
|
||||
} else {
|
||||
console.log('Waiting for manual login on redirect page.');
|
||||
if (cfg.headless) {
|
||||
console.log('Run `SHOW=1 node prime-gaming` to login in the opened browser.');
|
||||
await context.close(); // finishes potential recording
|
||||
process.exit(1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
await handleDirectLoginPage();
|
||||
// need to wait for some elements to exist before checking if signed in or accepting cookies:
|
||||
await Promise.any([
|
||||
'button:has-text("Sign in")',
|
||||
'button:has-text("Anmelden")',
|
||||
'[data-a-target="user-dropdown-first-name-text"]',
|
||||
'[data-testid="user-dropdown-first-name-text"]',
|
||||
].map(s => page.waitForSelector(s, { timeout: cfg.login_visible_timeout }))).catch(() => {});
|
||||
try {
|
||||
await page.click('[aria-label="Cookies usage disclaimer banner"] button:has-text("Accept Cookies")'); // to not waste screen space when non-headless; could be flaky
|
||||
} catch {
|
||||
// ignore if banner not present
|
||||
}
|
||||
while (await page.locator('button:has-text("Sign in"), button:has-text("Anmelden")').count() > 0) {
|
||||
await Promise.any(['button:has-text("Sign in")', '[data-a-target="user-dropdown-first-name-text"]'].map(s => page.waitForSelector(s)));
|
||||
page.click('[aria-label="Cookies usage disclaimer banner"] button:has-text("Accept Cookies")').catch(_ => { }); // to not waste screen space when non-headless, TODO does not work reliably, need to wait for something else first?
|
||||
while (await page.locator('button:has-text("Sign in")').count() > 0) {
|
||||
console.error('Not signed in anymore.');
|
||||
await page.click('button:has-text("Sign in")');
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
|
||||
|
|
@ -130,20 +55,24 @@ try {
|
|||
await page.fill('[name=email]', email);
|
||||
await page.click('input[type="submit"]');
|
||||
await page.fill('[name=password]', password);
|
||||
// await page.check('[name=rememberMe]'); // no longer exists
|
||||
await page.click('input[type="submit"]');
|
||||
await waitForSignedInOrMFA(page);
|
||||
try {
|
||||
await page.waitForURL('**/ap/signin**');
|
||||
page.waitForURL('**/ap/signin**').then(async () => { // check for wrong credentials
|
||||
const error = await page.locator('.a-alert-content').first().innerText();
|
||||
if (error.trim().length) {
|
||||
if (!error.trim.length) return;
|
||||
console.error('Login error:', error);
|
||||
await notify(`prime-gaming: login: ${error}`);
|
||||
await context.close(); // finishes potential recording
|
||||
process.exit(1);
|
||||
}
|
||||
} catch {
|
||||
// navigation ok
|
||||
}
|
||||
});
|
||||
// handle MFA, but don't await it
|
||||
page.waitForURL('**/ap/mfa**').then(async () => {
|
||||
console.log('Two-Step Verification - enter the One Time Password (OTP), e.g. generated by your Authenticator App');
|
||||
await page.check('[name=rememberDevice]');
|
||||
const otp = cfg.pg_otpkey && authenticator.generate(cfg.pg_otpkey) || await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||
await page.locator('input[name=otpCode]').pressSequentially(otp.toString());
|
||||
await page.click('input[type="submit"]');
|
||||
}).catch(_ => { });
|
||||
} else {
|
||||
console.log('Waiting for you to login in the browser.');
|
||||
await notify('prime-gaming: no longer signed in and not enough options set for automatic login.');
|
||||
|
|
@ -156,8 +85,11 @@ try {
|
|||
await page.waitForURL('https://gaming.amazon.com/home?signedIn=true');
|
||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
}
|
||||
user = await page.locator('[data-a-target="user-dropdown-first-name-text"], [data-testid="user-dropdown-first-name-text"]').first().innerText();
|
||||
user = await page.locator('[data-a-target="user-dropdown-first-name-text"]').first().innerText();
|
||||
console.log(`Signed in as ${user}`);
|
||||
// await page.click('button[aria-label="User dropdown and more options"]');
|
||||
// const twitch = await page.locator('[data-a-target="TwitchDisplayName"]').first().innerText();
|
||||
// console.log(`Twitch user name is ${twitch}`);
|
||||
db.data[user] ||= {};
|
||||
|
||||
if (await page.getByRole('button', { name: 'Try Prime' }).count()) {
|
||||
|
|
@ -181,337 +113,108 @@ try {
|
|||
// loading all games became flaky; see https://github.com/vogler/free-games-claimer/issues/357
|
||||
await page.keyboard.press('PageDown'); // scrolling to straight to the bottom started to skip loading some games
|
||||
await page.waitForLoadState('networkidle'); // wait for all games to be loaded
|
||||
await page.waitForTimeout(3000); // extra wait to load all already collected games
|
||||
await page.waitForTimeout(3000); // TODO networkidle wasn't enough to load all already collected games
|
||||
// do it again since once wasn't enough...
|
||||
await page.keyboard.press('PageDown');
|
||||
await page.waitForTimeout(3000);
|
||||
});
|
||||
|
||||
const openGamesTab = async () => {
|
||||
const selectors = [
|
||||
'button[data-type="Game"]', // old layout
|
||||
'button:has-text("Games")',
|
||||
'button:has-text("Games einlösen")',
|
||||
'[data-test-selector="category-picker"] button:has-text("Games")',
|
||||
'[data-testid="category-picker"] button:has-text("Games")',
|
||||
];
|
||||
for (const sel of selectors) {
|
||||
const btn = page.locator(sel).first();
|
||||
if (await btn.count()) {
|
||||
await btn.click();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// New Luna claims home: try the filter/CTA button with embedded <p title="Games einlösen">
|
||||
const gamesTitle = page.locator('p.offer-filters__button__title:has-text("Games"), p.offer-filters__button__title:has-text("einlösen")');
|
||||
if (await gamesTitle.count()) {
|
||||
const btn = gamesTitle.first().locator('xpath=ancestor::button[1]');
|
||||
if (await btn.count()) {
|
||||
await btn.click();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// New Luna claims home already shows games list
|
||||
};
|
||||
|
||||
await openGamesTab();
|
||||
|
||||
const locateGamesList = async () => {
|
||||
const selectors = [
|
||||
'div[data-a-target="offer-list-FGWP_FULL"]', // old layout
|
||||
'[data-testid="offer-list"]',
|
||||
'[data-test-selector="offer-list"]',
|
||||
'section:has(h2:has-text("Games with Prime"))',
|
||||
'section:has(h2:has-text("Games"))',
|
||||
];
|
||||
for (const sel of selectors) {
|
||||
const loc = page.locator(sel).first();
|
||||
if (await loc.count()) return loc;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const games = await locateGamesList();
|
||||
// Load all cards (old and new layout) by scrolling the container or the page
|
||||
if (games) await scrollUntilStable(() => games.evaluate(el => el.scrollHeight).catch(() => 0));
|
||||
await scrollUntilStable(() => page.evaluate(() => globalThis.document?.scrollingElement?.scrollHeight ?? 0));
|
||||
|
||||
const normalizeClaimUrl = url => {
|
||||
if (!url) return { url, key: null };
|
||||
const m = url.match(/(https?:\/\/[^/]+)?(\/claims\/[^?#]+)/);
|
||||
if (!m) return { url, key: url };
|
||||
const path = m[2];
|
||||
const slug = path.split('/')[2];
|
||||
return { url: 'https://luna.amazon.com' + path, key: slug || path };
|
||||
};
|
||||
|
||||
const cards = [];
|
||||
// New layout: direct claim buttons on cards (FGWPOffer) with "Spiel aktivieren"/"Claim"
|
||||
const fgwps = page.locator('[data-a-target="FGWPOffer"]');
|
||||
if (await fgwps.count()) {
|
||||
for (const handle of await fgwps.elementHandles()) {
|
||||
const href = await handle.getAttribute('href');
|
||||
const { url, key } = normalizeClaimUrl(href?.startsWith('/') ? href : href || '');
|
||||
const title =
|
||||
await handle.$eval('p[title], span[title]', el => el.getAttribute('title')).catch(() => null) ||
|
||||
await handle.$eval('p, span', el => el.textContent).catch(() => null) ||
|
||||
key ||
|
||||
'Unknown title';
|
||||
cards.push({ kind: 'external', title, url, key });
|
||||
}
|
||||
}
|
||||
|
||||
const anchorClaims = page.locator('a[href*="/claims/"][href*="amzn1.pg.item"]');
|
||||
if (await anchorClaims.count()) {
|
||||
const hrefs = [...new Set(await anchorClaims.evaluateAll(anchors => anchors.map(a => a.getAttribute('href')).filter(Boolean)))];
|
||||
for (const href of hrefs) {
|
||||
const { url, key } = normalizeClaimUrl(href);
|
||||
const title = key || await anchorClaims.first().innerText() || 'Unknown title';
|
||||
cards.push({ kind: 'external', title, url, key });
|
||||
}
|
||||
}
|
||||
|
||||
if (!cards.length && games) {
|
||||
const cardLocator = games.locator([
|
||||
'[data-testid="offer-card"]',
|
||||
'[data-test-selector="offer-card"]',
|
||||
'.item-card__action',
|
||||
].join(','));
|
||||
if (await cardLocator.count() === 0) {
|
||||
console.log('No games found in list.');
|
||||
} else {
|
||||
for (const handle of await cardLocator.elementHandles()) {
|
||||
const text = (await handle.textContent() || '').toLowerCase();
|
||||
if (text.includes('collected')) continue; // skip already claimed
|
||||
const title = await (await handle.$('h3, h4, [data-testid="item-card-title"], [data-test-selector="item-card-title"], .item-card-details__body__primary'))?.innerText() || 'Unknown title';
|
||||
const linkEl = await handle.$('a[href]');
|
||||
let url = linkEl && await linkEl.getAttribute('href');
|
||||
if (url?.startsWith('/')) url = 'https://luna.amazon.com' + url;
|
||||
const { url: normUrl, key } = normalizeClaimUrl(url);
|
||||
const hasLinkClaim = await handle.$('a:has-text("Claim"), a:has-text("Get"), a:has-text("Details")');
|
||||
const hasButtonClaim = await handle.$('button:has-text("Claim"), button:has-text("Get"), button:has-text("Get game"), button:has-text("Play")');
|
||||
const hasGermanCTA = await handle.$(':is(button,p,a):has-text("Spiel aktivieren"), :is(button,p,a):has-text("Spiel holen")');
|
||||
if (hasLinkClaim || hasGermanCTA) cards.push({ kind: 'external', title, url: normUrl, key });
|
||||
else if (hasButtonClaim) cards.push({ kind: 'internal', title, url: normUrl, key, handle });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dedup by URL to avoid duplicates from multiple selectors
|
||||
const seenUrl = new Set();
|
||||
const uniq = cards.filter(c => {
|
||||
const key = c.key || c.url || c.title;
|
||||
if (seenUrl.has(key)) return false;
|
||||
seenUrl.add(key);
|
||||
return true;
|
||||
});
|
||||
|
||||
const internal = uniq.filter(c => c.kind == 'internal');
|
||||
const external = uniq.filter(c => c.kind == 'external');
|
||||
await page.click('button[data-type="Game"]');
|
||||
const games = page.locator('div[data-a-target="offer-list-FGWP_FULL"]');
|
||||
await games.waitFor();
|
||||
// await scrollUntilStable(() => games.locator('.item-card__action').count()); // number of games
|
||||
await scrollUntilStable(() => page.evaluate(() => document.querySelector('.tw-full-width').scrollHeight)); // height may change during loading while number of games is still the same?
|
||||
console.log('Number of already claimed games (total):', await games.locator('p:has-text("Collected")').count());
|
||||
// can't use .all() since the list of elements via locator will change after click while we iterate over it
|
||||
const internal = await games.locator('.item-card__action:has(button[data-a-target="FGWPOffer"])').elementHandles();
|
||||
const external = await games.locator('.item-card__action:has(a[data-a-target="FGWPOffer"])').all();
|
||||
// bottom to top: oldest to newest games
|
||||
internal.reverse();
|
||||
external.reverse();
|
||||
const sameOrNewPage = async url => {
|
||||
const sameOrNewPage = async url => new Promise(async (resolve, _reject) => {
|
||||
const isNew = page.url() != url;
|
||||
let p = page;
|
||||
if (isNew) {
|
||||
p = await context.newPage();
|
||||
await p.goto(url, { waitUntil: 'domcontentloaded' });
|
||||
}
|
||||
return [p, isNew];
|
||||
};
|
||||
resolve([p, isNew]);
|
||||
});
|
||||
const skipBasedOnTime = async url => {
|
||||
// console.log(' Checking time left for game:', url);
|
||||
const [p, isNew] = await sameOrNewPage(url);
|
||||
const dueDateLoc = p.locator('.availability-date .tw-bold, [data-testid="availability-end-date"], [data-test-selector="availability-end-date"]');
|
||||
if (!await dueDateLoc.count()) {
|
||||
if (isNew) await p.close();
|
||||
return false;
|
||||
}
|
||||
const dueDateOrg = await dueDateLoc.first().innerText();
|
||||
const dueDateOrg = await p.locator('.availability-date .tw-bold').innerText();
|
||||
const dueDate = new Date(Date.parse(dueDateOrg + ' 17:00'));
|
||||
const daysLeft = (dueDate.getTime() - Date.now())/1000/60/60/24;
|
||||
const availabilityText = await p.locator('.availability-date, [data-testid="availability-end-date"], [data-test-selector="availability-end-date"]').first().innerText().catch(() => dueDateOrg);
|
||||
console.log(' ', availabilityText, '->', daysLeft.toFixed(2));
|
||||
console.log(' ', await p.locator('.availability-date').innerText(), '->', daysLeft.toFixed(2));
|
||||
if (isNew) await p.close();
|
||||
return daysLeft > cfg.pg_timeLeft;
|
||||
};
|
||||
}
|
||||
console.log('\nNumber of free unclaimed games (Prime Gaming):', internal.length);
|
||||
// claim games in internal store
|
||||
for (const card of internal) {
|
||||
await card.handle.scrollIntoViewIfNeeded();
|
||||
const title = card.title;
|
||||
const url = card.url;
|
||||
await card.scrollIntoViewIfNeeded();
|
||||
const title = await (await card.$('.item-card-details__body__primary')).innerText();
|
||||
const slug = await (await card.$('a')).getAttribute('href');
|
||||
const url = 'https://gaming.amazon.com' + slug.split('?')[0];
|
||||
console.log('Current free game:', chalk.blue(title));
|
||||
if (cfg.pg_timeLeft && url && await skipBasedOnTime(url)) continue;
|
||||
if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue;
|
||||
if (cfg.dryrun) continue;
|
||||
if (cfg.interactive) {
|
||||
const confirmed = await confirm();
|
||||
if (!confirmed) continue;
|
||||
}
|
||||
await card.handle.locator('.tw-button:has-text("Claim"), .tw-button:has-text("Get"), button:has-text("Claim"), button:has-text("Get")').first().click();
|
||||
if (cfg.interactive && !await confirm()) continue;
|
||||
await (await card.$('.tw-button:has-text("Claim")')).click();
|
||||
db.data[user][title] ||= { title, time: datetime(), url, store: 'internal' };
|
||||
notify_games.push({ title, status: 'claimed', url });
|
||||
await card.handle.screenshot({ path: screenshot('internal', `${filenamify(title)}.png`) });
|
||||
// const img = await (await card.$('img.tw-image')).getAttribute('src');
|
||||
// console.log('Image:', img);
|
||||
await card.screenshot({ path: screenshot('internal', `${filenamify(title)}.png`) });
|
||||
}
|
||||
console.log('\nNumber of free unclaimed games (external stores):', external.length);
|
||||
// claim games in external/linked stores. Linked: origin.com, epicgames.com; Redeem-key: gog.com, legacygames.com, microsoft
|
||||
const external_info = [];
|
||||
for (const card of external) { // need to get data incl. URLs in this loop and then navigate in another, otherwise .all() would update after coming back and .elementHandles() like above would lead to error due to page navigation: elementHandle.$: Protocol error (Page.adoptNode)
|
||||
const title = card.title;
|
||||
const url = card.url ? card.url.split('?')[0] : undefined;
|
||||
if (!url) continue;
|
||||
const title = await card.locator('.item-card-details__body__primary').innerText();
|
||||
const slug = await card.locator('a:has-text("Claim")').first().getAttribute('href');
|
||||
const url = 'https://gaming.amazon.com' + slug.split('?')[0];
|
||||
// await (await card.$('text=Claim')).click(); // goes to URL of game, no need to wait
|
||||
external_info.push({ title, url });
|
||||
}
|
||||
const clickCTA = async p => {
|
||||
const candidates = [
|
||||
p.locator('button[data-a-target="buy-box_call-to-action"]').first(),
|
||||
p.locator('[data-a-target="buy-box_call-to-action"]').first(),
|
||||
p.locator('[data-a-target="buy-box"] .tw-button:has-text("Get game")').first(),
|
||||
p.locator('[data-a-target="buy-box"] .tw-button:has-text("Claim")').first(),
|
||||
p.locator('.tw-button:has-text("Complete Claim")').first(),
|
||||
p.locator('[data-a-target="buy-box_call-to-action-text"]').first().locator('xpath=ancestor::button[1]'),
|
||||
p.locator('.tw-button:has-text("Spiel holen"), .tw-button:has-text("Spiel aktivieren")').first(),
|
||||
p.locator('p:has-text("Spiel holen"), p:has-text("Spiel aktivieren")').first().locator('xpath=ancestor::button[1]'),
|
||||
];
|
||||
for (const c of candidates) {
|
||||
if (await c.count()) {
|
||||
try {
|
||||
await c.waitFor({ state: 'visible', timeout: 5000 });
|
||||
const enabled = await c.isEnabled();
|
||||
if (enabled) await c.click();
|
||||
else {
|
||||
await c.evaluate(el => {
|
||||
el.disabled = false;
|
||||
el.removeAttribute('disabled');
|
||||
el.click();
|
||||
});
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
// try next candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// external_info = [ { title: 'Fallout 76 (XBOX)', url: 'https://gaming.amazon.com/fallout-76-xbox-fgwp/dp/amzn1.pg.item.9fe17d7b-b6c2-4f58-b494-cc4e79528d0b?ingress=amzn&ref_=SM_Fallout76XBOX_S01_FGWP_CRWN' } ];
|
||||
for (const { title, url } of external_info) {
|
||||
console.log('Current free game:', chalk.blue(title)); // , url);
|
||||
const existingStatus = db.data[user]?.[title]?.status;
|
||||
if (existingStatus && !existingStatus.startsWith('failed')) {
|
||||
console.log(` Already recorded as ${existingStatus}, skipping.`);
|
||||
notify_games.push({ title, url, status: 'existed' });
|
||||
continue;
|
||||
}
|
||||
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForSelector('[data-a-target="buy-box"]', { timeout: 10000 }).catch(() => {});
|
||||
if (cfg.debug) await page.pause();
|
||||
let store = 'unknown';
|
||||
const detailLoc = page.locator('[data-a-target="DescriptionItemDetails"], [data-testid="DescriptionItemDetails"]');
|
||||
if (await detailLoc.count()) {
|
||||
const item_text = await detailLoc.first().innerText();
|
||||
const lower = item_text.toLowerCase();
|
||||
const onPos = lower.lastIndexOf(' on ');
|
||||
if (onPos >= 0) store = lower.slice(onPos + 4).replace(/[.!]$/, '');
|
||||
} else if (url.includes('/claims/')) {
|
||||
const slug = url.split('/claims/')[1]?.split('/')[0] || '';
|
||||
if (slug.includes('gog')) store = 'gog.com';
|
||||
else if (slug.includes('epic')) store = 'epic-games';
|
||||
else if (slug.includes('origin')) store = 'origin';
|
||||
else if (slug.includes('xbox') || slug.includes('microsoft')) store = 'microsoft store';
|
||||
else if (slug.includes('legacy')) store = 'legacy games';
|
||||
const lunaPlay = await page.locator('[data-a-target="LunaOffer"], button[data-a-target="LunaOffer"], button:has-text("Spielen")').count();
|
||||
if (store == 'unknown' && lunaPlay) store = 'luna';
|
||||
}
|
||||
const item_text = await page.innerText('[data-a-target="DescriptionItemDetails"]');
|
||||
const store = item_text.toLowerCase().replace(/.* on /, '').slice(0, -1);
|
||||
console.log(' External store:', store);
|
||||
const notify_game = { title, url };
|
||||
notify_games.push(notify_game); // status is updated below
|
||||
// Already collected? skip
|
||||
const collectedLoc = page.locator('[data-a-target="ClaimStateQuantityAndDateContent"], [data-a-target="ClaimStateClaimCodeContent"]:has-text("Collected"), [data-a-target="ClaimStateVendorContent"], [data-a-target="ClaimStateViewDetailsAndInstructions"]');
|
||||
const collectedText = page.getByText(/You collected this on/i);
|
||||
const collectedEpic = page.getByText(/Sent to your Epic Games Store library/i);
|
||||
const collectedBanner = page.locator('p.tw-c-text-alert-success:has-text("Collected"), p.tw-c-text-alert-success:has-text("Collected this")');
|
||||
const collectedSuccessIcon = page.locator('[data-a-target="ItemCardDetailSuccessStatus"], .claim-state__success-icon');
|
||||
const disabledCTA = page.locator('[data-a-target="buy-box_call-to-action"][disabled], button[disabled]:has-text("Get game")');
|
||||
const collectedAny = await Promise.all([
|
||||
collectedLoc.count(),
|
||||
collectedBanner.count(),
|
||||
collectedText.count(),
|
||||
collectedEpic.count(),
|
||||
collectedSuccessIcon.count(),
|
||||
disabledCTA.count(),
|
||||
]).then(([a, b, c, d, e, f]) => a + b + c + d + e + f > 0);
|
||||
if (collectedAny) {
|
||||
console.log(' Already collected, skipping.');
|
||||
notify_game.status = 'existed';
|
||||
db.data[user][title] ||= { title, time: datetime(), url, store, status: 'existed' };
|
||||
continue;
|
||||
}
|
||||
// Disabled CTA (e.g., needs linking or not available)
|
||||
if (await disabledCTA.count()) {
|
||||
if (store === 'epic-games') {
|
||||
console.log(' CTA disabled for epic-games, will still try to link/claim.');
|
||||
} else {
|
||||
console.log(' CTA is disabled, skipping (likely needs linking/not available).');
|
||||
notify_game.status = 'disabled';
|
||||
db.data[user][title] ||= { title, time: datetime(), url, store, status: 'disabled' };
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (store == 'luna') {
|
||||
console.log(' Luna cloud title detected, skipping code redemption.');
|
||||
notify_game.status = 'luna (play)';
|
||||
db.data[user][title] ||= { title, time: datetime(), url, store: 'luna', status: 'luna (play)' };
|
||||
continue;
|
||||
}
|
||||
if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue;
|
||||
if (cfg.dryrun) continue;
|
||||
if (cfg.interactive) {
|
||||
const confirmed = await confirm();
|
||||
if (!confirmed) continue;
|
||||
}
|
||||
await clickCTA(page);
|
||||
await Promise.any([
|
||||
page.waitForSelector('.thank-you-title:has-text("Success")', { timeout: cfg.timeout }).catch(() => {}),
|
||||
page.waitForSelector('div:has-text("Link game account")', { timeout: cfg.timeout }).catch(() => {}),
|
||||
]).catch(() => {});
|
||||
if (cfg.interactive && !await confirm()) continue;
|
||||
await Promise.any([page.click('[data-a-target="buy-box"] .tw-button:has-text("Get game")'), page.click('[data-a-target="buy-box"] .tw-button:has-text("Claim")'), page.click('.tw-button:has-text("Complete Claim")'), page.waitForSelector('div:has-text("Link game account")'), page.waitForSelector('.thank-you-title:has-text("Success")')]); // waits for navigation
|
||||
db.data[user][title] ||= { title, time: datetime(), url, store };
|
||||
if (await page.locator('div:has-text("Link game account")').count() // epic games store also shows "Link account"
|
||||
const notify_game = { title, url };
|
||||
notify_games.push(notify_game); // status is updated below
|
||||
if (await page.locator('div:has-text("Link game account")').count() // TODO still needed? epic games store just has 'Link account' as the button text now.
|
||||
|| await page.locator('div:has-text("Link account")').count()) {
|
||||
console.error(' Account linking is required to claim this offer!');
|
||||
notify_game.status = `failed: need account linking for ${store}`;
|
||||
db.data[user][title].status = 'failed: need account linking';
|
||||
// await page.pause();
|
||||
// await page.click('[data-a-target="LinkAccountModal"] [data-a-target="LinkAccountButton"]');
|
||||
// login for epic games also needed if already logged in
|
||||
// TODO login for epic games also needed if already logged in
|
||||
// wait for https://www.epicgames.com/id/authorize?redirect_uri=https%3A%2F%2Fservice.link.amazon.gg...
|
||||
// await page.click('button[aria-label="Allow"]');
|
||||
} else {
|
||||
db.data[user][title].status = 'claimed';
|
||||
// print code if there is one
|
||||
const redeem = {
|
||||
// 'origin': 'https://www.origin.com/redeem', // kept for legacy flows; current path uses account linking
|
||||
// 'origin': 'https://www.origin.com/redeem', // TODO still needed or now only via account linking?
|
||||
'gog.com': 'https://www.gog.com/redeem',
|
||||
'microsoft store': 'https://account.microsoft.com/billing/redeem',
|
||||
xbox: 'https://account.microsoft.com/billing/redeem',
|
||||
'legacy games': 'https://www.legacygames.com/primedeal',
|
||||
};
|
||||
if (store in redeem) { // did not work for linked origin: && !await page.locator('div:has-text("Successfully Claimed")').count()
|
||||
let code;
|
||||
try {
|
||||
// ensure CTA was clicked in case code is behind it
|
||||
await clickCTA(page).catch(() => {});
|
||||
code = await Promise.any([
|
||||
page.inputValue('input[type="text"]'),
|
||||
page.textContent('[data-a-target="ClaimStateClaimCodeContent"]').then(s => s.replace('Your code: ', '')),
|
||||
]);
|
||||
} catch {
|
||||
console.error(' Could not find claim code on page (timeout). Please check manually.');
|
||||
db.data[user][title].status = 'claimed (code not found)';
|
||||
notify_game.status = 'claimed (code not found)';
|
||||
await page.screenshot({ path: screenshot('external', `${filenamify(title)}_nocode.png`), fullPage: true }).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
const code = await Promise.any([page.inputValue('input[type="text"]'), page.textContent('[data-a-target="ClaimStateClaimCodeContent"]').then(s => s.replace('Your code: ', ''))]); // input: Legacy Games; text: gog.com
|
||||
console.log(' Code to redeem game:', chalk.blue(code));
|
||||
if (store == 'legacy games') { // may be different URL like https://legacygames.com/primeday/puzzleoftheyear/
|
||||
redeem[store] = await (await page.$('li:has-text("Click here") a')).getAttribute('href'); // full text: Click here to enter your redemption code.
|
||||
|
|
@ -526,9 +229,13 @@ try {
|
|||
const page2 = await context.newPage();
|
||||
await page2.goto(redeem[store], { waitUntil: 'domcontentloaded' });
|
||||
if (store == 'gog.com') {
|
||||
// await page.goto(`https://redeem.gog.com/v1/bonusCodes/${code}`); // {"reason":"Invalid or no captcha"}
|
||||
await page2.fill('#codeInput', code);
|
||||
// wait for responses before clicking on Continue and then Redeem
|
||||
// first there are requests with OPTIONS and GET to https://redeem.gog.com/v1/bonusCodes/XYZ?language=de-DE
|
||||
const r1 = page2.waitForResponse(r => r.request().method() == 'GET' && r.url().startsWith('https://redeem.gog.com/'));
|
||||
await page2.click('[type="submit"]'); // click Continue
|
||||
// console.log(await page2.locator('.warning-message').innerText()); // does not exist if there is no warning
|
||||
const r1t = await (await r1).text();
|
||||
const reason = JSON.parse(r1t).reason;
|
||||
// {"reason":"Invalid or no captcha"}
|
||||
|
|
@ -543,9 +250,11 @@ try {
|
|||
} else if (reason == 'code_not_found') {
|
||||
redeem_action = 'redeem (not found)';
|
||||
console.error(' Code was not found!');
|
||||
} else { // unknown state; keep info log for later analysis
|
||||
} else { // TODO not logged in? need valid unused code to test.
|
||||
redeem_action = 'redeemed?';
|
||||
// console.log(' Redeemed successfully? Please report your Responses (if new) in https://github.com/vogler/free-games-claimer/issues/5');
|
||||
console.debug(` Response 1: ${r1t}`);
|
||||
// then after the click on Redeem there is a POST request which should return {} if claimed successfully
|
||||
const r2 = page2.waitForResponse(r => r.request().method() == 'POST' && r.url().startsWith('https://redeem.gog.com/'));
|
||||
await page2.click('[type="submit"]'); // click Redeem
|
||||
const r2t = await (await r2).text();
|
||||
|
|
@ -564,6 +273,7 @@ try {
|
|||
}
|
||||
} else if (store == 'microsoft store' || store == 'xbox') {
|
||||
console.error(` Redeem on ${store} is experimental!`);
|
||||
// await page2.pause();
|
||||
if (page2.url().startsWith('https://login.')) {
|
||||
console.error(' Not logged in! Please redeem the code above manually. You can now login in the browser for next time. Waiting for 60s.');
|
||||
await page2.waitForTimeout(60 * 1000);
|
||||
|
|
@ -574,7 +284,9 @@ try {
|
|||
await input.waitFor();
|
||||
await input.fill(code);
|
||||
const r = page2.waitForResponse(r => r.url().startsWith('https://cart.production.store-web.dynamics.com/v1.0/Redeem/PrepareRedeem'));
|
||||
// console.log(await page2.locator('.redeem_code_error').innerText());
|
||||
const rt = await (await r).text();
|
||||
// {"code":"NotFound","data":[],"details":[],"innererror":{"code":"TokenNotFound",...
|
||||
const j = JSON.parse(rt);
|
||||
const reason = j?.events?.cart.length && j.events.cart[0]?.data?.reason;
|
||||
if (reason == 'TokenNotFound') {
|
||||
|
|
@ -588,24 +300,26 @@ try {
|
|||
if (j?.events?.cart.length && j.events.cart[0]?.data?.reason == 'UserAlreadyOwnsContent') {
|
||||
redeem_action = 'already redeemed';
|
||||
console.error(' error: UserAlreadyOwnsContent');
|
||||
} else { // success path not seen yet; log below if needed
|
||||
} else if (true) { // TODO what's returned on success?
|
||||
redeem_action = 'redeemed';
|
||||
db.data[user][title].status = 'claimed and redeemed?';
|
||||
console.log(' Redeemed successfully? Please report if not in https://github.com/vogler/free-games-claimer/issues/5');
|
||||
}
|
||||
} else { // other responses; keep info log for analysis
|
||||
} else { // TODO find out other responses
|
||||
redeem_action = 'unknown';
|
||||
console.debug(` Response: ${rt}`);
|
||||
console.log(' Redeemed successfully? Please report your Response from above (if it is new) in https://github.com/vogler/free-games-claimer/issues/5');
|
||||
}
|
||||
}
|
||||
} else if (store == 'legacy games') {
|
||||
// await page2.pause();
|
||||
await page2.fill('[name=coupon_code]', code);
|
||||
await page2.fill('[name=email]', cfg.lg_email);
|
||||
await page2.fill('[name=email_validate]', cfg.lg_email);
|
||||
await page2.uncheck('[name=newsletter_sub]');
|
||||
await page2.click('[type="submit"]');
|
||||
try {
|
||||
// await page2.waitForResponse(r => r.url().startsWith('https://promo.legacygames.com/promotion-processing/order-management.php')); // status code 302
|
||||
await page2.waitForSelector('h2:has-text("Thanks for redeeming")');
|
||||
redeem_action = 'redeemed';
|
||||
db.data[user][title].status = 'claimed and redeemed';
|
||||
|
|
@ -626,18 +340,18 @@ try {
|
|||
notify_game.status = `claimed on ${store}`;
|
||||
db.data[user][title].status = 'claimed';
|
||||
}
|
||||
// save screenshot of potential code just in case
|
||||
await page.screenshot({ path: screenshot('external', `${filenamify(title)}.png`), fullPage: true });
|
||||
// console.info(' Saved a screenshot of page to', p);
|
||||
}
|
||||
// await page.pause();
|
||||
}
|
||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
|
||||
try {
|
||||
await page.click('button[data-type="Game"]');
|
||||
} catch {
|
||||
// ignore if filter already selected
|
||||
}
|
||||
|
||||
if (notify_games.length && games) { // make screenshot of all games if something was claimed and list exists
|
||||
if (notify_games.length) { // make screenshot of all games if something was claimed
|
||||
const p = screenshot(`${filenamify(datetime())}.png`);
|
||||
// await page.screenshot({ path: p, fullPage: true }); // fullPage does not make a difference since scroll not on body but on some element
|
||||
await scrollUntilStable(() => games.locator('.item-card__action').count());
|
||||
const viewportSize = page.viewportSize(); // current viewport size
|
||||
await page.setViewportSize({ ...viewportSize, height: 3000 }); // increase height, otherwise element screenshot is cut off at the top and bottom
|
||||
|
|
@ -652,7 +366,7 @@ try {
|
|||
await loot.waitFor();
|
||||
|
||||
process.stdout.write('Loading all DLCs on page...');
|
||||
await scrollUntilStable(() => loot.locator('[data-a-target="item-card"]').count());
|
||||
await scrollUntilStable(() => loot.locator('[data-a-target="item-card"]').count())
|
||||
|
||||
console.log('\nNumber of already claimed DLC:', await loot.locator('p:has-text("Collected")').count());
|
||||
|
||||
|
|
@ -680,36 +394,17 @@ try {
|
|||
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||
// most games have a button 'Get in-game content'
|
||||
// epic-games: Fall Guys: Claim -> Continue -> Go to Epic Games (despite account linked and logged into epic-games) -> not tied to account but via some cookie?
|
||||
const claimAndContinue = async () => {
|
||||
await page.click('.tw-button:has-text("Claim")');
|
||||
try {
|
||||
await page.click('button:has-text("Continue")');
|
||||
} catch {
|
||||
// continue button not always present
|
||||
}
|
||||
};
|
||||
|
||||
const claimOptions = [
|
||||
page.click('.tw-button:has-text("Get in-game content")'),
|
||||
page.click('.tw-button:has-text("Claim your gift")'),
|
||||
claimAndContinue(),
|
||||
];
|
||||
await Promise.any(claimOptions);
|
||||
try {
|
||||
await page.click('button:has-text("Continue")');
|
||||
} catch {
|
||||
// continue button not always present
|
||||
}
|
||||
await Promise.any([page.click('.tw-button:has-text("Get in-game content")'), page.click('.tw-button:has-text("Claim your gift")'), page.click('.tw-button:has-text("Claim")').then(() => page.click('button:has-text("Continue")'))]);
|
||||
page.click('button:has-text("Continue")').catch(_ => { });
|
||||
const linkAccountButton = page.locator('[data-a-target="LinkAccountButton"]');
|
||||
let unlinked_store;
|
||||
if (await linkAccountButton.count()) {
|
||||
unlinked_store = await linkAccountButton.first().getAttribute('aria-label');
|
||||
console.debug(' LinkAccountButton label:', unlinked_store);
|
||||
const match = unlinked_store?.match(/Link (.*) account/);
|
||||
const extracted = match?.[1];
|
||||
if (extracted) unlinked_store = extracted;
|
||||
const match = unlinked_store.match(/Link (.*) account/);
|
||||
if (match && match.length == 2) unlinked_store = match[1];
|
||||
} else if (await page.locator('text=Link game account').count()) { // epic-games only?
|
||||
console.error(' Missing account linking (epic-games specific button?):', await page.locator('button[data-a-target="gms-cta"]').innerText()); // track account-linking UI drift
|
||||
console.error(' Missing account linking (epic-games specific button?):', await page.locator('button[data-a-target="gms-cta"]').innerText()); // TODO needed?
|
||||
unlinked_store = 'epic-games';
|
||||
}
|
||||
if (unlinked_store) {
|
||||
|
|
@ -717,11 +412,13 @@ try {
|
|||
dlc_unlinked[unlinked_store] ??= [];
|
||||
dlc_unlinked[unlinked_store].push(title);
|
||||
} else {
|
||||
const code = await page.inputValue('input[type="text"]').catch(() => undefined);
|
||||
const code = await page.inputValue('input[type="text"]').catch(_ => undefined);
|
||||
console.log(' Code to redeem game:', chalk.blue(code));
|
||||
db.data[user][title].code = code;
|
||||
db.data[user][title].status = 'claimed';
|
||||
// notify_game.status = `<a href="${redeem[store]}">${redeem_action}</a> ${code} on ${store}`;
|
||||
}
|
||||
// await page.pause();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -7,11 +7,3 @@ sonar.sources=.
|
|||
|
||||
#Eslint issues
|
||||
sonar.eslint.reportPaths = eslint_report.json
|
||||
|
||||
# Ignore coverage and duplication requirements (community scan without reports)
|
||||
sonar.coverage.exclusions=**/*
|
||||
sonar.cpd.exclusions=**/*
|
||||
# Ignore "commented-out code" findings (javascript:S125) across the project
|
||||
sonar.issue.ignore.multicriteria=e1
|
||||
sonar.issue.ignore.multicriteria.e1.ruleKey=javascript:S125
|
||||
sonar.issue.ignore.multicriteria.e1.resourceKey=**/*
|
||||
|
|
|
|||
|
|
@ -1,159 +0,0 @@
|
|||
import { cfg } from './config.js';
|
||||
|
||||
const FLARESOLVERR_URL = process.env.FLARESOLVERR_URL || 'http://localhost:8191/v1';
|
||||
|
||||
/**
|
||||
* Check if FlareSolverr is available
|
||||
*/
|
||||
export const checkFlareSolverr = async () => {
|
||||
try {
|
||||
const response = await fetch(`${FLARESOLVERR_URL}/health`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
return response.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Solve Cloudflare challenge using FlareSolverr
|
||||
* @param {Object} page - Playwright page object
|
||||
* @param {string} url - The URL to visit
|
||||
* @returns {Promise<Object|null>} - Solution object with cookies and user agent
|
||||
*/
|
||||
export const solveCloudflare = async (page, url) => {
|
||||
try {
|
||||
console.log('🔍 Detecting Cloudflare challenge...');
|
||||
|
||||
// Check if FlareSolverr is available
|
||||
const flaresolverrUrl = cfg.flaresolverr_url || 'http://localhost:8191/v1';
|
||||
const healthResponse = await fetch(`${flaresolverrUrl}/health`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!healthResponse.ok) {
|
||||
console.warn('⚠️ FlareSolverr not available at', flaresolverrUrl);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Send request to FlareSolverr
|
||||
const response = await fetch(`${flaresolverrUrl}/request`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
cmd: 'request.get',
|
||||
url: url,
|
||||
maxTimeout: 60000,
|
||||
session: 'epic-games',
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status !== 'ok') {
|
||||
console.warn('FlareSolverr failed:', data.message);
|
||||
return null;
|
||||
}
|
||||
|
||||
const solution = data.solution;
|
||||
|
||||
// Apply cookies to the browser context
|
||||
const cookies = solution.cookies.map(cookie => ({
|
||||
name: cookie.name,
|
||||
value: cookie.value,
|
||||
domain: cookie.domain,
|
||||
path: cookie.path || '/',
|
||||
secure: cookie.secure,
|
||||
httpOnly: cookie.httpOnly,
|
||||
}));
|
||||
|
||||
// Get the browser context from the page
|
||||
const context = page.context();
|
||||
await context.addCookies(cookies);
|
||||
|
||||
console.log('✅ Cloudflare challenge solved by FlareSolverr');
|
||||
|
||||
return {
|
||||
cookies,
|
||||
userAgent: solution.userAgent,
|
||||
html: solution.html,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('FlareSolverr error:', error.message);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if Cloudflare challenge is present on the page
|
||||
* @param {Object} page - Playwright page object
|
||||
* @returns {Promise<boolean>} - True if Cloudflare challenge is detected
|
||||
*/
|
||||
export const isCloudflareChallenge = async page => {
|
||||
// Wait for page to be in a stable state before checking
|
||||
try {
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 5000 });
|
||||
} catch {
|
||||
// Page might still be loading, continue anyway
|
||||
}
|
||||
|
||||
// Check for Cloudflare iframe - wrap in try-catch to avoid frame race conditions
|
||||
try {
|
||||
const cfFrame = page.locator('iframe[title*="Cloudflare"], iframe[src*="challenges"]');
|
||||
if (await cfFrame.count() > 0) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// Frame access failed, ignore
|
||||
}
|
||||
|
||||
// Check for Cloudflare text - wrap in try-catch
|
||||
try {
|
||||
const cfText = page.locator('text=Verify you are human, text=Checking your browser');
|
||||
if (await cfText.count() > 0) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// Locator failed, ignore
|
||||
}
|
||||
|
||||
// Check for specific Cloudflare URLs
|
||||
try {
|
||||
const url = page.url();
|
||||
if (url.includes('cloudflare') || url.includes('challenges')) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// URL access failed, ignore
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wait for Cloudflare challenge to be solved
|
||||
* @param {Object} page - Playwright page object
|
||||
* @param {number} timeout - Timeout in milliseconds
|
||||
* @returns {Promise<boolean>} - True if challenge is solved
|
||||
*/
|
||||
export const waitForCloudflareSolved = async (page, timeout = 60000) => {
|
||||
const startTime = Date.now();
|
||||
|
||||
while (Date.now() - startTime < timeout) {
|
||||
if (!await isCloudflareChallenge(page)) {
|
||||
return true;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
|
@ -15,12 +15,10 @@ export const cfg = {
|
|||
get headless() {
|
||||
return !this.debug && !this.show;
|
||||
},
|
||||
eg_mode: process.env.EG_MODE || 'legacy', // epic-games: legacy playwright flow or 'new' API-driven flow
|
||||
width: Number(process.env.WIDTH) || 1920, // width of the opened browser
|
||||
height: Number(process.env.HEIGHT) || 1080, // height of the opened browser
|
||||
timeout: (Number(process.env.TIMEOUT) || 60) * 1000, // default timeout for playwright is 30s
|
||||
login_timeout: (Number(process.env.LOGIN_TIMEOUT) || 180) * 1000, // higher timeout for login, will wait twice: prompt + wait for manual login
|
||||
login_visible_timeout: (Number(process.env.LOGIN_VISIBLE_TIMEOUT) || 20) * 1000, // how long to wait for login button/user indicator to appear
|
||||
novnc_port: process.env.NOVNC_PORT, // running in docker if set
|
||||
notify: process.env.NOTIFY, // apprise notification services
|
||||
notify_title: process.env.NOTIFY_TITLE, // apprise notification title
|
||||
|
|
@ -35,11 +33,6 @@ export const cfg = {
|
|||
eg_password: process.env.EG_PASSWORD || process.env.PASSWORD,
|
||||
eg_otpkey: process.env.EG_OTPKEY,
|
||||
eg_parentalpin: process.env.EG_PARENTALPIN,
|
||||
// Device Auth (OAuth Device Flow - bypasses Cloudflare)
|
||||
deviceAuthClientId: process.env.EG_DEVICE_CLIENT_ID || process.env.DEVICE_CLIENT_ID || '3446cd72e193480d93d518c247381aba',
|
||||
deviceAuthSecret: process.env.EG_DEVICE_SECRET || process.env.DEVICE_SECRET || '7s62PokZ6yVfhsWYxIAfDn7nR38d7P6l',
|
||||
// Cloudflare bypass
|
||||
flaresolverr_url: process.env.FLARESOLVERR_URL || 'http://localhost:8191/v1',
|
||||
// auth prime-gaming
|
||||
pg_email: process.env.PG_EMAIL || process.env.EMAIL,
|
||||
pg_password: process.env.PG_PASSWORD || process.env.PASSWORD,
|
||||
|
|
|
|||
|
|
@ -1,43 +0,0 @@
|
|||
// Epic Games API Constants
|
||||
// Based on https://github.com/claabs/epicgames-freegames-node
|
||||
|
||||
export const EPIC_CLIENT_ID = '875a3b57d3a640a6b7f9b4e883463ab4';
|
||||
export const CSRF_ENDPOINT = 'https://www.epicgames.com/id/api/csrf';
|
||||
export const ACCOUNT_CSRF_ENDPOINT = 'https://www.epicgames.com/account/v2/refresh-csrf';
|
||||
export const ACCOUNT_SESSION_ENDPOINT = 'https://www.epicgames.com/account/personal';
|
||||
export const LOGIN_ENDPOINT = 'https://www.epicgames.com/id/api/login';
|
||||
export const REDIRECT_ENDPOINT = 'https://www.epicgames.com/id/api/redirect';
|
||||
export const GRAPHQL_ENDPOINT = 'https://store.epicgames.com/graphql';
|
||||
export const ARKOSE_BASE_URL = 'https://epic-games-api.arkoselabs.com';
|
||||
export const CHANGE_EMAIL_ENDPOINT = 'https://www.epicgames.com/account/v2/api/email/change';
|
||||
export const USER_INFO_ENDPOINT = 'https://www.epicgames.com/account/v2/personal/ajaxGet';
|
||||
export const RESEND_VERIFICATION_ENDPOINT = 'https://www.epicgames.com/account/v2/resendEmailVerification';
|
||||
export const REPUTATION_ENDPOINT = 'https://www.epicgames.com/id/api/reputation';
|
||||
export const STORE_CONTENT = 'https://store-content-ipv4.ak.epicgames.com/api/en-US/content';
|
||||
export const EMAIL_VERIFY = 'https://www.epicgames.com/id/api/email/verify';
|
||||
export const SETUP_MFA = 'https://www.epicgames.com/account/v2/security/ajaxUpdateTwoFactorAuthSettings';
|
||||
export const FREE_GAMES_PROMOTIONS_ENDPOINT = 'https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions';
|
||||
export const STORE_HOMEPAGE = 'https://store.epicgames.com/';
|
||||
export const STORE_HOMEPAGE_EN = `${STORE_HOMEPAGE}en-US/`;
|
||||
export const STORE_CART_EN = `${STORE_HOMEPAGE}en-US/cart`;
|
||||
export const ORDER_CONFIRM_ENDPOINT = 'https://payment-website-pci.ol.epicgames.com/purchase/confirm-order';
|
||||
export const ORDER_PREVIEW_ENDPOINT = 'https://payment-website-pci.ol.epicgames.com/purchase/order-preview';
|
||||
export const EPIC_PURCHASE_ENDPOINT = 'https://www.epicgames.com/store/purchase';
|
||||
export const MFA_LOGIN_ENDPOINT = 'https://www.epicgames.com/id/api/login/mfa';
|
||||
export const UNREAL_SET_SID_ENDPOINT = 'https://www.unrealengine.com/id/api/set-sid';
|
||||
export const TWINMOTION_SET_SID_ENDPOINT = 'https://www.twinmotion.com/id/api/set-sid';
|
||||
export const CLIENT_REDIRECT_ENDPOINT = `https://www.epicgames.com/id/api/client/${EPIC_CLIENT_ID}`;
|
||||
export const AUTHENTICATE_ENDPOINT = 'https://www.epicgames.com/id/api/authenticate';
|
||||
export const LOCATION_ENDPOINT = 'https://www.epicgames.com/id/api/location';
|
||||
export const PHASER_F_ENDPOINT = 'https://talon-service-prod.ak.epicgames.com/v1/phaser/f';
|
||||
export const PHASER_BATCH_ENDPOINT = 'https://talon-service-prod.ak.epicgames.com/v1/phaser/batch';
|
||||
export const TALON_IP_ENDPOINT = 'https://talon-service-v4-prod.ak.epicgames.com/v1/init/ip';
|
||||
export const TALON_INIT_ENDPOINT = 'https://talon-service-prod.ak.epicgames.com/v1/init';
|
||||
export const TALON_EXECUTE_ENDPOINT = 'https://talon-service-v4-prod.ak.epicgames.com/v1/init/execute';
|
||||
export const TALON_WEBSITE_BASE = 'https://talon-website-prod.ak.epicgames.com';
|
||||
export const TALON_REFERRER = 'https://talon-website-prod.ak.epicgames.com/challenge?env=prod&flow=login_prod&origin=https%3A%2F%2Fwww.epicgames.com';
|
||||
export const ACCOUNT_OAUTH_TOKEN = 'https://account-public-service-prod.ol.epicgames.com/account/api/oauth/token';
|
||||
export const ACCOUNT_OAUTH_DEVICE_AUTH = 'https://account-public-service-prod.ol.epicgames.com/account/api/oauth/deviceAuthorization';
|
||||
export const ID_LOGIN_ENDPOINT = 'https://www.epicgames.com/id/login';
|
||||
export const EULA_AGREEMENTS_ENDPOINT = 'https://eulatracking-public-service-prod-m.ol.epicgames.com/eulatracking/api/public/agreements';
|
||||
export const REQUIRED_EULAS = ['epicgames_privacy_policy_no_table', 'egstore'];
|
||||
148
src/cookie.js
148
src/cookie.js
|
|
@ -1,148 +0,0 @@
|
|||
// Cookie management for Epic Games
|
||||
// Based on https://github.com/claabs/epicgames-freegames-node
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import tough from 'tough-cookie';
|
||||
import { filenamify } from './util.js';
|
||||
import { dataDir } from './util.js';
|
||||
|
||||
const CONFIG_DIR = dataDir('config');
|
||||
const DEFAULT_COOKIE_NAME = 'default';
|
||||
|
||||
// Ensure config directory exists
|
||||
if (!fs.existsSync(CONFIG_DIR)) {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function getCookiePath(username) {
|
||||
const fileSafeUsername = filenamify(username);
|
||||
const cookieFilename = path.join(CONFIG_DIR, `${fileSafeUsername}-cookies.json`);
|
||||
return cookieFilename;
|
||||
}
|
||||
|
||||
// Cookie whitelist - only these cookies are stored
|
||||
const COOKIE_WHITELIST = ['EPIC_SSO_RM', 'EPIC_SESSION_AP', 'EPIC_DEVICE'];
|
||||
|
||||
// Cookie jar cache
|
||||
const cookieJars = new Map();
|
||||
|
||||
function getCookieJar(username) {
|
||||
let cookieJar = cookieJars.get(username);
|
||||
if (cookieJar) {
|
||||
return cookieJar;
|
||||
}
|
||||
cookieJar = new tough.CookieJar();
|
||||
cookieJars.set(username, cookieJar);
|
||||
return cookieJar;
|
||||
}
|
||||
|
||||
// Convert EditThisCookie format to tough-cookie file store format
|
||||
export function editThisCookieToToughCookieFileStore(etc) {
|
||||
const tcfs = {};
|
||||
|
||||
etc.forEach(etcCookie => {
|
||||
const domain = etcCookie.domain.replace(/^\./, '');
|
||||
const expires = etcCookie.expirationDate
|
||||
? new Date(etcCookie.expirationDate * 1000).toISOString()
|
||||
: undefined;
|
||||
const { path: cookiePath, name } = etcCookie;
|
||||
|
||||
if (COOKIE_WHITELIST.includes(name)) {
|
||||
const temp = {
|
||||
[domain]: {
|
||||
[cookiePath]: {
|
||||
[name]: {
|
||||
key: name,
|
||||
value: etcCookie.value,
|
||||
expires,
|
||||
domain,
|
||||
path: cookiePath,
|
||||
secure: etcCookie.secure,
|
||||
httpOnly: etcCookie.httpOnly,
|
||||
hostOnly: etcCookie.hostOnly,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
Object.assign(tcfs, temp);
|
||||
}
|
||||
});
|
||||
|
||||
return tcfs;
|
||||
}
|
||||
|
||||
// Get cookies as simple object
|
||||
export function getCookies(username) {
|
||||
const cookieJar = getCookieJar(username);
|
||||
const cookies = cookieJar.toJSON()?.cookies || [];
|
||||
return cookies.reduce((accum, cookie) => {
|
||||
if (cookie.key && cookie.value) {
|
||||
return { ...accum, [cookie.key]: cookie.value };
|
||||
}
|
||||
return accum;
|
||||
}, {});
|
||||
}
|
||||
|
||||
// Get raw cookies in tough-cookie file store format
|
||||
export async function getCookiesRaw(username) {
|
||||
const cookieFilename = getCookiePath(username);
|
||||
try {
|
||||
const existingCookies = JSON.parse(fs.readFileSync(cookieFilename, 'utf8'));
|
||||
return existingCookies;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
// Set cookies from Playwright/Cookie format
|
||||
export async function setPuppeteerCookies(username, newCookies) {
|
||||
const cookieJar = getCookieJar(username);
|
||||
|
||||
for (const cookie of newCookies) {
|
||||
const domain = cookie.domain.replace(/^\./, '');
|
||||
const tcfsCookie = new tough.Cookie({
|
||||
key: cookie.name,
|
||||
value: cookie.value,
|
||||
expires: cookie.expires ? new Date(cookie.expires * 1000) : undefined,
|
||||
domain,
|
||||
path: cookie.path,
|
||||
secure: cookie.secure,
|
||||
httpOnly: cookie.httpOnly,
|
||||
hostOnly: !cookie.domain.startsWith('.'),
|
||||
});
|
||||
|
||||
try {
|
||||
await cookieJar.setCookie(tcfsCookie, `https://${domain}`);
|
||||
} catch (err) {
|
||||
console.error('Error setting cookie:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete cookies for a user
|
||||
export async function deleteCookies(username) {
|
||||
const cookieFilename = getCookiePath(username || DEFAULT_COOKIE_NAME);
|
||||
try {
|
||||
fs.unlinkSync(cookieFilename);
|
||||
} catch {
|
||||
// File doesn't exist, that's fine
|
||||
}
|
||||
}
|
||||
|
||||
// Check if user has a valid cookie
|
||||
export async function userHasValidCookie(username, cookieName) {
|
||||
const cookieFilename = getCookiePath(username);
|
||||
try {
|
||||
const fileExists = fs.existsSync(cookieFilename);
|
||||
if (!fileExists) return false;
|
||||
|
||||
const cookieData = JSON.parse(fs.readFileSync(cookieFilename, 'utf8'));
|
||||
const rememberCookieExpireDate = cookieData['epicgames.com']?.['/']?.[cookieName]?.expires;
|
||||
if (!rememberCookieExpireDate) return false;
|
||||
|
||||
return new Date(rememberCookieExpireDate) > new Date();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
// Device authentication management for Epic Games
|
||||
// Based on https://github.com/claabs/epicgames-freegames-node
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { dataDir } from './util.js';
|
||||
|
||||
const CONFIG_DIR = dataDir('config');
|
||||
const deviceAuthsFilename = path.join(CONFIG_DIR, 'device-auths.json');
|
||||
|
||||
// Ensure config directory exists
|
||||
if (!fs.existsSync(CONFIG_DIR)) {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
export async function getDeviceAuths() {
|
||||
try {
|
||||
const deviceAuths = JSON.parse(fs.readFileSync(deviceAuthsFilename, 'utf-8'));
|
||||
return deviceAuths;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAccountAuth(account) {
|
||||
const deviceAuths = await getDeviceAuths();
|
||||
return deviceAuths?.[account];
|
||||
}
|
||||
|
||||
export async function writeDeviceAuths(deviceAuths) {
|
||||
fs.writeFileSync(deviceAuthsFilename, JSON.stringify(deviceAuths, null, 2));
|
||||
}
|
||||
|
||||
export async function setAccountAuth(account, accountAuth) {
|
||||
const existingDeviceAuths = await getDeviceAuths() ?? {};
|
||||
existingDeviceAuths[account] = accountAuth;
|
||||
await writeDeviceAuths(existingDeviceAuths);
|
||||
}
|
||||
|
|
@ -1,217 +0,0 @@
|
|||
import axios from 'axios';
|
||||
import { cfg } from './config.js';
|
||||
import { getAccountAuth, setAccountAuth } from './device-auths.js';
|
||||
import { ACCOUNT_OAUTH_TOKEN, ACCOUNT_OAUTH_DEVICE_AUTH } from './constants.js';
|
||||
import logger from './logger.js';
|
||||
|
||||
const L = logger.child({ module: 'device-login' });
|
||||
|
||||
/**
|
||||
* Epic Games OAuth Device Flow Login
|
||||
* This bypasses Cloudflare by using the official OAuth device authorization flow.
|
||||
* User gets a notification with a link to login in their own browser.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get client credentials token from Epic OAuth API
|
||||
*/
|
||||
async function getClientCredentialsToken() {
|
||||
L.trace('Getting client credentials token');
|
||||
|
||||
const resp = await axios.post(
|
||||
ACCOUNT_OAUTH_TOKEN,
|
||||
new URLSearchParams({ grant_type: 'client_credentials' }),
|
||||
{
|
||||
auth: {
|
||||
username: cfg.deviceAuthClientId || '3446cd72e193480d93d518c247381aba',
|
||||
password: cfg.deviceAuthSecret || '7s62PokZ6yVfhsWYxIAfDn7nR38d7P6l',
|
||||
},
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
},
|
||||
);
|
||||
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get device authorization code with verification URL
|
||||
*/
|
||||
async function getDeviceAuthorizationCode(clientCredentialsToken) {
|
||||
L.trace('Getting device authorization verification URL');
|
||||
|
||||
const resp = await axios.post(
|
||||
ACCOUNT_OAUTH_DEVICE_AUTH,
|
||||
new URLSearchParams({ prompt: 'login' }),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${clientCredentialsToken}`,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll for device authorization completion
|
||||
*/
|
||||
async function waitForDeviceAuthorization(deviceCode, expiresAt, interval) {
|
||||
const now = new Date();
|
||||
|
||||
if (expiresAt < now) {
|
||||
throw new Error('Device code login expired');
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await axios.post(
|
||||
ACCOUNT_OAUTH_TOKEN,
|
||||
new URLSearchParams({
|
||||
grant_type: 'device_code',
|
||||
device_code: deviceCode,
|
||||
}),
|
||||
{
|
||||
auth: {
|
||||
username: cfg.deviceAuthClientId || '3446cd72e193480d93d518c247381aba',
|
||||
password: cfg.deviceAuthSecret || '7s62PokZ6yVfhsWYxIAfDn7nR38d7P6l',
|
||||
},
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
},
|
||||
);
|
||||
|
||||
return resp.data;
|
||||
} catch (err) {
|
||||
if (!axios.isAxiosError(err)) {
|
||||
throw new Error('Unable to get device authorization token');
|
||||
}
|
||||
|
||||
// Check if still pending authorization
|
||||
if (err.response?.data?.errorCode !== 'errors.com.epicgames.account.oauth.authorization_pending') {
|
||||
L.error({ err, response: err.response?.data }, 'Authorization failed');
|
||||
throw new Error('Unable to get device authorization token');
|
||||
}
|
||||
|
||||
// Wait and retry
|
||||
await new Promise(resolve => setTimeout(resolve, interval * 1000));
|
||||
return waitForDeviceAuthorization(deviceCode, expiresAt, interval);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh existing device auth token
|
||||
*/
|
||||
export async function refreshDeviceAuth(user) {
|
||||
try {
|
||||
const existingAuth = await getAccountAuth(user);
|
||||
|
||||
if (!(existingAuth && new Date(existingAuth.refresh_expires_at) > new Date())) {
|
||||
L.trace('No valid refresh token available');
|
||||
return false;
|
||||
}
|
||||
|
||||
L.trace('Refreshing device auth token');
|
||||
|
||||
const resp = await axios.post(
|
||||
ACCOUNT_OAUTH_TOKEN,
|
||||
new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: existingAuth.refresh_token,
|
||||
}),
|
||||
{
|
||||
auth: {
|
||||
username: cfg.deviceAuthClientId || '3446cd72e193480d93d518c247381aba',
|
||||
password: cfg.deviceAuthSecret || '7s62PokZ6yVfhsWYxIAfDn7nR38d7P6l',
|
||||
},
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
},
|
||||
);
|
||||
|
||||
await setAccountAuth(user, resp.data);
|
||||
L.info('Device auth token refreshed successfully');
|
||||
return true;
|
||||
} catch (err) {
|
||||
L.warn({ err }, 'Failed to refresh device auth');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start new device auth login flow
|
||||
* Returns the verification URL that user needs to visit
|
||||
*/
|
||||
export async function startDeviceAuthLogin(user) {
|
||||
L.info({ user }, 'Starting device auth login flow');
|
||||
|
||||
// Get client credentials
|
||||
const clientCreds = await getClientCredentialsToken();
|
||||
|
||||
// Get device authorization code
|
||||
const deviceAuth = await getDeviceAuthorizationCode(clientCreds.access_token);
|
||||
|
||||
// Calculate expiry time
|
||||
const expiresAt = new Date();
|
||||
expiresAt.setSeconds(expiresAt.getSeconds() + deviceAuth.expires_in);
|
||||
|
||||
L.info({
|
||||
userCode: deviceAuth.user_code,
|
||||
verificationUrl: deviceAuth.verification_uri_complete,
|
||||
expiresAt,
|
||||
}, 'Device auth initiated - user must visit verification URL');
|
||||
|
||||
return {
|
||||
verificationUrl: deviceAuth.verification_uri_complete,
|
||||
userCode: deviceAuth.user_code,
|
||||
expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete device auth login by polling for authorization
|
||||
*/
|
||||
export async function completeDeviceAuthLogin(deviceCode, expiresAt, interval) {
|
||||
L.info('Waiting for user to complete authorization...');
|
||||
|
||||
const authToken = await waitForDeviceAuthorization(deviceCode, expiresAt, interval);
|
||||
|
||||
// Save the auth token
|
||||
await setAccountAuth('default', authToken);
|
||||
|
||||
L.info({ accountId: authToken.account_id }, 'Device auth login completed successfully');
|
||||
|
||||
return authToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get valid access token, refreshing if necessary
|
||||
*/
|
||||
export async function getValidAccessToken(user) {
|
||||
const existingAuth = await getAccountAuth(user);
|
||||
|
||||
if (!existingAuth) {
|
||||
L.trace('No existing auth found');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if access token is still valid (with 5 minute buffer)
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(existingAuth.expires_at);
|
||||
const bufferMs = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
if (expiresAt.getTime() > now.getTime() + bufferMs) {
|
||||
L.trace('Access token still valid');
|
||||
return existingAuth.access_token;
|
||||
}
|
||||
|
||||
// Try to refresh
|
||||
L.trace('Access token expired, attempting refresh');
|
||||
const refreshed = await refreshDeviceAuth(user);
|
||||
|
||||
if (refreshed) {
|
||||
const refreshedAuth = await getAccountAuth(user);
|
||||
return refreshedAuth?.access_token || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export { getClientCredentialsToken, getDeviceAuthorizationCode };
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
/**
|
||||
* Simple logger for free-games-claimer
|
||||
*/
|
||||
|
||||
const LOG_LEVELS = {
|
||||
trace: 0,
|
||||
debug: 1,
|
||||
info: 2,
|
||||
warn: 3,
|
||||
error: 4,
|
||||
};
|
||||
|
||||
const currentLevel = process.env.LOG_LEVEL
|
||||
? LOG_LEVELS[process.env.LOG_LEVEL.toLowerCase()]
|
||||
: LOG_LEVELS.info;
|
||||
|
||||
function formatMessage(level, module, message, data) {
|
||||
const timestamp = new Date().toISOString();
|
||||
const moduleStr = module ? `[${module}] ` : '';
|
||||
const dataStr = data && Object.keys(data).length > 0 ? ' ' + JSON.stringify(data) : '';
|
||||
return `${timestamp} ${level.toUpperCase().padEnd(5)} ${moduleStr}${message}${dataStr}`;
|
||||
}
|
||||
|
||||
function createLogger(module) {
|
||||
return {
|
||||
trace: (dataOrMessage, message) => {
|
||||
if (currentLevel <= LOG_LEVELS.trace) {
|
||||
const [data, msg] = typeof dataOrMessage === 'string' ? [null, dataOrMessage] : [dataOrMessage, message];
|
||||
console.log(formatMessage('trace', module, msg || '', data));
|
||||
}
|
||||
},
|
||||
debug: (dataOrMessage, message) => {
|
||||
if (currentLevel <= LOG_LEVELS.debug) {
|
||||
const [data, msg] = typeof dataOrMessage === 'string' ? [null, dataOrMessage] : [dataOrMessage, message];
|
||||
console.log(formatMessage('debug', module, msg || '', data));
|
||||
}
|
||||
},
|
||||
info: (dataOrMessage, message) => {
|
||||
if (currentLevel <= LOG_LEVELS.info) {
|
||||
const [data, msg] = typeof dataOrMessage === 'string' ? [null, dataOrMessage] : [dataOrMessage, message];
|
||||
console.log(formatMessage('info', module, msg || '', data));
|
||||
}
|
||||
},
|
||||
warn: (dataOrMessage, message) => {
|
||||
if (currentLevel <= LOG_LEVELS.warn) {
|
||||
const [data, msg] = typeof dataOrMessage === 'string' ? [null, dataOrMessage] : [dataOrMessage, message];
|
||||
console.log(formatMessage('warn', module, msg || '', data));
|
||||
}
|
||||
},
|
||||
error: (dataOrMessage, message) => {
|
||||
if (currentLevel <= LOG_LEVELS.error) {
|
||||
const [data, msg] = typeof dataOrMessage === 'string' ? [null, dataOrMessage] : [dataOrMessage, message];
|
||||
console.log(formatMessage('error', module, msg || '', data));
|
||||
}
|
||||
},
|
||||
child: childData => {
|
||||
const childModule = childData?.module || module;
|
||||
return createLogger(childModule);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const logger = createLogger('root');
|
||||
export default logger;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { existsSync } from 'node:fs';
|
||||
import { existsSync } from 'fs';
|
||||
import { Low } from 'lowdb';
|
||||
import { JSONFile } from 'lowdb/node';
|
||||
import { datetime } from './util.js';
|
||||
|
|
@ -18,6 +18,7 @@ const datetime_UTCtoLocalTimezone = async file => {
|
|||
db.data[user][game].time = time2;
|
||||
}
|
||||
}
|
||||
// console.log(db.data);
|
||||
await db.write(); // write out json db
|
||||
};
|
||||
|
||||
|
|
|
|||
46
src/util.js
46
src/util.js
|
|
@ -19,9 +19,7 @@ export const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|||
export const datetimeUTC = (d = new Date()) => d.toISOString().replace('T', ' ').replace('Z', '');
|
||||
// same as datetimeUTC() but for local timezone, e.g., UTC + 2h for the above in DE
|
||||
export const datetime = (d = new Date()) => datetimeUTC(new Date(d.getTime() - d.getTimezoneOffset() * 60000));
|
||||
export const filenamify = s => s
|
||||
.replaceAll(':', '.')
|
||||
.replaceAll(/[^a-z0-9 _\-.]/gi, '_'); // alternative: https://www.npmjs.com/package/filenamify - On Unix-like systems, / is reserved. On Windows, <>:"/\|?* along with trailing periods are reserved.
|
||||
export const filenamify = s => s.replaceAll(':', '.').replace(/[^a-z0-9 _\-.]/gi, '_'); // alternative: https://www.npmjs.com/package/filenamify - On Unix-like systems, / is reserved. On Windows, <>:"/\|?* along with trailing periods are reserved.
|
||||
|
||||
export const handleSIGINT = (context = null) => process.on('SIGINT', async () => { // e.g. when killed by Ctrl-C
|
||||
console.error('\nInterrupted by SIGINT. Exit!'); // Exception shows where the script was:\n'); // killed before catch in docker...
|
||||
|
|
@ -92,50 +90,42 @@ export const stealth = async context => {
|
|||
// alternative inquirer is big (node_modules 29MB, enquirer 9.7MB, prompts 9.8MB, none 9.4MB) and slower
|
||||
// open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372
|
||||
import Enquirer from 'enquirer'; const enquirer = new Enquirer();
|
||||
const timeoutHint = () => 'timeout';
|
||||
const cancelPromptWithHint = prompt => {
|
||||
prompt.hint = timeoutHint;
|
||||
const timeoutPlugin = timeout => enquirer => { // cancel prompt after timeout ms
|
||||
enquirer.on('prompt', prompt => {
|
||||
const t = setTimeout(() => {
|
||||
prompt.hint = () => 'timeout';
|
||||
prompt.cancel();
|
||||
}, timeout);
|
||||
prompt.on('submit', _ => clearTimeout(t));
|
||||
prompt.on('cancel', _ => clearTimeout(t));
|
||||
});
|
||||
};
|
||||
const applyPromptTimeout = (prompt, timeout) => {
|
||||
if (!timeout) return;
|
||||
const timer = setTimeout(cancelPromptWithHint, timeout, prompt);
|
||||
const clearTimer = () => clearTimeout(timer);
|
||||
prompt.on('submit', clearTimer);
|
||||
prompt.on('cancel', clearTimer);
|
||||
};
|
||||
// cancel prompt after timeout ms; can be disabled per prompt via options.timeout = 0
|
||||
const timeoutPlugin = defaultTimeout => enquirerInstance => {
|
||||
const onPrompt = prompt => applyPromptTimeout(prompt, prompt.options?.timeout ?? defaultTimeout);
|
||||
enquirerInstance.on('prompt', onPrompt);
|
||||
};
|
||||
enquirer.use(timeoutPlugin(cfg.login_timeout));
|
||||
enquirer.use(timeoutPlugin(cfg.login_timeout)); // TODO may not want to have this timeout for all prompts; better extend Prompt and add a timeout prompt option
|
||||
// single prompt that just returns the non-empty value instead of an object
|
||||
// @ts-ignore
|
||||
export const prompt = o => enquirer.prompt({ name: 'name', type: 'input', message: 'Enter value', ...o }).then(r => r.name).catch(() => {});
|
||||
export const prompt = o => enquirer.prompt({ name: 'name', type: 'input', message: 'Enter value', ...o }).then(r => r.name).catch(_ => {});
|
||||
export const confirm = o => prompt({ type: 'confirm', message: 'Continue?', ...o });
|
||||
|
||||
// notifications via apprise CLI
|
||||
import { execFile } from 'node:child_process';
|
||||
import { execFile } from 'child_process';
|
||||
import { cfg } from './config.js';
|
||||
|
||||
export const notify = html => new Promise(resolve => {
|
||||
export const notify = html => new Promise((resolve, reject) => {
|
||||
if (!cfg.notify) {
|
||||
if (cfg.debug) console.debug('notify: NOTIFY is not set!');
|
||||
return resolve();
|
||||
}
|
||||
const appriseBin = process.env.APPRISE_BIN || '/usr/local/bin/apprise';
|
||||
// const cmd = `apprise '${cfg.notify}' ${title} -i html -b '${html}'`; // this had problems if e.g. ' was used in arg; could have `npm i shell-escape`, but instead using safer execFile which takes args as array instead of exec which spawned a shell to execute the command
|
||||
const args = [cfg.notify, '-i', 'html', '-b', `'${html}'`];
|
||||
if (cfg.notify_title) args.push('-t', cfg.notify_title);
|
||||
if (cfg.debug) console.debug(`${appriseBin} ${args.join(' ')}`); // this also doesn't escape, but it's just for info
|
||||
execFile(appriseBin, args, (error, stdout, stderr) => {
|
||||
if (cfg.notify_title) args.push(...['-t', cfg.notify_title]);
|
||||
if (cfg.debug) console.debug(`apprise ${args.map(a => `'${a}'`).join(' ')}`); // this also doesn't escape, but it's just for info
|
||||
execFile('apprise', args, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log(`error: ${error.message}`);
|
||||
if (error.message.includes('command not found')) {
|
||||
console.info('Run `pip install apprise`. See https://github.com/vogler/free-games-claimer#notifications');
|
||||
}
|
||||
// don't fail the whole run on notification errors
|
||||
return resolve();
|
||||
return reject(error);
|
||||
}
|
||||
if (stderr) console.error(`stderr: ${stderr}`);
|
||||
if (stdout) console.log(`stdout: ${stdout}`);
|
||||
|
|
|
|||
|
|
@ -1,14 +1,15 @@
|
|||
import { log } from 'node:console';
|
||||
import { execFile } from 'node:child_process';
|
||||
// check if running the latest version
|
||||
|
||||
const gitBin = process.env.GIT_BIN || '/usr/bin/git';
|
||||
import { log } from 'console';
|
||||
import { exec } from 'child_process';
|
||||
|
||||
const runGit = (...args) => new Promise((resolve, reject) => {
|
||||
execFile(gitBin, args, { cwd: process.cwd() }, (error, stdout, stderr) => {
|
||||
const execp = cmd => new Promise((resolve, reject) => {
|
||||
exec(cmd, (error, stdout, stderr) => {
|
||||
if (stderr) console.error(`stderr: ${stderr}`);
|
||||
// if (stdout) console.log(`stdout: ${stdout}`);
|
||||
if (error) {
|
||||
console.log(`error: ${error.message}`);
|
||||
if (error.code === 'ENOENT' || error.message.includes('command not found')) {
|
||||
if (error.message.includes('command not found')) {
|
||||
console.info('Install git to check for updates!');
|
||||
}
|
||||
return reject(error);
|
||||
|
|
@ -17,7 +18,10 @@ const runGit = (...args) => new Promise((resolve, reject) => {
|
|||
});
|
||||
});
|
||||
|
||||
// const git_main = () => readFileSync('.git/refs/heads/main').toString().trim();
|
||||
|
||||
let sha, date;
|
||||
// if (existsSync('/.dockerenv')) { // did not work
|
||||
if (process.env.NOVNC_PORT) {
|
||||
log('Running inside Docker.');
|
||||
['COMMIT', 'BRANCH', 'NOW'].forEach(v => log(` ${v}:`, process.env[v]));
|
||||
|
|
@ -25,15 +29,24 @@ if (process.env.NOVNC_PORT) {
|
|||
date = process.env.NOW;
|
||||
} else {
|
||||
log('Not running inside Docker.');
|
||||
sha = await runGit('rev-parse', 'HEAD');
|
||||
date = await runGit('show', '-s', '--format=%cD'); // same as format as `date -R` (RFC2822)
|
||||
sha = await execp('git rev-parse HEAD');
|
||||
date = await execp('git show -s --format=%cD'); // same as format as `date -R` (RFC2822)
|
||||
// date = await execp('git show -s --format=%ch'); // %ch is same as --date=human (short/relative)
|
||||
}
|
||||
|
||||
const gh = await (await fetch('https://api.github.com/repos/vogler/free-games-claimer/commits/main')).json();
|
||||
const gh = await (await fetch('https://api.github.com/repos/vogler/free-games-claimer/commits/main', {
|
||||
// headers: { accept: 'application/vnd.github.VERSION.sha' }
|
||||
})).json();
|
||||
// log(gh);
|
||||
|
||||
log('Local commit:', sha, new Date(date));
|
||||
log('Online commit:', gh.sha, new Date(gh.commit.committer.date));
|
||||
|
||||
// git describe --all --long --dirty
|
||||
// --> heads/main-0-gdee47d2-dirty
|
||||
// git describe --tags --long --dirty
|
||||
// --> v1.7-35-gdee47d2-dirty
|
||||
|
||||
if (sha == gh.sha) {
|
||||
log('Running the latest version!');
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -12,12 +12,13 @@ import { FingerprintInjector } from 'fingerprint-injector';
|
|||
import { FingerprintGenerator } from 'fingerprint-generator';
|
||||
|
||||
const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({
|
||||
devices: ['desktop'],
|
||||
operatingSystems: ['windows'],
|
||||
devices: ["desktop"],
|
||||
operatingSystems: ["windows"],
|
||||
});
|
||||
|
||||
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||
headless: cfg.headless,
|
||||
// viewport: { width: cfg.width, height: cfg.height },
|
||||
locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL
|
||||
userAgent: fingerprint.navigator.userAgent,
|
||||
viewport: {
|
||||
|
|
@ -28,6 +29,7 @@ const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
|||
'accept-language': headers['accept-language'],
|
||||
},
|
||||
});
|
||||
// await stealth(context);
|
||||
await new FingerprintInjector().attachFingerprintToPlaywright(context, { fingerprint, headers });
|
||||
|
||||
context.setDefaultTimeout(cfg.debug ? 0 : cfg.timeout);
|
||||
|
|
@ -59,6 +61,7 @@ try {
|
|||
db.data[title] = stat;
|
||||
}
|
||||
|
||||
// await page.pause();
|
||||
} catch (error) {
|
||||
process.exitCode ||= 1;
|
||||
console.error('--- Exception:');
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
/* eslint-disable no-constant-condition */
|
||||
import { delay, html_game_list, notify } from '../src/util.js';
|
||||
import { cfg } from '../src/config.js';
|
||||
|
||||
|
|
@ -5,19 +6,18 @@ const URL_CLAIM = 'https://gaming.amazon.com/home'; // dummy URL
|
|||
|
||||
console.debug('NOTIFY:', cfg.notify);
|
||||
|
||||
const scenarios = [
|
||||
{
|
||||
enabled: process.env.TEST_NOTIFY_EPIC === '1',
|
||||
title: 'epic-games',
|
||||
games: [
|
||||
if (true) {
|
||||
const notify_games = [
|
||||
// { title: 'Kerbal Space Program', status: 'claimed', url: URL_CLAIM },
|
||||
// { title: "Shadow Tactics - Aiko's Choice", status: 'claimed', url: URL_CLAIM },
|
||||
{ title: 'Epistory - Typing Chronicles', status: 'claimed', url: URL_CLAIM },
|
||||
],
|
||||
},
|
||||
{
|
||||
enabled: process.env.TEST_NOTIFY_PG === '1',
|
||||
delayMs: 1000,
|
||||
title: 'prime-gaming',
|
||||
games: [
|
||||
];
|
||||
await notify(`epic-games:<br>${html_game_list(notify_games)}`);
|
||||
}
|
||||
|
||||
if (false) {
|
||||
await delay(1000);
|
||||
const notify_games = [
|
||||
{ title: 'Faraway 2: Jungle Escape', status: 'claimed', url: URL_CLAIM },
|
||||
{ title: 'Chicken Police - Paint it RED!', status: 'claimed', url: URL_CLAIM },
|
||||
{ title: 'Lawn Mowing Simulator', status: 'claimed', url: URL_CLAIM },
|
||||
|
|
@ -25,18 +25,14 @@ const scenarios = [
|
|||
{ title: 'The Evil Within 2', status: `<a href="${URL_CLAIM}">redeem</a> H97S6FB38FA6D09DEA on gog.com`, url: URL_CLAIM },
|
||||
{ title: 'Beat Cop', status: `<a href="${URL_CLAIM}">redeem</a> BMKM8558EC55F7B38F on gog.com`, url: URL_CLAIM },
|
||||
{ title: 'Dishonored 2', status: `<a href="${URL_CLAIM}">redeem</a> NNEK0987AB20DFBF8F on gog.com`, url: URL_CLAIM },
|
||||
],
|
||||
},
|
||||
{
|
||||
enabled: process.env.TEST_NOTIFY_GOG === '1',
|
||||
delayMs: 1000,
|
||||
title: 'gog',
|
||||
games: [{ title: 'Haven Park', status: 'claimed', url: URL_CLAIM }],
|
||||
},
|
||||
];
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
if (!scenario.enabled) continue;
|
||||
if (scenario.delayMs) await delay(scenario.delayMs);
|
||||
await notify(`${scenario.title}:<br>${html_game_list(scenario.games)}`);
|
||||
notify(`prime-gaming:<br>${html_game_list(notify_games)}`);
|
||||
}
|
||||
|
||||
if (false) {
|
||||
await delay(1000);
|
||||
const notify_games = [
|
||||
{ title: 'Haven Park', status: 'claimed', url: URL_CLAIM },
|
||||
];
|
||||
notify(`gog:<br>${html_game_list(notify_games)}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,10 +12,10 @@ function onRawSIGINT(fn) {
|
|||
}
|
||||
});
|
||||
}
|
||||
console.log(1);
|
||||
console.log(1)
|
||||
onRawSIGINT(() => {
|
||||
console.log('raw'); process.exit(1);
|
||||
});
|
||||
console.log(2);
|
||||
console.log(2)
|
||||
|
||||
// onRawSIGINT workaround for enquirer keeps the process from exiting here...
|
||||
|
|
|
|||
|
|
@ -1,14 +1,37 @@
|
|||
// https://github.com/enquirer/enquirer/issues/372
|
||||
import { prompt, handleSIGINT } from '../src/util.js';
|
||||
|
||||
// const handleSIGINT = () => process.on('SIGINT', () => { // e.g. when killed by Ctrl-C
|
||||
// console.log('\nInterrupted by SIGINT. Exit!');
|
||||
// process.exitCode = 130;
|
||||
// });
|
||||
handleSIGINT();
|
||||
|
||||
function onRawSIGINT(fn) {
|
||||
const { stdin, stdout } = process;
|
||||
stdin.setRawMode(true);
|
||||
stdin.resume();
|
||||
stdin.on('data', data => {
|
||||
const key = data.toString('utf-8');
|
||||
if (key === '\u0003') { // ctrl + c
|
||||
fn();
|
||||
} else {
|
||||
stdout.write(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
// onRawSIGINT(() => {
|
||||
// console.log('raw'); process.exit(1);
|
||||
// });
|
||||
|
||||
console.log('hello');
|
||||
console.error('hello error');
|
||||
try {
|
||||
const first = await prompt(); // SIGINT no longer handled if this is executed
|
||||
const second = await prompt(); // SIGINT no longer handled if this is executed
|
||||
console.log('values:', first, second);
|
||||
let i = 'foo';
|
||||
i = await prompt(); // SIGINT no longer handled if this is executed
|
||||
i = await prompt(); // SIGINT no longer handled if this is executed
|
||||
// handleSIGINT();
|
||||
console.log('value:', i);
|
||||
setTimeout(() => console.log('timeout 3s'), 3000);
|
||||
} catch (e) {
|
||||
process.exitCode ||= 1;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
// TODO This is mostly a copy of epic-games.js
|
||||
// New assets to claim every first Tuesday of a month.
|
||||
|
||||
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||
import { authenticator } from 'otplib';
|
||||
import path from 'node:path';
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import path from 'path';
|
||||
import { writeFileSync } from 'fs';
|
||||
import { resolve, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js';
|
||||
import { cfg } from './src/config.js';
|
||||
|
||||
|
|
@ -18,7 +21,8 @@ const db = await jsonDb('unrealengine.json', {});
|
|||
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||
headless: cfg.headless,
|
||||
viewport: { width: cfg.width, height: cfg.height },
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36', // Windows UA avoids "device not supported"; update when browser version changes
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36', // see replace of Headless in util.newStealthContext. TODO Windows UA enough to avoid 'device not supported'? update if browser is updated?
|
||||
// userAgent for firefox: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:106.0) Gecko/20100101 Firefox/106.0
|
||||
locale: 'en-US', // ignore OS locale to be sure to have english text for locators
|
||||
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined, // will record a .webm video for each page navigated; without size, video would be scaled down to fit 800x800
|
||||
recordHar: cfg.record ? { path: `data/record/ue-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools
|
||||
|
|
@ -32,7 +36,8 @@ await stealth(context);
|
|||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||
|
||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
||||
|
||||
const notify_games = [];
|
||||
let user;
|
||||
|
|
@ -55,32 +60,23 @@ try {
|
|||
const email = cfg.eg_email || await prompt({ message: 'Enter email' });
|
||||
const password = email && (cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||
if (email && password) {
|
||||
// await page.click('text=Sign in with Epic Games');
|
||||
await page.fill('#email', email);
|
||||
await page.click('button[type="submit"]');
|
||||
await page.fill('#password', password);
|
||||
await page.click('button[type="submit"]');
|
||||
const watchCaptchaDuringLogin = async () => {
|
||||
try {
|
||||
await page.waitForSelector('#h_captcha_challenge_login_prod iframe', { timeout: 15000 });
|
||||
page.waitForSelector('#h_captcha_challenge_login_prod iframe').then(() => {
|
||||
console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
|
||||
notify('unrealengine: got captcha during login. Please check.');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
};
|
||||
const watchMfa = async () => {
|
||||
try {
|
||||
await page.waitForURL('**/id/login/mfa**', { timeout: cfg.login_timeout });
|
||||
}).catch(_ => { });
|
||||
// handle MFA, but don't await it
|
||||
page.waitForURL('**/id/login/mfa**').then(async () => {
|
||||
console.log('Enter the security code to continue - This appears to be a new device, browser or location. A security code has been sent to your email address at ...');
|
||||
// TODO locator for text (email or app?)
|
||||
const otp = cfg.eg_otpkey && authenticator.generate(cfg.eg_otpkey) || await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||
await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString());
|
||||
await page.click('button[type="submit"]');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
};
|
||||
watchCaptchaDuringLogin();
|
||||
watchMfa();
|
||||
}).catch(_ => { });
|
||||
} else {
|
||||
console.log('Waiting for you to login in the browser.');
|
||||
await notify('unrealengine: no longer signed in and not enough options set for automatic login.');
|
||||
|
|
@ -98,11 +94,7 @@ try {
|
|||
console.log(`Signed in as ${user}`);
|
||||
db.data[user] ||= {};
|
||||
|
||||
try {
|
||||
await page.locator('button:has-text("Accept All Cookies")').click();
|
||||
} catch {
|
||||
// button may not be present
|
||||
}
|
||||
page.locator('button:has-text("Accept All Cookies")').click().catch(_ => { });
|
||||
|
||||
const ids = [];
|
||||
for (const p of await page.locator('article.asset').all()) {
|
||||
|
|
@ -131,7 +123,7 @@ try {
|
|||
}
|
||||
ids.push(id);
|
||||
}
|
||||
if (ids.length === 0) {
|
||||
if (!ids.length) {
|
||||
console.log('Nothing to claim');
|
||||
} else {
|
||||
await page.waitForTimeout(2000);
|
||||
|
|
@ -143,22 +135,18 @@ try {
|
|||
notify('unrealengine: ' + err);
|
||||
process.exit(1);
|
||||
}
|
||||
// await page.pause();
|
||||
console.log('Click shopping cart');
|
||||
await page.locator('.shopping-cart').click();
|
||||
// await page.waitForTimeout(2000);
|
||||
await page.locator('button.checkout').click();
|
||||
console.log('Click checkout');
|
||||
// maybe: Accept End User License Agreement
|
||||
const acceptEulaIfPresent = async () => {
|
||||
try {
|
||||
await page.locator('[name=accept-label]').check({ timeout: 10000 });
|
||||
page.locator('[name=accept-label]').check().then(() => {
|
||||
console.log('Accept End User License Agreement');
|
||||
await page.locator('span:text-is("Accept")').click(); // otherwise matches 'Accept All Cookies'
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
};
|
||||
acceptEulaIfPresent();
|
||||
await page.waitForSelector('#webPurchaseContainer iframe');
|
||||
page.locator('span:text-is("Accept")').click(); // otherwise matches 'Accept All Cookies'
|
||||
}).catch(_ => { });
|
||||
await page.waitForSelector('#webPurchaseContainer iframe'); // TODO needed?
|
||||
const iframe = page.frameLocator('#webPurchaseContainer iframe');
|
||||
|
||||
if (cfg.debug) await page.pause();
|
||||
|
|
@ -173,27 +161,14 @@ try {
|
|||
|
||||
// I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872
|
||||
const btnAgree = iframe.locator('button:has-text("I Agree")');
|
||||
const acceptIfRequired = async () => {
|
||||
try {
|
||||
await btnAgree.waitFor({ timeout: 10000 });
|
||||
await btnAgree.click();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}; // EU: wait for and click 'I Agree'
|
||||
acceptIfRequired();
|
||||
btnAgree.waitFor().then(() => btnAgree.click()).catch(_ => { }); // EU: wait for and click 'I Agree'
|
||||
try {
|
||||
// context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s?
|
||||
const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe');
|
||||
const watchCaptchaChallenge = async () => {
|
||||
try {
|
||||
await captcha.waitFor({ timeout: 10000 });
|
||||
captcha.waitFor().then(async () => { // don't await, since element may not be shown
|
||||
// console.info(' Got hcaptcha challenge! NopeCHA extension will likely solve it.')
|
||||
console.error(' Got hcaptcha challenge! Lost trust due to too many login attempts? You can solve the captcha in the browser or get a new IP address.');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}; // may time out if not shown
|
||||
watchCaptchaChallenge();
|
||||
}).catch(_ => { }); // may time out if not shown
|
||||
await page.waitForSelector('text=Thank you');
|
||||
for (const id of ids) {
|
||||
db.data[user][id].status = 'claimed';
|
||||
|
|
@ -201,12 +176,16 @@ try {
|
|||
}
|
||||
notify_games.forEach(g => g.status == 'failed' && (g.status = 'claimed'));
|
||||
console.log('Claimed successfully!');
|
||||
// context.setDefaultTimeout(cfg.timeout);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
// console.error(' Failed to claim! Try again if NopeCHA timed out. Click the extension to see if you ran out of credits (refill after 24h). To avoid captchas try to get a new IP or set a cookie from https://www.hcaptcha.com/accessibility');
|
||||
console.error(' Failed to claim! To avoid captchas try to get a new IP address.');
|
||||
await page.screenshot({ path: screenshot('failed', `${filenamify(datetime())}.png`), fullPage: true });
|
||||
// db.data[user][id].status = 'failed';
|
||||
notify_games.forEach(g => g.status = 'failed');
|
||||
}
|
||||
// notify_game.status = db.data[user][game_id].status; // claimed or failed
|
||||
|
||||
if (notify_games.length) await page.screenshot({ path: screenshot(`${filenamify(datetime())}.png`), fullPage: false }); // fullPage is quite long...
|
||||
console.log('Done');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue