Make the shared backend code run in Cloudflare Workers

Replace the remaining Node-only dependencies so the updaters and social
posters bundle and run in workerd, while the Node runner keeps working:

- Replace nxapi with app/splatnet/coral.mjs (fetch + WebCrypto), aligned
  with nxapi 1.6.1-next.257: znca compatibility 3.5.0, the current client
  version, and the slimmer Login parameter. Use one znca-api client per
  Nintendo account, since its token binds to the first account it serves.
  Cache the remote config in private storage instead of restarting daily.
  Sessions cached by the nxapi package trigger a fresh login.
- Convert images through #image-converter: sharp in Node, the Images
  binding in Workers. Read Bluesky aspect ratios from the PNG header.
- Replace twitter-api-v2 with OAuth 1.0a signed fetch; TwitterClient now
  only updates the seasonal X profile (posts go through Buffer).
- Load avatars through #avatars (bundled as Data modules in Workers) and
  keep the local Chrome driver out of Worker bundles via
  #local-screenshot-driver.
- prefixedConsole forwards to the global console; shared code reports to
  Sentry through @sentry/core.

Verified live: full credential refresh for all four regions in Node, and
the complete Coral → bullet token → GraphQL chain for EU inside workerd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Matt Isenhower
2026-11-08 16:51:54 -08:00
parent 21a4f5d85c
commit 8a02e2bfdc
34 changed files with 964 additions and 1709 deletions

View File

@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
Splatoon3.ink displays Splatoon 3 map rotations, Salmon Run schedules, SplatNet gear, and more. It has a Vue 3 frontend (`src/`) and a Node.js backend (`app/`) in a single repository. The backend fetches data from Nintendo's SplatNet3 GraphQL API via nxapi and publishes updates to social media (Mastodon, Bluesky, Threads).
Splatoon3.ink displays Splatoon 3 map rotations, Salmon Run schedules, SplatNet gear, and more. It has a Vue 3 frontend (`src/`) and a Node.js backend (`app/`) in a single repository. The backend fetches data from Nintendo's SplatNet3 GraphQL API (authenticating through the nxapi znca API; `app/splatnet/coral.mjs` reimplements the nxapi client so it also runs in Workers) and publishes updates to social media (X via Buffer, Mastodon, Bluesky, Threads).
## Commands
@@ -43,9 +43,10 @@ npm start # Run the Node backend locally: splatnet → social → c
- ESLint flat config with Vue, JSDoc, and import-alias plugins
- 2-space indentation, single quotes, semicolons, trailing commas on multiline
- Shared backend code must also run in Cloudflare Workers: avoid Node-only APIs there. Runtime-specific pieces use package imports with `workerd` and `default` conditions (`#image-converter`, `#avatars`, `#local-screenshot-driver` in package.json)
- In `src/` files, use `@/` import alias (e.g., `import Foo from '@/components/Foo.vue'`)
- Vue: multi-word component names not required, up to 4 attributes per single line, self-closing void HTML elements
- Node.js 22, ESM modules throughout (`.mjs` extension for backend files, `.js`/`.vue` for frontend)
- Node.js 24, ESM modules throughout (`.mjs` extension for backend files, `.js`/`.vue` for frontend)
## Testing

View File

@@ -0,0 +1,16 @@
import sharp from 'sharp';
// Node implementation of #image-converter. The package import keeps native sharp out of the
// Worker bundle; convert.worker.mjs is the Workers counterpart.
/**
* @param {Uint8Array} png
* @param {object} [options]
* @param {number} [options.quality]
* @returns {Promise<Uint8Array>} JPEG bytes
*/
export async function convertToJpeg(png, { quality = 80 } = {}) {
return new Uint8Array(
await sharp(png).flatten({ background: '#ffffff' }).jpeg({ quality }).toBuffer(),
);
}

View File

@@ -0,0 +1,19 @@
import { env } from 'cloudflare:workers';
// Workers implementation of #image-converter, using the Images binding.
/**
* @param {Uint8Array} png
* @param {object} [options]
* @param {number} [options.quality]
* @param {object} [options.images] Images binding (defaults to env.IMAGES)
* @returns {Promise<Uint8Array>} JPEG bytes
*/
export async function convertToJpeg(png, { quality = 80, images = env.IMAGES } = {}) {
let result = await images
.input(new Response(png).body)
.transform({ background: '#ffffff' })
.output({ format: 'image/jpeg', quality });
return new Uint8Array(await result.response().arrayBuffer());
}

View File

@@ -0,0 +1,27 @@
import sharp from 'sharp';
import { describe, expect, it } from 'vitest';
import { convertToJpeg } from '#image-converter';
import { pngSize } from './png.mjs';
async function png(width, height) {
return new Uint8Array(await sharp({
create: { width, height, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
}).png().toBuffer());
}
describe('images', () => {
it('reads PNG dimensions', async () => {
expect(pngSize(await png(12, 7))).toEqual({ width: 12, height: 7 });
expect(pngSize(new Uint8Array([1, 2, 3]))).toBeNull();
});
it('converts PNGs to JPEG on a white background in Node', async () => {
let jpeg = await convertToJpeg(await png(4, 3));
let { data, info } = await sharp(jpeg).raw().toBuffer({ resolveWithObject: true });
expect(jpeg).toBeInstanceOf(Uint8Array);
expect([jpeg[0], jpeg[1]]).toEqual([0xff, 0xd8]);
expect(info).toMatchObject({ width: 4, height: 3 });
expect(data[0]).toBeGreaterThan(240);
});
});

16
app/common/image/png.mjs Normal file
View File

@@ -0,0 +1,16 @@
/**
* Width and height from a PNG's IHDR chunk.
* @param {Uint8Array} bytes
* @returns {{ width: number, height: number }|null} The size, or null if the bytes are not a PNG
*/
export function pngSize(bytes) {
let signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
if (!bytes || bytes.length < 24 || !signature.every((byte, index) => bytes[index] === byte)) {
return null;
}
let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return { width: view.getUint32(16), height: view.getUint32(20) };
}

View File

@@ -1,12 +1,24 @@
import { Console } from 'node:console';
import consoleStamp from 'console-stamp';
const methods = ['log', 'info', 'warn', 'error', 'debug'];
/**
* A console whose messages start with [prefix] labels. It forwards to the global console at
* call time, so the Node CLI's timestamps (console-stamp) and Workers logging both apply.
* @param {...string} prefixes
* @returns {Record<'log'|'info'|'warn'|'error'|'debug', (...args: unknown[]) => void>} The prefixed console
*/
export default function prefixedConsole(...prefixes) {
let result = new Console({ stdout: process.stdout, stderr: process.stderr });
let prefix = prefixes.map(s => `[${s}]`).join(' ');
let format = `:date(dd.mm.yyyy HH:MM:ss.l) :label(7) ${prefix}`.trim();
consoleStamp(result, { format });
return result;
return Object.fromEntries(methods.map(method => [method, (...args) => {
if (!prefix) {
return console[method](...args);
}
// Keep printf-style placeholders in the first argument working.
if (typeof args[0] === 'string') {
return console[method](`${prefix} ${args[0]}`, ...args.slice(1));
}
return console[method](prefix, ...args);
}]));
}

View File

@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import prefixedConsole from './prefixedConsole.mjs';
describe('prefixedConsole', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('prefixes messages and keeps format placeholders working', () => {
let info = vi.spyOn(console, 'info').mockImplementation(() => {});
prefixedConsole('Updater', 'US').info('Fetching page %s', 2);
expect(info).toHaveBeenCalledWith('[Updater] [US] Fetching page %s', 2);
});
it('passes non-string values after the prefix', () => {
let error = vi.spyOn(console, 'error').mockImplementation(() => {});
let failure = new Error('failed');
prefixedConsole('Images').error(failure);
expect(error).toHaveBeenCalledWith('[Images]', failure);
});
it('looks up the global console when called', () => {
let logger = prefixedConsole('Late');
let warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
logger.warn('message');
expect(warn).toHaveBeenCalledWith('[Late] message');
});
});

