import { createHash, timingSafeEqual } from "node:crypto"; import { HttpError } from "./errors"; import type { PlatformCredential } from "./types"; export type Grant = { platform: string }; // Supported platforms are trusted to authorize their publishers. Credentials // identify a platform, not a publisher, repository, or list of podcast shows. export class PlatformAuth { private readonly credentials: Array<{ hash: Buffer; grant: Grant }>; constructor(credentials: PlatformCredential[]) { if (!credentials.length) throw new Error("Configure at least one supported platform credential"); const seen = new Set(); this.credentials = credentials.map((credential) => { if (!credential || typeof credential.platform !== "string" || !/^[a-z0-9][a-z0-9._-]{0,252}$/i.test(credential.platform) || typeof credential.token !== "string" || !/^[^\s]{32,1024}$/.test(credential.token)) { throw new Error("Each credential needs a platform identifier and a token of 32–1024 non-whitespace characters"); } const hash = createHash("sha256").update(credential.token).digest(); const key = hash.toString("hex"); if (seen.has(key)) throw new Error("Duplicate platform credential"); seen.add(key); return { hash, grant: { platform: credential.platform.toLowerCase() } }; }); } authenticate(request: Request): Grant { const header = request.headers.get("authorization") ?? ""; const match = /^Bearer ([^\s]{32,1024})$/.exec(header); const hash = createHash("sha256").update(match?.[1] ?? "").digest(); let grant: Grant | undefined; for (const entry of this.credentials) { if (timingSafeEqual(entry.hash, hash) && match) grant = entry.grant; } if (!grant) throw new HttpError(401, "unauthorized", "Supported platform credential required"); return grant; } } export class RateLimiter { private readonly windows = new Map(); constructor(private readonly limit = 60, private readonly windowMs = 60_000) {} check(key: string, now = Date.now()): void { const existing = this.windows.get(key); if (!existing || existing.expires <= now) { // Bound cardinality even when keys are supplied by untrusted clients. for (const [key, value] of this.windows) if (value.expires <= now) this.windows.delete(key); if (this.windows.size >= 10_000) throw new HttpError(429, "rate_limited", "Too many requests"); this.windows.set(key, { count: 1, expires: now + this.windowMs }); } else if (++existing.count > this.limit) { throw new HttpError(429, "rate_limited", "Too many requests"); } } }