From faf22aafb1db5c51af6bbad32abc2be2ad1274a3 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 11:41:09 +0000 Subject: [PATCH 01/16] =?UTF-8?q?=F0=9F=90=9B=20fix(prime-gaming):=20updat?= =?UTF-8?q?e=20URL=20and=20selectors=20for=20claims?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - change URL_CLAIM to point to new Luna claims home - update selectors for sign-in and user verification - improve handling of cookies acceptance ✨ feat(prime-gaming): enhance game claiming logic - add support for new layout and game list detection - implement flexible scrolling for loading all game cards - refine logic for internal and external game claims - improve store identification for external claims ♻️ refactor(prime-gaming): modularize game tab and list location - extract functions for opening games tab and locating games list - enhance code readability and maintainability 🐛 fix(prime-gaming): handle dynamic selectors for availability dates - support multiple selectors for availability date detection - improve error handling and logging for missing elements --- prime-gaming.js | 156 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 125 insertions(+), 31 deletions(-) diff --git a/prime-gaming.js b/prime-gaming.js index dada15f..8e755b8 100644 --- a/prime-gaming.js +++ b/prime-gaming.js @@ -7,7 +7,7 @@ import { cfg } from './src/config.js'; const screenshot = (...a) => resolve(cfg.dir.screenshots, 'prime-gaming', ...a); // 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'; +const URL_CLAIM = 'https://luna.amazon.com/claims/home'; console.log(datetime(), 'started checking prime-gaming'); @@ -40,9 +40,14 @@ let user; try { await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever // need to wait for some elements to exist before checking if signed in or accepting cookies: - await Promise.any(['button:has-text("Sign in")', '[data-a-target="user-dropdown-first-name-text"]'].map(s => page.waitForSelector(s))); + 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))); 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) { + while (await page.locator('button:has-text("Sign in"), button:has-text("Anmelden")').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 @@ -85,7 +90,7 @@ 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"]').first().innerText(); + user = await page.locator('[data-a-target="user-dropdown-first-name-text"], [data-testid="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(); @@ -119,15 +124,83 @@ try { await page.waitForTimeout(3000); }); - 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(); + const openGamesTab = async () => { + const selectors = [ + 'button[data-type="Game"]', // old layout + 'button:has-text("Games")', + '[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 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(() => document.scrollingElement?.scrollHeight ?? 0)); + + const cards = []; + 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) { + let url = href; + if (url.startsWith('/')) url = 'https://luna.amazon.com' + url; + const title = url.split('/claims/')[1]?.split('/')[0] || (await anchorClaims.first().innerText()) || 'Unknown title'; + cards.push({ kind: 'external', title, url }); + } + } + + 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://gaming.amazon.com' + 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")'); + if (hasLinkClaim) cards.push({ kind: 'external', title, url }); + else if (hasButtonClaim) cards.push({ kind: 'internal', title, url, handle }); + } + } + } + + const internal = cards.filter(c => c.kind == 'internal'); + const external = cards.filter(c => c.kind == 'external'); // bottom to top: oldest to newest games internal.reverse(); external.reverse(); @@ -143,39 +216,41 @@ try { const skipBasedOnTime = async url => { // console.log(' Checking time left for game:', url); const [p, isNew] = await sameOrNewPage(url); - const dueDateOrg = await p.locator('.availability-date .tw-bold').innerText(); + 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 dueDate = new Date(Date.parse(dueDateOrg + ' 17:00')); const daysLeft = (dueDate.getTime() - Date.now())/1000/60/60/24; - console.log(' ', await p.locator('.availability-date').innerText(), '->', daysLeft.toFixed(2)); + 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)); 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.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]; + await card.handle.scrollIntoViewIfNeeded(); + const title = card.title; + const url = card.url; console.log('Current free game:', chalk.blue(title)); - if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue; + if (cfg.pg_timeLeft && url && await skipBasedOnTime(url)) continue; if (cfg.dryrun) continue; if (cfg.interactive && !await confirm()) continue; - await (await card.$('.tw-button:has-text("Claim")')).click(); + await card.handle.locator('.tw-button:has-text("Claim"), .tw-button:has-text("Get"), button:has-text("Claim"), button:has-text("Get")').first().click(); db.data[user][title] ||= { title, time: datetime(), url, store: 'internal' }; notify_games.push({ title, status: 'claimed', url }); - // const img = await (await card.$('img.tw-image')).getAttribute('src'); - // console.log('Image:', img); - await card.screenshot({ path: screenshot('internal', `${filenamify(title)}.png`) }); + await card.handle.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 = 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 + const title = card.title; + const url = card.url ? card.url.split('?')[0] : undefined; + if (!url) continue; external_info.push({ title, url }); } // 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' } ]; @@ -183,13 +258,32 @@ try { console.log('Current free game:', chalk.blue(title)); // , url); await page.goto(url, { waitUntil: 'domcontentloaded' }); if (cfg.debug) await page.pause(); - const item_text = await page.innerText('[data-a-target="DescriptionItemDetails"]'); - const store = item_text.toLowerCase().replace(/.* on /, '').slice(0, -1); + 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(); + store = item_text.toLowerCase().replace(/.* on /, '').slice(0, -1); + } 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'; + } console.log(' External store:', store); if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue; if (cfg.dryrun) continue; 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 + 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.click('[data-a-target="buy-box_call-to-action-text"]'), + page.click('p[data-a-target="buy-box_call-to-action-text"]'), + 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 }; const notify_game = { title, url }; notify_games.push(notify_game); // status is updated below From 76f578e2e6edd24d1ea374ab9736ec92c598a475 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 14:15:22 +0000 Subject: [PATCH 02/16] =?UTF-8?q?=E2=9C=A8=20feat(auth):=20enhance=20autom?= =?UTF-8?q?atic=20login=20and=20MFA=20handling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add handleMFA function for improved two-step verification - implement direct login page handling with automatic sign-in 🐛 fix(claim): improve game claim process and duplicate prevention - normalize claim URLs and deduplicate by URL - fix various selectors for claim buttons and handle different languages - prevent duplicate game claims by checking existing records ♻️ refactor(utils): improve code readability and maintainability - extract normalizeClaimUrl function for URL handling - restructure logic for claim and notification processes 🌐 i18n(claim): add support for game claim text in German - handle German text for claim buttons and status checks --- prime-gaming.js | 230 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 199 insertions(+), 31 deletions(-) diff --git a/prime-gaming.js b/prime-gaming.js index 8e755b8..dc39bba 100644 --- a/prime-gaming.js +++ b/prime-gaming.js @@ -37,8 +37,53 @@ await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO wo 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; +}; + 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 handleMFA(page).catch(_ => {}); + page.waitForURL('**/ap/signin**').then(async () => { // check for wrong credentials + const error = await page.locator('.a-alert-content').first().innerText(); + 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); + }); + 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")', @@ -70,14 +115,7 @@ try { await context.close(); // finishes potential recording process.exit(1); }); - // 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(_ => { }); + handleMFA(page).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.'); @@ -128,6 +166,7 @@ try { 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")', ]; @@ -138,6 +177,15 @@ try { return; } } + // New Luna claims home: try the filter/CTA button with embedded