View File

@@ -1,5 +1,4 @@
import { CronJob } from 'cron';
import { setTimeout as sleep } from 'node:timers/promises';
import { updateFast, updateSlow } from './data/index.mjs';
import { warmCaches } from './splatnet/index.mjs';
import { sendStatuses } from './social/index.mjs';
@@ -8,7 +7,6 @@ import { compressArchives } from './data/ArchiveCompressor.mjs';
import { updateAvatars } from './social/updateAvatars.mjs';
let updating = false;
const restartGracePeriod = 5 * 60 * 1000; // 5 minutes
async function updateIfNotUpdating(mode) {
if (updating) {
@@ -30,28 +28,6 @@ async function updateIfNotUpdating(mode) {
}
}
// nxapi caches remote config for the life of the process, so restart daily to refresh it.
async function restartToRefreshConfig() {
const restartDeadline = Date.now() + restartGracePeriod;
if (updating) {
console.log('[Cron] Restart pending; waiting for in-progress update to finish...');
while (updating && Date.now() < restartDeadline) {
await sleep(5000);
}
}
if (updating) {
console.warn('[Cron] Update did not finish within 5 minutes; restarting anyway');
}
updating = true;
console.log('[Cron] Exiting to refresh nxapi remote config; container will restart');
process.exit(0);
}
export default function() {
new CronJob('5,20,35,50 * * * *', warmCaches, null, true);
new CronJob('15 0,1,2,3,4 * * * *', () => {
@@ -66,5 +42,4 @@ export default function() {
new CronJob('30 * * * *', updateAvatars, null, true);
new CronJob('30 0 * * *', () => compressArchives(10), null, true, 'UTC');
new CronJob('0 55 4 * * *', restartToRefreshConfig, null, true);
}

View File

@@ -15,9 +15,6 @@ vi.mock('cron', () => ({
}
},
}));
vi.mock('node:timers/promises', () => ({
setTimeout: ms => new Promise(resolve => setTimeout(resolve, ms)),
}));
vi.mock('./data/index.mjs', () => ({ updateFast: mocks.updateFast, updateSlow: mocks.updateSlow }));
vi.mock('./splatnet/index.mjs', () => ({ warmCaches: vi.fn() }));
vi.mock('./social/index.mjs', () => ({ sendStatuses: mocks.sendStatuses }));
@@ -67,27 +64,4 @@ describe('cron update coordination', () => {
expect(mocks.updateFast).toHaveBeenCalledTimes(2);
});
it('restarts after a bounded wait when an update never settles', async () => {
vi.useFakeTimers();
mocks.updateFast.mockReturnValue(new Promise(() => {}));
vi.spyOn(console, 'log').mockImplementation(() => {});
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const exit = vi.spyOn(process, 'exit').mockImplementation(() => {});
await loadJobs();
const update = mocks.jobs.get('15 0,1,2,3,4 * * * *');
const restart = mocks.jobs.get('0 55 4 * * *');
update();
const restarting = restart();
await vi.advanceTimersByTimeAsync(5 * 60 * 1000 - 1);
expect(exit).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(warn).toHaveBeenCalledWith('[Cron] Update did not finish within 5 minutes; restarting anyway');
expect(exit).toHaveBeenCalledWith(0);
await restarting;
});
});

View File

@@ -1,4 +1,5 @@
import * as Sentry from '@sentry/node';
// @sentry/core reports to whichever SDK the runtime initialized (Node or Cloudflare).
import * as Sentry from '@sentry/core';
import GearUpdater from './updaters/GearUpdater.mjs';
import StageScheduleUpdater from './updaters/StageScheduleUpdater.mjs';
import CoopUpdater from './updaters/CoopUpdater.mjs';

View File

