diff --git a/app/splatnet/auth.mjs b/app/splatnet/auth.mjs index 80bb06a..0a348c9 100644 --- a/app/splatnet/auth.mjs +++ b/app/splatnet/auth.mjs @@ -7,9 +7,28 @@ import queryHashes from './queryHashes.json' with { type: 'json' }; export const SPLATNET3_WEB_SERVICE_ID = '4834290508791808'; const SPLATNET3_BASE_URL = 'https://api.lp1.av5ja.srv.nintendo.net'; +// We can assume a bullet token expires after two hours. +const BULLET_TOKEN_TTL_SECONDS = 7200; + // Serialize token acquisition per account (NSO session token), across all callers. const bulletTokenLimits = new Map(); +function tokenLimit(nsoClient) { + let key = nsoClient.cachePrefix; + let limit = bulletTokenLimits.get(key); + + if (!limit) { + limit = pLimit(1); + bulletTokenLimits.set(key, limit); + } + + return limit; +} + +function bulletTokenCacheFor(nsoClient) { + return new ValueCache(`${nsoClient.cachePrefix}.bulletToken`); +} + /** * Obtains SplatNet 3 bullet tokens: Nintendo Account → Coral → web service token → bullet * token, cached in private storage at each step. @@ -26,16 +45,8 @@ export class LocalAuth { * @param {boolean} [options.useCache] false to obtain a fresh token */ bulletToken(nsoClient, { language = 'en-US', useCache = true } = {}) { - const key = nsoClient.cachePrefix; - let tokenLimit = bulletTokenLimits.get(key); - - if (!tokenLimit) { - tokenLimit = pLimit(1); - bulletTokenLimits.set(key, tokenLimit); - } - - return tokenLimit(async () => { - let bulletTokenCache = new ValueCache(`${key}.bulletToken`); + return tokenLimit(nsoClient)(async () => { + let bulletTokenCache = bulletTokenCacheFor(nsoClient); let bulletToken = useCache ? await bulletTokenCache.getData() @@ -50,6 +61,22 @@ export class LocalAuth { }); } + /** + * Cache a bullet token obtained elsewhere (the iPad's SplatNet 3 app, through splat-mitmproxy), + * in place of the account's current one. It is kept as long as one created here. + * @param {import('./NsoClient.mjs').default} nsoClient The account the token belongs to + * @param {object} bulletToken The bullet token response + * @returns {Promise} When the cached token expires (epoch milliseconds) + */ + storeBulletToken(nsoClient, bulletToken) { + return tokenLimit(nsoClient)(async () => { + let expiry = calculateCacheExpiry(BULLET_TOKEN_TTL_SECONDS); + await bulletTokenCacheFor(nsoClient).setData(bulletToken, expiry); + + return expiry; + }); + } + /** * Renew every credential for the account ahead of time, bypassing the caches. A step that * fails is logged and the next one still runs: the bullet token step obtains whatever it @@ -85,8 +112,7 @@ export class LocalAuth { let bulletToken = await response.json(); - // We can assume the token expires after 7200 seconds - let expiry = calculateCacheExpiry(7200); + let expiry = calculateCacheExpiry(BULLET_TOKEN_TTL_SECONDS); await bulletTokenCache.setData(bulletToken, expiry); console.debug(`Caching bullet token until: ${expiry}`); diff --git a/app/splatnet/auth.test.mjs b/app/splatnet/auth.test.mjs index d4b6d1a..e04c918 100644 --- a/app/splatnet/auth.test.mjs +++ b/app/splatnet/auth.test.mjs @@ -69,6 +69,19 @@ describe('auth', () => { expect(fetch).toHaveBeenCalledOnce(); }); + it('serves a bullet token stored from elsewhere until it expires', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ bulletToken: 'fresh' }))); + let local = new LocalAuth; + + let expires = await local.storeBulletToken(fakeNsoClient(), { bulletToken: 'uploaded' }); + + // Two hours, less the five minutes every cached token gives up. + expect(expires).toBeGreaterThan(Date.now() + 114 * 60_000); + expect(expires).toBeLessThanOrEqual(Date.now() + 115 * 60_000); + expect(await local.bulletToken(fakeNsoClient())).toEqual({ bulletToken: 'uploaded' }); + expect(fetch).not.toHaveBeenCalled(); + }); + it('lets SplatNet clients use a configured provider', async () => { let provider = { bulletToken: vi.fn().mockResolvedValue({ bulletToken: 'remote' }), refresh: vi.fn() }; configureAuth(provider); diff --git a/workers/updater/README.md b/workers/updater/README.md index 1356e85..da420b6 100644 --- a/workers/updater/README.md +++ b/workers/updater/README.md @@ -20,6 +20,12 @@ Node runner (`npm run splatnet`, `npm run social`, …) uses the same code with renewals are turned off in the admin panel (tokens are then obtained when an update needs one). A renewal counts as failed only if it ends without a new bullet token; a step that failed and was made up for by a later one is kept as a warning. +- **iPad token uploads** (`PUT /bullet-token`): splat-mitmproxy on ghost captures the bullet + token the iPad's SplatNet 3 app receives (an hourly Shortcuts automation opens it) and + uploads it to both the dev and production Workers. It replaces the cached token of the + `TOKEN_UPLOAD_REGION` account (`US`, the North America account) until the next renewal or + upload, and shows on the admin timeline's Nintendo auth row as "iPad upload". It is an extra + source of tokens: nothing depends on it. - A cron trigger every five minutes only re-arms missing alarms. It never enables a lane. Failed runs are not retried: the lane's next slot runs again, 1–15 minutes later for the @@ -49,7 +55,8 @@ runner does not report to Sentry. "Dev Data Assets" for `dev.splatoon3.ink`), or the fast lane's published-data check fails. 3. Secrets (`npx wrangler secret put NAME --config workers/updater/wrangler.jsonc --env dev`): `NINTENDO_TOKEN_US`, `NINTENDO_TOKEN_EU`, `NINTENDO_TOKEN_JP`, `NINTENDO_TOKEN_AP`, - `NXAPI_CLIENT_ID`, `NXAPI_SHARED_SECRET`, `USER_AGENT`, `RUN_TOKEN`, `ACCESS_TEAM_DOMAIN` + `NXAPI_CLIENT_ID`, `NXAPI_SHARED_SECRET`, `USER_AGENT`, `RUN_TOKEN`, `TOKEN_UPLOAD_TOKEN` + (see iPad token uploads), `ACCESS_TEAM_DOMAIN` and `ACCESS_AUD` (see Admin panel), `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` (see Archive), optional `SENTRY_DSN` and `CLOUDFLARE_CACHE_PURGE_ZONE_ID` / `CLOUDFLARE_CACHE_PURGE_API_TOKEN`. Social account @@ -92,6 +99,16 @@ Manual runs are queued and executed by the lane's alarm; poll `/status` for the A manual run interrupted mid-way is reported as failed rather than replayed, so social posts are never repeated automatically. +## iPad token uploads + +`PUT /bullet-token` takes the body of a SplatNet 3 `/api/bullet_tokens` response, with +`Authorization: Bearer $TOKEN_UPLOAD_TOKEN`. That token only allows uploads (it cannot reach +the control endpoints), and uploads are disabled without it. splat-mitmproxy uses the same +value for both environments, so set the same secret on dev and production. + +It answers `{ ok, region, expires }`, or 400 for a body without a `bulletToken`. Do not test +it with a made-up token: whatever is uploaded replaces the region's working one. + ## Archive With `ARCHIVE_DATA` set, every data file an updater publishes is also written to the archive diff --git a/workers/updater/admin/mock/api.mjs b/workers/updater/admin/mock/api.mjs index 78b7cce..646e628 100644 --- a/workers/updater/admin/mock/api.mjs +++ b/workers/updater/admin/mock/api.mjs @@ -471,6 +471,15 @@ export function createMockApi() { }); } + // The iPad uploads a North America token about once an hour, at no fixed minute. + if (region === 'US') { + for (let at = now - (now % HOUR) + 12 * MINUTE; at >= from; at -= HOUR) { + let uploadAt = at + Math.round(random(at + 1) * 20 * MINUTE); + + events.push({ at: uploadAt, finishedAt: uploadAt + 40, ok: true, trigger: 'upload', errors: [], warnings: [] }); + } + } + if (refreshed[region]) { events.push({ at: refreshed[region], finishedAt: refreshed[region] + 2400, ok: true, trigger: 'manual', errors: [], warnings: [] }); } @@ -479,6 +488,10 @@ export function createMockApi() { } function authLogs(region, event) { + if (event.trigger === 'upload') { + return { lines: [{ at: event.at, level: 'info', text: `Cached a bullet token uploaded from the iPad, until ${new Date(event.at + 115 * MINUTE).toISOString()}` }], omitted: 0 }; + } + let lines = [ { at: event.at + 30, level: 'info', text: `[NSO] [${region}] Renewing credentials...` }, ...event.warnings.map(text => ({ at: event.at + 600, level: 'error', text })), @@ -500,7 +513,7 @@ export function createMockApi() { return { region, alarmAt: !authScheduled ? null : hour + offset > now ? hour + offset : hour + HOUR + offset, - lastRefreshAt: events[0]?.finishedAt ?? null, + lastRefreshAt: events.find(event => event.trigger !== 'upload')?.finishedAt ?? null, enabled: authScheduled, hasSessionToken: true, events, diff --git a/workers/updater/admin/src/components/ActivityDetail.vue b/workers/updater/admin/src/components/ActivityDetail.vue index 0cd88a2..ffa1634 100644 --- a/workers/updater/admin/src/components/ActivityDetail.vue +++ b/workers/updater/admin/src/components/ActivityDetail.vue @@ -67,7 +67,7 @@ {{ TRIGGER_LABELS[item.event.trigger] ?? 'Renewal' }} -
+
Duration
@@ -104,6 +104,9 @@ A step failed along the way, but a later one made up for it and the renewal finished with new tokens.

+

+ A bullet token the iPad's SplatNet 3 app received, captured by splat-mitmproxy on ghost. It replaced the cached token until the next renewal or upload. +

The tokens from the last successful renewal keep working for about two hours, so one failed renewal does not stop updates.

@@ -117,7 +120,7 @@

- {{ logError ?? (logs ? 'This renewal printed nothing.' : 'Loading…') }} + {{ logError ?? (logs ? 'Nothing was printed.' : 'Loading…') }}

diff --git a/workers/updater/admin/src/components/AuthCard.vue b/workers/updater/admin/src/components/AuthCard.vue index bc3dd9b..0daa9e2 100644 --- a/workers/updater/admin/src/components/AuthCard.vue +++ b/workers/updater/admin/src/components/AuthCard.vue @@ -32,17 +32,24 @@ -