mirror of
https://github.com/misenhower/splatoon3.ink.git
synced 2026-11-18 16:58:18 -06:00
Accept bullet tokens uploaded from the iPad and show them on the timeline
splat-mitmproxy now PUTs the captured /api/bullet_tokens response to /bullet-token on each updater Worker, authenticated with its own TOKEN_UPLOAD_TOKEN. The Worker caches it for the TOKEN_UPLOAD_REGION account (US) and records an "iPad upload" event on the Nintendo auth row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<number>} 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}`);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
{{ TRIGGER_LABELS[item.event.trigger] ?? 'Renewal' }}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<div v-if="item.event.trigger !== 'upload'">
|
||||
<dt class="label">
|
||||
Duration
|
||||
</dt>
|
||||
@@ -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.
|
||||
</p>
|
||||
</template>
|
||||
<p v-if="item.event.trigger === 'upload'" class="text-muted">
|
||||
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.
|
||||
</p>
|
||||
<p v-if="!item.event.ok" class="text-muted">
|
||||
The tokens from the last successful renewal keep working for about two hours, so one failed renewal does not stop updates.
|
||||
</p>
|
||||
@@ -117,7 +120,7 @@
|
||||
</div>
|
||||
<LogLines v-if="logs?.lines.length" :lines="logs.lines" class="max-h-72" />
|
||||
<p v-else class="text-muted">
|
||||
{{ logError ?? (logs ? 'This renewal printed nothing.' : 'Loading…') }}
|
||||
{{ logError ?? (logs ? 'Nothing was printed.' : 'Loading…') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -32,17 +32,24 @@
|
||||
<template v-else-if="auth.alarmAt">
|
||||
Next at <span class="font-mono">{{ clock.time(auth.alarmAt, false) }}</span>
|
||||
</template>
|
||||
<template v-if="(auth.enabled === false || auth.alarmAt) && auth.events?.[0]">
|
||||
<template v-if="(auth.enabled === false || auth.alarmAt) && lastRenewal(auth)">
|
||||
·
|
||||
</template>
|
||||
<RouterLink
|
||||
v-if="auth.events?.[0]"
|
||||
:to="{ name: 'timeline', query: { item: `auth:${region}:${auth.events[0].at}` } }"
|
||||
v-if="lastRenewal(auth)"
|
||||
:to="{ name: 'timeline', query: { item: `auth:${region}:${lastRenewal(auth).at}` } }"
|
||||
class="underline decoration-muted underline-offset-2 hover:decoration-ink"
|
||||
>
|
||||
Last renewal
|
||||
</RouterLink>
|
||||
</span>
|
||||
<RouterLink
|
||||
v-if="lastUpload(auth)"
|
||||
:to="{ name: 'timeline', query: { item: `auth:${region}:${lastUpload(auth).at}` } }"
|
||||
class="text-[13px] text-muted underline decoration-muted underline-offset-2 hover:decoration-ink"
|
||||
>
|
||||
iPad token uploaded {{ formatRelative(lastUpload(auth).at, store.now) }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -84,9 +91,18 @@ const props = defineProps({
|
||||
// One switch covers every region; it counts as on while any region is still on.
|
||||
const scheduled = computed(() => Object.values(props.regions).some(auth => auth.enabled !== false));
|
||||
|
||||
// The latest events come newest first, iPad uploads among the renewals.
|
||||
function lastRenewal(auth) {
|
||||
return auth.events?.find(event => event.trigger !== 'upload') ?? null;
|
||||
}
|
||||
|
||||
function lastUpload(auth) {
|
||||
return auth.events?.find(event => event.trigger === 'upload') ?? null;
|
||||
}
|
||||
|
||||
// The most recent renewal's error, if it failed.
|
||||
function failure(auth) {
|
||||
let latest = auth.events?.[0];
|
||||
let latest = lastRenewal(auth);
|
||||
|
||||
return latest && !latest.ok ? latest.errors[0] ?? 'Last renewal failed' : null;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Everything the updater did or is about to do, as one list: lane runs, credential renewals,
|
||||
// social posts and archive compressions. The timeline and the activity list both draw from it, so they always show
|
||||
// the same things. Pure functions; no Vue in here.
|
||||
// Everything the updater did or is about to do, as one list: lane runs, credential renewals and
|
||||
// iPad token uploads, social posts and archive compressions. The timeline and the activity list
|
||||
// both draw from it, so they always show the same things. Pure functions; no Vue in here.
|
||||
|
||||
import { formatDuration, ROW_LABELS, runKind, TRIGGER_LABELS } from './format.js';
|
||||
import { collectUpcoming, currentRun, HOUR, MINUTE, normalizeRun } from './runs.js';
|
||||
@@ -58,6 +58,17 @@ function upcomingItem(slot) {
|
||||
}
|
||||
|
||||
function authItem(region, event) {
|
||||
let summary;
|
||||
|
||||
if (!event.ok) {
|
||||
summary = event.errors?.[0] ?? 'Renewal failed';
|
||||
} else if (event.trigger === 'upload') {
|
||||
// Received, not obtained: there is no duration worth showing.
|
||||
summary = TRIGGER_LABELS.upload;
|
||||
} else {
|
||||
summary = `${TRIGGER_LABELS[event.trigger] ?? 'Renewal'} · ${formatDuration(event.finishedAt - event.at)}`;
|
||||
}
|
||||
|
||||
return {
|
||||
key: `auth:${region}:${event.at}`,
|
||||
kind: 'auth',
|
||||
@@ -66,9 +77,7 @@ function authItem(region, event) {
|
||||
end: event.finishedAt,
|
||||
state: event.ok ? 'ok' : 'failed',
|
||||
title: `${ROW_LABELS.auth} · ${region}`,
|
||||
summary: event.ok
|
||||
? `${TRIGGER_LABELS[event.trigger] ?? 'Renewal'} · ${formatDuration(event.finishedAt - event.at)}`
|
||||
: event.errors?.[0] ?? 'Renewal failed',
|
||||
summary,
|
||||
manual: event.trigger === 'manual',
|
||||
region,
|
||||
event,
|
||||
|
||||
@@ -75,6 +75,19 @@ describe('buildActivity', () => {
|
||||
expect(byKey[`auth:US:${T0 - 25 * MINUTE}`]).toMatchObject({ row: 'auth', region: 'US', title: 'Nintendo auth · US', summary: 'HTTP 502' });
|
||||
});
|
||||
|
||||
it('shows iPad token uploads among the renewals, without a duration', () => {
|
||||
let now = T0 + 10 * MINUTE;
|
||||
let upload = { at: T0 - 5 * MINUTE, finishedAt: T0 - 5 * MINUTE + 40, ok: true, trigger: 'upload', errors: [], warnings: [] };
|
||||
let items = buildActivity({
|
||||
status: status(now, { auth: { US: { hasSessionToken: true, alarmAt: null } } }),
|
||||
history: history({ auth: { US: { [upload.at]: upload } } }),
|
||||
});
|
||||
|
||||
expect(items.find(item => item.key === `auth:US:${upload.at}`)).toMatchObject({
|
||||
row: 'auth', state: 'ok', title: 'Nintendo auth · US', summary: 'iPad upload', manual: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows archive compressions, the one in progress, and the next when it is close', () => {
|
||||
let now = T0 + 10 * MINUTE;
|
||||
let done = { id: 'c1', trigger: 'scheduled', maxDays: 10, dryRun: false, startedAt: T0 - 9 * HOUR, finishedAt: T0 - 9 * HOUR + 43_000, ok: true, exitCode: 0 };
|
||||
|
||||
@@ -125,4 +125,5 @@ export const TRIGGER_LABELS = {
|
||||
scheduled: 'Scheduled',
|
||||
continuation: 'Continuation',
|
||||
manual: 'Manual',
|
||||
upload: 'iPad upload',
|
||||
};
|
||||
|
||||
@@ -34,7 +34,8 @@ export function nextRefreshAt(region, now = Date.now()) {
|
||||
* It runs the same LocalAuth code as the Node runner; caches stay in private R2 storage.
|
||||
*
|
||||
* Storage: "region"; "scheduled" (false once scheduled renewals are turned off); "lastRefreshAt";
|
||||
* "event:*" (the last 48 hours of renewals, each with what it printed, for the admin panel).
|
||||
* "event:*" (the last 48 hours of renewals and iPad uploads, each with what it printed, for the
|
||||
* admin panel).
|
||||
*/
|
||||
export class RegionAuth extends DurableObject {
|
||||
#auth = new LocalAuth;
|
||||
@@ -92,9 +93,8 @@ export class RegionAuth extends DurableObject {
|
||||
let problems = log.lines.filter(line => line.level === 'error').map(line => line.text);
|
||||
// A renewal that failed without printing why still needs a reason.
|
||||
let errors = ok ? [] : problems.length ? problems : ['The renewal did not end with a new bullet token'];
|
||||
let expired = await this.ctx.storage.list({ prefix: 'event:', end: `event:${stamp(Date.now() - HISTORY_MS)}` });
|
||||
|
||||
await this.ctx.storage.put(`event:${stamp(startedAt)}`, {
|
||||
await this.#record({
|
||||
at: startedAt,
|
||||
finishedAt: Date.now(),
|
||||
ok,
|
||||
@@ -105,10 +105,6 @@ export class RegionAuth extends DurableObject {
|
||||
});
|
||||
await this.ctx.storage.put('lastRefreshAt', Date.now());
|
||||
|
||||
if (expired.size) {
|
||||
await this.ctx.storage.delete([...expired.keys()].slice(0, 128));
|
||||
}
|
||||
|
||||
if (errors.length) {
|
||||
Sentry.captureException(failure ?? new Error(`Nintendo credential renewal failed: ${errors[0]}`), { tags: { region, trigger } });
|
||||
}
|
||||
@@ -118,6 +114,42 @@ export class RegionAuth extends DurableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache a bullet token uploaded from the iPad (splat-mitmproxy) in place of the region's
|
||||
* current one, and show it among the renewals. The next renewal replaces it in turn.
|
||||
* @param {{ region: string, bulletToken: object }} options
|
||||
* @returns {Promise<{ region: string, expires: number }>} When the cached token expires
|
||||
*/
|
||||
async storeUpload({ region, bulletToken }) {
|
||||
await this.#remember(region);
|
||||
|
||||
let at = Date.now();
|
||||
let expires = await this.#auth.storeBulletToken(this.#nsoClient(region), bulletToken);
|
||||
|
||||
await this.#record({
|
||||
at,
|
||||
finishedAt: Date.now(),
|
||||
ok: true,
|
||||
trigger: 'upload',
|
||||
errors: [],
|
||||
warnings: [],
|
||||
logs: { lines: [{ at, level: 'info', text: `Cached a bullet token uploaded from the iPad, until ${new Date(expires).toISOString()}` }], omitted: 0 },
|
||||
});
|
||||
|
||||
return { region, expires };
|
||||
}
|
||||
|
||||
// Keep an event for the admin panel, and forget those older than the history it shows.
|
||||
async #record(event) {
|
||||
let expired = await this.ctx.storage.list({ prefix: 'event:', end: `event:${stamp(Date.now() - HISTORY_MS)}` });
|
||||
|
||||
await this.ctx.storage.put(`event:${stamp(event.at)}`, event);
|
||||
|
||||
if (expired.size) {
|
||||
await this.ctx.storage.delete([...expired.keys()].slice(0, 128));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renewals that started in a span of time, newest first, without their log lines.
|
||||
* @param {{ from?: number, to?: number, limit?: number }} [options] `to` is exclusive
|
||||
|
||||
@@ -40,14 +40,18 @@ function timingSafeEqual(a, b) {
|
||||
return left.byteLength === right.byteLength && crypto.subtle.timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
function authorized(request, env) {
|
||||
if (!env.RUN_TOKEN) {
|
||||
function hasBearer(request, secret) {
|
||||
if (!secret) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let [scheme, token] = (request.headers.get('Authorization') ?? '').split(' ');
|
||||
|
||||
return scheme === 'Bearer' && !!token && timingSafeEqual(token, env.RUN_TOKEN);
|
||||
return scheme === 'Bearer' && !!token && timingSafeEqual(token, secret);
|
||||
}
|
||||
|
||||
function authorized(request, env) {
|
||||
return hasBearer(request, env.RUN_TOKEN);
|
||||
}
|
||||
|
||||
function json(body, status = 200) {
|
||||
@@ -76,6 +80,44 @@ async function armAll(env) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /bullet-token: splat-mitmproxy on ghost uploads the bullet token response it captured from
|
||||
* the iPad's SplatNet 3 app. It belongs to the account of TOKEN_UPLOAD_REGION and replaces that
|
||||
* region's cached token. The upload token only allows this; it cannot start runs.
|
||||
* @param {Request} request
|
||||
* @param {object} env Worker environment
|
||||
* @returns {Promise<Response>} The response
|
||||
*/
|
||||
async function tokenUpload(request, env) {
|
||||
if (!hasBearer(request, env.TOKEN_UPLOAD_TOKEN)) {
|
||||
return new Response(env.TOKEN_UPLOAD_TOKEN ? 'Unauthorized' : 'Token uploads are disabled', { status: 401 });
|
||||
}
|
||||
|
||||
if (request.method !== 'PUT') {
|
||||
return json({ ok: false, error: 'Use PUT' }, 405);
|
||||
}
|
||||
|
||||
let region = env.TOKEN_UPLOAD_REGION;
|
||||
|
||||
if (!REGIONS.includes(region)) {
|
||||
return json({ ok: false, error: 'TOKEN_UPLOAD_REGION is not set to a region' }, 500);
|
||||
}
|
||||
|
||||
let bulletToken;
|
||||
|
||||
try {
|
||||
bulletToken = await request.json();
|
||||
} catch {
|
||||
return json({ ok: false, error: 'The body must be the bullet token response as JSON' }, 400);
|
||||
}
|
||||
|
||||
if (typeof bulletToken?.bulletToken !== 'string' || !bulletToken.bulletToken) {
|
||||
return json({ ok: false, error: 'The body has no bulletToken' }, 400);
|
||||
}
|
||||
|
||||
return json({ ok: true, ...(await regionAuth(env, region).storeUpload({ region, bulletToken })) });
|
||||
}
|
||||
|
||||
async function control(request, env) {
|
||||
let url = new URL(request.url);
|
||||
let route = `${request.method} ${url.pathname}`;
|
||||
@@ -173,6 +215,17 @@ export default withSentry(sentryOptions, {
|
||||
}
|
||||
}
|
||||
|
||||
if (new URL(request.url).pathname === '/bullet-token') {
|
||||
try {
|
||||
return await tokenUpload(request, env);
|
||||
} catch (error) {
|
||||
// RegionAuth reports its own errors to Sentry.
|
||||
console.error('Token upload failed:', error);
|
||||
|
||||
return json({ ok: false, error: 'The upload failed' }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
if (!authorized(request, env)) {
|
||||
return new Response(env.RUN_TOKEN ? 'Unauthorized' : 'Control endpoints are disabled', { status: 401 });
|
||||
}
|
||||
|
||||
@@ -321,6 +321,25 @@ describe('RegionAuth', () => {
|
||||
expect(event).toMatchObject({ ok: true, errors: [], warnings: ['[znca-api] f: 503 Service Unavailable'] });
|
||||
});
|
||||
|
||||
it('caches an uploaded bullet token in place of the current one, and records the upload', async () => {
|
||||
await env.PRIVATE.put('cache/nso.12345678.bulletToken.json', JSON.stringify({
|
||||
expires: Date.now() + 3600_000,
|
||||
data: { bulletToken: 'cached-token' },
|
||||
}));
|
||||
let us = regionAuth();
|
||||
|
||||
let { expires } = await us.storeUpload({ region: 'US', bulletToken: { bulletToken: 'ipad-token' } });
|
||||
|
||||
expect(expires).toBeGreaterThan(Date.now() + 110 * 60_000);
|
||||
expect(await us.bulletToken({ region: 'US' })).toEqual({ bulletToken: 'ipad-token' });
|
||||
|
||||
let status = await us.status();
|
||||
expect(status.events[0]).toMatchObject({ ok: true, trigger: 'upload', errors: [], warnings: [] });
|
||||
// Uploads are not renewals.
|
||||
expect(status.lastRefreshAt).toBeNull();
|
||||
expect((await us.event({ at: status.events[0].at })).logs.lines[0].text).toMatch(/uploaded from the iPad/);
|
||||
});
|
||||
|
||||
it('counts a renewal that ended without a new bullet token as failed', async () => {
|
||||
// console.error is left alone: replacing it would skip the renewal's log capture.
|
||||
vi.spyOn(LocalAuth.prototype, 'refresh').mockImplementation(async () => {
|
||||
@@ -337,6 +356,43 @@ describe('RegionAuth', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('bullet token uploads', () => {
|
||||
function upload(body, { method = 'PUT', token = 'test-upload-token' } = {}) {
|
||||
return worker.fetch(new Request('https://updater.test/bullet-token', {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: typeof body === 'string' ? body : JSON.stringify(body),
|
||||
}), env);
|
||||
}
|
||||
|
||||
it('requires the upload token, which is not the run token', async () => {
|
||||
expect((await upload({ bulletToken: 'x' }, { token: null })).status).toBe(401);
|
||||
expect((await upload({ bulletToken: 'x' }, { token: 'test-run-token' })).status).toBe(401);
|
||||
expect((await request('/status', { token: 'test-upload-token' })).status).toBe(401);
|
||||
});
|
||||
|
||||
it('rejects anything but a bullet token response', async () => {
|
||||
expect((await upload({ bulletToken: 'x' }, { method: 'POST' })).status).toBe(405);
|
||||
expect((await upload('not json')).status).toBe(400);
|
||||
expect((await upload({ token: 'x' })).status).toBe(400);
|
||||
expect((await upload({ bulletToken: '' })).status).toBe(400);
|
||||
});
|
||||
|
||||
it('caches the token for the North America account', async () => {
|
||||
let body = { bulletToken: 'from-ipad', lang: 'en-US', is_noe_country: 'false' };
|
||||
let response = await upload(body);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toMatchObject({ ok: true, region: 'US', expires: expect.any(Number) });
|
||||
|
||||
let cached = await env.PRIVATE.get('cache/nso.12345678.bulletToken.json').then(object => object.json());
|
||||
expect(cached).toMatchObject({ data: body, expires: expect.any(Number), cachedAt: expect.any(String) });
|
||||
|
||||
let [event] = (await env.REGION_AUTH.getByName('US').status()).events;
|
||||
expect(event).toMatchObject({ trigger: 'upload', ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('control endpoints', () => {
|
||||
it('requires the run token', async () => {
|
||||
expect((await request('/status', { token: null })).status).toBe(401);
|
||||
|
||||
@@ -14,6 +14,7 @@ export default defineConfig({
|
||||
miniflare: {
|
||||
bindings: {
|
||||
RUN_TOKEN: 'test-run-token',
|
||||
TOKEN_UPLOAD_TOKEN: 'test-upload-token',
|
||||
NINTENDO_TOKEN_US: 'session-token-us-12345678',
|
||||
NXAPI_CLIENT_ID: 'client',
|
||||
NXAPI_SHARED_SECRET: 'secret',
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
// Select --env dev or --env production explicitly. Automatic scheduling starts off for a
|
||||
// new scheduler; POST /schedule?enabled=true turns it on and the setting survives deploys.
|
||||
// Secrets: NINTENDO_TOKEN_{US,EU,JP,AP}, NXAPI_CLIENT_ID, NXAPI_SHARED_SECRET, USER_AGENT,
|
||||
// RUN_TOKEN, ACCESS_TEAM_DOMAIN and ACCESS_AUD (admin panel sign-in), AWS_ACCESS_KEY_ID and
|
||||
// RUN_TOKEN, TOKEN_UPLOAD_TOKEN (splat-mitmproxy's iPad bullet token uploads, PUT /bullet-token),
|
||||
// ACCESS_TEAM_DOMAIN and ACCESS_AUD (admin panel sign-in), AWS_ACCESS_KEY_ID and
|
||||
// AWS_SECRET_ACCESS_KEY (a DigitalOcean Spaces key that can write to the archive bucket),
|
||||
// optional SENTRY_DSN, CLOUDFLARE_CACHE_PURGE_ZONE_ID/API_TOKEN, and (production only) the
|
||||
// social account credentials.
|
||||
@@ -39,6 +40,8 @@
|
||||
},
|
||||
"vars": {
|
||||
"ENVIRONMENT": "dev",
|
||||
// The region whose account the iPad uploads bullet tokens for (North America).
|
||||
"TOKEN_UPLOAD_REGION": "US",
|
||||
"ADMIN_HOSTNAME": "admin.dev.splatoon3.ink",
|
||||
"SITE_URL": "https://dev.splatoon3.ink",
|
||||
// The dev bucket's own custom domain, like assets.splatoon3.ink in production.
|
||||
@@ -84,6 +87,8 @@
|
||||
},
|
||||
"vars": {
|
||||
"ENVIRONMENT": "production",
|
||||
// The region whose account the iPad uploads bullet tokens for (North America).
|
||||
"TOKEN_UPLOAD_REGION": "US",
|
||||
"ADMIN_HOSTNAME": "admin.splatoon3.ink",
|
||||
"SITE_URL": "https://splatoon3.ink",
|
||||
"ASSET_URL": "https://assets.splatoon3.ink",
|
||||
|
||||
Reference in New Issue
Block a user