@@ -1,4 +1,3 @@
import { Console } from 'node:console';
import ical from 'ical-generator';
import pFilter from 'p-filter';
import prefixedConsole from '../../common/prefixedConsole.mjs';
@@ -49,7 +48,7 @@ export default class DataUpdater
: defaultLocale;
}
/** @type {Console} */
/** @type {ReturnType<typeof prefixedConsole>} */
get console() {
this._console ??= prefixedConsole('Updater', this.region, this.name);

View File

@@ -0,0 +1,9 @@
// Workers stand-in for #local-screenshot-driver: the local driver needs Chrome, puppeteer and
// an HTTP server, so it is kept out of the Worker bundle. Workers use the Cloudflare driver.
export default class LocalScreenshotDriver {
async open() {
throw new Error('Local screenshots are not available in Workers; use SCREENSHOT_PROVIDER=cloudflare');
}
async close() {}
}

View File

@@ -1,5 +1,6 @@
import CloudflareScreenshotDriver from './CloudflareScreenshotDriver.mjs';
import LocalScreenshotDriver from './LocalScreenshotDriver.mjs';
// A package import keeps puppeteer and Chrome out of the Worker bundle.
import LocalScreenshotDriver from '#local-screenshot-driver';
export default function createScreenshotDriver(name, dependencies = {}) {
if (name === 'local') {

View File

@@ -1,4 +1,5 @@
import * as Sentry from '@sentry/node';
// @sentry/core reports to whichever SDK the runtime initialized (Node or Cloudflare).
import * as Sentry from '@sentry/core';
import prefixedConsole from '../common/prefixedConsole.mjs';
import ScreenshotHelper from '../screenshots/ScreenshotHelper.mjs';
import Client from './clients/Client.mjs';

View File

@@ -1,10 +1,10 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { captureException } from '@sentry/node';
import { captureException } from '@sentry/core';
import StatusGeneratorManager from './StatusGeneratorManager.mjs';
import BufferTwitterClient from './clients/BufferTwitterClient.mjs';
import { defaultClients } from './index.mjs';
vi.mock('@sentry/node', () => ({ captureException: vi.fn() }));
vi.mock('@sentry/core', () => ({ captureException: vi.fn() }));
vi.mock('../common/prefixedConsole.mjs', () => ({
default: () => ({ log: vi.fn(), info: vi.fn(), error: vi.fn(), warn: vi.fn() }),
}));

View File

@@ -0,0 +1,11 @@
import fs from 'node:fs/promises';
// Node implementation of #avatars; index.worker.mjs bundles the same files for Workers.
/**
* @param {string} filename An avatar file in this directory, such as default.png
* @returns {Promise<Uint8Array>} The PNG bytes
*/
export async function readAvatar(filename) {
return new Uint8Array(await fs.readFile(new URL(`./${filename}`, import.meta.url)));
}

View File

@@ -0,0 +1,23 @@
// Workers implementation of #avatars. Wrangler bundles the PNGs as Data modules
// (see the "rules" in the updater's wrangler config).
import defaultAvatar from './default.png';
import halloweenAvatar from './halloween.png';
import prideAvatar from './pride.png';
const avatars = {
'default.png': defaultAvatar,
'halloween.png': halloweenAvatar,
'pride.png': prideAvatar,
};
/**
* @param {string} filename An avatar file in this directory, such as default.png
* @returns {Promise<Uint8Array>} The PNG bytes
*/
export async function readAvatar(filename) {
if (!avatars[filename]) {
throw new Error(`Unknown avatar: ${filename}`);
}
return new Uint8Array(avatars[filename]);
}

View File

@@ -1,5 +1,6 @@
import { BskyAgent, RichText } from '@atproto/api';
import sharp from 'sharp';
import { convertToJpeg } from '#image-converter';
import { pngSize } from '../../common/image/png.mjs';
import Client from './Client.mjs';
export default class BlueskyClient extends Client
@@ -44,7 +45,7 @@ export default class BlueskyClient extends Client
async updateProfile(avatarBuffer, displayName) {
await this.login();
let jpeg = await sharp(avatarBuffer).jpeg().toBuffer();
let jpeg = await convertToJpeg(avatarBuffer);
let uploadResponse = await this._agent.uploadBlob(jpeg, { encoding: 'image/jpeg' });
await this._agent.upsertProfile((existing) => {
@@ -69,16 +70,15 @@ export default class BlueskyClient extends Client
let images = await Promise.all(
status.media.map(async m => {
// We have to convert the PNG to a JPG for Bluesky because of size limits
let jpeg = sharp(m.file).jpeg();
let metadata = await jpeg.metadata();
let buffer = await jpeg.toBuffer();
let size = pngSize(m.file);
let buffer = await convertToJpeg(m.file);
let response = await this._agent.uploadBlob(buffer, { encoding: 'image/jpeg' });
return {
image: response.data.blob,
alt: m.altText || '',
aspectRatio: { width: metadata.width, height: metadata.height },
...(size && { aspectRatio: size }),
};
}),
);

View File

@@ -1,4 +1,4 @@
import sharp from 'sharp';
import { convertToJpeg } from '#image-converter';
import Client from './Client.mjs';
import prefixedConsole from '../../common/prefixedConsole.mjs';
import ValueCache from '../../common/ValueCache.mjs';
@@ -80,7 +80,7 @@ export default class ThreadsClient extends Client {
}
let accessToken = await this._getAccessToken();
let jpeg = await sharp(status.media[0].file).jpeg().toBuffer();
let jpeg = await convertToJpeg(status.media[0].file);
// Upload the image to public storage so Threads can fetch it
let { imageUrl, storageKey } = await this._uploadImage(jpeg, generator.key);

View File

@@ -1,62 +1,63 @@
import { TwitterApi } from 'twitter-api-v2';
import Client from './Client.mjs';
import { oauth1Header } from './oauth1.mjs';
const API_URL = 'https://api.x.com/1.1/';
/**
* Direct X API access for seasonal profile updates (avatar and display name), which Buffer
* cannot change. Posts go through BufferTwitterClient instead.
*/
export default class TwitterClient extends Client
{
key = 'twitter';
name = 'Twitter';
/** @member {TwitterApi} */
_api;
async canSend() {
return ['CONSUMER_KEY', 'CONSUMER_SECRET', 'ACCESS_TOKEN_KEY', 'ACCESS_TOKEN_SECRET']
.every(key => !!process.env[`TWITTER_${key}`]);
get credentials() {
return {
consumerKey: process.env.TWITTER_CONSUMER_KEY,
consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
accessToken: process.env.TWITTER_ACCESS_TOKEN_KEY,
accessSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
};
}
api() {
if (!this._api) {
this._api = new TwitterApi({
appKey: process.env.TWITTER_CONSUMER_KEY,
appSecret: process.env.TWITTER_CONSUMER_SECRET,
accessToken: process.env.TWITTER_ACCESS_TOKEN_KEY,
accessSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});
}
return this._api;
async canSend() {
return Object.values(this.credentials).every(Boolean);
}
async updateProfile(avatarBuffer, displayName) {
await this.api().v1.updateAccountProfileImage(avatarBuffer);
await this.api().v1.updateAccountProfile({ name: displayName });
// Multipart bodies are not part of the OAuth signature.
let form = new FormData();
form.append('image', new Blob([avatarBuffer], { type: 'image/png' }), 'avatar.png');
await this.request('account/update_profile_image.json', { body: form });
let params = { name: displayName };
await this.request('account/update_profile.json', { params, body: new URLSearchParams(params) });
}
async send(status, generator) {
if (!status.media?.length) {
console.error(`[${this.name}] No media provided for ${generator.key}`);
return;
async request(path, { params = {}, body }) {
let url = new URL(path, API_URL).href;
let response = await fetch(url, {
method: 'POST',
headers: {
Authorization: await oauth1Header({ method: 'POST', url, params, credentials: this.credentials }),
},
body,
});
if (!response.ok) {
let detail = await response.text();
try {
let data = JSON.parse(detail);
detail = data.errors?.map(error => error.message).join('; ') || data.detail || detail;
} catch {
// Use the body as-is
}
throw new Error(`X API ${path} failed (${response.status}): ${detail}`);
}
try {
// Upload images
let mediaIds = await Promise.all(
status.media.map(async m => {
let id = await this.api().v1.uploadMedia(Buffer.from(m.file), { mimeType: m.type });
if (m.altText) {
await this.api().v1.createMediaMetadata(id, { alt_text: { text: m.altText } });
}
return id;
}),
);
// Send status
await this.api().v2.tweet(status.status, { media: { media_ids: mediaIds } });
} catch (error) {
console.error(`[${this.name}] Failed to post ${generator.key}:`, error.message);
throw error;
}
return response.json();
}
}

View File

@@ -0,0 +1,60 @@
// OAuth 1.0a request signing (HMAC-SHA1) with WebCrypto, for X's v1.1 account endpoints.
// https://developer.x.com/en/docs/authentication/oauth-1-0a/creating-a-signature
function percentEncode(value) {
return encodeURIComponent(value).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
}
function base64(bytes) {
let binary = '';
for (let byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
/**
* Build the Authorization header for a request.
* @param {object} request
* @param {string} request.method
* @param {string} request.url Request URL; its query parameters are signed
* @param {Record<string, string>} [request.params] Form-encoded body parameters (signed); omit for multipart bodies
* @param {{ consumerKey: string, consumerSecret: string, accessToken: string, accessSecret: string }} request.credentials
* @param {string} [request.nonce]
* @param {number} [request.timestamp] Seconds since the epoch
* @returns {Promise<string>} The OAuth Authorization header value
*/
export async function oauth1Header({ method, url, params = {}, credentials, nonce, timestamp }) {
let oauth = {
oauth_consumer_key: credentials.consumerKey,
oauth_nonce: nonce ?? crypto.randomUUID().replaceAll('-', ''),
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: String(timestamp ?? Math.floor(Date.now() / 1000)),
oauth_token: credentials.accessToken,
oauth_version: '1.0',
};
let target = new URL(url);
let signed = [
...Object.entries(oauth),
...target.searchParams.entries(),
...Object.entries(params),
].map(([key, value]) => [percentEncode(key), percentEncode(value)])
.sort(([a, x], [b, y]) => (a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0))
.map(([key, value]) => `${key}=${value}`)
.join('&');
let baseUrl = `${target.origin}${target.pathname}`;
let baseString = [method.toUpperCase(), percentEncode(baseUrl), percentEncode(signed)].join('&');
let signingKey = `${percentEncode(credentials.consumerSecret)}&${percentEncode(credentials.accessSecret)}`;
let encoder = new TextEncoder();
let key = await crypto.subtle.importKey('raw', encoder.encode(signingKey), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign']);
let signature = base64(new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(baseString))));
return 'OAuth ' + Object.entries({ ...oauth, oauth_signature: signature })
.map(([name, value]) => `${percentEncode(name)}="${percentEncode(value)}"`)
.join(', ');
}

View File

@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { oauth1Header } from './oauth1.mjs';
describe('oauth1Header', () => {
it('matches the signature from X\'s documentation example', async () => {
let header = await oauth1Header({
method: 'POST',
url: 'https://api.twitter.com/1.1/statuses/update.json?include_entities=true',
params: { status: 'Hello Ladies + Gentlemen, a signed OAuth request!' },
credentials: {
consumerKey: 'xvz1evFS4wEEPTGEFPHBog',
consumerSecret: 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw',
accessToken: '370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb',
accessSecret: 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE',
},
nonce: 'kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg',
timestamp: 1318622958,
});
expect(header).toContain('oauth_signature="hCtSmYh%2BiHYCEqBWrE7C7hYmtUk%3D"');
expect(header).toMatch(/^OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog", /);
});
});

View File

@@ -1,4 +1,3 @@
import { Console } from 'node:console';
import { createPinia } from 'pinia';
import { useCoopDataStore, useFestivalsDataStore, useGearDataStore, useSchedulesDataStore } from '../../../src/stores/data.mjs';
import prefixedConsole from '../../common/prefixedConsole.mjs';
@@ -34,7 +33,7 @@ export default class StatusGenerator
return this.messages.game(category, node, field);
}
/** @type {Console} */
/** @type {ReturnType<typeof prefixedConsole>} */
get console() {
this._console ??= prefixedConsole('Social', this.name);

View File

@@ -10,7 +10,7 @@ import ScreenshotHelper from '../screenshots/ScreenshotHelper.mjs';
vi.mock('../common/prefixedConsole.mjs', () => ({
default: () => ({ log: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
vi.mock('@sentry/node', () => ({ captureException: vi.fn() }));
vi.mock('@sentry/core', () => ({ captureException: vi.fn() }));
afterEach(() => {
vi.restoreAllMocks();

View File

@@ -1,15 +1,10 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import { readAvatar } from '#avatars';
import prefixedConsole from '../common/prefixedConsole.mjs';
import ValueCache from '../common/ValueCache.mjs';
import { defaultClients } from './index.mjs';
import { getCurrentVariant } from './avatarVariants.mjs';
import TwitterClient from './clients/TwitterClient.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const avatarsDir = path.join(__dirname, 'avatars');
const console = prefixedConsole('Social', 'Avatar');
function cacheForClient(client) {
@@ -40,8 +35,7 @@ export async function updateAvatars() {
// Read avatar file on first client that needs an update
if (!avatarBuffer) {
try {
let avatarPath = path.join(avatarsDir, variant.avatar);
avatarBuffer = await fs.readFile(avatarPath);
avatarBuffer = await readAvatar(variant.avatar);
} catch (error) {
console.error(`Failed to read avatar file ${variant.avatar}:`, error.message);
return;

View File

@@ -50,11 +50,10 @@ describe('Seasonal profile updates', () => {
updateImage = vi.fn().mockResolvedValue({});
updateProfile = vi.fn().mockResolvedValue({});
vi.spyOn(TwitterClient.prototype, 'api').mockReturnValue({
v1: {
updateAccountProfileImage: updateImage,
updateAccountProfile: updateProfile,
},
vi.spyOn(TwitterClient.prototype, 'request').mockImplementation(async (path, { params, body }) => {
return path === 'account/update_profile_image.json'
? updateImage(new Uint8Array(await body.get('image').arrayBuffer()))
: updateProfile(params);
});
});
@@ -87,7 +86,7 @@ describe('Seasonal profile updates', () => {
await updateAvatars();
await updateAvatars();
expect(updateImage).toHaveBeenCalledExactlyOnceWith(avatar);
expect(updateImage).toHaveBeenCalledExactlyOnceWith(new Uint8Array(avatar));
expect(updateProfile).toHaveBeenCalledExactlyOnceWith({ name: 'Splatoon3.eek 🎃' });
expect(cache.get('social.twitter.avatar')).toBe('halloween');
});

View File

@@ -1,60 +1,67 @@
import { createHmac } from 'node:crypto';
import CoralApi from 'nxapi/coral';
import { addUserAgent, setClientAuthentication } from 'nxapi';
import pLimit from 'p-limit';
import ValueCache from '../common/ValueCache.mjs';
import prefixedConsole from '../common/prefixedConsole.mjs';
import { calculateCacheExpiry } from '../common/util.mjs';
import { getRemoteConfig, getWebServiceToken, loginWithSessionToken, ZncaApiClient } from './coral.mjs';
const coralLimit = pLimit(1);
const webServiceLimit = pLimit(1);
let _nxapiInitialized = false;
// nxapi's remote config can disable Coral authentication, so refresh it regularly rather than
// keeping it for the life of the process (the old Node container restarted daily for this).
const remoteConfigLifetime = { min: 10 * 60, default: 60 * 60, max: 24 * 60 * 60 };
class SharedSecretAssertionProvider {
constructor(clientId, sharedSecret) {
this.clientId = clientId;
this.sharedSecret = sharedSecret;
this.scope = 'ca:gf ca:er ca:dr';
}
// One znca-api client per Nintendo account: its access token becomes bound to the first
// account that uses it, so clients cannot be shared between regions.
const zncaClients = new Map();
async create(aud, exp = 300) {
const now = Math.floor(Date.now() / 1000);
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
const payload = Buffer.from(JSON.stringify({
typ: 'client_assertion',
iss: this.clientId,
aud,
exp: now + exp,
iat: now,
})).toString('base64url');
const signData = `${header}.${payload}`;
const signature = createHmac('sha256', this.sharedSecret)
.update(signData)
.digest()
.toString('base64url');
return {
assertion: `${signData}.${signature}`,
type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
};
}
function userAgent() {
return ['splatoon3.ink', process.env.USER_AGENT].filter(Boolean).join(' ');
}
function initializeNxapi() {
if (!_nxapiInitialized) {
addUserAgent(process.env.USER_AGENT);
function remoteConfigExpiry(cacheControl) {
let maxAge = Number(/max-age=(\d+)/.exec(cacheControl ?? '')?.[1]);
let seconds = Number.isFinite(maxAge) ? maxAge : remoteConfigLifetime.default;
seconds = Math.min(Math.max(seconds, remoteConfigLifetime.min), remoteConfigLifetime.max);
if (process.env.NXAPI_CLIENT_ID && process.env.NXAPI_SHARED_SECRET) {
setClientAuthentication(
new SharedSecretAssertionProvider(process.env.NXAPI_CLIENT_ID, process.env.NXAPI_SHARED_SECRET),
);
}
return Date.now() + seconds * 1000;
}
/**
* The znca-api client (f generation and Coral request encryption) selected by nxapi's remote
* configuration, plus the Nintendo Switch Online app version to present.
* @param {string} account Identifies the Nintendo account the client will be used for
* @returns {Promise<{ znca: ZncaApiClient, zncaVersion: string }>} The client and app version
*/
export async function getZnca(account) {
let cache = new ValueCache('nxapi.config');
let config = await cache.getData();
if (!config) {
config = await getRemoteConfig(userAgent());
await cache.setData(config, remoteConfigExpiry(config.cacheControl));
}
_nxapiInitialized = true;
if (!process.env.NXAPI_CLIENT_ID || !process.env.NXAPI_SHARED_SECRET) {
throw new Error('NXAPI_CLIENT_ID and NXAPI_SHARED_SECRET are required for Coral authentication');
}
// Reuse the account's client (and its znca-api token) while the configuration is unchanged.
let zncaClient = zncaClients.get(account);
if (zncaClient?.configUrl !== config.zncaApiUrl || zncaClient?.zncaVersion !== config.zncaVersion) {
zncaClient = new ZncaApiClient({
url: config.zncaApiUrl,
clientId: process.env.NXAPI_CLIENT_ID,
sharedSecret: process.env.NXAPI_SHARED_SECRET,
zncaVersion: config.zncaVersion,
userAgent: userAgent(),
});
zncaClient.configUrl = config.zncaApiUrl;
zncaClients.set(account, zncaClient);
}
return { znca: zncaClient, zncaVersion: config.zncaVersion };
}
export function regionTokens() {
@@ -74,11 +81,13 @@ function getDefaultRegion() {
throw new Error('Session token not set for any region');
}
function isCoralSession(data) {
return !!(data?.coralUserId && data.credential?.accessToken && data.user?.id);
}
export default class NsoClient
{
constructor(region, nintendoToken) {
initializeNxapi();
this.console = prefixedConsole('NSO', region);
this.region = region;
this.nintendoToken = nintendoToken;
@@ -101,29 +110,35 @@ export default class NsoClient
return `nso.${token}`;
}
// Coral API
// Coral session
_getCoralCache() {
return new ValueCache(`${this.cachePrefix}.coral`);
}
async getCoralApi(useCache = true) {
/**
* @param {boolean} [useCache] false to log in again
* @returns {Promise<{ user: object, coralUserId: number, credential: { accessToken: string, expiresIn: number } }>} The Coral session
*/
async getCoralSession(useCache = true) {
return coralLimit(async () => {
let data = useCache
? await this._getCoralCache().getData()
: null;
if (!data) {
// Sessions cached by the nxapi package have a different shape; log in again.
if (!isCoralSession(data)) {
data = await this._createCoralSession();
}
return CoralApi.createWithSavedToken(data);
return data;
});
}
async _createCoralSession() {
this.console.info('Creating Coral session...');
let { data } = await CoralApi.createWithSessionToken(this.nintendoToken);
let { znca, zncaVersion } = await getZnca(this.cachePrefix);
let data = await loginWithSessionToken(this.nintendoToken, { znca, zncaVersion });
let expires = calculateCacheExpiry(data.credential.expiresIn);
this.console.debug(`Caching Coral session until: ${expires}`);
@@ -154,10 +169,17 @@ export default class NsoClient
}
async _createWebServiceToken(id, tokenCache) {
let coral = await this.getCoralApi();
let session = await this.getCoralSession();
let { znca, zncaVersion } = await getZnca(this.cachePrefix);
this.console.info(`Creating web service token for ID ${id}...`);
let { result } = await coral.getWebServiceToken(id);
let result = await getWebServiceToken(id, {
znca,
zncaVersion,
coralAccessToken: session.credential.accessToken,
coralUserId: session.coralUserId,
naId: session.user.id,
});
let expires = calculateCacheExpiry(result.expiresIn);
this.console.debug(`Caching web service token for ID ${id} until: ${expires}`);

View File

@@ -1,12 +1,125 @@
import { execFileSync } from 'node:child_process';
import { describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { testBuckets } from '../test/storage.mjs';
const coral = vi.hoisted(() => ({
getRemoteConfig: vi.fn(),
loginWithSessionToken: vi.fn(),
getWebServiceToken: vi.fn(),
ZncaApiClient: vi.fn(function (options) {
Object.assign(this, options);
}),
}));
vi.mock('./coral.mjs', () => coral);
vi.mock('../common/prefixedConsole.mjs', () => ({
default: () => ({ info: vi.fn(), debug: vi.fn() }),
}));
const { default: NsoClient, getZnca } = await import('./NsoClient.mjs');
const session = {
user: { id: 'na-user' },
coralUserId: 1234,
credential: { accessToken: 'coral-token', expiresIn: 7200 },
};
describe('NsoClient', () => {
it('loads the nxapi authentication integration in Node', () => {
expect(() => execFileSync(process.execPath, [
'--input-type=module',
'--eval',
'await import(\'./app/splatnet/NsoClient.mjs\')',
], { cwd: process.cwd() })).not.toThrow();
beforeEach(() => {
vi.stubEnv('NINTENDO_TOKEN_US', 'session-token-us-12345678');
vi.stubEnv('NXAPI_CLIENT_ID', 'client');
vi.stubEnv('NXAPI_SHARED_SECRET', 'secret');
vi.stubEnv('USER_AGENT', 'test-agent');
coral.getRemoteConfig.mockResolvedValue({
zncaVersion: '3.4.0',
zncaApiUrl: 'https://znca.test/api/',
cacheControl: 'public, max-age=1800',
});
coral.loginWithSessionToken.mockResolvedValue(session);
coral.getWebServiceToken.mockResolvedValue({ accessToken: 'web-token', expiresIn: 7200 });
});
afterEach(() => {
vi.unstubAllEnvs();
vi.clearAllMocks();
});
it('caches the nxapi remote config in private storage', async () => {
let first = await getZnca('nso.a');
let second = await getZnca('nso.a');
let otherAccount = await getZnca('nso.b');
expect(coral.getRemoteConfig).toHaveBeenCalledOnce();
expect(coral.getRemoteConfig).toHaveBeenCalledWith('splatoon3.ink test-agent');
expect(first.zncaVersion).toBe('3.4.0');
expect(second.znca).toBe(first.znca);
// znca-api tokens become bound to one Nintendo account
expect(otherAccount.znca).not.toBe(first.znca);
let cached = testBuckets().private.json('cache/nxapi.config.json');
expect(cached.data.zncaApiUrl).toBe('https://znca.test/api/');
expect(cached.expires - Date.now()).toBeGreaterThan(29 * 60 * 1000);
expect(cached.expires - Date.now()).toBeLessThanOrEqual(30 * 60 * 1000);
});
it('does not cache a remote config that disables Coral authentication', async () => {
coral.getRemoteConfig.mockRejectedValue(new Error('Remote configuration prevents Coral authentication'));
await expect(getZnca('nso.a')).rejects.toThrow('prevents Coral authentication');
expect(testBuckets().private.objects.size).toBe(0);
});
it('requires nxapi client credentials', async () => {
vi.stubEnv('NXAPI_SHARED_SECRET', '');
await expect(getZnca('nso.a')).rejects.toThrow('NXAPI_CLIENT_ID and NXAPI_SHARED_SECRET');
});
it('logs in once and reuses the cached Coral session', async () => {
let nso = NsoClient.make('US');
expect(await nso.getCoralSession()).toEqual(session);
expect(await nso.getCoralSession()).toEqual(session);
expect(coral.loginWithSessionToken).toHaveBeenCalledOnce();
expect(coral.loginWithSessionToken.mock.calls[0][0]).toBe('session-token-us-12345678');
expect(testBuckets().private.json('cache/nso.12345678.coral.json').data).toEqual(session);
});
it('logs in again instead of using a session cached by the nxapi package', async () => {
await testBuckets().private.put('cache/nso.12345678.coral.json', JSON.stringify({
expires: Date.now() + 3600_000,
data: { nintendoAccountToken: {}, nsoAccount: {}, credential: { accessToken: 'old' } },
}));
expect(await NsoClient.make('US').getCoralSession()).toEqual(session);
expect(coral.loginWithSessionToken).toHaveBeenCalledOnce();
});
it('creates and caches web service tokens from the Coral session', async () => {
let nso = NsoClient.make('US');
expect(await nso.getWebServiceToken('4834290508791808')).toBe('web-token');
expect(await nso.getWebServiceToken('4834290508791808')).toBe('web-token');
expect(coral.getWebServiceToken).toHaveBeenCalledOnce();
expect(coral.getWebServiceToken.mock.calls[0]).toEqual(['4834290508791808', expect.objectContaining({
zncaVersion: '3.4.0',
coralAccessToken: 'coral-token',
coralUserId: 1234,
naId: 'na-user',
})]);
expect(testBuckets().private.json('cache/nso.12345678.webservicetoken.4834290508791808.json').data)
.toEqual({ accessToken: 'web-token', expiresIn: 7200 });
});
it('bypasses the caches when asked', async () => {
let nso = NsoClient.make('US');
await nso.getWebServiceToken('1');
await nso.getCoralSession(false);
await nso.getWebServiceToken('1', false);
expect(coral.loginWithSessionToken).toHaveBeenCalledTimes(2);
expect(coral.getWebServiceToken).toHaveBeenCalledTimes(2);
});
});

View File

@@ -55,7 +55,7 @@ export class LocalAuth {
* @param {import('./NsoClient.mjs').default} nsoClient
*/
async refresh(nsoClient) {
await safe(() => nsoClient.getCoralApi(false));
await safe(() => nsoClient.getCoralSession(false));
await safe(() => nsoClient.getWebServiceToken(SPLATNET3_WEB_SERVICE_ID, false));
await safe(() => this.bulletToken(nsoClient, { useCache: false }));
}

View File

@@ -10,7 +10,7 @@ function fakeNsoClient() {
return {
region: 'US',
cachePrefix: 'nso.test',
getCoralApi: vi.fn().mockResolvedValue({}),
getCoralSession: vi.fn().mockResolvedValue({}),
getWebServiceToken: vi.fn().mockResolvedValue('web-token'),
};
}
@@ -29,14 +29,14 @@ describe('auth', () => {
await local.refresh(nso);
expect(nso.getCoralApi).toHaveBeenCalledWith(false);
expect(nso.getCoralSession).toHaveBeenCalledWith(false);
expect(nso.getWebServiceToken).toHaveBeenCalledWith(SPLATNET3_WEB_SERVICE_ID, false);
expect(bulletToken).toHaveBeenCalledWith(nso, { useCache: false });
});
it('keeps refreshing later credentials when an earlier step fails', async () => {
let nso = fakeNsoClient();
nso.getCoralApi.mockRejectedValue(new Error('Coral unavailable'));
nso.getCoralSession.mockRejectedValue(new Error('Coral unavailable'));
vi.spyOn(console, 'error').mockImplementation(() => {});
let local = new LocalAuth;
vi.spyOn(local, 'bulletToken').mockResolvedValue({ bulletToken: 'b' });

353
app/splatnet/coral.mjs Normal file
View File

@@ -0,0 +1,353 @@
// Reimplementation of the nxapi code path splatoon3.ink actually exercises, so the same code
// runs in Node and in Cloudflare Workers (importing the nxapi package crashes workerd):
//
// Nintendo Account session token
// -> Nintendo Account token + user (accounts.nintendo.com)
// -> nxapi znca-api bearer token (client assertion, scope ca:gf ca:er ca:dr)
// -> genf with encrypt_token_request (znca-api produces the encrypted Coral body)
// -> POST /v4/Account/Login (api-lp1.znc.srv.nintendo.net, octet-stream)
// -> decrypt-response (znca-api)
// -> same genf/POST/decrypt for /v4/Game/GetWebServiceToken
//
// Mirrors nxapi 1.6.1-next.257 (dist/api/coral.js, f.js, na.js, common/remote-config.js) using only
// fetch, WebCrypto, TextEncoder and atob/btoa. No Node built-ins.
const NA_CLIENT_ID = '71b963c1b7b6d119';
const ZNC_URL = 'https://api-lp1.znc.srv.nintendo.net';
const ZNCA_PLATFORM = 'Android';
const ZNCA_PLATFORM_VERSION = '12';
const ZNCA_API_COMPATIBILITY_VERSION = 'd8fAZDPzwimzQ7c6';
const ZNCA_API_SCOPE = 'ca:gf ca:er ca:dr';
const CONFIG_URL = 'https://fancy.org.uk/api/nxapi/config';
// The nxapi release whose protocol this file mirrors. The remote config endpoint varies its
// answer on these headers and refuses versions it no longer supports (nxapi's own kill switch).
// When it does, compare these constants and the request shapes below with the current nxapi
// release (ZNCA_VERSION and ZNCA_API_COMPATIBILITY_VERSION in dist/api/coral.js).
const NXAPI_COMPAT_VERSION = '1.6.1';
const ZNCA_COMPAT_VERSION = '3.5.0';
export const HashMethod = { CORAL: '1', WEB_SERVICE: '2' };
export class HttpError extends Error {
constructor(label, response, data) {
super(`${label}: ${response.status} ${response.statusText}`);
this.name = 'HttpError';
this.status = response.status;
this.url = response.url;
this.data = data;
}
}
async function readBody(response) {
let text = await response.text();
try {
return JSON.parse(text);
} catch {
return text;
}
}
async function expectOk(response, label) {
if (!response.ok) {
throw new HttpError(label, response, await readBody(response));
}
}
// Base64 helpers on plain Uint8Array (no Buffer).
function base64Encode(bytes) {
let binary = '';
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
}
return btoa(binary);
}
function base64Decode(value) {
// Accept both the standard and URL-safe alphabets, padded or not (Buffer.from is lenient too).
let normalized = value.replace(/-/g, '+').replace(/_/g, '/');
normalized += '='.repeat((4 - normalized.length % 4) % 4);
return Uint8Array.from(atob(normalized), c => c.charCodeAt(0));
}
function base64UrlEncode(bytes) {
return base64Encode(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// Same JWT that app/splatnet/NsoClient.mjs builds with node:crypto, using WebCrypto instead.
export async function createClientAssertion(clientId, sharedSecret, audience, lifetimeSeconds = 300) {
let encoder = new TextEncoder();
let now = Math.floor(Date.now() / 1000);
let header = base64UrlEncode(encoder.encode(JSON.stringify({ alg: 'HS256', typ: 'JWT' })));
let payload = base64UrlEncode(encoder.encode(JSON.stringify({
typ: 'client_assertion',
iss: clientId,
aud: audience,
exp: now + lifetimeSeconds,
iat: now,
})));
let key = await crypto.subtle.importKey(
'raw', encoder.encode(sharedSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
);
let signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(`${header}.${payload}`)));
return `${header}.${payload}.${base64UrlEncode(signature)}`;
}
// nxapi's remote configuration: the znca app version to impersonate, which f-generation
// provider to use, and whether Coral authentication is allowed at all.
export async function getRemoteConfig(userAgent) {
let response = await fetch(CONFIG_URL, {
headers: {
'User-Agent': userAgent,
'X-nxapi-Version': NXAPI_COMPAT_VERSION,
'X-znca-Compatible-Version': ZNCA_COMPAT_VERSION,
},
});
await expectOk(response, '[nxapi] remote config');
let config = await response.json();
if (!config.require_version?.includes(NXAPI_COMPAT_VERSION)) {
throw new Error(`[nxapi] remote config no longer supports protocol version ${NXAPI_COMPAT_VERSION} (accepts ${config.require_version?.join(', ')})`);
}
if (!config.coral) {
throw new Error('Remote configuration prevents Coral authentication');
}
let provider = config.coral_auth?.default;
if (!Array.isArray(provider) || provider[0] !== 'nxapi' || !provider[1]) {
throw new Error(`[nxapi] remote config selects an unsupported f-generation provider: ${JSON.stringify(provider)}`);
}
return {
zncaVersion: config.coral.znca_version,
zncaApiUrl: provider[1],
splatnet3: config.coral_gws_splatnet3 ?? null,
cacheControl: response.headers.get('Cache-Control'),
};
}
// Client for the nxapi znca-api (f generation + request encryption/response decryption).
export class ZncaApiClient {
constructor({ url, clientId, sharedSecret, zncaVersion, userAgent }) {
this.url = url.endsWith('/') ? url : `${url}/`;
this.origin = new URL(url).origin;
this.clientId = clientId;
this.sharedSecret = sharedSecret;
this.zncaVersion = zncaVersion;
this.userAgent = userAgent;
this.token = null;
}
async _getJson(url) {
let response = await fetch(url, { headers: { 'User-Agent': this.userAgent, 'Accept': 'application/json' } });
await expectOk(response, `[znca-api] ${url}`);
return response.json();
}
// OAuth 2 protected-resource discovery, then client_credentials with a JWT client assertion.
async authenticate() {
let resource = await this._getJson(`${this.origin}/.well-known/oauth-protected-resource`);
let issuer = resource.authorization_servers?.[0];
if (!issuer) throw new Error('[znca-api] no authorization server advertised');
let issuerUrl = new URL(issuer);
issuerUrl.pathname = '/.well-known/oauth-authorization-server' + (issuerUrl.pathname === '/' ? '' : issuerUrl.pathname);
let server = await this._getJson(issuerUrl);
if (!server.token_endpoint) throw new Error('[znca-api] authorization server has no token endpoint');
let body = new URLSearchParams({
grant_type: 'client_credentials',
scope: ZNCA_API_SCOPE,
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
client_assertion: await createClientAssertion(this.clientId, this.sharedSecret, server.issuer),
});
let response = await fetch(server.token_endpoint, {
method: 'POST',
headers: { 'User-Agent': this.userAgent, 'Accept': 'application/json' },
body,
});
await expectOk(response, '[znca-api] token');
let result = await response.json();
this.token = {
token: result.access_token,
expiresAt: Date.now() + result.expires_in * 1000,
scope: result.scope ?? null,
};
return { expiresIn: result.expires_in, scope: result.scope ?? null, tokenEndpoint: server.token_endpoint };
}
async _post(path, body, accept = 'application/json') {
if (!this.token || this.token.expiresAt <= Date.now()) {
await this.authenticate();
}
let response = await fetch(new URL(path, this.url), {
method: 'POST',
headers: {
'User-Agent': this.userAgent,
'X-znca-Client-Version': ZNCA_API_COMPATIBILITY_VERSION,
'X-znca-Platform': ZNCA_PLATFORM,
'X-znca-Version': this.zncaVersion,
'Content-Type': 'application/json',
'Accept': accept,
'Authorization': `Bearer ${this.token.token}`,
},
body: JSON.stringify(body),
});
await expectOk(response, `[znca-api] ${path}`);
return response;
}
// Generate f and, in the same call, the encrypted body for the Coral request that will use it.
async genf(token, hashMethod, user, encryptTokenRequest) {
let response = await this._post('f', {
hash_method: hashMethod,
token,
...user,
encrypt_token_request: encryptTokenRequest,
});
let data = await response.json();
if ('error' in data) {
throw new Error(`[znca-api] ${data.error_message ?? data.error}`);
}
if (!data.encrypted_token_request) {
throw new Error('[znca-api] f response did not include encrypted_token_request');
}
return {
f: data.f,
timestamp: data.timestamp,
requestId: data.request_id,
encryptedRequest: base64Decode(data.encrypted_token_request),
};
}
// Decrypt a Coral response body. Without the ca:na scope nxapi asks for text/plain and gets
// the decrypted JSON text back directly.
async decryptResponse(bytes) {
let response = await this._post('decrypt-response', { data: base64Encode(bytes) }, 'text/plain');
return JSON.parse(await response.text());
}
}
export async function getNintendoAccountToken(sessionToken) {
let response = await fetch('https://accounts.nintendo.com/connect/1.0.0/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 8.0.0)',
},
body: JSON.stringify({
client_id: NA_CLIENT_ID,
session_token: sessionToken,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer-session-token',
}),
});
await expectOk(response, '[na] token');
let token = await response.json();
if ('error' in token) throw new Error(`[na] ${token.error_description ?? token.error}`);
if ('errorCode' in token) throw new Error(`[na] ${token.detail}`);
return token; // { access_token, id_token, expires_in, scope, token_type }
}
export async function getNintendoAccountUser(naToken) {
let response = await fetch('https://api.accounts.nintendo.com/2.0.0/users/me', {
headers: {
'Accept-Language': 'en-GB',
'User-Agent': 'NASDKAPI; Android',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${naToken.access_token}`,
},
});
await expectOk(response, '[na] users/me');
let user = await response.json();
if ('errorCode' in user) throw new Error(`[na] ${user.detail}`);
return user; // { id, birthday, country, language, nickname, ... }
}
// POST an already-encrypted body to Coral and decrypt the reply. Header set mirrors nxapi:
// the unauthenticated Login call sends the short set, authenticated calls add the rest.
async function coralRequest(path, encryptedBody, { znca, zncaVersion, accessToken = null }) {
let headers = {
'User-Agent': `com.nintendo.znca/${zncaVersion}(${ZNCA_PLATFORM}/${ZNCA_PLATFORM_VERSION})`,
'X-Platform': ZNCA_PLATFORM,
'X-ProductVersion': zncaVersion,
'Content-Type': 'application/octet-stream',
'Accept': 'application/octet-stream,application/json',
};
if (accessToken) {
Object.assign(headers, {
'Authorization': `Bearer ${accessToken}`,
'Accept-Language': 'en-GB',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
});
}
let response = await fetch(ZNC_URL + path, { method: 'POST', headers, body: encryptedBody });
let bytes = new Uint8Array(await response.arrayBuffer());
let data;
if (/^application\/json($|;)/i.test(response.headers.get('Content-Type') ?? '')) {
data = await znca.decryptResponse(bytes);
} else {
let text = new TextDecoder().decode(bytes);
throw new HttpError(`[znc] ${path} ${response.ok ? 'unacceptable response type' : 'error'}`, response, text);
}
if (!response.ok) throw new HttpError(`[znc] ${path}`, response, data);
if ('errorMessage' in data) throw new Error(`[znc] ${path}: ${data.errorMessage} (status ${data.status})`);
if (data.status !== 0) throw new Error(`[znc] ${path}: Coral status ${data.status}`);
return data;
}
export async function loginWithSessionToken(sessionToken, { znca, zncaVersion }) {
let naToken = await getNintendoAccountToken(sessionToken);
let user = await getNintendoAccountUser(naToken);
let parameter = {
naIdToken: naToken.id_token,
language: user.language,
// Filled in by znca-api while encrypting.
timestamp: 0,
requestId: '',
f: '',
};
let fdata = await znca.genf(naToken.id_token, HashMethod.CORAL, { na_id: user.id }, {
url: `${ZNC_URL}/v4/Account/Login`,
parameter,
});
let data = await coralRequest('/v4/Account/Login', fdata.encryptedRequest, { znca, zncaVersion });
return {
user,
coralUserId: data.result.user.id,
credential: data.result.webApiServerCredential, // { accessToken, expiresIn }
};
}
export async function getWebServiceToken(id, { znca, zncaVersion, coralAccessToken, coralUserId, naId }) {
let parameter = { id, registrationToken: '', f: '', requestId: '', timestamp: 0 };
let fdata = await znca.genf(coralAccessToken, HashMethod.WEB_SERVICE, {
na_id: naId,
coral_user_id: `${coralUserId}`,
}, {
url: `${ZNC_URL}/v4/Game/GetWebServiceToken`,
parameter,
});
let data = await coralRequest('/v4/Game/GetWebServiceToken', fdata.encryptedRequest, {
znca, zncaVersion, accessToken: coralAccessToken,
});
return data.result; // { accessToken, expiresIn }
}

View File

@@ -0,0 +1,66 @@
import { createHmac } from 'node:crypto';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createClientAssertion, getRemoteConfig } from './coral.mjs';
function remoteConfig(overrides = {}) {
return {
require_version: ['1.6.1'],
coral: { znca_version: '3.4.0' },
coral_auth: { default: ['nxapi', 'https://znca.test/api'] },
...overrides,
};
}
describe('coral', () => {
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});
it('signs client assertions exactly like the previous node:crypto implementation', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-11-08T12:00:00Z'));
let assertion = await createClientAssertion('client-id', 'shared-secret', 'https://issuer.test');
let [header, payload, signature] = assertion.split('.');
let expected = createHmac('sha256', 'shared-secret').update(`${header}.${payload}`).digest('base64url');
expect(JSON.parse(Buffer.from(header, 'base64url'))).toEqual({ alg: 'HS256', typ: 'JWT' });
expect(JSON.parse(Buffer.from(payload, 'base64url'))).toEqual({
typ: 'client_assertion',
iss: 'client-id',
aud: 'https://issuer.test',
exp: 1794139500,
iat: 1794139200,
});
expect(signature).toBe(expected);
});
it('reads the znca version and f-generation provider from the remote config', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json(remoteConfig(), {
headers: { 'Cache-Control': 'max-age=600' },
})));
let config = await getRemoteConfig('test-agent');
expect(config).toMatchObject({
zncaVersion: '3.4.0',
zncaApiUrl: 'https://znca.test/api',
cacheControl: 'max-age=600',
});
expect(fetch.mock.calls[0][1].headers).toMatchObject({
'User-Agent': 'test-agent',
'X-nxapi-Version': '1.6.1',
});
});
it.each([
[{ coral: null }, 'prevents Coral authentication'],
[{ require_version: ['2.0.0'] }, 'no longer supports protocol version'],
[{ coral_auth: { default: ['imink', 'https://example.test'] } }, 'unsupported f-generation provider'],
])('refuses a remote config that does not allow this client (%o)', async (overrides, message) => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json(remoteConfig(overrides))));
await expect(getRemoteConfig('test-agent')).rejects.toThrow(message);
});
});

1509
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,20 @@
"engines": {
"node": "24.x"
},
"imports": {
"#image-converter": {
"workerd": "./app/common/image/convert.worker.mjs",
"default": "./app/common/image/convert.node.mjs"
},
"#avatars": {
"workerd": "./app/social/avatars/index.worker.mjs",
"default": "./app/social/avatars/index.node.mjs"
},
"#local-screenshot-driver": {
"workerd": "./app/screenshots/drivers/LocalScreenshotDriver.worker.mjs",
"default": "./app/screenshots/drivers/LocalScreenshotDriver.mjs"
}
},
"scripts": {
"dev": "vite",
"build": "vite build",
@@ -45,6 +59,7 @@
"@headlessui/vue": "^1.7.23",
"@heroicons/vue": "^2.2.0",
"@noble/hashes": "^2.4.0",
"@sentry/core": "^10.38.0",
"@sentry/node": "^10.38.0",
"console-stamp": "^3.0.6",
"cron": "^4.4.0",
@@ -53,7 +68,6 @@
"jsonpath-plus": "^10.4.0",
"lodash": "^4.17.21",
"masto": "^8.0.0",
"nxapi": "1.6.1-next.257",
"p-filter": "^4.1.0",
"p-limit": "^7.3.0",
"p-queue": "^9.1.0",
@@ -62,7 +76,6 @@
"sharp": "^0.35.4",
"sirv": "^3.0.2",
"tar-stream": "^3.2.0",
"twitter-api-v2": "^1.29.0",
"vue": "^3.5.42",
"vue-i18n": "^11.4.10",
"vue-router": "^5.0.2"