dorfteich/apps/api/src/notifications/unsubscribe-token.ts
Claude Fable 5 1f56f34113
All checks were successful
CD / Smoke tests against Test (push) Successful in 1m25s
CD / Promote to Int (push) Successful in 12s
Release / Build release images and notes (push) Successful in 3m31s
Release / Release-candidate operations QA (push) Successful in 46s
CI / Build container images (push) Has been skipped
Prod deploy / Deploy the released images to Prod (push) Successful in 58s
CI / Import/export fidelity gate (push) Successful in 59s
CI / Lint, typecheck, test (push) Successful in 6m40s
CI / Auth e2e pack (push) Successful in 8m21s
Restore drill / Restore the latest backup into a scratch stack (push) Successful in 1m18s
CI / Build container images (pull_request) Successful in 2m53s
CI / Auth e2e pack (pull_request) Successful in 8m34s
CI / Lint, typecheck, test (pull_request) Successful in 6m22s
CI / Import/export fidelity gate (pull_request) Successful in 59s
CD / Build and push images (push) Successful in 19s
CD / Deploy to Test (push) Successful in 14s
#296: remove the unsubscribe-token dual-verify window early
Operator decision at the ADR 0020 acceptance: verification is
subkey-only now instead of waiting for the stated 2026-11-01 expiry.
Links in digest mails sent before the #188 key separation stop working;
recipients use the in-app notification settings. A regression test pins
that the legacy derivation (root key + purpose prefix) can never verify
again; security.md records the removal.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AUtYMxwTCMHG9mVHnwbFg8
2026-07-31 23:03:03 +02:00

66 lines
2.4 KiB
TypeScript

import { createHmac, timingSafeEqual } from 'node:crypto';
import { deriveTokenKey } from '@dorfteich/shared/token-crypto';
/**
* Single-purpose unsubscribe tokens for the digest mails (issue #95): a
* signed `{userId, exp}` blob whose only power is flipping that user's
* digest setting to `off` — it never creates a session (ADR 0007's "signed
* tokens" pattern). Purpose-binding is structural since #188 (ADR 0020):
* the HMAC key is the HKDF subkey for `unsubscribe`, so a token signed for
* any other purpose cannot verify here regardless of its content.
*/
const TTL_SECONDS = 90 * 24 * 60 * 60;
// The pre-#188 dual-verify window (root secret + `digest-unsubscribe.`
// prefix) was removed EARLY by operator decision at the ADR 0020
// acceptance (issue #296): links in mails sent before the key separation
// no longer work — recipients use the in-app notification settings.
// Verification is subkey-only; the regression test pins that the legacy
// derivation can never verify again.
function signature(body: string, rootSecret: string): Buffer {
return createHmac('sha256', deriveTokenKey(rootSecret, 'unsubscribe')).update(body).digest();
}
export function signUnsubscribeToken(userId: string, rootSecret: string, now = Date.now()): string {
const body = Buffer.from(
JSON.stringify({ userId, exp: Math.floor(now / 1000) + TTL_SECONDS }),
'utf8',
).toString('base64url');
return `${body}.${signature(body, rootSecret).toString('base64url')}`;
}
function matches(provided: Buffer, expected: Buffer): boolean {
return provided.length === expected.length && timingSafeEqual(provided, expected);
}
/** The user id, or null for anything invalid or expired. Never throws. */
export function verifyUnsubscribeToken(
token: string,
rootSecret: string,
now = Date.now(),
): string | null {
const [body, sig] = token.split('.');
if (!body || !sig) return null;
let provided: Buffer;
try {
provided = Buffer.from(sig, 'base64url');
} catch {
return null;
}
if (!matches(provided, signature(body, rootSecret))) return null;
try {
const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as {
userId?: string;
exp?: number;
};
if (typeof payload.userId !== 'string' || typeof payload.exp !== 'number') return null;
if (payload.exp * 1000 < now) return null;
return payload.userId;
} catch {
return null;
}
}