feat(server): give each installation a key for the TREK services and report its allowance

A new service-identity domain registers the installation with places.liketrek.com on its first Places request, in the background and behind a light scrypt proof of work, keeps the key encrypted in app_settings, renews it from day 60 through a daily job, drops it after three 401s in a row with up to six hours of jitter, and freezes it on a revocation until an admin starts over. TREK_SERVICES_KEY wins and turns registration off; TREK_SERVICES=off sends no key; a mirror set with TREK_PLACES_URL never registers and never sees the key, which goes only to the hosts in TREK_SERVICES_HOSTS over https.

The Places client takes its headers from the identity port, sends a TREK/<version> User-Agent and keeps the instance token. A 401 or 403 does not open its breaker. GET /api/admin/service-identity reports the state, tier and today's allowance, asking the issuer at most every 20 seconds; POST .../regenerate starts a new identity.
This commit is contained in:
Maurice
2026-10-29 08:59:07 +01:00
committed by Maurice
parent f19f0a33b2
commit 01ae91c939
47 changed files with 2570 additions and 16 deletions
+20 -1
View File
@@ -9,7 +9,7 @@
* mutate mid-lifetime, belongs in derive.ts instead.
*/
import type { RawEnv } from './derive';
import { parseBool, positiveIntOr, stripTrailingSlashes } from './parsers';
import { csvListFiltered, parseBool, positiveIntOr, stripTrailingSlashes } from './parsers';
/**
* Longer than the upstream idle timeout of the common reverse proxies and load
@@ -62,12 +62,31 @@ export function deriveKitinerary(raw: RawEnv) {
};
}
/** The liketrek hosts that receive the installation key when nothing else is configured. */
const DEFAULT_SERVICE_HOSTS = ['places.liketrek.com'];
/**
* How this installation identifies itself to the liketrek services. Unset is
* `auto`; any other value than `auto` switches them off, so a typo fails closed.
* A key from the environment wins over the stored one and stops registration.
*/
export function deriveServices(raw: RawEnv) {
const mode = raw.TREK_SERVICES?.trim().toLowerCase() || 'auto';
const hosts = csvListFiltered(raw.TREK_SERVICES_HOSTS?.toLowerCase());
return {
mode: mode === 'auto' ? ('auto' as const) : ('off' as const),
key: raw.TREK_SERVICES_KEY?.trim() || null,
hosts: hosts?.length ? hosts : DEFAULT_SERVICE_HOSTS,
};
}
/** One entry per token: the namespace it registers under and the function it derives with. */
export const BOOT_DERIVERS = {
http: deriveHttpBoot,
storage: deriveStorage,
transit: deriveTransit,
kitinerary: deriveKitinerary,
services: deriveServices,
} as const;
export type BootNamespace = keyof typeof BOOT_DERIVERS;
+4
View File
@@ -11,6 +11,7 @@
*/
import {
isP256PrivateKey,
isServiceKeyShape,
isUncompressedP256Key,
isVapidSubject,
parseDurationMs,
@@ -184,6 +185,9 @@ export const envSchema = z.object({
GOOGLE_LIST_DATA_BASE: url,
TREK_PLACES_URL: url,
TREK_PLACES_ENABLED: boolStr,
TREK_SERVICES: oneOf(['auto', 'off']),
TREK_SERVICES_KEY: optionalWith(isServiceKeyShape, 'must be a TREK services key (tk1.<kid>.<payload>.<signature>)'),
TREK_SERVICES_HOSTS: anyString,
PLACES_API_KEY: anyString,
AMAP_API_BASE: url,
AMAP_API_KEY: anyString,
+1
View File
@@ -27,6 +27,7 @@ export const SECRET_ENV_KEYS: ReadonlySet<string> = new Set([
'UNSPLASH_ACCESS_KEY',
'ADMIN_PASSWORD',
'PLACES_API_KEY',
'TREK_SERVICES_KEY',
'AMAP_API_KEY',
'AMAP_API_SECRET',
'MAPBOX_ACCESS_TOKEN',
+8
View File
@@ -253,3 +253,11 @@ export function isVapidSubject(value: string): boolean {
return false;
}
}
const BASE64URL_SEGMENT = /^[A-Za-z0-9_-]+$/;
/** A TREK services key: `tk1.<kid>.<payload>.<signature>`, the last three base64url. */
export function isServiceKeyShape(value: string): boolean {
const [version, ...parts] = value.trim().split('.');
return version === 'tk1' && parts.length === 3 && parts.every((part) => BASE64URL_SEGMENT.test(part));
}
@@ -85,6 +85,15 @@ export class AppSettingsRepository extends TrekRepository<AppSettings> {
return rows.map((row) => toRow(row) as AppSettingsRow);
}
/**
* `INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING`:
* the first writer keeps the row, so several processes on one database can
* race to create a value and all read back the same one afterwards.
*/
async insertIfAbsent(key: string, value: string): Promise<void> {
await this.upsert({ key, value }, { onConflictFields: ['key'], onConflictAction: 'ignore' });
}
/** `DELETE FROM app_settings WHERE key = ?` */
async deleteValue(key: string): Promise<number> {
return this.nativeDelete({ key });
+3 -1
View File
@@ -31,5 +31,7 @@ export const storageConfig = registerAs('storage', () => BOOT_DERIVERS.storage(p
export const transitConfig = registerAs('transit', () => BOOT_DERIVERS.transit(process.env));
/** KitineraryExtractorService's binary probe (KITINERARY_EXTRACTOR_PATH, then PATH). */
export const kitineraryConfig = registerAs('kitinerary', () => BOOT_DERIVERS.kitinerary(process.env));
/** The installation identity towards the liketrek services (TREK_SERVICES, TREK_SERVICES_KEY, TREK_SERVICES_HOSTS). */
export const servicesConfig = registerAs('services', () => BOOT_DERIVERS.services(process.env));
export const BOOT_STABLE_TOKENS = [httpConfig, storageConfig, transitConfig, kitineraryConfig];
export const BOOT_STABLE_TOKENS = [httpConfig, storageConfig, transitConfig, kitineraryConfig, servicesConfig];
+2
View File
@@ -86,6 +86,7 @@ import { RoadtripModule } from './roadtrip/roadtrip.module';
import { RouteUsageModule } from './route-usage/route-usage.module';
import { SchedulingModule } from './scheduling/scheduling.module';
import { SchoolHolidaysModule } from './school-holidays/school-holidays.module';
import { ServiceIdentityModule } from './service-identity/service-identity.module';
import { SessionsModule } from './sessions/sessions.module';
import { SettingsModule } from './settings/settings.module';
import { ShareModule } from './share/share.module';
@@ -182,6 +183,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
TransitModule,
FeedsModule,
SettingsModule,
ServiceIdentityModule,
StorageModule,
BackupModule,
AuthModule,
@@ -139,6 +139,10 @@ export const APP_SETTINGS = {
ai_assistant_web_search: { schema: flag, default: 'true' },
/** `urn:uuid:<uuid>`: this install as one host to Sign in with ChatGPT, created on the first sign-in. */
ai_siwc_host_id: { schema: text, default: null },
/** This installation's key towards the liketrek services, issued on first use (service-identity). */
service_key: { schema: text, default: null, encrypted: 'always', managedLocked: true },
/** The key's bookkeeping as JSON: when to renew, when to ask again after a refusal, a revocation. */
service_key_state: { schema: text, default: null },
} as const satisfies Record<string, AppSettingDef>;
export type AppSettingKey = keyof typeof APP_SETTINGS;
+2
View File
@@ -92,6 +92,8 @@ export const MANAGED_LOCKED_SETTING_KEYS = [
'oidc_registration',
'openweather_api_key',
'routing_base_url',
// The operator issues a managed install its key through TREK_SERVICES_KEY.
'service_key',
'smtp_from',
'smtp_host',
'smtp_pass',
@@ -125,6 +125,7 @@ export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
'PluginsController.link',
'PluginsController.reload',
'PluginsController.upload',
'ServiceIdentityController.regenerate',
'StorageAdminController.backfillCancel',
'StorageAdminController.backfillStart',
'StorageAdminController.get',
+18 -11
View File
@@ -7,11 +7,13 @@
* autocomplete, and paying Google for a text search whose terms then forbid
* storing what comes back.
*
* Everything here is read-only, unauthenticated and cacheable. There is no key
* to configure and no quota to exhaust, so the failure modes are the network
* Everything here is read-only and cacheable. There is no key to configure:
* service-identity adds the installation's headers and reads each answer, and a
* refused key falls back to the shared pool. The failure modes stay the network
* and the service being down, both of which fall back to what TREK did before.
*/
import { readEnv, getAppUrl } from '../../app-config';
import { serviceIdentitySlot } from '../service-identity/service-identity.interface';
import { toApiLang } from './maps.helpers';
import {
normalizePlaceWebsite,
@@ -253,6 +255,17 @@ function noteFailure(err: unknown, breaker: Breaker): void {
}
}
/** A request carrying who is asking: the instance token, and the installation key where it may go. */
async function identifiedFetch(url: URL, headers: Record<string, string>, signal: AbortSignal): Promise<Response> {
const identity = serviceIdentitySlot.get();
const res = await fetch(url, {
signal,
headers: { ...headers, 'X-TREK-Instance': instanceToken(), ...identity.headersFor(url) },
});
identity.observe(url, res);
return res;
}
function statusError(status: number): Error & { status: number } {
const err = new Error(`TREK Places API ${status}`) as Error & { status: number };
err.status = status;
@@ -275,13 +288,7 @@ async function getJson<T>(
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? TIMEOUT_MS);
try {
const res = await fetch(url, {
signal: controller.signal,
headers: {
Accept: 'application/json',
'X-TREK-Instance': instanceToken(),
},
});
const res = await identifiedFetch(url, { Accept: 'application/json' }, controller.signal);
if (!res.ok) throw statusError(res.status);
// Read with a cap rather than res.json(): a hostile or broken upstream
// should not be able to hand us an unbounded body to buffer.
@@ -928,9 +935,9 @@ async function getWinter(
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), limits.timeoutMs);
try {
const headers: Record<string, string> = { Accept: accept, 'X-TREK-Instance': instanceToken() };
const headers: Record<string, string> = { Accept: accept };
if (etag) headers['If-None-Match'] = `"${etag}"`;
const res = await fetch(url, { signal: controller.signal, headers });
const res = await identifiedFetch(url, headers, controller.signal);
if (res.status === 304 && etag) {
layersBreaker.failures = 0;
return { status: 'not_modified' };
@@ -0,0 +1,88 @@
import { safeFetch } from '../../utils/ssrfGuard';
import { SERVICE_ISSUER_ORIGIN } from './service-identity.constants';
import { retryAfterMs, serverDateMs } from './service-identity.helpers';
import { serviceUserAgent } from './user-agent';
import { Injectable } from '@nestjs/common';
import {
serviceChallengeSchema,
serviceKeyGrantSchema,
serviceQuotaSchema,
type ServiceChallenge,
type ServiceKeyGrant,
type ServiceQuota,
} from '@trek/shared';
import type { z } from 'zod';
const TIMEOUT_MS = 10_000;
/** Every answer of the issuer is a few hundred bytes. */
const MAX_BYTES = 4096;
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(
readonly status: number,
readonly retryAfterMs: number | null,
readonly serverMs: number | null,
) {
super(`the TREK services issuer answered ${status}`);
this.name = 'IssuerError';
}
}
/** The four calls TREK makes to the key issuer at places.liketrek.com. */
@Injectable()
export class IssuerClient {
challenge(): Promise<IssuerAnswer<ServiceChallenge>> {
return this.call('GET', '/v1/register/challenge', serviceChallengeSchema);
}
register(request: RegistrationRequest): Promise<IssuerAnswer<ServiceKeyGrant>> {
return this.call('POST', '/v1/register', serviceKeyGrantSchema, { body: request });
}
renew(key: string): Promise<IssuerAnswer<ServiceKeyGrant>> {
return this.call('POST', '/v1/register/renew', serviceKeyGrantSchema, { bearer: key });
}
/** Today's allowance of the key, or of the shared legacy pool without one. Costs no allowance itself. */
quota(key: string | null): Promise<IssuerAnswer<ServiceQuota>> {
return this.call('GET', '/v1/quota', serviceQuotaSchema, { bearer: key });
}
private async call<T>(
method: 'GET' | 'POST',
path: string,
schema: z.ZodType<T>,
opts: { body?: RegistrationRequest; bearer?: string | null } = {},
): Promise<IssuerAnswer<T>> {
const headers: Record<string, string> = { 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(
`${SERVICE_ISSUER_ORIGIN}${path}`,
{
method,
headers,
body: opts.body ? JSON.stringify(opts.body) : undefined,
signal: AbortSignal.timeout(TIMEOUT_MS),
},
{ maxBytes: MAX_BYTES },
);
const serverMs = serverDateMs(res.headers);
if (!res.ok) throw new IssuerError(res.status, retryAfterMs(res.headers), serverMs);
return { body: schema.parse(await res.json()), serverMs };
}
}
@@ -0,0 +1,28 @@
import type { QuotaReading } from './service-identity.helpers';
import { Injectable } from '@nestjs/common';
interface QuotaSighting extends QuotaReading {
/** When a liketrek service last answered this process. */
seenAt: string;
}
/**
* The allowance as the last liketrek answer stated it. Kept in memory only:
* it is a fallback for the admin card when the issuer cannot be asked.
*/
@Injectable()
export class QuotaTracker {
private last: QuotaSighting | null = null;
record(reading: QuotaReading | null, at = new Date()): void {
this.last = {
tier: reading?.tier ?? this.last?.tier ?? null,
quota: reading?.quota ?? this.last?.quota ?? null,
seenAt: at.toISOString(),
};
}
latest(): QuotaSighting | null {
return this.last;
}
}
@@ -0,0 +1,25 @@
import { Injectable } from '@nestjs/common';
/**
* The liketrek services' clock, as far as this process has seen it. Key times
* (`iat`, `exp`, `renew_after`, a challenge's `expires_at`) are theirs, so a
* server whose own clock is off still renews on time.
*/
@Injectable()
export class ServiceClock {
private offsetMs = 0;
/** Takes the offset from a Date header the services sent. */
learn(serverMs: number | null): void {
if (serverMs !== null) this.offsetMs = serverMs - Date.now();
}
nowSeconds(): number {
return Math.floor((Date.now() + this.offsetMs) / 1000);
}
/** A time on the services' clock, read on this one. */
toLocalMs(serviceSeconds: number): number {
return serviceSeconds * 1000 - this.offsetMs;
}
}
@@ -0,0 +1,2 @@
/** 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';
@@ -0,0 +1,39 @@
import type { User } from '../../types';
import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { AdminGuard } from '../auth-core/admin.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { ServiceIdentityService } from './service-identity.service';
import { Controller, Get, HttpCode, Post, Req, UseGuards } from '@nestjs/common';
import { serviceIdentityStatusSchema, type ServiceIdentityStatus } from '@trek/shared';
import type { Request } from 'express';
/** /api/admin/service-identity: how this installation stands with the liketrek services, and a fresh start. */
@Controller('api/admin/service-identity')
@UseGuards(JwtAuthGuard, AdminGuard)
export class ServiceIdentityController {
constructor(
private readonly identity: ServiceIdentityService,
private readonly audit: AuditService,
) {}
@Get()
@ResponseContract(serviceIdentityStatusSchema)
async status(): Promise<ServiceIdentityStatus> {
return this.identity.status();
}
@Post('regenerate')
@HttpCode(200)
@ManagedForbidden('the installation key of a managed install comes from its operator through TREK_SERVICES_KEY')
@ResponseContract(serviceIdentityStatusSchema)
async regenerate(@CurrentUser() user: User, @Req() req: Request): Promise<ServiceIdentityStatus> {
const status = await this.identity.regenerate();
await this.audit.writeAudit({ userId: user.id, action: 'admin.service_identity_regenerate', ip: getClientIp(req) });
return status;
}
}
@@ -0,0 +1,74 @@
import { serviceTierSchema, type ServiceQuotaView, type ServiceTier } from '@trek/shared';
import { createHash } from 'node:crypto';
/**
* Two service addresses name the same service when host and path agree. The
* scheme, the case and trailing slashes do not count, so a compose line that
* was only uncommented still reads as the public instance.
*/
export function sameServiceUrl(a: string, b: string): boolean {
const left = serviceAddress(a);
return left !== null && left === serviceAddress(b);
}
function serviceAddress(raw: string): string | null {
const trimmed = raw.trim();
if (!trimmed) return null;
try {
const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`);
return `${url.host}${url.pathname.replace(/\/+$/, '')}`.toLowerCase();
} catch {
return null;
}
}
/** Only an https request to a listed host carries the installation key. */
export function isAllowlisted(url: URL, hosts: readonly string[]): boolean {
return url.protocol === 'https:' && hosts.includes(url.hostname.toLowerCase());
}
export interface QuotaReading {
tier: ServiceTier | null;
quota: ServiceQuotaView | null;
}
/** The X-TREK-Tier and X-TREK-Quota-* headers a liketrek answer carries, or null without any. */
export function readQuotaHeaders(headers: Headers): QuotaReading | null {
const tier = serviceTierSchema.safeParse(headers.get('x-trek-tier'));
const limit = wholeNumber(headers.get('x-trek-quota-limit'));
const remaining = wholeNumber(headers.get('x-trek-quota-remaining'));
const reset = wholeNumber(headers.get('x-trek-quota-reset'));
const quota =
limit !== null && remaining !== null && reset !== null
? { limit, used: Math.max(0, limit - remaining), remaining, resetAt: new Date(reset * 1000).toISOString() }
: null;
if (!tier.success && !quota) return null;
return { tier: tier.success ? tier.data : null, quota };
}
function wholeNumber(raw: string | null): number | null {
if (raw === null || !/^\d{1,12}$/.test(raw.trim())) return null;
return Number(raw.trim());
}
/** Retry-After as milliseconds from now, in either of its two spellings. */
export function retryAfterMs(headers: Headers, now = Date.now()): number | null {
const raw = headers.get('retry-after')?.trim();
if (!raw) return null;
if (/^\d{1,9}$/.test(raw)) return Number(raw) * 1000;
const at = Date.parse(raw);
return Number.isNaN(at) ? null : Math.max(0, at - now);
}
/** The answering server's clock from its Date header. */
export function serverDateMs(headers: Headers): number | null {
const raw = headers.get('date');
const at = raw ? Date.parse(raw) : Number.NaN;
return Number.isNaN(at) ? null : at;
}
/** Names a key in stored bookkeeping without storing the key itself. */
export function keyFingerprint(token: string): string {
return createHash('sha256').update(token).digest('hex').slice(0, 16);
}
@@ -0,0 +1,26 @@
import { ProcessStoreSlot } from '../common/process-store-slot';
/**
* What a client of a liketrek service asks before and after each request: the
* headers that identify this installation, and a look at the answer (quota
* headers, the server's clock, a refused key).
*
* The Places client is plain functions, so it reads the port from the slot
* below instead of taking it through a constructor. ServiceIdentityModule
* installs the implementation the container resolved.
*/
export abstract class ServiceIdentityPort {
abstract headersFor(url: URL): Record<string, string>;
abstract observe(url: URL, response: Response): void;
}
/** A process without the module (a hand-built test) sends what it sent before. */
class AnonymousIdentity extends ServiceIdentityPort {
headersFor(): Record<string, string> {
return {};
}
observe(): void {}
}
export const serviceIdentitySlot = new ProcessStoreSlot<ServiceIdentityPort>(new AnonymousIdentity());
@@ -0,0 +1,45 @@
import { AppConfigModule } from '../app-config/app-config.module';
import { AuditModule } from '../audit/audit.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { SettingsModule } from '../settings/settings.module';
import { IssuerClient } from './issuer.client';
import { QuotaTracker } from './quota-tracker';
import { ServiceClock } from './service-clock';
import { ServiceIdentityController } from './service-identity.controller';
import { ServiceIdentityPort, serviceIdentitySlot } from './service-identity.interface';
import { ServiceIdentityService } from './service-identity.service';
import { ServiceKeyJob } from './service-key.job';
import { ServiceKeyService } from './service-key.service';
import { ServiceKeyStore } from './service-key.store';
import { ServiceRequestIdentity } from './service-request-identity';
import { Module, type OnModuleDestroy } from '@nestjs/common';
/**
* The installation identity towards the liketrek services: the key, its
* registration and renewal, and the admin view of it. The Places client reads
* the request side through serviceIdentitySlot, which this module fills with
* the port the container resolved.
*/
@Module({
imports: [AppConfigModule, AuditModule, SchedulingModule, SettingsModule],
controllers: [ServiceIdentityController],
providers: [
IssuerClient,
QuotaTracker,
ServiceClock,
ServiceIdentityService,
ServiceKeyJob,
ServiceKeyService,
ServiceKeyStore,
{ provide: ServiceIdentityPort, useClass: ServiceRequestIdentity },
],
})
export class ServiceIdentityModule implements OnModuleDestroy {
constructor(private readonly port: ServiceIdentityPort) {
serviceIdentitySlot.install(port);
}
onModuleDestroy(): void {
serviceIdentitySlot.release(this.port);
}
}
@@ -0,0 +1,83 @@
import { logDebug } from '../audit/audit-log.logger';
import { IssuerClient } from './issuer.client';
import { QuotaTracker } from './quota-tracker';
import { ServiceClock } from './service-clock';
import { ServiceKeyService, type KeySnapshot } from './service-key.service';
import { Injectable } from '@nestjs/common';
import {
serviceTierSchema,
type ServiceIdentityStatus,
type ServiceQuota,
type ServiceQuotaView,
type ServiceTier,
} from '@trek/shared';
/** The admin card refreshes every 30 s; one issuer call serves every open card for this long. */
const QUOTA_CACHE_MS = 20_000;
const OFF: ServiceIdentityStatus = { state: 'off', tier: null, keySource: null, quota: null, lastSeenAt: null };
/** What the admin sees of this installation's identity, and the one thing an admin can do with it. */
@Injectable()
export class ServiceIdentityService {
private cached: { bearer: string | null; at: number; quota: ServiceQuota | null } | null = null;
constructor(
private readonly keys: ServiceKeyService,
private readonly issuer: IssuerClient,
private readonly tracker: QuotaTracker,
private readonly clock: ServiceClock,
) {}
async status(): Promise<ServiceIdentityStatus> {
const key = await this.keys.snapshot();
if (key.state === 'off') return OFF;
const fresh = await this.freshQuota(key.bearer);
const seen = this.tracker.latest();
return {
state: key.state,
tier: fresh?.tier ?? seen?.tier ?? keyTier(key),
keySource: key.source,
quota: fresh ? quotaView(fresh) : (seen?.quota ?? null),
lastSeenAt: seen?.seenAt ?? null,
};
}
async regenerate(): Promise<ServiceIdentityStatus> {
await this.keys.regenerate();
this.cached = null;
return this.status();
}
/** GET /v1/quota, which costs no allowance; null when the issuer cannot be asked right now. */
private async freshQuota(bearer: string | null): Promise<ServiceQuota | null> {
if (this.cached && this.cached.bearer === bearer && Date.now() - this.cached.at < QUOTA_CACHE_MS) {
return this.cached.quota;
}
let quota: ServiceQuota | null = null;
try {
const answer = await this.issuer.quota(bearer);
this.clock.learn(answer.serverMs);
quota = answer.body;
} catch (err) {
logDebug(`TREK services: quota not available: ${err instanceof Error ? err.message : String(err)}`);
}
this.cached = { bearer, at: Date.now(), quota };
return quota;
}
}
function keyTier(key: KeySnapshot): ServiceTier | null {
if (!key.key) return key.state === 'legacy' || key.state === 'registering' ? 'legacy' : null;
const tier = serviceTierSchema.safeParse(key.key.payload.q);
return tier.success ? tier.data : null;
}
function quotaView(quota: ServiceQuota): ServiceQuotaView {
return {
limit: quota.limit,
used: quota.used,
remaining: quota.remaining,
resetAt: new Date(quota.reset_at * 1000).toISOString(),
};
}
@@ -0,0 +1,40 @@
import { z } from 'zod';
const BASE64URL = /^[A-Za-z0-9_-]+$/;
const payloadSchema = z.object({
i: z.string().min(1).max(64).regex(BASE64URL),
iat: z.number().int().nonnegative(),
exp: z.number().int().positive(),
q: z.string().min(1).max(32),
});
type ServiceKeyPayload = z.infer<typeof payloadSchema>;
export interface ServiceKey {
token: string;
kid: string;
payload: ServiceKeyPayload;
}
/**
* Reads `tk1.<kid>.<payload>.<signature>`. The signature is the gate's to
* check; TREK only needs the expiry and the class it was given, and treats
* anything that does not read as no key at all.
*/
export function parseServiceKey(token: string): ServiceKey | null {
const parts = token.trim().split('.');
if (parts.length !== 4 || parts[0] !== 'tk1') return null;
const [, kid, body, signature] = parts;
if (![kid, body, signature].every((part) => BASE64URL.test(part))) return null;
const payload = payloadSchema.safeParse(decodeSegment(body));
return payload.success ? { token: parts.join('.'), kid, payload: payload.data } : null;
}
function decodeSegment(segment: string): unknown {
try {
return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
} catch {
return null;
}
}
@@ -0,0 +1,25 @@
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { ServiceKeyService } from './service-key.service';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { randomInt } from 'node:crypto';
/**
* Once a day, at a minute and hour picked per start, renews the installation
* key when it is due. Spread out so the installations of the world do not all
* knock on the issuer at the same moment.
*/
@Injectable()
export class ServiceKeyJob implements OnApplicationBootstrap {
constructor(
private readonly keys: ServiceKeyService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
this.registrar.register('service-key-renewal', `${randomInt(60)} ${randomInt(24)} * * *`, () =>
this.keys.renewIfDue(),
);
}
}
@@ -0,0 +1,38 @@
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> {
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) =>
err ? reject(err) : resolve(hash),
);
});
}
export function leadingZeroBits(hash: Uint8Array): number {
let bits = 0;
for (const byte of hash) {
if (byte !== 0) return bits + Math.clz32(byte) - 24;
bits += 8;
}
return bits;
}
/** The first decimal nonce whose hash has at least `bits` leading zero bits, tried until `deadlineMs`. */
export async function solvePow(challenge: ServiceChallenge, deadlineMs: number): Promise<string> {
for (let nonce = 0; Date.now() < deadlineMs; nonce++) {
const hash = await powHash(challenge.c, String(nonce), challenge);
if (leadingZeroBits(hash) >= challenge.bits) return String(nonce);
}
throw new Error('the registration challenge expired before it was solved');
}
@@ -0,0 +1,290 @@
import { runningVersion } from '../../app-config';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { servicesConfig } from '../app-config/tokens';
import { logInfo, logWarn } from '../audit/audit-log.logger';
import { conflict } from '../common/domain-error';
import { withRequestContext } from '../database/request-context';
import { IssuerClient, IssuerError } from './issuer.client';
import { ServiceClock } from './service-clock';
import { 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';
import { EMPTY_KEY_STATE, ServiceKeyStore, type KeyState, type StoredIdentity } from './service-key.store';
import { MikroORM } from '@mikro-orm/core';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import type { ServiceIdentityState, ServiceKeyGrant } from '@trek/shared';
import { 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;
/** Refusals in a row before a key counts as gone, so one broken deploy upstream drops nothing. */
const INVALID_STREAK_LIMIT = 3;
/** 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;
const MAX_BACKOFF_MS = 6 * 3_600_000;
export interface KeySnapshot {
state: ServiceIdentityState;
key: ServiceKey | null;
source: 'env' | 'registered' | null;
/** What a request may carry right now; null while revoked or without a key. */
bearer: string | null;
}
/**
* The installation key: loaded lazily, registered in the background on the
* first call to a liketrek service, renewed from day 60, given up after
* repeated refusals and frozen when the services revoke it.
*
* Nothing here ever makes a request wait. Until a key is there, requests go
* out as they always did, and the shared legacy pool answers them.
*/
@Injectable()
export class ServiceKeyService {
private loaded = false;
private key: ServiceKey | null = null;
/** The stored row exists but cannot be used, so a new key overwrites it instead of claiming. */
private staleRow = false;
private state: KeyState = EMPTY_KEY_STATE;
private work: Promise<void> | null = null;
private registering = false;
private nextAttemptAt = 0;
private failures = 0;
private invalidStreak = 0;
constructor(
@Inject(servicesConfig.KEY) private readonly config: ConfigType<typeof servicesConfig>,
private readonly env: RuntimeEnvService,
private readonly store: ServiceKeyStore,
private readonly issuer: IssuerClient,
private readonly clock: ServiceClock,
private readonly orm: MikroORM,
) {}
/** Whether the Places service this instance uses is one the key goes to. */
inUse(): boolean {
const maps = this.env.env().maps;
if (this.config.mode === 'off' || !maps.trekPlacesEnabled) return false;
try {
return isAllowlisted(new URL(this.placesUrl()), this.config.hosts);
} catch {
return false;
}
}
/** The bearer for a request to an allowlisted host; starts a registration in the background when there is none. */
bearer(): string | null {
if (!this.inUse()) return null;
this.settleInBackground();
const token = this.config.key ?? this.key?.token ?? null;
return token && !this.isRevoked(token) ? token : null;
}
/** What the admin card shows. Reads only: a GET must not register. */
async snapshot(): Promise<KeySnapshot> {
if (!this.inUse()) return { state: 'off', key: null, source: null, bearer: null };
await this.load();
const token = this.config.key ?? this.key?.token ?? null;
if (!token) return { state: this.registering ? 'registering' : 'legacy', key: null, source: null, bearer: null };
const source = this.config.key ? 'env' : 'registered';
const key = parseServiceKey(token);
if (this.isRevoked(token)) return { state: 'revoked', key, source, bearer: null };
return { state: 'connected', key, source, bearer: token };
}
/** A liketrek service accepted the key. */
noteAccepted(): void {
this.invalidStreak = 0;
}
/** A liketrek service answered 401 to the key; the third in a row gives it up. */
noteInvalid(): void {
if (!this.config.key && !this.key) return;
this.invalidStreak += 1;
if (this.invalidStreak < INVALID_STREAK_LIMIT) return;
this.invalidStreak = 0;
if (this.config.key) {
logWarn(
'TREK services: the key in TREK_SERVICES_KEY is refused. Place search continues through the shared pool.',
);
return;
}
this.inBackground(() => this.dropKey());
}
/** A liketrek service answered that the key is revoked. */
noteRevoked(): void {
const token = this.config.key ?? this.key?.token;
if (!token || this.isRevoked(token)) return;
this.inBackground(() => this.markRevoked(token));
}
/** The daily check: renews the key once it is due. A key past its grace period is already gone on load. */
async renewIfDue(): Promise<void> {
if (!this.inUse() || this.config.key) return;
await this.load();
const key = this.key;
if (!key || this.isRevoked(key.token)) return;
if (this.clock.nowSeconds() < (this.state.renewAfter ?? key.payload.iat + RENEW_AGE_SECONDS)) return;
const renewal = await this.issuer.renew(key.token).then(
(grant) => ({ grant, error: null }),
(error: unknown) => ({ grant: null, error }),
);
if (!renewal.grant) {
await this.refused(renewal.error, key.token);
return;
}
this.clock.learn(renewal.grant.serverMs);
const renewed = this.readGrant(renewal.grant.body);
this.state = { ...this.state, renewAfter: renewal.grant.body.renew_after };
await this.store.replace(renewed, this.state);
this.key = renewed;
logInfo('TREK services: renewed the key of this installation.');
}
/** The admin's way out of a revoked or cloned identity: forget the key and ask for a new one. */
async regenerate(): Promise<void> {
if (this.config.key) throw conflict('The key is set by TREK_SERVICES_KEY and is changed there');
if (!this.inUse()) throw conflict('TREK services are not in use on this instance');
await this.store.clear();
this.adopt({ key: null, unreadable: false, state: EMPTY_KEY_STATE });
this.nextAttemptAt = 0;
this.failures = 0;
this.invalidStreak = 0;
logInfo('TREK services: an admin asked for a new identity for this installation.');
this.settleInBackground();
}
/** Test seam: resolves once the background work queued so far has run. */
async whenIdle(): Promise<void> {
const work = this.work;
if (!work) return;
await work;
await this.whenIdle();
}
private placesUrl(): string {
return this.env.env().maps.trekPlacesUrl?.trim() || SERVICE_ISSUER_ORIGIN;
}
private mayRegister(): boolean {
return !this.config.key && !this.env.isTest() && sameServiceUrl(this.placesUrl(), SERVICE_ISSUER_ORIGIN);
}
private wantsRegistration(): boolean {
const now = Date.now();
return (
this.mayRegister() &&
this.key === null &&
this.state.revoked === null &&
now >= this.nextAttemptAt &&
now >= (this.state.reregisterAt ?? 0)
);
}
private isRevoked(token: string): boolean {
return this.state.revoked !== null && this.state.revoked === keyFingerprint(token);
}
private settleInBackground(): void {
if (this.work || (this.loaded && !this.wantsRegistration())) return;
this.inBackground(async () => {
await this.load();
if (this.wantsRegistration()) await this.register();
});
}
/** Runs work outside the request that triggered it, one piece at a time, and never lets it fail a caller. */
private inBackground(task: () => Promise<void>): void {
const previous = this.work ?? Promise.resolve();
const next = previous
.then(() => withRequestContext(this.orm, task))
.catch((err: unknown) => logWarn(`TREK services: ${err instanceof Error ? err.message : String(err)}`))
.finally(() => {
if (this.work === next) this.work = null;
});
this.work = next;
}
private async load(): Promise<void> {
if (this.loaded) return;
this.adopt(await this.store.read());
}
private adopt(stored: StoredIdentity): void {
const expired = stored.key !== null && this.clock.nowSeconds() > stored.key.payload.exp + RENEW_GRACE_SECONDS;
this.key = expired ? null : stored.key;
this.staleRow = stored.unreadable || expired;
this.state = stored.state;
this.loaded = true;
}
private async register(): Promise<void> {
this.registering = true;
try {
const challenge = await this.issuer.challenge();
this.clock.learn(challenge.serverMs);
const nonce = await solvePow(challenge.body, this.clock.toLocalMs(challenge.body.expires_at));
const grant = await this.issuer.register({ c: challenge.body.c, nonce, v: runningVersion() });
this.clock.learn(grant.serverMs);
const key = this.readGrant(grant.body);
const state: KeyState = { ...EMPTY_KEY_STATE, renewAfter: grant.body.renew_after };
if (this.staleRow) {
await this.store.replace(key, state);
this.adopt({ key, unreadable: false, state });
} else {
this.adopt(await this.store.claim(key, state));
}
this.failures = 0;
logInfo('TREK services: this installation is registered.');
} catch (err) {
this.backOff(err);
throw err;
} finally {
this.registering = false;
}
}
private readGrant(grant: ServiceKeyGrant): ServiceKey {
const key = parseServiceKey(grant.key);
if (!key) throw new Error('the issuer handed out a key TREK cannot read');
return key;
}
private backOff(err: unknown): void {
this.failures += 1;
const asked = err instanceof IssuerError ? err.retryAfterMs : null;
const backoff = Math.min(MAX_BACKOFF_MS, FIRST_BACKOFF_MS * 2 ** (this.failures - 1));
this.nextAttemptAt = Date.now() + (asked ?? backoff);
}
private async refused(err: unknown, token: string): Promise<void> {
if (!(err instanceof IssuerError) || (err.status !== 401 && err.status !== 403)) throw err;
if (err.status === 403) await this.markRevoked(token);
else await this.dropKey();
}
private async dropKey(): Promise<void> {
this.key = null;
this.state = { ...this.state, renewAfter: null, reregisterAt: Date.now() + randomInt(REREGISTER_JITTER_MS) };
await this.store.dropKey(this.state);
logWarn('TREK services: the key of this installation is no longer accepted; a new one is requested later.');
}
private async markRevoked(token: string): Promise<void> {
await this.load();
this.state = { ...this.state, revoked: keyFingerprint(token) };
await this.store.writeState(this.state);
logWarn(
'TREK services: the key of this installation was revoked. Place search continues through the shared pool; ' +
'an admin can create a new identity under Admin, Settings, API Keys.',
);
}
}
@@ -0,0 +1,93 @@
import { decrypt_api_key, encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { UnitOfWork } from '../database/unit-of-work';
import { SettingsService } from '../settings/settings.service';
import { parseServiceKey, type ServiceKey } from './service-key.format';
import { Injectable } from '@nestjs/common';
import { z } from 'zod';
const keyStateSchema = z.object({
/** Fingerprint of a key the services revoked; cleared only by an admin's new identity. */
revoked: z.string().nullable().catch(null),
/** Local epoch ms before which no new registration is tried, after a key was refused. */
reregisterAt: z.number().nullable().catch(null),
/** When the key is due for renewal, on the services' clock (unix seconds). */
renewAfter: z.number().nullable().catch(null),
});
export type KeyState = z.infer<typeof keyStateSchema>;
export const EMPTY_KEY_STATE: KeyState = { revoked: null, reregisterAt: null, renewAfter: null };
export interface StoredIdentity {
key: ServiceKey | null;
/** A row is there but does not open with this ENCRYPTION_KEY, or does not read as a key. */
unreadable: boolean;
state: KeyState;
}
/**
* The installation key in app_settings, encrypted like the other instance
* secrets, and the small state record beside it. Nothing here talks to the
* services; it only keeps what they handed out.
*/
@Injectable()
export class ServiceKeyStore {
constructor(
private readonly settings: SettingsService,
private readonly uow: UnitOfWork,
) {}
async read(): Promise<StoredIdentity> {
const ciphertext = await this.settings.getAppSetting('service_key');
const state = readState(await this.settings.getAppSetting('service_key_state'));
if (!ciphertext) return { key: null, unreadable: false, state };
const key = parseServiceKey(decrypt_api_key(ciphertext) ?? '');
return { key, unreadable: key === null, state };
}
/**
* Keeps a freshly issued key unless another process on this database stored
* one first, then answers whatever is stored now.
*/
async claim(key: ServiceKey, state: KeyState): Promise<StoredIdentity> {
await this.uow.transactional(async () => {
await this.settings.insertAppSettingIfAbsent('service_key', encrypt_api_key(key.token));
await this.settings.setAppSettings({ service_key_state: JSON.stringify(state) });
});
return this.read();
}
/** Overwrites the stored key: a renewal, or a row that could not be read. */
async replace(key: ServiceKey, state: KeyState): Promise<void> {
await this.settings.setAppSettings({
service_key: encrypt_api_key(key.token),
service_key_state: JSON.stringify(state),
});
}
async writeState(state: KeyState): Promise<void> {
await this.settings.setAppSettings({ service_key_state: JSON.stringify(state) });
}
/** Forgets the key but keeps the state that says when to ask again. */
async dropKey(state: KeyState): Promise<void> {
await this.uow.transactional(async () => {
await this.settings.deleteAppSettings(['service_key']);
await this.writeState(state);
});
}
async clear(): Promise<void> {
await this.settings.deleteAppSettings(['service_key', 'service_key_state']);
}
}
function readState(raw: string | null): KeyState {
if (!raw) return EMPTY_KEY_STATE;
try {
return keyStateSchema.parse({ ...EMPTY_KEY_STATE, ...(JSON.parse(raw) as object) });
} catch {
return EMPTY_KEY_STATE;
}
}
@@ -0,0 +1,73 @@
import { servicesConfig } from '../app-config/tokens';
import { QuotaTracker } from './quota-tracker';
import { ServiceClock } from './service-clock';
import { isAllowlisted, readQuotaHeaders, serverDateMs } from './service-identity.helpers';
import { ServiceIdentityPort } from './service-identity.interface';
import { ServiceKeyService } from './service-key.service';
import { serviceUserAgent } from './user-agent';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
/** A revocation notice is one short JSON object; nothing longer is read. */
const NOTICE_MAX_CHARS = 2048;
/**
* The identity every request to a liketrek service carries, and what TREK
* learns from each answer. The key goes to the allowlisted hosts only; a
* mirror, a plugin's egress or any other host never sees it.
*/
@Injectable()
export class ServiceRequestIdentity extends ServiceIdentityPort {
constructor(
@Inject(servicesConfig.KEY) private readonly config: ConfigType<typeof servicesConfig>,
private readonly keys: ServiceKeyService,
private readonly tracker: QuotaTracker,
private readonly clock: ServiceClock,
) {
super();
}
headersFor(url: URL): Record<string, string> {
const headers: Record<string, string> = { 'User-Agent': serviceUserAgent() };
if (!isAllowlisted(url, this.config.hosts)) return headers;
const bearer = this.keys.bearer();
if (bearer) headers.Authorization = `Bearer ${bearer}`;
return headers;
}
observe(url: URL, response: Response): void {
if (!isAllowlisted(url, this.config.hosts)) return;
this.clock.learn(serverDateMs(response.headers));
this.tracker.record(readQuotaHeaders(response.headers));
if (response.ok) this.keys.noteAccepted();
else if (response.status === 401) this.keys.noteInvalid();
else if (response.status === 403) void this.checkRevocation(response.clone());
}
private async checkRevocation(response: Response): Promise<void> {
if (await saysRevoked(response)) this.keys.noteRevoked();
}
}
/** A 403 means a revoked key only when the body says so; anything else leaves the key alone. */
async function saysRevoked(response: Response): Promise<boolean> {
try {
return (await readUpTo(response, NOTICE_MAX_CHARS)).includes('key_revoked');
} catch {
return false;
}
}
async function readUpTo(response: Response, maxChars: number): Promise<string> {
const reader = response.body?.getReader();
if (!reader) return '';
const decoder = new TextDecoder();
let text = '';
while (text.length <= maxChars) {
const { done, value } = await reader.read();
if (done) return text;
text += decoder.decode(value, { stream: true });
}
await reader.cancel();
return text;
}
@@ -0,0 +1,6 @@
import { runningVersion } from '../../app-config';
/** How every request to a liketrek service names its sender. */
export function serviceUserAgent(): string {
return `TREK/${runningVersion()} (+https://github.com/liketrek/TREK)`;
}
@@ -383,6 +383,21 @@ export class SettingsService {
return await readAppSetting(this.appSettings, key);
}
/** Writes a registered instance setting only while it has no row; the first of several processes keeps it. */
async insertAppSettingIfAbsent(key: AppSettingKey, value: string): Promise<void> {
await this.appSettings.insertIfAbsent(key, value);
}
/** Removes registered instance settings together. */
async deleteAppSettings(keys: AppSettingKey[]): Promise<void> {
await this.uow.transactional(() =>
keys.reduce<Promise<void>>(async (previous, key) => {
await previous;
await this.appSettings.deleteValue(key);
}, Promise.resolve()),
);
}
/** Registered instance settings written together: every value lands, or none does. */
async setAppSettings(values: Partial<Record<AppSettingKey, string>>): Promise<void> {
const entries = Object.entries(values).filter((entry): entry is [string, string] => entry[1] !== undefined);