+ 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 }; @@ -163,15 +211,38 @@ try { if (games) await scrollUntilStable(() => games.evaluate(el => el.scrollHeight).catch(() => 0)); await scrollUntilStable(() => page.evaluate(() => 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) { - let url = href; - if (url.startsWith('/')) url = 'https://luna.amazon.com' + url; - const title = url.split('/claims/')[1]?.split('/')[0] || (await anchorClaims.first().innerText()) || 'Unknown title'; - cards.push({ kind: 'external', title, url }); + const { url, key } = normalizeClaimUrl(href); + const title = key || (await anchorClaims.first().innerText()) || 'Unknown title'; + cards.push({ kind: 'external', title, url, key }); } } @@ -190,17 +261,28 @@ try { 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://gaming.amazon.com' + url; + 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")'); - if (hasLinkClaim) cards.push({ kind: 'external', title, url }); - else if (hasButtonClaim) cards.push({ kind: 'internal', title, url, handle }); + 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 }); } } } - const internal = cards.filter(c => c.kind == 'internal'); - const external = cards.filter(c => c.kind == 'external'); + // 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'); // bottom to top: oldest to newest games internal.reverse(); external.reverse(); @@ -254,9 +336,46 @@ try { external_info.push({ title, url }); } // 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' } ]; + + 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 }); + if (!await c.isEnabled()) { + await c.evaluate(el => { el.disabled = false; el.removeAttribute('disabled'); el.click(); }); + } else { + await c.click(); + } + return true; + } catch (_) { + // try next candidate + } + } + } + return false; + }; + for (const { title, url } of external_info) { console.log('Current free game:', chalk.blue(title)); // , url); + const existing = db.data[user]?.[title]; + if (existing && existing.status && !existing.status.startsWith('failed')) { + console.log(` Already recorded as ${existing.status}, 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"]'); @@ -270,23 +389,59 @@ try { 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'; } 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 is disabled, skipping (likely needs linking/not available).'); + notify_game.status = 'disabled'; + db.data[user][title] ||= { title, time: datetime(), url, store, status: 'disabled' }; + continue; + } else { + console.log(' CTA disabled for epic-games, will still try to link/claim.'); + } + } + 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 && !await confirm()) continue; + await clickCTA(page); 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.click('[data-a-target="buy-box_call-to-action-text"]'), - page.click('p[data-a-target="buy-box_call-to-action-text"]'), - page.waitForSelector('div:has-text("Link game account")'), - page.waitForSelector('.thank-you-title:has-text("Success")'), - ]); // waits for navigation + 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(_ => {}); db.data[user][title] ||= { title, time: datetime(), url, store }; - 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!'); @@ -308,7 +463,21 @@ try { '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() - 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 + 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; + } 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. @@ -441,11 +610,10 @@ try { // await page.pause(); } await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); - await page.click('button[data-type="Game"]'); + page.click('button[data-type="Game"]').catch(_ => {}); - if (notify_games.length) { // make screenshot of all games if something was claimed + if (notify_games.length && games) { // make screenshot of all games if something was claimed and list exists 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 From a21dced86ec47540efc722cb43ce900343509bc7 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 14:31:25 +0000 Subject: [PATCH 03/16] =?UTF-8?q?=F0=9F=93=A6=20build(ci):=20add=20build-a?= =?UTF-8?q?nd-push=20workflow=20for=20docker=20images?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - create a new CI workflow to automate image building and pushing - trigger workflow on push to main branch - include steps for checkout, login, build, and push docker images --- .forgejo/workflows/build.yml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .forgejo/workflows/build.yml diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml new file mode 100644 index 0000000..97fa8a0 --- /dev/null +++ b/.forgejo/workflows/build.yml @@ -0,0 +1,26 @@ +name: build-and-push + +on: + push: + branches: + - main + +jobs: + docker: + runs-on: self-hosted + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Login to registry + run: echo "${{ secrets.REG_TOKEN }}" | docker login "${{ secrets.REGISTRY }}" -u "${{ secrets.REG_USER }}" --password-stdin + + - name: Build image + run: | + docker build -t "${{ secrets.REGISTRY_IMAGE }}:${{ github.sha }}" \ + -t "${{ secrets.REGISTRY_IMAGE }}:latest" . + + - name: Push image + run: | + docker push "${{ secrets.REGISTRY_IMAGE }}:${{ github.sha }}" + docker push "${{ secrets.REGISTRY_IMAGE }}:latest" From 6f778d71ac751dec0f079739141a48c4d11ebf1d Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 14:33:14 +0000 Subject: [PATCH 04/16] =?UTF-8?q?=F0=9F=93=9D=20docs(README):=20add=20inst?= =?UTF-8?q?ructions=20for=20building=20images=20in=20Forgejo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - include steps for building and pushing Docker images using Forgejo - provide details on setting Forgejo secrets and using self-hosted runners --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 17ec854..5e0ab4d 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,14 @@ _This currently gives you a captcha challenge for epic-games. Until [issue #183] 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`. +### Eigene Images aus Forgejo bauen +Falls du den Fork in einer selbst gehosteten Forgejo-Instanz pflegst: + +- Der Workflow `.forgejo/workflows/build.yml` baut/pusht das Docker-Image auf `push` nach `main`. +- Setze in Forgejo die Secrets `REGISTRY`, `REGISTRY_IMAGE`, `REG_USER`, `REG_TOKEN` (PAT mit Paket-Push). +- Self-hosted Runner mit Docker muss registriert sein (`runs-on: self-hosted`). +- Danach kannst du das Image ziehen, z.B.: `docker pull $REGISTRY_IMAGE:latest`. +

I want to run without Docker or develop locally. From bde0f34a80e8f59dce8b6b8e74b5e5286fda3320 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 14:36:18 +0000 Subject: [PATCH 05/16] =?UTF-8?q?=F0=9F=93=9D=20docs(README):=20simplify?= =?UTF-8?q?=20and=20update=20documentation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - remove detailed setup instructions and history - add quick-start guide for Docker and Docker Compose - update CI and configuration sections - streamline language and formatting for clarity --- README.md | 300 +++++++++++++++--------------------------------------- 1 file changed, 80 insertions(+), 220 deletions(-) diff --git a/README.md b/README.md index 5e0ab4d..be82e97 100644 --- a/README.md +++ b/README.md @@ -1,232 +1,92 @@ -

-logo-free-games-claimer -

+Free Games Claimer (Fork) +========================== -[![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=vogler_free-games-claimer&metric=code_smells)](https://sonarcloud.io/project/overview?id=vogler_free-games-claimer) -# free-games-claimer +Automates claiming of free games for: +- Epic Games Store (and Epic-linked assets) +- Amazon Prime Gaming / Luna claims (incl. external stores like GOG, Legacy, Microsoft) +- GOG giveaways +- Optional extras: Steam stats, AliExpress dailies (experimental) -Claims free games periodically on -- [Epic Games Store](https://www.epicgames.com/store/free-games) -- [Amazon Prime Gaming](https://gaming.amazon.com) -- [GOG](https://www.gog.com) -- [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) - +This fork adds a Forgejo CI pipeline and instructions for running the pre-built image from your own registry. -Pull requests welcome :) +Requirements +------------ +- Docker or Podman (empfohlen) **oder** Node.js ≥ 20 zum lokalen Lauf +- (Optional) Python `apprise` für Benachrichtigungen: `pip install apprise` +- Für Playwright: Linux-Desktop-Abhängigkeiten sind im Container enthalten; lokal ggf. `npm install` zieht Firefox mit. -![Telegram Screenshot](https://user-images.githubusercontent.com/493741/214667078-eb5c1877-2bdd-40c1-b94e-4a50d6852c06.png) - -_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: +Schnellstart (Docker Run) +------------------------- ``` -docker run --rm -it -p 6080:6080 -v fgc:/fgc/data --pull=always ghcr.io/vogler/free-games-claimer +docker run --rm -it \ + -p 6080:6080 \ + -v fgc:/fgc/data \ + -e SHOW=1 \ + :latest \ + node prime-gaming.js +``` +- `` z. B. `git.sky-net.it/nocci/free-games-claimer` +- Ports 6080/5900: noVNC/VNC (nur nötig mit `SHOW=1`) +- Daten/Configs landen in Volume `fgc` unter `/fgc/data` + +Docker Compose Beispiel +----------------------- +```yaml +services: + fgc: + image: :latest + container_name: fgc + environment: + - SHOW=1 # Browser sichtbar via VNC/noVNC + # - PG_EMAIL=... + # - PG_PASSWORD=... + # - PG_OTPKEY=... + volumes: + - fgc:/fgc/data + ports: + - "6080:6080" # noVNC + # - "5900:5900" # VNC optional + command: bash -c "node epic-games; node prime-gaming; node gog" +volumes: + fgc: ``` -_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)._ +CI / eigenes Image +------------------ +- Workflow: `.forgejo/workflows/build.yml` baut/pusht auf `push` nach `main`. +- Secrets in Forgejo setzen: + - `REGISTRY` (z. B. `git.sky-net.it`) + - `REGISTRY_IMAGE` (z. B. `git.sky-net.it/nocci/free-games-claimer`) + - `REG_USER`, `REG_TOKEN` (PAT mit Paket-Push) +- Self-hosted Runner mit Docker-Access (`runs-on: self-hosted`) wird benötigt. -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`. +Konfiguration (Umgebungsvariablen) +---------------------------------- +Typische Optionen: +- `SHOW=0/1` (0 = headless, 1 = UI) +- `WIDTH`, `HEIGHT` (Browsergröße) +- `TIMEOUT`, `LOGIN_TIMEOUT` (Sek.) +- Login: `EMAIL`, `PASSWORD` global; spezifisch `EG_EMAIL`, `EG_PASSWORD`, `EG_OTPKEY`, `PG_EMAIL`, `PG_PASSWORD`, `PG_OTPKEY`, `GOG_EMAIL`, `GOG_PASSWORD` +- Prime-Gaming: `PG_REDEEM=1` (Keys automatisch einlösen, experimentell), `PG_CLAIMDLC=1`, `PG_TIMELEFT=` zum Überspringen mit langer Restzeit +- Screenshots: `SCREENSHOTS_DIR` (Standard `data/screenshots`) +- Notifications: `NOTIFY='...'` (Apprise-URL), optional `NOTIFY_TITLE` -### Eigene Images aus Forgejo bauen -Falls du den Fork in einer selbst gehosteten Forgejo-Instanz pflegst: +Du kannst eine `data/config.env` anlegen; sie wird per dotenv geladen und überschreibt nichts, was bereits in der Umgebung gesetzt ist. -- Der Workflow `.forgejo/workflows/build.yml` baut/pusht das Docker-Image auf `push` nach `main`. -- Setze in Forgejo die Secrets `REGISTRY`, `REGISTRY_IMAGE`, `REG_USER`, `REG_TOKEN` (PAT mit Paket-Push). -- Self-hosted Runner mit Docker muss registriert sein (`runs-on: self-hosted`). -- Danach kannst du das Image ziehen, z.B.: `docker pull $REGISTRY_IMAGE:latest`. +Lokal ohne Docker +----------------- +``` +npm install +SHOW=0 PG_EMAIL=... PG_PASSWORD=... PG_OTPKEY=... node prime-gaming.js +``` +- Playwright lädt Firefox beim `npm install` in `~/.cache/ms-playwright`. +- Für sichtbaren Browser `SHOW=1` (GUI/Xvfb nötig). -
- I want to run without Docker or develop locally. +Persistenz & Ausgaben +--------------------- +- Daten & Status: `data/*.json` (pro Store) +- Browserprofil: `data/browser` +- Screenshots: `data/screenshots//` +- Optionale Videos/HAR: `RECORD=1` → `data/record/` -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`... - -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`. - -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. -
- -## 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 - - -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.~~ - - - - -### 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*. - - -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 -
- Click to expand - -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. - - -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`. - - -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). -
- -[![Star History Chart](https://api.star-history.com/svg?repos=vogler/free-games-claimer&type=Date)](https://star-history.com/#vogler/free-games-claimer&Date) - - -![Alt](https://repobeats.axiom.co/api/embed/a1c5e6e420d90e0d6b34c1285e92a69a44138faa.svg "Repobeats analytics image") - ---- - -Logo with smaller aspect ratio (for Telegram bot etc.): 👾 - [emojipedia](https://emojipedia.org/alien-monster/) - -![logo-fgc](https://user-images.githubusercontent.com/493741/214589922-093d6557-6393-421c-b577-da58ff3671bc.png) +Tipp: Bei Captchas oder Erst-Login `SHOW=1` nutzen und einmal manuell einloggen; Cookies bleiben im Profil. Notifications via `NOTIFY` helfen bei Fehlermeldungen (z. B. Captcha, Login).*** From eba07721ca09a04c0c95e2f9672f87d084c6ee15 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 14:38:54 +0000 Subject: [PATCH 06/16] =?UTF-8?q?=F0=9F=93=9D=20docs(README):=20update=20i?= =?UTF-8?q?nstructions=20and=20clarify=20configurations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - update registry image references to point to `git.sky-net.it/nocci/free-games-claimer` - improve clarity on Docker and Docker Compose examples - translate German sections into English for wider accessibility - add detailed explanations for environment variables and configurations - enhance quickstart and CI instructions for better understanding --- README.md | 83 +++++++++++++++++++++++++++---------------------------- 1 file changed, 41 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index be82e97..8ccf31c 100644 --- a/README.md +++ b/README.md @@ -3,41 +3,40 @@ Free Games Claimer (Fork) Automates claiming of free games for: - Epic Games Store (and Epic-linked assets) -- Amazon Prime Gaming / Luna claims (incl. external stores like GOG, Legacy, Microsoft) +- Amazon Prime Gaming / Luna claims (including external stores like GOG, Legacy, Microsoft) - GOG giveaways - Optional extras: Steam stats, AliExpress dailies (experimental) -This fork adds a Forgejo CI pipeline and instructions for running the pre-built image from your own registry. +This fork adds a Forgejo CI pipeline and instructions for running the pre-built image from the registry at `git.sky-net.it/nocci/free-games-claimer`. Requirements ------------ -- Docker or Podman (empfohlen) **oder** Node.js ≥ 20 zum lokalen Lauf -- (Optional) Python `apprise` für Benachrichtigungen: `pip install apprise` -- Für Playwright: Linux-Desktop-Abhängigkeiten sind im Container enthalten; lokal ggf. `npm install` zieht Firefox mit. +- 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. -Schnellstart (Docker Run) -------------------------- +Quickstart (Docker Run) +----------------------- ``` docker run --rm -it \ -p 6080:6080 \ -v fgc:/fgc/data \ -e SHOW=1 \ - :latest \ + git.sky-net.it/nocci/free-games-claimer:latest \ node prime-gaming.js ``` -- `` z. B. `git.sky-net.it/nocci/free-games-claimer` -- Ports 6080/5900: noVNC/VNC (nur nötig mit `SHOW=1`) -- Daten/Configs landen in Volume `fgc` unter `/fgc/data` +- Ports 6080/5900: noVNC/VNC (only needed with `SHOW=1`) +- Data/configs are stored in volume `fgc` under `/fgc/data` -Docker Compose Beispiel ------------------------ +Docker Compose Example +---------------------- ```yaml services: fgc: - image: :latest + image: git.sky-net.it/nocci/free-games-claimer:latest container_name: fgc environment: - - SHOW=1 # Browser sichtbar via VNC/noVNC + - SHOW=1 # show browser via VNC/noVNC # - PG_EMAIL=... # - PG_PASSWORD=... # - PG_OTPKEY=... @@ -51,42 +50,42 @@ volumes: fgc: ``` -CI / eigenes Image ------------------- -- Workflow: `.forgejo/workflows/build.yml` baut/pusht auf `push` nach `main`. -- Secrets in Forgejo setzen: - - `REGISTRY` (z. B. `git.sky-net.it`) - - `REGISTRY_IMAGE` (z. B. `git.sky-net.it/nocci/free-games-claimer`) - - `REG_USER`, `REG_TOKEN` (PAT mit Paket-Push) -- Self-hosted Runner mit Docker-Access (`runs-on: self-hosted`) wird benötigt. +CI / Build Your Own Image +------------------------- +- Workflow: `.forgejo/workflows/build.yml` builds/pushes on `push` to `main`. +- Secrets needed in Forgejo: + - `REGISTRY` (e.g., `git.sky-net.it`) + - `REGISTRY_IMAGE` (e.g., `git.sky-net.it/nocci/free-games-claimer`) + - `REG_USER`, `REG_TOKEN` (PAT with package push) +- Requires a self-hosted runner with Docker access (`runs-on: self-hosted`). -Konfiguration (Umgebungsvariablen) ----------------------------------- -Typische Optionen: +Configuration (Environment Variables) +------------------------------------- +Common options: - `SHOW=0/1` (0 = headless, 1 = UI) -- `WIDTH`, `HEIGHT` (Browsergröße) -- `TIMEOUT`, `LOGIN_TIMEOUT` (Sek.) -- Login: `EMAIL`, `PASSWORD` global; spezifisch `EG_EMAIL`, `EG_PASSWORD`, `EG_OTPKEY`, `PG_EMAIL`, `PG_PASSWORD`, `PG_OTPKEY`, `GOG_EMAIL`, `GOG_PASSWORD` -- Prime-Gaming: `PG_REDEEM=1` (Keys automatisch einlösen, experimentell), `PG_CLAIMDLC=1`, `PG_TIMELEFT=` zum Überspringen mit langer Restzeit -- Screenshots: `SCREENSHOTS_DIR` (Standard `data/screenshots`) -- Notifications: `NOTIFY='...'` (Apprise-URL), optional `NOTIFY_TITLE` +- `WIDTH`, `HEIGHT` (browser size) +- `TIMEOUT`, `LOGIN_TIMEOUT` (seconds) +- 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=` to skip long-remaining offers +- Screenshots: `SCREENSHOTS_DIR` (default `data/screenshots`) +- Notifications: `NOTIFY='...'` (Apprise URL), optional `NOTIFY_TITLE` -Du kannst eine `data/config.env` anlegen; sie wird per dotenv geladen und überschreibt nichts, was bereits in der Umgebung gesetzt ist. +You can place a `data/config.env`; it is loaded via dotenv and is overridden by explicitly set environment variables. -Lokal ohne Docker ------------------ +Local Run Without Docker +------------------------ ``` npm install SHOW=0 PG_EMAIL=... PG_PASSWORD=... PG_OTPKEY=... node prime-gaming.js ``` -- Playwright lädt Firefox beim `npm install` in `~/.cache/ms-playwright`. -- Für sichtbaren Browser `SHOW=1` (GUI/Xvfb nötig). +- Playwright downloads Firefox to `~/.cache/ms-playwright`. +- Use `SHOW=1` for a visible browser (requires GUI/Xvfb). -Persistenz & Ausgaben +Persistence & Outputs --------------------- -- Daten & Status: `data/*.json` (pro Store) -- Browserprofil: `data/browser` +- Data/status: `data/*.json` (per store) +- Browser profile: `data/browser` - Screenshots: `data/screenshots//` -- Optionale Videos/HAR: `RECORD=1` → `data/record/` +- Optional videos/HAR: `RECORD=1` → `data/record/` -Tipp: Bei Captchas oder Erst-Login `SHOW=1` nutzen und einmal manuell einloggen; Cookies bleiben im Profil. Notifications via `NOTIFY` helfen bei Fehlermeldungen (z. B. Captcha, Login).*** +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). From eb5b9bbb6e8890e51072c2a592dd14d45a469d83 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 15:01:55 +0000 Subject: [PATCH 07/16] =?UTF-8?q?=F0=9F=91=B7=20ci(build):=20enhance=20doc?= =?UTF-8?q?ker=20build=20process=20with=20buildx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add Docker Buildx setup for advanced build capabilities - update build step to use buildx for multi-platform support --- .forgejo/workflows/build.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index 97fa8a0..3aa7b56 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -9,6 +9,9 @@ jobs: docker: runs-on: self-hosted steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Checkout uses: actions/checkout@v4 @@ -17,8 +20,9 @@ jobs: - name: Build image run: | - docker build -t "${{ secrets.REGISTRY_IMAGE }}:${{ github.sha }}" \ - -t "${{ secrets.REGISTRY_IMAGE }}:latest" . + docker buildx build --load \ + -t "${{ secrets.REGISTRY_IMAGE }}:${{ github.sha }}" \ + -t "${{ secrets.REGISTRY_IMAGE }}:latest" . - name: Push image run: | From 0a729d0cbfa562f6913bbe2d7a0085e2da07ab72 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 15:08:00 +0000 Subject: [PATCH 08/16] =?UTF-8?q?=F0=9F=94=A7=20chore(workflow):=20simplif?= =?UTF-8?q?y=20docker=20image=20tagging=20and=20pushing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - remove specific sha tag from build and push steps - streamline workflow by focusing on latest tag --- .forgejo/workflows/build.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index 3aa7b56..cb83fb0 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -21,10 +21,8 @@ jobs: - name: Build image run: | docker buildx build --load \ - -t "${{ secrets.REGISTRY_IMAGE }}:${{ github.sha }}" \ -t "${{ secrets.REGISTRY_IMAGE }}:latest" . - name: Push image run: | - docker push "${{ secrets.REGISTRY_IMAGE }}:${{ github.sha }}" docker push "${{ secrets.REGISTRY_IMAGE }}:latest" From 9d79f9ac7851f8d4dabdb0cb0e5bc1dd3cc29525 Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 15:54:41 +0000 Subject: [PATCH 09/16] =?UTF-8?q?=F0=9F=93=9D=20docs(README):=20update=20c?= =?UTF-8?q?onfiguration=20and=20remove=20CI=20section?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - remove outdated CI/build instructions - add new environment variable options for configuration 🐛 fix(util): handle notification errors gracefully - resolve promise instead of rejecting on notification errors - prevent whole run from failing due to notification issues --- README.md | 16 +++++++--------- src/util.js | 3 ++- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 8ccf31c..16ac157 100644 --- a/README.md +++ b/README.md @@ -50,15 +50,6 @@ volumes: fgc: ``` -CI / Build Your Own Image -------------------------- -- Workflow: `.forgejo/workflows/build.yml` builds/pushes on `push` to `main`. -- Secrets needed in Forgejo: - - `REGISTRY` (e.g., `git.sky-net.it`) - - `REGISTRY_IMAGE` (e.g., `git.sky-net.it/nocci/free-games-claimer`) - - `REG_USER`, `REG_TOKEN` (PAT with package push) -- Requires a self-hosted runner with Docker access (`runs-on: self-hosted`). - Configuration (Environment Variables) ------------------------------------- Common options: @@ -69,6 +60,13 @@ Common options: - Prime Gaming: `PG_REDEEM=1` (auto-redeem keys, experimental), `PG_CLAIMDLC=1`, `PG_TIMELEFT=` 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) You can place a `data/config.env`; it is loaded via dotenv and is overridden by explicitly set environment variables. diff --git a/src/util.js b/src/util.js index 308952d..49424f8 100644 --- a/src/util.js +++ b/src/util.js @@ -125,7 +125,8 @@ export const notify = html => new Promise((resolve, reject) => { if (error.message.includes('command not found')) { console.info('Run `pip install apprise`. See https://github.com/vogler/free-games-claimer#notifications'); } - return reject(error); + // don't fail the whole run on notification errors + return resolve(); } if (stderr) console.error(`stderr: ${stderr}`); if (stdout) console.log(`stdout: ${stdout}`); From e39cca93c23fe1412ca1bdecbbeda45843bd060f Mon Sep 17 00:00:00 2001 From: nocci Date: Mon, 29 Dec 2025 17:19:39 +0100 Subject: [PATCH 10/16] better README.md --- README.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 16ac157..248995e 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,9 @@ Free Games Claimer (Fork) ========================== Automates claiming of free games for: -- Epic Games Store (and Epic-linked assets) -- Amazon Prime Gaming / Luna claims (including external stores like GOG, Legacy, Microsoft) +- Amazon Luna Gaming / Luna claims (including external stores like GOG, Epic Games, Legacy Games ) - GOG giveaways -- Optional extras: Steam stats, AliExpress dailies (experimental) - -This fork adds a Forgejo CI pipeline and instructions for running the pre-built image from the registry at `git.sky-net.it/nocci/free-games-claimer`. +- Optional extras: Steam stats, AliExpress dailies (not implemated yet) Requirements ------------ From 0e5303da623e186951c8ff01614f688ca09bcd16 Mon Sep 17 00:00:00 2001 From: nocci Date: Tue, 30 Dec 2025 11:02:01 +0000 Subject: [PATCH 11/16] =?UTF-8?q?=F0=9F=91=B7=20ci(workflow):=20add=20lint?= =?UTF-8?q?=20job=20to=20build=20workflow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - introduce lint job in build.yml for code quality checks - ensure lint job runs before docker job - setup Node.js and install dependencies for ESLint --- .forgejo/workflows/build.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index cb83fb0..c15f8c5 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -6,7 +6,22 @@ on: - main jobs: + lint: + runs-on: self-hosted + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + - name: Install dependencies + run: npm ci + - name: Run ESLint + run: npm run lint + docker: + needs: lint runs-on: self-hosted steps: - name: Set up Docker Buildx From d40a577f4778669c10e644f582aa2cd0012af490 Mon Sep 17 00:00:00 2001 From: nocci Date: Tue, 30 Dec 2025 12:38:03 +0000 Subject: [PATCH 12/16] =?UTF-8?q?=F0=9F=91=B7=20ci(build):=20add=20SonarQu?= =?UTF-8?q?be=20scan=20to=20build=20workflow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - introduce SonarQube scanning step for code quality analysis - update workflow dependencies and execution order 🐛 fix(auth): improve error handling and code formatting - remove unused imports and fix code indentation - enhance error handling with improved catch blocks 💄 style(general): standardize code formatting and style consistency - update various files to ensure consistent code style - adjust indentation and whitespace for readability --- .forgejo/workflows/build.yml | 25 ++++++++++- aliexpress.js | 30 ++++++++----- prime-gaming.js | 54 ++++++++++++----------- src/util.js | 8 ++-- steam-games.js | 10 ++--- test/sigint-enquirer-raw-keeps-running.js | 4 +- test/sigint-enquirer-raw.js | 26 +++++------ 7 files changed, 95 insertions(+), 62 deletions(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index c15f8c5..882e541 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -20,9 +20,32 @@ jobs: - name: Run ESLint run: npm run lint - docker: + sonar: needs: lint runs-on: self-hosted + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: SonarQube Scan + env: + SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: | + docker run --rm \ + -e SONAR_HOST_URL="$SONAR_HOST_URL" \ + -e SONAR_TOKEN="$SONAR_TOKEN" \ + -v "$PWD:/usr/src" \ + -w /usr/src \ + sonarsource/sonar-scanner-cli \ + sonar-scanner \ + -Dsonar.host.url="$SONAR_HOST_URL" \ + -Dsonar.login="$SONAR_TOKEN" + + docker: + needs: [lint, sonar] + runs-on: self-hosted steps: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 diff --git a/aliexpress.js b/aliexpress.js index 52e75a0..6d654d3 100644 --- a/aliexpress.js +++ b/aliexpress.js @@ -1,5 +1,5 @@ import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra -import { datetime, filenamify, prompt, handleSIGINT, stealth } from './src/util.js'; +import { datetime, filenamify, prompt, handleSIGINT } from './src/util.js'; import { cfg } from './src/config.js'; // using https://github.com/apify/fingerprint-suite worked, but has no launchPersistentContext... @@ -8,8 +8,8 @@ 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, { @@ -21,11 +21,11 @@ const context = await firefox.launchPersistentContext(cfg.dir.browser, { handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved userAgent: fingerprint.navigator.userAgent, viewport: { - width: fingerprint.screen.width, - height: fingerprint.screen.height, + width: fingerprint.screen.width, + height: fingerprint.screen.height, }, extraHTTPHeaders: { - 'accept-language': headers['accept-language'], + 'accept-language': headers['accept-language'], }, }); handleSIGINT(context); @@ -36,7 +36,7 @@ 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 @@ -45,7 +45,7 @@ const auth = async (url) => { console.error('Not logged in! Will wait for 120s for you to 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 + 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"]'); @@ -58,11 +58,11 @@ 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); // 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(_ => {}); + 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()); @@ -80,6 +80,7 @@ const urls = { merge: 'https://m.aliexpress.com/p/merge-market/index.html', }; +/* eslint-disable no-unused-vars */ const coins = async () => { // await auth(urls.coins); await Promise.any([page.locator('.checkin-button').click(), page.locator('.addcoin').waitFor()]); @@ -103,6 +104,7 @@ const euro = async () => { const merge = async () => { await page.pause(); }; +/* eslint-enable no-unused-vars */ try { // await coins(); @@ -112,7 +114,11 @@ try { // 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) { diff --git a/prime-gaming.js b/prime-gaming.js index dc39bba..0c982bd 100644 --- a/prime-gaming.js +++ b/prime-gaming.js @@ -41,7 +41,7 @@ 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(_ => {}); + 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(); @@ -61,7 +61,7 @@ try { await page.click('input[type="submit"]'); await page.fill('[name=password]', password); await page.click('input[type="submit"]'); - await handleMFA(page).catch(_ => {}); + await handleMFA(page).catch(() => {}); page.waitForURL('**/ap/signin**').then(async () => { // check for wrong credentials const error = await page.locator('.a-alert-content').first().innerText(); if (!error.trim.length) return; @@ -91,7 +91,7 @@ try { '[data-a-target="user-dropdown-first-name-text"]', '[data-testid="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? + 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"), button:has-text("Anmelden")').count() > 0) { console.error('Not signed in anymore.'); await page.click('button:has-text("Sign in")'); @@ -115,7 +115,7 @@ try { await context.close(); // finishes potential recording process.exit(1); }); - handleMFA(page).catch(_ => {}); + handleMFA(page).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.'); @@ -209,7 +209,7 @@ try { 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(() => document.scrollingElement?.scrollHeight ?? 0)); + await scrollUntilStable(() => page.evaluate(() => globalThis.document?.scrollingElement?.scrollHeight ?? 0)); const normalizeClaimUrl = url => { if (!url) return { url, key: null }; @@ -241,7 +241,7 @@ try { 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'; + const title = key || await anchorClaims.first().innerText() || 'Unknown title'; cards.push({ kind: 'external', title, url, key }); } } @@ -286,15 +286,15 @@ try { // bottom to top: oldest to newest games internal.reverse(); external.reverse(); - const sameOrNewPage = async url => new Promise(async (resolve, _reject) => { + const sameOrNewPage = async url => { const isNew = page.url() != url; let p = page; if (isNew) { p = await context.newPage(); await p.goto(url, { waitUntil: 'domcontentloaded' }); } - resolve([p, isNew]); - }); + return [p, isNew]; + }; const skipBasedOnTime = async url => { // console.log(' Checking time left for game:', url); const [p, isNew] = await sameOrNewPage(url); @@ -305,12 +305,12 @@ try { } const dueDateOrg = await dueDateLoc.first().innerText(); const dueDate = new Date(Date.parse(dueDateOrg + ' 17:00')); - const daysLeft = (dueDate.getTime() - Date.now())/1000/60/60/24; + 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)); 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) { @@ -353,12 +353,16 @@ try { try { await c.waitFor({ state: 'visible', timeout: 5000 }); if (!await c.isEnabled()) { - await c.evaluate(el => { el.disabled = false; el.removeAttribute('disabled'); el.click(); }); + await c.evaluate(el => { + el.disabled = false; + el.removeAttribute('disabled'); + el.click(); + }); } else { await c.click(); } return true; - } catch (_) { + } catch { // try next candidate } } @@ -375,7 +379,7 @@ try { continue; } await page.goto(url, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('[data-a-target="buy-box"]', { timeout: 10000 }).catch(_ => {}); + 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"]'); @@ -438,9 +442,9 @@ try { if (cfg.interactive && !await confirm()) 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(_ => {}); + 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(() => {}); db.data[user][title] ||= { title, time: datetime(), url, store }; 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()) { @@ -466,16 +470,16 @@ try { let code; try { // ensure CTA was clicked in case code is behind it - await clickCTA(page).catch(_ => {}); + 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 (_) { + } 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(_ => {}); + await page.screenshot({ path: screenshot('external', `${filenamify(title)}_nocode.png`), fullPage: true }).catch(() => {}); continue; } console.log(' Code to redeem game:', chalk.blue(code)); @@ -563,7 +567,7 @@ try { if (j?.events?.cart.length && j.events.cart[0]?.data?.reason == 'UserAlreadyOwnsContent') { redeem_action = 'already redeemed'; console.error(' error: UserAlreadyOwnsContent'); - } else if (true) { // TODO what's returned on success? + } else { // 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'); @@ -610,7 +614,7 @@ try { // await page.pause(); } await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); - page.click('button[data-type="Game"]').catch(_ => {}); + page.click('button[data-type="Game"]').catch(() => {}); if (notify_games.length && games) { // make screenshot of all games if something was claimed and list exists const p = screenshot(`${filenamify(datetime())}.png`); @@ -628,7 +632,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()); @@ -657,7 +661,7 @@ try { // 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? 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(_ => { }); + page.click('button:has-text("Continue")').catch(() => { }); const linkAccountButton = page.locator('[data-a-target="LinkAccountButton"]'); let unlinked_store; if (await linkAccountButton.count()) { @@ -674,7 +678,7 @@ 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'; diff --git a/src/util.js b/src/util.js index 49424f8..8ba63a3 100644 --- a/src/util.js +++ b/src/util.js @@ -96,21 +96,21 @@ const timeoutPlugin = timeout => enquirer => { // cancel prompt after timeout ms prompt.hint = () => 'timeout'; prompt.cancel(); }, timeout); - prompt.on('submit', _ => clearTimeout(t)); - prompt.on('cancel', _ => clearTimeout(t)); + prompt.on('submit', () => clearTimeout(t)); + prompt.on('cancel', () => clearTimeout(t)); }); }; 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 'child_process'; import { cfg } from './config.js'; -export const notify = html => new Promise((resolve, reject) => { +export const notify = html => new Promise(resolve => { if (!cfg.notify) { if (cfg.debug) console.debug('notify: NOTIFY is not set!'); return resolve(); diff --git a/steam-games.js b/steam-games.js index 9b307fc..ed54253 100644 --- a/steam-games.js +++ b/steam-games.js @@ -12,8 +12,8 @@ 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, { @@ -22,11 +22,11 @@ const context = await firefox.launchPersistentContext(cfg.dir.browser, { 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: { - width: fingerprint.screen.width, - height: fingerprint.screen.height, + width: fingerprint.screen.width, + height: fingerprint.screen.height, }, extraHTTPHeaders: { - 'accept-language': headers['accept-language'], + 'accept-language': headers['accept-language'], }, }); // await stealth(context); diff --git a/test/sigint-enquirer-raw-keeps-running.js b/test/sigint-enquirer-raw-keeps-running.js index 23d9983..ccb3081 100644 --- a/test/sigint-enquirer-raw-keeps-running.js +++ b/test/sigint-enquirer-raw-keeps-running.js @@ -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... diff --git a/test/sigint-enquirer-raw.js b/test/sigint-enquirer-raw.js index e6b538d..c85ee0d 100644 --- a/test/sigint-enquirer-raw.js +++ b/test/sigint-enquirer-raw.js @@ -7,19 +7,19 @@ import { prompt, handleSIGINT } from '../src/util.js'; // }); 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); - } - }); -} +// 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); // }); From 5b1d966c6e7569658ff9f5920a4ab383ce954905 Mon Sep 17 00:00:00 2001 From: nocci Date: Tue, 30 Dec 2025 12:40:06 +0000 Subject: [PATCH 13/16] =?UTF-8?q?=F0=9F=91=B7=20ci(build):=20enhance=20son?= =?UTF-8?q?ar=20scanner=20configuration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - extract project key from properties file for dynamic setup - add projectBaseDir to sonar scanner command for accurate analysis --- .forgejo/workflows/build.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index 882e541..a251a62 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -33,6 +33,7 @@ jobs: SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} run: | + PROJECT_KEY=$(grep -E '^sonar.projectKey=' sonar-project.properties | cut -d= -f2 | tr -d '\r') docker run --rm \ -e SONAR_HOST_URL="$SONAR_HOST_URL" \ -e SONAR_TOKEN="$SONAR_TOKEN" \ @@ -41,7 +42,9 @@ jobs: sonarsource/sonar-scanner-cli \ sonar-scanner \ -Dsonar.host.url="$SONAR_HOST_URL" \ - -Dsonar.login="$SONAR_TOKEN" + -Dsonar.token="$SONAR_TOKEN" \ + -Dsonar.projectKey="${PROJECT_KEY:-free-games-claimer}" \ + -Dsonar.projectBaseDir=/usr/src docker: needs: [lint, sonar] From 56ca1f63d4a7894d79ad80d1736380d03ae732af Mon Sep 17 00:00:00 2001 From: nocci Date: Tue, 30 Dec 2025 12:42:36 +0000 Subject: [PATCH 14/16] =?UTF-8?q?=F0=9F=91=B7=20ci(build):=20enhance=20son?= =?UTF-8?q?ar=20project=20key=20configuration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add SONAR_PROJECT_KEY environment variable for flexibility - fallback to default or file-based project key if not set --- .forgejo/workflows/build.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index a251a62..d2aa8e0 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -32,8 +32,13 @@ jobs: env: SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + SONAR_PROJECT_KEY: ${{ secrets.SONAR_PROJECT_KEY }} run: | - PROJECT_KEY=$(grep -E '^sonar.projectKey=' sonar-project.properties | cut -d= -f2 | tr -d '\r') + 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 + PROJECT_KEY=${PROJECT_KEY:-free-games-claimer} docker run --rm \ -e SONAR_HOST_URL="$SONAR_HOST_URL" \ -e SONAR_TOKEN="$SONAR_TOKEN" \ From 8626fa5a0f856c66c9cc5b16ad71ef1db80864e2 Mon Sep 17 00:00:00 2001 From: nocci Date: Tue, 30 Dec 2025 12:57:44 +0000 Subject: [PATCH 15/16] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(build):=20e?= =?UTF-8?q?nhance=20sonar=20scanner=20configuration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - set default host url for sonar scanner to ensure consistency - add sonar.sources and sonar.scm.provider for improved analysis --- .forgejo/workflows/build.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index d2aa8e0..501cf33 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -34,21 +34,24 @@ jobs: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} SONAR_PROJECT_KEY: ${{ secrets.SONAR_PROJECT_KEY }} run: | + HOST_URL=${SONAR_HOST_URL:-https://sonata.cyber77.de} 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 PROJECT_KEY=${PROJECT_KEY:-free-games-claimer} docker run --rm \ - -e SONAR_HOST_URL="$SONAR_HOST_URL" \ + -e SONAR_HOST_URL="$HOST_URL" \ -e SONAR_TOKEN="$SONAR_TOKEN" \ -v "$PWD:/usr/src" \ -w /usr/src \ sonarsource/sonar-scanner-cli \ sonar-scanner \ - -Dsonar.host.url="$SONAR_HOST_URL" \ + -Dsonar.host.url="$HOST_URL" \ -Dsonar.token="$SONAR_TOKEN" \ -Dsonar.projectKey="${PROJECT_KEY:-free-games-claimer}" \ + -Dsonar.sources=. \ + -Dsonar.scm.provider=git \ -Dsonar.projectBaseDir=/usr/src docker: From e11d40bdda5f2628229ec3456ac3faad77ecc1e8 Mon Sep 17 00:00:00 2001 From: nocci Date: Tue, 30 Dec 2025 13:01:14 +0000 Subject: [PATCH 16/16] =?UTF-8?q?=F0=9F=91=B7=20ci(build):=20enforce=20son?= =?UTF-8?q?ar=20host=20url=20secret=20presence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - update HOST_URL to require SONAR_HOST_URL secret for enhanced security configuration - improve error handling by ensuring critical secrets are set --- .forgejo/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index 501cf33..b1cbd6d 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -34,7 +34,7 @@ jobs: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} SONAR_PROJECT_KEY: ${{ secrets.SONAR_PROJECT_KEY }} run: | - HOST_URL=${SONAR_HOST_URL:-https://sonata.cyber77.de} + HOST_URL=${SONAR_HOST_URL:?SONAR_HOST_URL secret not set} 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')