mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
feat(service-identity): register through the dialect of the running release
Registration now goes through a registration dialect module: the paths of the challenge and the registration, the bytes scrypt runs over and the body and headers of the request. Each stable release will carry the dialect the TREK services issuer writes for it; until the first such release the module speaks the original registration, so nothing changes on the wire. An issuer that no longer takes the release's dialect answers 410. TREK then says so once per process, waits a day (or what Retry-After asks) and keeps searching through the shared pool. The issuer client only lets a dialect register at the issuer's own paths, with X-TREK-* headers that are not the gate's and a body of registration size. Renewal needs no dialect, and an expired key may now be renewed for a year instead of 30 days, the same period the issuer allows, so an installation that was offline for long comes back without an update. The key format ignores the new optional dialect claim; the shared vectors gain one key that carries it.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { safeFetch } from '../../utils/ssrfGuard';
|
||||
import type { RegistrationRequest } from './registration-dialect.types';
|
||||
import { SERVICE_ISSUER_ORIGIN } from './service-identity.constants';
|
||||
import { retryAfterMs, serverDateMs } from './service-identity.helpers';
|
||||
import { serviceUserAgent } from './user-agent';
|
||||
@@ -18,18 +19,27 @@ const TIMEOUT_MS = 10_000;
|
||||
/** Every answer of the issuer is a few hundred bytes. */
|
||||
const MAX_BYTES = 4096;
|
||||
|
||||
/*
|
||||
* What a registration dialect may ask of a request. The dialect module is
|
||||
* written by the issuer, so it is held to the paths the issuer serves, to
|
||||
* headers of its own and to a small body; anything else is refused before it
|
||||
* leaves. scripts/ci/check-registration-dialect.mjs applies the same rules to
|
||||
* a new dialect in the release job.
|
||||
*/
|
||||
const CHALLENGE_PATH = /^\/v1\/register(\/[A-Za-z0-9_-]{12})?\/challenge$/;
|
||||
const REGISTER_PATH = /^\/v1\/register(\/[A-Za-z0-9_-]{12})?$/;
|
||||
const DIALECT_HEADER = /^X-TREK-[A-Za-z0-9-]{1,40}$/;
|
||||
/** The headers the gate itself answers with or reads; a dialect never sends them. */
|
||||
const RESERVED_HEADER = /^X-TREK-(Install|Tier|Legacy|Quota|Instance|Notice)(-|$)/i;
|
||||
const HEADER_VALUE = /^[\x20-\x7e]{1,256}$/;
|
||||
const MAX_REGISTRATION_BYTES = 2048;
|
||||
|
||||
export interface IssuerAnswer<T> {
|
||||
body: T;
|
||||
/** The issuer's clock from its Date header. */
|
||||
serverMs: number | null;
|
||||
}
|
||||
|
||||
interface RegistrationRequest {
|
||||
c: string;
|
||||
nonce: string;
|
||||
v: string;
|
||||
}
|
||||
|
||||
/** A refusal of the issuer, with how long it asked to be left alone. */
|
||||
export class IssuerError extends Error {
|
||||
constructor(
|
||||
@@ -45,12 +55,18 @@ export class IssuerError extends Error {
|
||||
/** The calls TREK makes to the key issuer at places.liketrek.com, and the allowance any liketrek host reports. */
|
||||
@Injectable()
|
||||
export class IssuerClient {
|
||||
challenge(): Promise<IssuerAnswer<ServiceChallenge>> {
|
||||
return this.call('GET', '/v1/register/challenge', serviceChallengeSchema);
|
||||
/** A challenge to solve, at the path of the dialect this build registers in. */
|
||||
challenge(path = '/v1/register/challenge'): Promise<IssuerAnswer<ServiceChallenge>> {
|
||||
if (!CHALLENGE_PATH.test(path)) {
|
||||
return Promise.reject(new Error('the registration dialect asks for a challenge elsewhere'));
|
||||
}
|
||||
return this.call('GET', path, serviceChallengeSchema);
|
||||
}
|
||||
|
||||
register(request: RegistrationRequest): Promise<IssuerAnswer<ServiceKeyGrant>> {
|
||||
return this.call('POST', '/v1/register', serviceKeyGrantSchema, { body: request });
|
||||
register(path: string, request: RegistrationRequest): Promise<IssuerAnswer<ServiceKeyGrant>> {
|
||||
const refusal = registrationRefusal(path, request);
|
||||
if (refusal) return Promise.reject(new Error(`the registration dialect ${refusal}`));
|
||||
return this.call('POST', path, serviceKeyGrantSchema, { body: request.body, headers: request.headers });
|
||||
}
|
||||
|
||||
renew(key: string): Promise<IssuerAnswer<ServiceKeyGrant>> {
|
||||
@@ -69,9 +85,18 @@ export class IssuerClient {
|
||||
method: 'GET' | 'POST',
|
||||
path: string,
|
||||
schema: z.ZodType<T>,
|
||||
opts: { body?: RegistrationRequest; bearer?: string | null; origin?: string } = {},
|
||||
opts: {
|
||||
body?: Record<string, unknown>;
|
||||
headers?: Record<string, string>;
|
||||
bearer?: string | null;
|
||||
origin?: string;
|
||||
} = {},
|
||||
): Promise<IssuerAnswer<T>> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json', 'User-Agent': serviceUserAgent() };
|
||||
const headers: Record<string, string> = {
|
||||
...opts.headers,
|
||||
Accept: 'application/json',
|
||||
'User-Agent': serviceUserAgent(),
|
||||
};
|
||||
if (opts.bearer) headers.Authorization = `Bearer ${opts.bearer}`;
|
||||
if (opts.body) headers['Content-Type'] = 'application/json';
|
||||
const res = await safeFetch(
|
||||
@@ -89,3 +114,17 @@ export class IssuerClient {
|
||||
return { body: schema.parse(await res.json()), serverMs };
|
||||
}
|
||||
}
|
||||
|
||||
/** Why a dialect's registration may not go out, or null when it may. */
|
||||
function registrationRefusal(path: string, request: RegistrationRequest): string | null {
|
||||
if (!REGISTER_PATH.test(path)) return 'registers elsewhere';
|
||||
if (!Object.entries(request.headers).every(isDialectHeader)) return 'sends a header TREK does not send';
|
||||
if (Buffer.byteLength(JSON.stringify(request.body), 'utf8') > MAX_REGISTRATION_BYTES) {
|
||||
return 'sends a body larger than a registration';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isDialectHeader([name, value]: [string, string]): boolean {
|
||||
return DIALECT_HEADER.test(name) && !RESERVED_HEADER.test(name) && HEADER_VALUE.test(value);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* How this build of TREK registers with the TREK services.
|
||||
*
|
||||
* Each stable release replaces this file with the one the issuer writes for
|
||||
* its version, in the version bump commit (.github/workflows/docker.yml); its
|
||||
* layout is then the generator's, so Prettier leaves it alone. Until the first
|
||||
* such release it speaks the original registration, which the issuer accepts
|
||||
* for a transition period. Renewing a key never goes through this file: an
|
||||
* installation keeps its key whatever release it runs. After a stable release,
|
||||
* merge main into dev so that dev and prerelease builds register with the
|
||||
* current dialect.
|
||||
*
|
||||
* The dialect is the registration's, not SQL's; lint:dialect has nothing to
|
||||
* look for here.
|
||||
*/
|
||||
import type { DialectSelfCheck, RegistrationDialect } from './registration-dialect.types';
|
||||
|
||||
const DIALECT = '0';
|
||||
const SALT = Buffer.from('trek-pow-v1', 'utf8');
|
||||
|
||||
export const registrationDialect: RegistrationDialect = {
|
||||
id: DIALECT,
|
||||
releasedFor: 'dev',
|
||||
createdAt: '2026-10-29',
|
||||
challengePath: '/v1/register/challenge',
|
||||
registerPath: '/v1/register',
|
||||
begin({ challenge, version }) {
|
||||
return {
|
||||
work(nonce) {
|
||||
return { password: Buffer.from(`${challenge.c}.${nonce}`, 'utf8'), salt: SALT };
|
||||
},
|
||||
request(nonce) {
|
||||
return { body: { c: challenge.c, nonce: String(nonce), v: version }, headers: {} };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/** Fixed inputs and what this module must make of them; TREK's tests and release job run it. */
|
||||
export const SELF_CHECK: DialectSelfCheck = {
|
||||
challenge: { c: 'v1.selfcheck.0', alg: 'scrypt', N: 16, r: 1, p: 1, bits: 0, expires_at: 1 },
|
||||
version: 'dev',
|
||||
random: '000102030405060708090a0b0c0d0e0f',
|
||||
nowSeconds: 1800000000,
|
||||
nonce: 41,
|
||||
passwordSha256: '6da395852966856653d9efba4dd3230e31f0fa325558474c91ae719247cc20ac',
|
||||
saltSha256: '9a4f2641b36f212d95eeceb212ce3587672322074288da20da4822809816aa7b',
|
||||
scrypt: 'f3de9aab4d5d9e114d63ba51bb0c8f007a644c1e24ef7b8e4062d49e9eed5376',
|
||||
requestSha256: '840dd80c265fba34a73ff4927eaa8416aa344d32372bf4d85273bf5ce130af99',
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* The shape of a registration dialect: how one release of TREK turns a
|
||||
* challenge of the issuer into a proof of work and a registration request.
|
||||
*
|
||||
* Each release registers in a dialect of its own, written by the issuer and
|
||||
* committed as registration-dialect.ts with the version bump. This file is the
|
||||
* stable side of that contract: the generated module imports these types, and
|
||||
* the key service only ever talks to a dialect through them. Renewing a key
|
||||
* never goes through a dialect.
|
||||
*/
|
||||
import type { ServiceChallenge } from '@trek/shared';
|
||||
|
||||
/** What a dialect gets to work with for one registration. */
|
||||
export interface DialectInputs {
|
||||
challenge: ServiceChallenge;
|
||||
/** The running version, at most 32 characters. */
|
||||
version: string;
|
||||
/** 16 random bytes, fresh for every registration and never stored. */
|
||||
random: Buffer;
|
||||
/** Unix seconds on the issuer's clock. */
|
||||
nowSeconds: number;
|
||||
}
|
||||
|
||||
/** What scrypt runs over for one nonce. */
|
||||
export interface ProofInput {
|
||||
password: Buffer;
|
||||
salt: Buffer;
|
||||
}
|
||||
|
||||
/** The registration as it goes out: the JSON body and the extra X-TREK-* headers. */
|
||||
export interface RegistrationRequest {
|
||||
body: Record<string, unknown>;
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
/** One registration in progress. A nonce runs from 0 to 2^40. */
|
||||
export interface DialectAttempt {
|
||||
work(nonce: number): ProofInput;
|
||||
request(nonce: number): RegistrationRequest;
|
||||
}
|
||||
|
||||
export interface RegistrationDialect {
|
||||
/** '0' for the original registration, otherwise the issuer's 12-character id. */
|
||||
id: string;
|
||||
/** The release the issuer wrote the dialect for. */
|
||||
releasedFor: string;
|
||||
/** YYYY-MM-DD; the issuer accepts a dialect for new registrations for 180 days from then. */
|
||||
createdAt: string;
|
||||
challengePath: string;
|
||||
registerPath: string;
|
||||
begin(inputs: DialectInputs): DialectAttempt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixed inputs and what the dialect must make of them, as the issuer computed
|
||||
* it. The password, the salt and the request are compared by their SHA-256
|
||||
* (the request as JSON.stringify({ body, headers })); scrypt runs with the
|
||||
* challenge's N=16, r=1, p=1 and 32 bytes of output.
|
||||
*/
|
||||
export interface DialectSelfCheck {
|
||||
challenge: ServiceChallenge;
|
||||
version: string;
|
||||
/** Hex. */
|
||||
random: string;
|
||||
nowSeconds: number;
|
||||
nonce: number;
|
||||
passwordSha256: string;
|
||||
saltSha256: string;
|
||||
/** Hex. */
|
||||
scrypt: string;
|
||||
requestSha256: string;
|
||||
}
|
||||
@@ -1,2 +1,5 @@
|
||||
/** The issuer of installation keys: the Places host itself, so no new egress domain is needed. */
|
||||
export const SERVICE_ISSUER_ORIGIN = 'https://places.liketrek.com';
|
||||
|
||||
/** The registration dialect this build speaks (registration-dialect.ts); tests hand in their own. */
|
||||
export const REGISTRATION_DIALECT = Symbol('REGISTRATION_DIALECT');
|
||||
|
||||
@@ -4,7 +4,9 @@ import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { SettingsModule } from '../settings/settings.module';
|
||||
import { IssuerClient } from './issuer.client';
|
||||
import { QuotaTracker } from './quota-tracker';
|
||||
import { registrationDialect } from './registration-dialect';
|
||||
import { ServiceClock } from './service-clock';
|
||||
import { REGISTRATION_DIALECT } from './service-identity.constants';
|
||||
import { ServiceIdentityController } from './service-identity.controller';
|
||||
import { ServiceIdentityPort, serviceIdentitySlot } from './service-identity.interface';
|
||||
import { ServiceIdentityService } from './service-identity.service';
|
||||
@@ -33,6 +35,7 @@ import { Module, type OnModuleDestroy } from '@nestjs/common';
|
||||
ServiceKeyService,
|
||||
ServiceKeyStore,
|
||||
{ provide: ServiceIdentityPort, useClass: ServiceRequestIdentity },
|
||||
{ provide: REGISTRATION_DIALECT, useValue: registrationDialect },
|
||||
],
|
||||
exports: [ServiceIdentityPort],
|
||||
})
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import type { DialectAttempt, ProofInput } from './registration-dialect.types';
|
||||
import type { ServiceChallenge } from '@trek/shared';
|
||||
|
||||
import { scrypt } from 'node:crypto';
|
||||
|
||||
const SALT = 'trek-pow-v1';
|
||||
const HASH_BYTES = 32;
|
||||
|
||||
type ScryptCost = Pick<ServiceChallenge, 'N' | 'r' | 'p'>;
|
||||
|
||||
/** scrypt(c + "." + nonce, "trek-pow-v1"), off the event loop. */
|
||||
export function powHash(challenge: string, nonce: string, cost: ScryptCost): Promise<Buffer> {
|
||||
/** scrypt over what the dialect made of one nonce, off the event loop. */
|
||||
export function powHash(input: ProofInput, cost: ScryptCost): Promise<Buffer> {
|
||||
const { N, r, p } = cost;
|
||||
// Twice what scrypt needs, so Node's 32 MB default never refuses a valid challenge.
|
||||
const maxmem = 2 * 128 * N * r + 128 * r * p;
|
||||
return new Promise((resolve, reject) => {
|
||||
scrypt(`${challenge}.${nonce}`, SALT, HASH_BYTES, { N, r, p, maxmem }, (err, hash) =>
|
||||
scrypt(input.password, input.salt, HASH_BYTES, { N, r, p, maxmem }, (err, hash) =>
|
||||
err ? reject(err) : resolve(hash),
|
||||
);
|
||||
});
|
||||
@@ -28,14 +28,19 @@ export function leadingZeroBits(hash: Uint8Array): number {
|
||||
return bits;
|
||||
}
|
||||
|
||||
/** The first decimal nonce whose hash has at least `bits` leading zero bits, tried until `deadlineMs`. */
|
||||
export function solvePow(challenge: ServiceChallenge, deadlineMs: number): Promise<string> {
|
||||
return firstNonceFrom(0, challenge, deadlineMs);
|
||||
/** The first nonce whose hash has at least `bits` leading zero bits, tried until `deadlineMs`. */
|
||||
export function solvePow(challenge: ServiceChallenge, attempt: DialectAttempt, deadlineMs: number): Promise<number> {
|
||||
return firstNonceFrom(0, challenge, attempt, deadlineMs);
|
||||
}
|
||||
|
||||
async function firstNonceFrom(nonce: number, challenge: ServiceChallenge, deadlineMs: number): Promise<string> {
|
||||
async function firstNonceFrom(
|
||||
nonce: number,
|
||||
challenge: ServiceChallenge,
|
||||
attempt: DialectAttempt,
|
||||
deadlineMs: number,
|
||||
): Promise<number> {
|
||||
if (Date.now() >= deadlineMs) throw new Error('the registration challenge expired before it was solved');
|
||||
const hash = await powHash(challenge.c, String(nonce), challenge);
|
||||
if (leadingZeroBits(hash) >= challenge.bits) return String(nonce);
|
||||
return firstNonceFrom(nonce + 1, challenge, deadlineMs);
|
||||
const hash = await powHash(attempt.work(nonce), challenge);
|
||||
if (leadingZeroBits(hash) >= challenge.bits) return nonce;
|
||||
return firstNonceFrom(nonce + 1, challenge, attempt, deadlineMs);
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ import { conflict } from '../common/domain-error';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
import { IssuerClient, IssuerError, type IssuerAnswer } from './issuer.client';
|
||||
import { RefusalStreak } from './refusal-streak';
|
||||
import type { RegistrationDialect } from './registration-dialect.types';
|
||||
import { ServiceClock } from './service-clock';
|
||||
import { SERVICE_ISSUER_ORIGIN } from './service-identity.constants';
|
||||
import { REGISTRATION_DIALECT, SERVICE_ISSUER_ORIGIN } from './service-identity.constants';
|
||||
import { isAllowlisted, keyFingerprint, sameServiceUrl } from './service-identity.helpers';
|
||||
import { parseServiceKey, type ServiceKey } from './service-key.format';
|
||||
import { solvePow } from './service-key.pow';
|
||||
@@ -17,13 +18,20 @@ import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import type { ServiceIdentityState, ServiceKeyGrant } from '@trek/shared';
|
||||
|
||||
import { randomInt } from 'node:crypto';
|
||||
import { randomBytes, randomInt } from 'node:crypto';
|
||||
|
||||
const DAY_SECONDS = 86_400;
|
||||
/** A key is renewed from day 60 of its 90, unless the issuer said otherwise. */
|
||||
const RENEW_AGE_SECONDS = 60 * DAY_SECONDS;
|
||||
/** An expired key can still be renewed for this long; after that it registers anew. */
|
||||
const RENEW_GRACE_SECONDS = 30 * DAY_SECONDS;
|
||||
/**
|
||||
* An expired key can still be renewed for this long; after that it registers
|
||||
* anew. Renewing needs no dialect, so an installation that was offline for up
|
||||
* to a year past its key's expiry comes back without an update. The issuer
|
||||
* allows the same period; the two move together.
|
||||
*/
|
||||
const RENEW_GRACE_SECONDS = 365 * DAY_SECONDS;
|
||||
/** How long to leave the issuer alone after it no longer takes this release's dialect, unless it says. */
|
||||
const DIALECT_REFUSED_WAIT_MS = 24 * 3_600_000;
|
||||
/** Spreads the new registrations of every installation a broken key hit, instead of all at once. */
|
||||
const REREGISTER_JITTER_MS = 6 * 3_600_000;
|
||||
const FIRST_BACKOFF_MS = 5 * 60_000;
|
||||
@@ -57,6 +65,7 @@ export class ServiceKeyService {
|
||||
private registering = false;
|
||||
private nextAttemptAt = 0;
|
||||
private failures = 0;
|
||||
private dialectRefusalLogged = false;
|
||||
private readonly refusals = new RefusalStreak();
|
||||
|
||||
constructor(
|
||||
@@ -66,6 +75,7 @@ export class ServiceKeyService {
|
||||
private readonly issuer: IssuerClient,
|
||||
private readonly clock: ServiceClock,
|
||||
private readonly orm: MikroORM,
|
||||
@Inject(REGISTRATION_DIALECT) private readonly dialect: RegistrationDialect,
|
||||
) {}
|
||||
|
||||
/** Whether the Places service this instance uses is one the key goes to. */
|
||||
@@ -262,6 +272,10 @@ export class ServiceKeyService {
|
||||
this.failures = 0;
|
||||
logInfo('TREK services: this installation is registered.');
|
||||
} catch (err) {
|
||||
if (err instanceof IssuerError && err.status === 410) {
|
||||
this.dialectRefused(err);
|
||||
return;
|
||||
}
|
||||
this.backOff(err);
|
||||
throw err;
|
||||
} finally {
|
||||
@@ -284,10 +298,32 @@ export class ServiceKeyService {
|
||||
}
|
||||
|
||||
private async solveChallenge(): Promise<IssuerAnswer<ServiceKeyGrant>> {
|
||||
const challenge = await this.issuer.challenge();
|
||||
const challenge = await this.issuer.challenge(this.dialect.challengePath);
|
||||
this.clock.learn(challenge.serverMs);
|
||||
const nonce = await solvePow(challenge.body, this.clock.toLocalMs(challenge.body.expires_at));
|
||||
return this.issuer.register({ c: challenge.body.c, nonce, v: runningVersion() });
|
||||
const attempt = this.dialect.begin({
|
||||
challenge: challenge.body,
|
||||
version: runningVersion().slice(0, 32),
|
||||
random: randomBytes(16),
|
||||
nowSeconds: this.clock.nowSeconds(),
|
||||
});
|
||||
const nonce = await solvePow(challenge.body, attempt, this.clock.toLocalMs(challenge.body.expires_at));
|
||||
return this.issuer.register(this.dialect.registerPath, attempt.request(nonce));
|
||||
}
|
||||
|
||||
/**
|
||||
* The issuer no longer takes new registrations in this release's dialect.
|
||||
* Nothing is wrong with the installation, and nothing it can do about it but
|
||||
* an update, so this is said once per process and asked again a day later;
|
||||
* until then requests go through the shared pool as without a key.
|
||||
*/
|
||||
private dialectRefused(err: IssuerError): void {
|
||||
this.nextAttemptAt = Date.now() + (err.retryAfterMs ?? DIALECT_REFUSED_WAIT_MS);
|
||||
if (this.dialectRefusalLogged) return;
|
||||
this.dialectRefusalLogged = true;
|
||||
logWarn(
|
||||
'TREK services: this release can no longer register with the TREK services. Searches and routes ' +
|
||||
'continue through the shared pool and the public services; updating TREK restores the key.',
|
||||
);
|
||||
}
|
||||
|
||||
/** Same installation, new expiry; the old key is the proof, so no proof of work. */
|
||||
|
||||
Reference in New Issue
Block a user