Files
splatoon3.ink/app/splatnet/auth.mjs
Matt Isenhower cf9c30ad63 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>
2026-11-15 14:32:05 -08:00

153 lines
4.9 KiB
JavaScript

import pLimit from 'p-limit';
import ValueCache from '../common/ValueCache.mjs';
import prefixedConsole from '../common/prefixedConsole.mjs';
import { calculateCacheExpiry } from '../common/util.mjs';
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.
*
* This runs in-process. The Node runner uses it directly; in the Worker, each region's
* RegionAuth Durable Object runs this same code so that parallel updaters share one token
* and never log in at the same time.
*/
export class LocalAuth {
/**
* @param {import('./NsoClient.mjs').default} nsoClient
* @param {object} [options]
* @param {string} [options.language] Accept-Language for a newly created token
* @param {boolean} [options.useCache] false to obtain a fresh token
*/
bulletToken(nsoClient, { language = 'en-US', useCache = true } = {}) {
return tokenLimit(nsoClient)(async () => {
let bulletTokenCache = bulletTokenCacheFor(nsoClient);
let bulletToken = useCache
? await bulletTokenCache.getData()
: null;
if (!bulletToken) {
let webServiceToken = await nsoClient.getWebServiceToken(SPLATNET3_WEB_SERVICE_ID);
bulletToken = await this._createBulletToken(nsoClient, webServiceToken, language, bulletTokenCache);
}
return bulletToken;
});
}
/**
* 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
* needs that is missing, so it can make up for an earlier failure.
* @param {import('./NsoClient.mjs').default} nsoClient
* @returns {Promise<boolean>} Whether it ended with a new bullet token
*/
async refresh(nsoClient) {
await safe(() => nsoClient.getCoralSession(false));
await safe(() => nsoClient.getWebServiceToken(SPLATNET3_WEB_SERVICE_ID, false));
return safe(() => this.bulletToken(nsoClient, { useCache: false }));
}
async _createBulletToken(nsoClient, webServiceToken, language, bulletTokenCache) {
const console = prefixedConsole('SplatNet', nsoClient.region);
console.info('Creating bullet token...');
let response = await fetch(SPLATNET3_BASE_URL + '/api/bullet_tokens', {
method: 'POST',
headers: {
'X-Web-View-Ver': queryHashes.version,
'X-NACOUNTRY': 'US', // TODO
'X-GameWebToken': webServiceToken,
'Accept-Language': language,
'User-Agent': process.env.USER_AGENT,
},
});
if (!response.ok) {
throw new Error(`Invalid bullet token response code: ${response.status}`);
}
let bulletToken = await response.json();
let expiry = calculateCacheExpiry(BULLET_TOKEN_TTL_SECONDS);
await bulletTokenCache.setData(bulletToken, expiry);
console.debug(`Caching bullet token until: ${expiry}`);
return bulletToken;
}
}
// Returns whether the step succeeded.
async function safe(callable) {
try {
await callable();
return true;
} catch (e) {
console.error(e);
return false;
}
}
let provider = null;
/**
* Replace the token provider (the Worker routes requests to RegionAuth Durable Objects).
* @param {object|null} auth An object with bulletToken() and refresh(), or null for LocalAuth
*/
export function configureAuth(auth) {
provider = auth;
}
/**
* @returns {LocalAuth} The configured token provider (LocalAuth or an equivalent)
*/
export function auth() {
return provider ??= new LocalAuth;
}