refactor(server): fold webauthn, account erasure, oauth and the wiki out of services/ (#1840)

* refactor(server): move the webauthn config and the account erasure into nest/auth

webauthnConfig resolved the RP ID through its own getSetting() on the db
singleton; it is a WebauthnConfigService over DatabaseService now, injected into
AuthService (passkey_configured) and PasskeyService (four ceremonies). readEnv()
is still read per call, so an operator flipping the RP ID at runtime takes effect
on the next ceremony instead of after a restart.

userCleanupService follows as UserCleanupService. It keeps taking
removeUserFromBudgetItems from budget.bridge rather than injecting BudgetService:
BudgetModule imports AuthModule for the demo guard in BudgetMcp, so AuthModule
cannot import BudgetModule back, and breaking that edge the other way drags
BudgetController, BudgetMcp and its trips.bridge chain into every graph that
imports AuthModule.

The legacy module had no tests of its own - the erasure only ever ran through
AdminService.deleteUser and TripsService.deleteGuest - so USER-CLEANUP-001..009
pin both halves, including the orphan data dir that no permissions row can
describe and the all-or-nothing deletion transaction.

* refactor(server): fold the oauth 2.1 server out of services/

694 lines move into OauthService over DatabaseService, AddonsService and
AuditService. The thin wrapper that only forwarded is gone, and so is the second
path to the MCP addon flag - validateAuthorizeRequest read it through
addons.bridge while the wrapper read it through the injected service, which would
have let the two drift.

The pending authorization codes stay a module singleton in oauth.pending-codes.ts
instead of becoming instance state. The SDK still serves /oauth/authorize,
/oauth/register and /oauth/consent from its own router, mounted on Express before
app.init(), so it reaches the domain through the new oauth.bridge.ts - two maps
would break the authorization-code flow silently, since the SDK only ever answers
"Authorization grant is invalid.". The import-time sweep keeps its .unref() and is
a named function now so a test can drive it.

scopes and sessionManager are imported deep, never through the src/mcp barrel:
the barrel re-exports revokeUserSessionsForClient and pulls the domain bridges
back in, which is the nest -> mcp -> nest cycle. Same comment as admin.service and
auth.service carry.

The 70 cases of the legacy suite moved over unchanged, bound to a hand-built
service. Fifteen more cover what free functions never let anyone reach: the code
store at capacity, an expired code, an expired access token, refresh against a
public and an unknown client, the RFC 8707 resource checks, and that a code
written through the container is read back through the bridge.

* refactor(server): move the wiki reader into the help module

wikiService had exactly one consumer, HelpController, and touches no database -
it stays a plain module rather than becoming a provider, the way
auth/ephemeral-tokens.ts does, so the text and asset caches keep being one per
process without any ceremony around it.

The WIKI_DIR anchor needed one more level: src/services sits three below the repo
root, src/nest/help sits four. The existing path-resolution case caught it, which
is what it is there for - a wrong anchor makes help degrade to the GitHub fallback
without anybody noticing.

Also brings the nest README back in line: services/ is down to five top-level
files, and the passkey and budget entries no longer point at paths that were
deleted since they were written.
This commit is contained in:
Maurice
2026-08-08 11:14:24 +02:00
committed by GitHub
parent 5eab8128bd
commit 03493a2edd
39 changed files with 2528 additions and 2049 deletions
-694
View File
@@ -1,694 +0,0 @@
import crypto, { randomBytes, createHash, randomUUID } from 'crypto';
import { db } from '../db/database';
import { isAddonEnabled } from '../nest/addons/addons.bridge';
import { validateScopes } from '../mcp/scopes';
import { ADDON_IDS } from '../addons';
import { User } from '../types';
import { writeAudit, logWarn } from '../nest/audit/audit.bridge';
import { revokeUserSessionsForClient } from '../mcp/sessionManager';
import { getMcpSafeUrl } from '../app-config';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const ACCESS_TOKEN_TTL_S = 60 * 60; // 1 hour
const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days rolling
const AUTH_CODE_TTL_MS = 2 * 60 * 1000; // 2 minutes
// PKCE format (RFC 7636)
const CODE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/;
const CODE_VERIFIER_RE = /^[A-Za-z0-9\-._~]{43,128}$/;
// ---------------------------------------------------------------------------
// In-memory auth code store (short-lived, no need for DB persistence)
// ---------------------------------------------------------------------------
interface PendingCode {
clientId: string;
userId: number;
redirectUri: string;
scopes: string[];
resource: string | null;
codeChallenge: string;
codeChallengeMethod: 'S256';
expiresAt: number;
}
const MAX_PENDING_CODES = 500;
const pendingCodes = new Map<string, PendingCode>();
setInterval(() => {
const now = Date.now();
for (const [key, entry] of pendingCodes) {
if (now > entry.expiresAt) pendingCodes.delete(key);
}
}, 60_000).unref();
// ---------------------------------------------------------------------------
// DB row types
// ---------------------------------------------------------------------------
interface OAuthClientRow {
id: string;
user_id: number;
name: string;
client_id: string;
client_secret_hash: string;
redirect_uris: string; // JSON array
allowed_scopes: string; // JSON array
created_at: string;
is_public: number; // 0 | 1 (SQLite boolean)
created_via: string; // 'settings_ui' | 'browser-registration'
allows_client_credentials: number; // 0 | 1
}
interface OAuthTokenRow {
id: number;
client_id: string;
user_id: number;
access_token_hash: string;
refresh_token_hash: string;
scopes: string; // JSON array
audience: string | null;
access_token_expires_at: string;
refresh_token_expires_at: string;
revoked_at: string | null;
parent_token_id: number | null;
}
// ---------------------------------------------------------------------------
// Token helpers
// ---------------------------------------------------------------------------
function hashToken(raw: string): string {
return createHash('sha256').update(raw).digest('hex');
}
/** Constant-time comparison of two hex-encoded SHA-256 hashes. */
function timingSafeEqualHex(a: string, b: string): boolean {
if (a.length !== b.length) return false;
try {
return crypto.timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
} catch { return false; }
}
function generateAccessToken(): string {
return 'trekoa_' + randomBytes(32).toString('hex');
}
function generateRefreshToken(): string {
return 'trekrf_' + randomBytes(32).toString('hex');
}
// ---------------------------------------------------------------------------
// Client management (self-service, gated by MCP addon)
// ---------------------------------------------------------------------------
export function listOAuthClients(userId: number): Record<string, unknown>[] {
const rows = db.prepare(
'SELECT id, user_id, name, client_id, redirect_uris, allowed_scopes, created_at, is_public, created_via, allows_client_credentials FROM oauth_clients WHERE user_id = ? ORDER BY created_at DESC'
).all(userId) as OAuthClientRow[];
return rows.map(r => ({
...r,
is_public: Boolean(r.is_public),
allows_client_credentials: Boolean(r.allows_client_credentials),
redirect_uris: JSON.parse(r.redirect_uris),
allowed_scopes: JSON.parse(r.allowed_scopes),
}));
}
export function createOAuthClient(
userId: number | null,
name: string,
redirectUris: string[],
allowedScopes: string[],
ip?: string | null,
options?: { isPublic?: boolean; createdVia?: string; allowsClientCredentials?: boolean },
): { error?: string; status?: number; client?: Record<string, unknown> } {
if (!name?.trim()) return { error: 'Name is required', status: 400 };
if (name.trim().length > 100) return { error: 'Name must be 100 characters or less', status: 400 };
const isMachineClient = Boolean(options?.allowsClientCredentials);
if (!isMachineClient && (!redirectUris || redirectUris.length === 0)) return { error: 'At least one redirect URI is required', status: 400 };
if (redirectUris.length > 10) return { error: 'Maximum 10 redirect URIs per client', status: 400 };
for (const uri of redirectUris) {
let parsed: URL;
try {
parsed = new URL(uri);
} catch {
return { error: `Invalid redirect URI: ${uri}`, status: 400 };
}
if (parsed.protocol !== 'https:' && parsed.hostname !== 'localhost' && parsed.hostname !== '127.0.0.1') {
return { error: `Redirect URI must use HTTPS (localhost exempt): ${uri}`, status: 400 };
}
}
if (!allowedScopes || allowedScopes.length === 0) return { error: 'At least one scope is required', status: 400 };
const { valid, invalid } = validateScopes(allowedScopes);
if (!valid) return { error: `Invalid scopes: ${invalid.join(', ')}`, status: 400 };
if (userId !== null) {
const count = (db.prepare('SELECT COUNT(*) as count FROM oauth_clients WHERE user_id = ?').get(userId) as { count: number }).count;
if (count >= 10) return { error: 'Maximum of 10 OAuth clients per user', status: 400 };
} else {
// Anonymous DCR clients: enforce a global cap to prevent unbounded registration abuse
const count = (db.prepare('SELECT COUNT(*) as count FROM oauth_clients WHERE user_id IS NULL').get() as { count: number }).count;
if (count >= 500) return { error: 'server_error', status: 503 };
}
// Machine clients (client_credentials) must always be confidential — ignore isPublic for them.
const isPublic = isMachineClient ? false : (options?.isPublic ?? false);
const createdVia = options?.createdVia ?? 'settings_ui';
const id = randomUUID();
const clientId = randomUUID();
// Public clients have no usable secret; store an opaque random value to satisfy NOT NULL.
const rawSecret = isPublic ? null : 'trekcs_' + randomBytes(24).toString('hex');
const secretHash = rawSecret ? hashToken(rawSecret) : randomBytes(32).toString('hex');
db.prepare(
'INSERT INTO oauth_clients (id, user_id, name, client_id, client_secret_hash, redirect_uris, allowed_scopes, is_public, created_via, allows_client_credentials) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(id, userId, name.trim(), clientId, secretHash, JSON.stringify(redirectUris), JSON.stringify(allowedScopes), isPublic ? 1 : 0, createdVia, isMachineClient ? 1 : 0);
const row = db.prepare(
'SELECT id, user_id, name, client_id, redirect_uris, allowed_scopes, created_at, is_public, created_via, allows_client_credentials FROM oauth_clients WHERE id = ?'
).get(id) as OAuthClientRow;
writeAudit({ userId, action: 'oauth.client.create', details: { client_id: clientId, name: name.trim(), is_public: isPublic, allows_client_credentials: isMachineClient }, ip });
return {
client: {
id: row.id,
user_id: row.user_id,
name: row.name,
client_id: row.client_id,
redirect_uris: JSON.parse(row.redirect_uris),
allowed_scopes: JSON.parse(row.allowed_scopes),
created_at: row.created_at,
is_public: Boolean(row.is_public),
allows_client_credentials: Boolean(row.allows_client_credentials),
created_via: row.created_via,
// client_secret only present for confidential clients — shown once, not stored in plain text
...(rawSecret ? { client_secret: rawSecret } : {}),
},
};
}
export function rotateOAuthClientSecret(
userId: number,
clientRowId: string,
ip?: string | null,
): { error?: string; status?: number; client_secret?: string } {
const row = db.prepare('SELECT id, client_id, is_public FROM oauth_clients WHERE id = ? AND user_id = ?').get(clientRowId, userId) as OAuthClientRow | undefined;
if (!row) return { error: 'Client not found', status: 404 };
if (row.is_public) return { error: 'Public clients do not use a client secret', status: 400 };
const rawSecret = 'trekcs_' + randomBytes(24).toString('hex');
const secretHash = hashToken(rawSecret);
db.prepare('UPDATE oauth_clients SET client_secret_hash = ? WHERE id = ?').run(secretHash, clientRowId);
// Revoke all existing tokens for this client so old sessions are invalidated
db.prepare("UPDATE oauth_tokens SET revoked_at = datetime('now') WHERE client_id = ? AND revoked_at IS NULL").run(row.client_id);
// Terminate active MCP sessions for this (user, client) pair
revokeUserSessionsForClient(userId, row.client_id);
writeAudit({ userId, action: 'oauth.client.rotate_secret', details: { client_id: row.client_id }, ip });
return { client_secret: rawSecret };
}
export function deleteOAuthClient(
userId: number,
clientRowId: string,
ip?: string | null,
): { error?: string; status?: number; success?: boolean } {
const row = db.prepare('SELECT id, client_id FROM oauth_clients WHERE id = ? AND user_id = ?').get(clientRowId, userId) as OAuthClientRow | undefined;
if (!row) return { error: 'Client not found', status: 404 };
db.prepare('DELETE FROM oauth_clients WHERE id = ?').run(clientRowId);
writeAudit({ userId, action: 'oauth.client.delete', details: { client_id: row.client_id }, ip });
return { success: true };
}
// ---------------------------------------------------------------------------
// Auth code (in-memory, 2-minute TTL)
// ---------------------------------------------------------------------------
export function createAuthCode(params: {
clientId: string;
userId: number;
redirectUri: string;
scopes: string[];
resource: string | null;
codeChallenge: string;
codeChallengeMethod: 'S256';
}): string | null {
if (pendingCodes.size >= MAX_PENDING_CODES) return null;
const rawCode = randomBytes(32).toString('hex');
pendingCodes.set(rawCode, { ...params, expiresAt: Date.now() + AUTH_CODE_TTL_MS });
return rawCode;
}
export function consumeAuthCode(code: string): PendingCode | null {
const entry = pendingCodes.get(code);
if (!entry) return null;
pendingCodes.delete(code);
if (Date.now() > entry.expiresAt) return null;
return entry;
}
// ---------------------------------------------------------------------------
// Consent management
// ---------------------------------------------------------------------------
export function getConsent(clientId: string, userId: number): string[] | null {
const row = db.prepare(
'SELECT scopes FROM oauth_consents WHERE client_id = ? AND user_id = ?'
).get(clientId, userId) as { scopes: string } | undefined;
return row ? JSON.parse(row.scopes) : null;
}
export function saveConsent(clientId: string, userId: number, scopes: string[], ip?: string | null): void {
// Union existing consent with newly approved scopes (M5: never narrow stored consent)
const existing = getConsent(clientId, userId) ?? [];
const merged = Array.from(new Set([...existing, ...scopes]));
db.prepare(
'INSERT OR REPLACE INTO oauth_consents (client_id, user_id, scopes, updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)'
).run(clientId, userId, JSON.stringify(merged));
writeAudit({ userId, action: 'oauth.consent.grant', details: { client_id: clientId, scopes: merged }, ip });
}
export function isConsentSufficient(existingScopes: string[], requestedScopes: string[]): boolean {
return requestedScopes.every(s => existingScopes.includes(s));
}
// ---------------------------------------------------------------------------
// Token issuance
// ---------------------------------------------------------------------------
export function issueTokens(
clientId: string,
userId: number,
scopes: string[],
parentTokenId: number | null = null,
audience: string | null = null,
): {
access_token: string;
refresh_token: string;
token_type: 'Bearer';
expires_in: number;
scope: string;
} {
const rawAccess = generateAccessToken();
const rawRefresh = generateRefreshToken();
const accessHash = hashToken(rawAccess);
const refreshHash = hashToken(rawRefresh);
const now = new Date();
const accessExpiry = new Date(now.getTime() + ACCESS_TOKEN_TTL_S * 1000);
const refreshExpiry = new Date(now.getTime() + REFRESH_TOKEN_TTL_MS);
db.prepare(`
INSERT INTO oauth_tokens
(client_id, user_id, access_token_hash, refresh_token_hash, scopes, audience, access_token_expires_at, refresh_token_expires_at, parent_token_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(clientId, userId, accessHash, refreshHash, JSON.stringify(scopes), audience, accessExpiry.toISOString(), refreshExpiry.toISOString(), parentTokenId);
return {
access_token: rawAccess,
refresh_token: rawRefresh,
token_type: 'Bearer',
expires_in: ACCESS_TOKEN_TTL_S,
scope: scopes.join(' '),
};
}
// Issues an access token only — no refresh token (RFC 6749 §4.4.3).
// Used exclusively for the client_credentials grant. A random opaque hash is
// stored in refresh_token_hash to satisfy the NOT NULL/UNIQUE constraint; it
// can never be presented as a valid refresh token (same precedent as public
// client secret hashes stored in client_secret_hash).
export function issueClientCredentialsToken(
clientId: string,
userId: number,
scopes: string[],
audience: string,
): {
access_token: string;
token_type: 'Bearer';
expires_in: number;
scope: string;
} {
const rawAccess = generateAccessToken();
const accessHash = hashToken(rawAccess);
const placeholderHash = randomBytes(32).toString('hex');
const now = new Date();
const accessExpiry = new Date(now.getTime() + ACCESS_TOKEN_TTL_S * 1000);
db.prepare(`
INSERT INTO oauth_tokens
(client_id, user_id, access_token_hash, refresh_token_hash, scopes, audience, access_token_expires_at, refresh_token_expires_at, parent_token_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(clientId, userId, accessHash, placeholderHash, JSON.stringify(scopes), audience, accessExpiry.toISOString(), now.toISOString(), null);
return {
access_token: rawAccess,
token_type: 'Bearer',
expires_in: ACCESS_TOKEN_TTL_S,
scope: scopes.join(' '),
};
}
// ---------------------------------------------------------------------------
// Token verification (used by MCP handler on every request)
// ---------------------------------------------------------------------------
export interface OAuthTokenInfo {
user: User;
scopes: string[];
clientId: string;
audience: string | null;
}
export function getUserByAccessToken(rawToken: string): OAuthTokenInfo | null {
const hash = hashToken(rawToken);
const row = db.prepare(`
SELECT ot.scopes, ot.audience, ot.revoked_at, ot.access_token_expires_at,
ot.user_id, ot.client_id, u.username, u.email, u.role
FROM oauth_tokens ot
JOIN users u ON ot.user_id = u.id
WHERE ot.access_token_hash = ?
`).get(hash) as (OAuthTokenRow & { username: string; email: string; role: string }) | undefined;
if (!row) return null;
if (row.revoked_at) return null;
if (new Date(row.access_token_expires_at) < new Date()) return null;
return {
user: { id: row.user_id, username: row.username, email: row.email, role: row.role as 'admin' | 'user' },
scopes: JSON.parse(row.scopes),
clientId: row.client_id,
audience: row.audience ?? null,
};
}
// ---------------------------------------------------------------------------
// Token refresh (rotation + replay detection)
// ---------------------------------------------------------------------------
/** Walk parent_token_id upward to find the root token id of this rotation chain. */
function findChainRoot(tokenId: number): number {
let current = tokenId;
for (let i = 0; i < 100; i++) {
const row = db.prepare('SELECT id, parent_token_id FROM oauth_tokens WHERE id = ?').get(current) as { id: number; parent_token_id: number | null } | undefined;
if (!row || row.parent_token_id === null) return current;
current = row.parent_token_id;
}
return current;
}
/** Revoke all tokens in the rotation chain rooted at rootId. Returns affected ids. */
function revokeChain(rootId: number): number[] {
const rows = db.prepare(`
WITH RECURSIVE chain(id) AS (
SELECT id FROM oauth_tokens WHERE id = ?
UNION ALL
SELECT t.id FROM oauth_tokens t JOIN chain c ON t.parent_token_id = c.id
)
SELECT id FROM chain
`).all(rootId) as { id: number }[];
const ids = rows.map(r => r.id);
if (ids.length > 0) {
db.prepare(
`UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id IN (${ids.map(() => '?').join(',')}) AND revoked_at IS NULL`
).run(...ids);
}
return ids;
}
export function refreshTokens(
rawRefreshToken: string,
clientId: string,
clientSecret: string | undefined,
ip?: string | null,
): { error?: string; status?: number; tokens?: ReturnType<typeof issueTokens> } {
const client = db.prepare('SELECT client_id, client_secret_hash, is_public FROM oauth_clients WHERE client_id = ?').get(clientId) as OAuthClientRow | undefined;
if (!client) return { error: 'invalid_client', status: 401 };
if (!client.is_public) {
if (!clientSecret || !timingSafeEqualHex(hashToken(clientSecret), client.client_secret_hash)) {
return { error: 'invalid_client', status: 401 };
}
}
const hash = hashToken(rawRefreshToken);
const row = db.prepare(`
SELECT id, client_id, user_id, scopes, audience, refresh_token_expires_at, revoked_at, parent_token_id
FROM oauth_tokens WHERE refresh_token_hash = ?
`).get(hash) as OAuthTokenRow | undefined;
if (!row) return { error: 'invalid_grant', status: 400 };
if (row.client_id !== clientId) return { error: 'invalid_grant', status: 400 };
// ---- Replay detection (C3) ----
if (row.revoked_at) {
// A revoked refresh token was replayed — assume token theft. Cascade-revoke the chain.
const rootId = findChainRoot(row.id);
revokeChain(rootId);
revokeUserSessionsForClient(row.user_id, clientId);
writeAudit({
userId: row.user_id,
action: 'oauth.token.replay_detected',
details: { client_id: clientId },
ip,
});
logWarn(`[OAuth] Refresh token replay detected for user=${row.user_id} client=${clientId} ip=${ip ?? '-'}`);
return { error: 'invalid_grant', status: 400 };
}
if (new Date(row.refresh_token_expires_at) < new Date()) return { error: 'invalid_grant', status: 400 };
// Revoke old pair immediately (rotation) and issue new pair linked to old row.
// Do NOT revoke active MCP sessions here: a legitimate refresh isn't a security
// event (that's handled above, in the replay-detection branch), and mcpHandler
// already re-validates session.userId/clientId against the new token on every
// request. Killing the session on every routine hourly refresh broke long-lived
// MCP connections (#1475).
db.prepare('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?').run(row.id);
const tokens = issueTokens(clientId, row.user_id, JSON.parse(row.scopes), row.id, row.audience ?? null);
writeAudit({ userId: row.user_id, action: 'oauth.token.refresh', details: { client_id: clientId }, ip });
return { tokens };
}
// ---------------------------------------------------------------------------
// Token revocation
// ---------------------------------------------------------------------------
export function revokeToken(rawToken: string, clientId: string, userId?: number, ip?: string | null): void {
const hash = hashToken(rawToken);
// Get the user_id for the token so we can revoke its MCP sessions
const row = db.prepare(
'SELECT user_id FROM oauth_tokens WHERE (access_token_hash = ? OR refresh_token_hash = ?) AND client_id = ?'
).get(hash, hash, clientId) as { user_id: number } | undefined;
db.prepare(`
UPDATE oauth_tokens
SET revoked_at = CURRENT_TIMESTAMP
WHERE (access_token_hash = ? OR refresh_token_hash = ?) AND client_id = ?
`).run(hash, hash, clientId);
const affectedUserId = row?.user_id ?? userId;
if (affectedUserId) {
revokeUserSessionsForClient(affectedUserId, clientId);
writeAudit({ userId: affectedUserId, action: 'oauth.token.revoke', details: { client_id: clientId, method: 'token' }, ip });
}
}
// ---------------------------------------------------------------------------
// Active session listing (for user settings page)
// ---------------------------------------------------------------------------
export function listOAuthSessions(userId: number): Record<string, unknown>[] {
const rows = db.prepare(`
SELECT ot.id, ot.client_id, oc.name AS client_name, ot.scopes,
ot.access_token_expires_at, ot.refresh_token_expires_at, ot.created_at
FROM oauth_tokens ot
JOIN oauth_clients oc ON ot.client_id = oc.client_id
WHERE ot.user_id = ?
AND ot.revoked_at IS NULL
AND ot.refresh_token_expires_at > CURRENT_TIMESTAMP
ORDER BY ot.created_at DESC
`).all(userId) as Record<string, unknown>[];
return rows.map(r => ({ ...r, scopes: JSON.parse(r.scopes as string) }));
}
export function revokeSession(
userId: number,
sessionId: number,
ip?: string | null,
): { error?: string; status?: number; success?: boolean } {
const row = db.prepare('SELECT id, client_id FROM oauth_tokens WHERE id = ? AND user_id = ?').get(sessionId, userId) as { id: number; client_id: string } | undefined;
if (!row) return { error: 'Session not found', status: 404 };
db.prepare('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?').run(sessionId);
revokeUserSessionsForClient(userId, row.client_id);
writeAudit({ userId, action: 'oauth.token.revoke', details: { client_id: row.client_id, method: 'session' }, ip });
return { success: true };
}
// ---------------------------------------------------------------------------
// Authorize request validation (option A: called by SPA via GET /api/oauth/authorize/validate)
// ---------------------------------------------------------------------------
export interface AuthorizeParams {
response_type: string;
client_id: string;
redirect_uri: string;
scope: string;
state?: string;
code_challenge: string;
code_challenge_method: string;
resource?: string;
}
export interface ValidateAuthorizeResult {
valid: boolean;
error?: string;
error_description?: string;
client?: { name: string; allowed_scopes: string[] };
scopes?: string[];
resource?: string | null;
/** true when user is logged in but consent UI must be shown */
consentRequired?: boolean;
/** true when the request is valid but user is not authenticated */
loginRequired?: boolean;
/** true when the client was registered via machine DCR — user may adjust scopes on the consent screen */
scopeSelectable?: boolean;
}
export function validateAuthorizeRequest(
params: AuthorizeParams,
userId: number | null,
): ValidateAuthorizeResult {
if (!isAddonEnabled(ADDON_IDS.MCP)) {
return { valid: false, error: 'mcp_disabled', error_description: 'MCP is not enabled on this server' };
}
if (params.response_type !== 'code') {
return { valid: false, error: 'unsupported_response_type', error_description: 'Only response_type=code is supported' };
}
if (!params.code_challenge || params.code_challenge_method !== 'S256') {
return { valid: false, error: 'invalid_request', error_description: 'PKCE with code_challenge_method=S256 is required (OAuth 2.1)' };
}
// H1: Enforce code_challenge format (RFC 7636 §4.2)
if (!CODE_CHALLENGE_RE.test(params.code_challenge)) {
return { valid: false, error: 'invalid_request', error_description: 'code_challenge must be 43 base64url characters (S256)' };
}
if (!params.client_id) {
return { valid: false, error: 'invalid_request', error_description: 'client_id is required' };
}
const client = db.prepare('SELECT * FROM oauth_clients WHERE client_id = ?').get(params.client_id) as OAuthClientRow | undefined;
if (!client) {
return { valid: false, error: 'invalid_client', error_description: 'Unknown client_id' };
}
const allowedUris: string[] = JSON.parse(client.redirect_uris);
if (!params.redirect_uri || !allowedUris.includes(params.redirect_uri)) {
return { valid: false, error: 'invalid_redirect_uri', error_description: 'redirect_uri does not match any registered URI' };
}
// RFC 8707 resource indicator: if provided, must identify the TREK
// MCP endpoint exactly. If the client didn't supply `resource`, we
// bind the token to the MCP endpoint by default — previously this
// left `audience = null`, and the audience-bind check on MCP requests
// then treated a null audience as "valid for any resource".
const mcpResource = `${getMcpSafeUrl().replace(/\/+$/, '')}/mcp`;
const resource = params.resource
? params.resource.replace(/\/+$/, '')
: mcpResource;
if (resource !== mcpResource) {
return { valid: false, error: 'invalid_target', error_description: 'Requested resource must be the TREK MCP endpoint' };
}
const requestedScopes = (params.scope || '').split(' ').filter(Boolean);
if (requestedScopes.length === 0) {
return { valid: false, error: 'invalid_scope', error_description: 'At least one scope is required' };
}
const allowedScopes: string[] = JSON.parse(client.allowed_scopes);
// Narrow to the intersection: drop scopes the client isn't permitted for rather
// than rejecting the whole request (per OAuth 2.0 §3.3 scope narrowing).
const grantedScopes = requestedScopes.filter(s => allowedScopes.includes(s));
if (grantedScopes.length === 0) {
return { valid: false, error: 'invalid_scope', error_description: 'None of the requested scopes are permitted for this client' };
}
if (userId === null) {
// H3: return only the minimum required fields — do NOT expose scopes, client.name, or
// allowed_scopes to unauthenticated callers to prevent client enumeration.
return { valid: true, loginRequired: true };
}
const existingConsent = getConsent(params.client_id, userId);
const consentRequired = !existingConsent || !isConsentSufficient(existingConsent, grantedScopes);
return {
valid: true,
client: { name: client.name, allowed_scopes: allowedScopes },
scopes: grantedScopes,
resource: resource ?? mcpResource,
consentRequired,
scopeSelectable: client.created_via === 'dcr',
};
}
// ---------------------------------------------------------------------------
// PKCE verification
// ---------------------------------------------------------------------------
export function verifyPKCE(codeVerifier: string, codeChallenge: string): boolean {
// H1: validate code_verifier format before hashing
if (!CODE_VERIFIER_RE.test(codeVerifier)) return false;
const expected = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
// Constant-time compare (both are base64url strings of equal length for S256)
if (expected.length !== codeChallenge.length) return false;
try {
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(codeChallenge));
} catch { return false; }
}
// ---------------------------------------------------------------------------
// Client authentication (for token endpoint)
// ---------------------------------------------------------------------------
export function authenticateClient(clientId: string, clientSecret: string | undefined): OAuthClientRow | null {
const client = db.prepare('SELECT * FROM oauth_clients WHERE client_id = ?').get(clientId) as OAuthClientRow | undefined;
if (!client) return null;
if (client.is_public) {
// Public clients are identified by client_id alone — PKCE provides the security guarantee.
return client;
}
// H4: constant-time comparison to prevent timing side-channel
if (!clientSecret) return null;
if (!timingSafeEqualHex(hashToken(clientSecret), client.client_secret_hash)) return null;
return client;
}
-65
View File
@@ -1,65 +0,0 @@
import fs from 'node:fs';
import { db } from '../db/database';
import { pluginsDataRoot } from '../nest/plugins/paths';
import { removeUserFromBudgetItems } from '../nest/budget/budget.bridge';
/**
* Erase a user's PLUGIN-held data on account deletion. Two parts:
* 1. Host-side per-user plugin tables (encrypted config values, OAuth access/refresh
* tokens, in-flight OAuth state) — deleted directly; these live in trek.db, not in
* a plugin's own db, so nothing else ever removes them.
* 2. A durable erasure row per plugin that holds `hook:user-data`, so its OWN db is
* purged of the user (drained to the plugin when it is next active).
*
* Runs in the core deletion path (NOT via the plugin runtime), so it works even when
* TREK_PLUGINS_ENABLED=false or before the runtime has booted — otherwise a deletion in
* those windows would leave the user's plugin data behind forever. Best-effort per table
* so a slimmed-down schema (some tests) can't fail the user deletion itself.
*/
export function erasePluginUserData(userId: number): void {
for (const table of ['plugin_user_config', 'plugin_oauth_tokens', 'plugin_oauth_state']) {
try { db.prepare(`DELETE FROM ${table} WHERE user_id = ?`).run(userId); } catch { /* table absent (slim schema) */ }
}
try {
const rows = db.prepare('SELECT id, permissions FROM plugins').all() as Array<{ id: string; permissions: string | null }>;
const installed = new Set(rows.map((r) => r.id));
const insert = db.prepare('INSERT OR IGNORE INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES (?, ?)');
for (const r of rows) {
let perms: unknown;
try { perms = JSON.parse(r.permissions ?? '[]'); } catch { perms = []; }
if (Array.isArray(perms) && perms.includes('hook:user-data')) insert.run(r.id, userId);
}
// Also enqueue for plugins UNINSTALLED with their data retained (deleteData=false):
// their data dir still holds the user's rows and a same-id reinstall would re-adopt
// them. No permissions record survives uninstall, so we can't check hook:user-data —
// enqueue for every orphan data dir; the row sits inert (no FK) and drains only if
// that id is reinstalled + active (erasure delivery is a duty, not grant-gated).
try {
for (const entry of fs.readdirSync(pluginsDataRoot(), { withFileTypes: true })) {
if (entry.isDirectory() && !installed.has(entry.name)) insert.run(entry.name, userId);
}
} catch { /* no plugin data root yet */ }
} catch { /* plugins / queue table absent (slim schema) */ }
}
function cleanupUserReferences(userId: number): void {
db.prepare('UPDATE trip_members SET invited_by = NULL WHERE invited_by = ?').run(userId);
db.prepare('UPDATE budget_items SET paid_by_user_id = NULL WHERE paid_by_user_id = ?').run(userId);
removeUserFromBudgetItems(userId);
db.prepare('DELETE FROM share_tokens WHERE created_by = ?').run(userId);
db.prepare('DELETE FROM journey_share_tokens WHERE created_by = ?').run(userId);
// Owned journeys cascade-delete their entries/contributors/share_tokens/photos via journey_id FKs
db.prepare('DELETE FROM journeys WHERE user_id = ?').run(userId);
// Entries authored on other users' journeys (not covered by the cascade above)
db.prepare('DELETE FROM journey_entries WHERE author_id = ?').run(userId);
db.prepare('DELETE FROM journey_contributors WHERE user_id = ?').run(userId);
}
export function deleteUserCompletely(userId: number): void {
const tx = db.transaction((id: number) => {
cleanupUserReferences(id);
erasePluginUserData(id);
db.prepare('DELETE FROM users WHERE id = ?').run(id);
});
tx(userId);
}
-86
View File
@@ -1,86 +0,0 @@
import { readEnv } from '../app-config';
import { db } from '../db/database';
import { getAppUrl } from '../app-config';
/**
* Resolves the WebAuthn Relying Party ID + allowed origins for this deployment.
*
* SECURITY: the RP ID and the allowed origins are derived ONLY from server-side
* configuration — the `webauthn_rp_id` / `webauthn_origins` admin settings (or
* the matching env vars), falling back to APP_URL. They are NEVER taken from the
* request `Host` / `X-Forwarded-Host` header: a forged forwarded host would
* otherwise let an attacker bind credentials to a domain they control, or brick
* every enrolled user. This mirrors how OIDC derives its redirect URI from
* APP_URL (oidc.controller.ts) rather than from request input.
*
* Returns null when no usable RP ID can be resolved (bare IP host, or nothing
* configured) — the feature then reports itself as "not configured" and stays
* disabled so nobody can enrol a credential bound to the wrong origin.
*/
function getSetting(key: string): string | null {
const raw = (db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value;
const trimmed = raw?.trim();
return trimmed ? trimmed : null;
}
function hostOf(url: string): string | null {
try {
return new URL(url).hostname || null;
} catch {
return null;
}
}
/** WebAuthn RP IDs must be registrable domains — never bare IP literals. */
function isIpHost(host: string): boolean {
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true; // IPv4
if (host.includes(':')) return true; // IPv6 (hostname keeps the colons)
return false;
}
export interface WebauthnConfig {
rpID: string;
rpName: string;
/** Exact allowed origins (scheme + host + port). One in prod; localhost dev adds the Vite/API ports. */
origins: string[];
}
export function resolveWebauthnConfig(): WebauthnConfig | null {
// 1. Explicit operator config always wins.
const explicitRpId = (readEnv().webauthn.rpId || getSetting('webauthn_rp_id'))?.trim() || null;
const explicitOrigins = (readEnv().webauthn.origins || getSetting('webauthn_origins') || '')
.split(',')
.map((o) => o.trim().replace(/\/+$/, ''))
.filter(Boolean);
const appUrl = getAppUrl();
const appHost = hostOf(appUrl);
// 2. Derive the RP ID from APP_URL when not explicitly set.
let rpID = explicitRpId;
if (!rpID && appHost && !isIpHost(appHost)) {
rpID = appHost; // a real domain, or "localhost"
}
if (!rpID) return null; // bare IP / unresolved → WebAuthn cannot be used here
// 3. Resolve the allowed origins. Explicit list wins verbatim (operator's
// responsibility). Otherwise derive a SINGLE origin from APP_URL — we never
// silently union dev localhost origins into a production allow-list.
let origins = explicitOrigins;
if (origins.length === 0) {
if (appHost) origins = [appUrl.replace(/\/+$/, '')];
if (rpID === 'localhost') {
// Dev: the browser origin is the Vite dev server (:5173), not the API port.
origins = Array.from(new Set([...origins, 'http://localhost:5173', 'http://localhost:3001']));
}
}
if (origins.length === 0) return null;
return { rpID, rpName: 'TREK', origins };
}
/** True when a usable RP ID resolves for this deployment (exposed as a pure boolean on app-config). */
export function isPasskeyConfigured(): boolean {
return resolveWebauthnConfig() !== null;
}
-258
View File
@@ -1,258 +0,0 @@
import { existsSync, promises as fs } from 'fs';
import path from 'path';
import { readEnv } from '../app-config';
/**
* In-app Help/Wiki content, sourced from the `wiki/**` directory that ships with
* the app — the same content that CI mirrors to the public GitHub wiki. Reading
* from disk keeps the help pages pinned to the running version (a v1.2 install
* shows v1.2 docs, not whatever `main` says) and works offline.
*
* If that directory can't be resolved — an unusual layout, an image built without
* it — we fall back to fetching from the GitHub wiki over the network and caching
* hourly, so help degrades instead of disappearing. The client never talks to
* GitHub directly either way; images are proxied through /api/help/asset.
*/
const REPO = 'liketrek/TREK';
const RAW_BASE = `https://raw.githubusercontent.com/${REPO}/main/wiki`;
const TTL_MS = 60 * 60 * 1000; // remote fallback only: refresh from GitHub at most hourly
const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
/**
* `server/{src,dist}/services` both sit three levels under the repo root, so this
* one anchor resolves in dev, a built source install, vitest, and Docker (where
* the Dockerfile copies `wiki/` to /app/wiki). `process.cwd()` would not — Docker
* runs the server from /app/server.
*/
const WIKI_DIR = readEnv().paths.wikiDir ?? path.join(__dirname, '..', '..', '..', 'wiki');
/**
* Probe for the sidebar rather than the bare directory: an empty or half-copied
* `wiki/` should fall back to GitHub, not serve an empty table of contents.
*/
const useLocalWiki = existsSync(path.join(WIKI_DIR, '_Sidebar.md'));
if (!useLocalWiki) {
console.warn(
`[help] wiki not found at ${WIKI_DIR} — falling back to the GitHub wiki (help may not match this version)`,
);
}
export class WikiNotFound extends Error {
status = 404;
}
interface TextEntry {
data: string;
ts: number;
}
const textCache = new Map<string, TextEntry>();
const assetCache = new Map<string, { buf: Buffer; type: string; ts: number }>();
const fresh = (ts: number): boolean => Date.now() - ts < TTL_MS;
/** Resolve a path inside the wiki dir, refusing anything that escapes it. */
function resolveInWiki(rel: string): string {
const root = path.resolve(WIKI_DIR);
const full = path.resolve(root, rel);
if (full !== root && !full.startsWith(root + path.sep)) throw new WikiNotFound(rel);
return full;
}
/** Fetch a wiki text file: local disk, or GitHub with cache → stale-cache fallback. */
async function fetchText(file: string): Promise<string> {
if (useLocalWiki) {
try {
return await fs.readFile(resolveInWiki(file), 'utf8');
} catch (err) {
if (err instanceof WikiNotFound) throw err;
if ((err as NodeJS.ErrnoException).code === 'ENOENT') throw new WikiNotFound(file);
throw err;
}
}
const cached = textCache.get(file);
if (cached && fresh(cached.ts)) return cached.data;
try {
const res = await fetch(`${RAW_BASE}/${encodeURIComponent(file)}`, {
headers: { 'User-Agent': 'TREK-help', Accept: 'text/plain' },
});
if (res.ok) {
const text = await res.text();
textCache.set(file, { data: text, ts: Date.now() });
return text;
}
if (res.status === 404) throw new WikiNotFound(file);
} catch (err) {
if (err instanceof WikiNotFound) throw err;
// network/parse error — fall through to stale cache
}
if (cached) return cached.data; // serve stale rather than fail
throw new WikiNotFound(file);
}
export interface WikiNavItem {
title: string;
slug: string;
}
export interface WikiNavSection {
title: string;
pages: WikiNavItem[];
}
/** Parse the wiki `_Sidebar.md` into ordered sections of `[[Title|Slug]]` links. */
function parseSidebar(md: string): WikiNavSection[] {
const sections: WikiNavSection[] = [];
let current: WikiNavSection | null = null;
for (const raw of md.split('\n')) {
const heading = raw.match(/^#{1,4}\s+(.+?)\s*$/);
if (heading) {
current = { title: heading[1].replace(/[*_`]/g, '').trim(), pages: [] };
sections.push(current);
continue;
}
const link = raw.match(/^\s*[-*]\s*\[\[([^\]]+)\]\]/);
if (link) {
if (!current) {
current = { title: '', pages: [] };
sections.push(current);
}
const inner = link[1];
const [title, slugRaw] = inner.includes('|') ? inner.split('|') : [inner, inner];
const slug = slugRaw.trim().replace(/\s+/g, '-');
if (SLUG_RE.test(slug)) current.pages.push({ title: title.trim(), slug });
}
}
return sections.filter((s) => s.pages.length > 0);
}
/** Rewrite GitHub-wiki `[[..]]` links to /help routes and proxy relative images. */
function processMarkdown(md: string): string {
// Strip HTML comments (e.g. `<!-- TODO: screenshot … -->` placeholders) — the
// markdown renderer would otherwise surface them as raw text.
let out = md.replace(/<!--[\s\S]*?-->/g, '');
out = out.replace(/\[\[([^\]]+)\]\]/g, (_m, inner: string) => {
const [titleRaw, slugRaw] = inner.includes('|') ? inner.split('|') : [inner, inner];
const slug = slugRaw.trim().replace(/\s+/g, '-');
// `[[Plugin Development#talking-to-plugins|Plugin-Development]]` must not
// render its anchor as visible link text.
const [title, anchor] = titleRaw.includes('#') ? titleRaw.split('#') : [titleRaw, ''];
const hash = anchor ? `#${anchor.trim()}` : '';
return `[${title.trim()}](/help/${slug}${hash})`;
});
out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)([^)]*)\)/g, (m, alt: string, url: string) => {
if (/^https?:\/\//i.test(url) || url.startsWith('/api/help/asset/')) return m;
const clean = url.replace(/^\.?\//, '').replace(/^wiki\//, '');
return `![${alt}](/api/help/asset/${clean})`;
});
// Bare relative links — `[Currencies](Currencies)`, the native GitHub-wiki
// spelling and by far the most common in these pages (455 of them across 81
// files, against 114 `[[..]]` links). GitHub resolves them against the wiki
// root; in-app they used to fall through to HelpPage's external-link branch
// and open a dead tab. Rewriting them here fixes every page at once and keeps
// the source GitHub-compatible, so contributors can keep writing either form.
//
// Runs last: `[[..]]` links and images have already become absolute paths by
// this point, so the leading-slash guard skips them.
out = outsideCode(out, (segment) =>
segment.replace(/(^|[^!])\[([^\]]+)\]\(([^)\s]+)\)/g, (m, prefix: string, text: string, url: string) => {
if (/^(https?:|mailto:|tel:|#|\/)/i.test(url)) return m;
const [pageRaw, anchor] = url.includes('#') ? url.split('#') : [url, ''];
const page = pageRaw.replace(/^\.?\//, '').replace(/\.md$/i, '').trim();
if (!page || !SLUG_RE.test(page)) return m;
return `${prefix}[${text}](/help/${page}${anchor ? `#${anchor}` : ''})`;
}),
);
return out;
}
/**
* Apply `fn` to the parts of the markdown that are NOT code, leaving fenced
* blocks and inline spans untouched.
*
* Without this the link rewriter corrupts code samples: Plugin-Development.md
* documents `actions[key](ctx)`, which reads as a markdown link and would be
* rewritten to `actions[key](/help/ctx)` inside what is supposed to be a
* verbatim snippet.
*/
function outsideCode(md: string, fn: (segment: string) => string): string {
// Alternation order matters: fenced blocks first, so a ``` fence containing
// backticks is consumed whole rather than being split by the inline rule.
const CODE = /(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/g;
const parts = md.split(CODE);
// split() with a capturing group yields [text, code, text, code, …].
return parts.map((part, i) => (i % 2 === 1 ? part : fn(part))).join('');
}
function extractTitle(md: string, fallback: string): string {
const h1 = md.match(/^#\s+(.+?)\s*$/m);
return h1 ? h1[1].replace(/[*_`]/g, '').trim() : fallback.replace(/-/g, ' ');
}
export interface WikiPage {
slug: string;
title: string;
markdown: string;
}
/** True when help is served from the bundled wiki rather than fetched from GitHub. */
export const isLocalWiki = (): boolean => useLocalWiki;
export async function getWikiIndex(): Promise<{ sections: WikiNavSection[] }> {
const md = await fetchText('_Sidebar.md');
return { sections: parseSidebar(md) };
}
export async function getWikiPage(slug: string): Promise<WikiPage> {
if (!SLUG_RE.test(slug)) throw new WikiNotFound(slug);
const md = await fetchText(`${slug}.md`);
return { slug, title: extractTitle(md, slug), markdown: processMarkdown(md) };
}
const ASSET_TYPES: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
};
/** Read a wiki image from disk, or proxy it from GitHub so the browser never calls it directly. */
export async function getWikiAsset(assetPath: string): Promise<{ buf: Buffer; type: string }> {
// Defend against traversal; allow nested image folders.
if (assetPath.includes('..') || !/^[A-Za-z0-9/._-]+$/.test(assetPath)) throw new WikiNotFound(assetPath);
const ext = path.extname(assetPath).toLowerCase();
const type = ASSET_TYPES[ext];
if (!type) throw new WikiNotFound(assetPath);
if (useLocalWiki) {
try {
// resolveInWiki re-checks containment: the regex above is a filter, this is the boundary.
const buf = await fs.readFile(resolveInWiki(assetPath));
return { buf, type };
} catch (err) {
if (err instanceof WikiNotFound) throw err;
if ((err as NodeJS.ErrnoException).code === 'ENOENT') throw new WikiNotFound(assetPath);
throw err;
}
}
const cached = assetCache.get(assetPath);
if (cached && fresh(cached.ts)) return { buf: cached.buf, type: cached.type };
try {
const res = await fetch(`${RAW_BASE}/${assetPath.split('/').map(encodeURIComponent).join('/')}`, {
headers: { 'User-Agent': 'TREK-help' },
});
if (res.ok) {
const buf = Buffer.from(await res.arrayBuffer());
assetCache.set(assetPath, { buf, type, ts: Date.now() });
return { buf, type };
}
} catch {
/* fall through */
}
if (cached) return { buf: cached.buf, type: cached.type };
throw new WikiNotFound(assetPath);
}