diff --git a/src/entrypoint.ts b/src/entrypoint.ts index 077d99ef5..4b0f71eb7 100644 --- a/src/entrypoint.ts +++ b/src/entrypoint.ts @@ -8,6 +8,11 @@ import worker, { } from "./worker"; export { NoemaOidcReplayGuard, NoemaRateLimiter }; +/** + * Runtime configuration accepted by the public request-edge worker. It inherits the + * credential, replay-protection, rate-limit, and workflow-trust settings required by + * the protected worker while keeping this entrypoint's outbound GitHub API checks explicit. + */ export interface Env extends WorkerEnv {} const TRUSTED_GITHUB_API_ORIGIN = "https://api.github.com"; @@ -32,10 +37,22 @@ type ExchangeBodyFailure = { status: 400 | 413 | 415; }; +/** + * Result of bounding an exchange request body at the public request edge. Successful + * results preserve the original Request when no POST body needs bounding, while POST + * requests with bodies carry the rebuilt bounded Request. Failures carry only the reviewed + * reason and HTTP status needed to produce a fail-closed response without exposing body bytes. + */ export type BoundedExchangeRequest = | { ok: true; request: Request } | { ok: false; failure: ExchangeBodyFailure }; +/** + * Validate that a configured GitHub API base is exactly the trusted GitHub Cloud REST + * origin, with no credentials, path, query, or fragment that could redirect secrets. + * @param value Candidate runtime configuration value to validate. + * @returns True only when the value is the exact accepted GitHub API base origin. + */ export function isTrustedGithubApiBase(value: unknown): value is string { if ( typeof value !== "string" @@ -64,6 +81,8 @@ export function isTrustedGithubApiBase(value: unknown): value is string { /** * Accept only a compact, bounded JWT envelope before any decoding or credential use. * Missing and non-Bearer authorization values are delegated to the normal API error path. + * @param value Authorization header value observed at the request edge, or null when absent. + * @returns False only when a Bearer JWT envelope is structurally invalid or exceeds limits. */ export function isBoundedOidcBearer(value: string | null): boolean { if (value === null) return true; @@ -153,6 +172,9 @@ function hasDuplicateTargetRepositoryKey(body: Uint8Array): boolean { * Streaming consumption prevents a chunked request from bypassing Content-Length checks. * The security-relevant top-level `target_repository` member must appear at most once after * JSON escape decoding so downstream parsing cannot silently apply last-key-wins semantics. + * @param request Incoming request whose optional JSON body must be bounded before delegation. + * @returns The original request when it is not a POST or has no body; otherwise a rebuilt + * bounded request, or a typed failure describing the fail-closed response. */ export async function boundExchangeJsonBody(request: Request): Promise { if (request.method !== "POST" || request.body === null) { @@ -453,6 +475,11 @@ function recordExchangeBodyFailure(request: Request, failure: ExchangeBodyFailur } } +/** + * Public Cloudflare Worker entrypoint that enforces request-body, OIDC-envelope, and + * GitHub egress policy before delegating to the credential-exchange worker. It fails closed + * on rejected security boundaries; requests outside /exchange retain the underlying contract. + */ export default { async fetch(request: Request, env: Env): Promise { const url = new URL(request.url); diff --git a/src/index.ts b/src/index.ts index 09f58a5cf..b9a9b1e51 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,11 @@ import { type OidcReplayProtectionEnv, } from "./oidc-replay"; +/** + * Runtime configuration consumed by Noema's base credential-exchange worker. These + * values define the trusted GitHub Actions OIDC issuer/audience/workflow boundary, + * GitHub App identity, exact API origin, replay protection, and bounded cache/rate limits. + */ export interface Env extends OidcReplayProtectionEnv { ALLOWED_ISSUER: string; ALLOWED_AUDIENCE: string; @@ -608,6 +613,11 @@ async function handleExchange(request: Request, env: Env, traceId: string): Prom /* v8 ignore stop */ } +/** + * Base public Worker entrypoint for Noema health and credential exchange. It validates + * methods, OIDC/GitHub App exchange policy, local rate limits, structured errors, and + * bounded operational headers/log metadata while returning credentials only on success. + */ export default { async fetch(request: Request, env: Env): Promise { const traceId = traceIdFromRequest(request); diff --git a/src/oidc-replay.ts b/src/oidc-replay.ts index 087e33bb4..01dd47033 100644 --- a/src/oidc-replay.ts +++ b/src/oidc-replay.ts @@ -4,10 +4,18 @@ const MAX_TOKEN_LIFETIME_SECONDS = 3_600; const ALARM_GRACE_MS = 30_000; const trustedJtiPattern = /^[A-Za-z0-9._:-]+$/; +/** + * Supplies the Cloudflare Durable Object namespace that owns replay-claim state. + * The binding is optional at the type boundary so callers can fail closed when deployment wiring is absent. + */ export interface OidcReplayProtectionEnv { NOEMA_OIDC_REPLAY_GUARD?: DurableObjectNamespace; } +/** + * Reports whether a single-use OIDC token claim was accepted and the authoritative expiry attached to that claim. + * A rejected `accepted` value preserves the stored expiry so callers can distinguish replay from infrastructure failure. + */ export type OidcReplayClaimDecision = { accepted: boolean; expires_at_epoch_seconds: number; @@ -22,6 +30,10 @@ type ReplayAlarmDecision = | { action: "delete" } | { action: "reschedule"; expires_at_epoch_seconds: number }; +/** + * Signals a confirmed OIDC replay after an atomic claim finds a still-live prior use. + * The original expiry remains available for bounded diagnostics without disclosing the bearer token itself. + */ export class OidcReplayDetected extends Error { constructor(public readonly expiresAtEpochSeconds: number) { super("GitHub Actions OIDC token has already been used"); @@ -30,6 +42,10 @@ export class OidcReplayDetected extends Error { } } +/** + * Signals that replay protection cannot produce a trustworthy decision and therefore must fail closed. + * This covers missing bindings, malformed responses, invalid expiry windows, and Durable Object failures. + */ export class OidcReplayUnavailable extends Error { constructor(message: string) { super(message); @@ -78,6 +94,12 @@ async function sha256Hex(value: string): Promise { return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); } +/** + * Derives the stable, non-secret Durable Object name used to serialize claims for one OIDC `jti`. + * @param jti Unique JWT identifier supplied by the already-validated OIDC token. + * @returns A SHA-256 hash-derived object name that never embeds the raw token identifier. + * @throws {OidcReplayUnavailable} When the identifier is empty, oversized, or outside the accepted character set. + */ export async function oidcReplayObjectName(jti: string): Promise { if (!validJti(jti)) { throw new OidcReplayUnavailable("OIDC jti claim is missing or malformed"); @@ -95,6 +117,15 @@ function isClaimDecision(value: unknown): value is OidcReplayClaimDecision { ); } +/** + * Atomically claims one validated GitHub Actions OIDC token before privileged credential exchange can continue. + * @param jti Unique token identifier used only to derive the replay-guard object name. + * @param expiresAtEpochSeconds Validated token expiry that bounds how long replay state is retained. + * @param env Environment containing the required replay-protection Durable Object namespace. + * @returns The accepted claim decision with the exact expiry echoed by the replay guard. + * @throws {OidcReplayDetected} When the same live token identifier has already been claimed. + * @throws {OidcReplayUnavailable} When replay authority is missing, malformed, mismatched, or otherwise unavailable. + */ export async function claimOidcTokenUsage( jti: string, expiresAtEpochSeconds: number, @@ -161,9 +192,18 @@ function parseClaimRequest(value: unknown, nowEpochSeconds: number): number | un return expiresAt; } +/** + * Cloudflare Durable Object that provides the atomic single-use authority for GitHub Actions OIDC tokens. + * Storage transactions ensure concurrent claims cannot both succeed, while alarms bound retention to token expiry. + */ export class NoemaOidcReplayGuard { constructor(private readonly state: DurableObjectState) {} + /** + * Applies the fail-closed replay claim protocol to the internal Durable Object endpoint. + * @param request Internal POST request carrying only the validated token expiry, never the bearer token. + * @returns A JSON response whose 201 or 409 status reflects the atomic replay decision; replay-boundary validation returns 404 for the wrong path or method, 415 for a non-JSON media type, and 400 for malformed JSON or an invalid expiration value. + */ async fetch(request: Request): Promise { const url = new URL(request.url); if (request.method !== "POST" || url.pathname !== "/claim") { @@ -213,6 +253,10 @@ export class NoemaOidcReplayGuard { return jsonResponse(decision, decision.accepted ? 201 : 409); } + /** + * Removes expired replay state or reschedules cleanup when an alarm fires before the authoritative expiry. + * @returns A promise that resolves after cleanup or alarm reschedule has been durably requested. + */ async alarm(): Promise { const nowEpochSeconds = Math.floor(Date.now() / 1_000); const decision = await this.state.storage.transaction(async (transaction) => { diff --git a/src/outbound-fetch-policy.ts b/src/outbound-fetch-policy.ts index 1ee6cfe7c..d30096248 100644 --- a/src/outbound-fetch-policy.ts +++ b/src/outbound-fetch-policy.ts @@ -1,8 +1,16 @@ +/** + * Represents the fetch capability wrapped by Noema's credential-egress policy. + * Implementations receive a request target plus optional request initialization and return the resulting response promise. + */ export type FetchLike = ( input: RequestInfo | URL, init?: RequestInit, ) => Promise; +/** + * Represents a mutable host on which Noema can install and later verify the fail-closed outbound fetch wrapper. + * The fetch member is optional so missing runtime capability is detected explicitly instead of silently bypassed. + */ export type FetchHost = { fetch?: FetchLike; }; @@ -209,7 +217,11 @@ function githubApiOperation(url: URL): GitHubApiOperation | undefined { return undefined; } -/** Return whether an outbound request is inside Noema's credential egress destination allowlist. */ +/** + * Checks whether an outbound destination is on the exact HTTPS credential-egress allowlist used by Noema. + * @param input Candidate request target supplied to the protected fetch path. + * @returns `true` only for reviewed GitHub API or GitHub OIDC discovery/JWKS allowlist destinations. + */ export function isTrustedCredentialEgress(input: RequestInfo | URL): boolean { const url = outboundUrl(input); if ( @@ -231,10 +243,10 @@ export function isTrustedCredentialEgress(input: RequestInfo | URL): boolean { } /** - * Enforce endpoint-specific request shape so credentials cannot cross protocol roles. - * OIDC metadata is public GET-only traffic with no body or ambient credentials. - * GitHub REST traffic is restricted to the reviewed App-JWT installation operations: - * repository lookup, app installation inventory, and least-privilege installation-token issuance. + * Enforces endpoint-specific request shape so credentials cannot cross protocol roles or accompany public OIDC metadata traffic. + * @param input Candidate destination that must already belong to the reviewed credential-egress allowlist. + * @param init Optional request initialization containing method, headers, and body semantics to validate. + * @returns `true` only when the request matches the reviewed credential protocol for its exact endpoint role. */ export function isTrustedCredentialEgressRequest( input: RequestInfo | URL, @@ -284,8 +296,9 @@ export function isTrustedCredentialEgressRequest( } /** - * Wrap fetch so credentials cannot leave reviewed GitHub endpoints, cross endpoint roles, - * follow redirects, return unbounded bodies, or hold an exchange request open indefinitely. + * Wraps fetch with fail-closed credential destination, request-role, redirect, response-size, and timeout enforcement. + * @param rawFetch Trusted underlying fetch implementation that performs only requests admitted by the wrapper. + * @returns A fetch-compatible function that blocks redirects and timeout violations instead of leaking credentials. */ export function createFailClosedFetch(rawFetch: FetchLike): FetchLike { return async (input, init) => { @@ -328,7 +341,11 @@ export function createFailClosedFetch(rawFetch: FetchLike): FetchLike { }; } -/** Install the policy once on a fetch host and detect later tampering fail-closed. */ +/** + * Installs the fail-closed fetch policy exactly once on a host and detects later fetch replacement as tamper evidence. + * @param host Mutable fetch host to protect; defaults to the current global runtime object. + * @returns `true` only when the wrapper is installed and still intact, otherwise `false` without bypassing policy. + */ export function ensureGlobalOutboundFetchPolicy( host: FetchHost = globalThis, ): boolean { @@ -358,7 +375,11 @@ export function ensureGlobalOutboundFetchPolicy( return true; } -/** Restore a host after tests; production never removes the installed policy. */ +/** + * Restores an installed fetch host during tests while leaving production policy installation one-way for normal operation. + * @param host Mutable fetch host whose test-only installation state should be removed. + * @returns Nothing; cleanup is best-effort and never masks the security behavior being tested. + */ export function resetGlobalOutboundFetchPolicy( host: FetchHost = globalThis, ): void { diff --git a/src/rate-limit.ts b/src/rate-limit.ts index 832132b9b..ed4c7c2f8 100644 --- a/src/rate-limit.ts +++ b/src/rate-limit.ts @@ -13,11 +13,19 @@ const rateLimitDecisionKeys = new Set([ "retry_after_seconds", ]); +/** + * Provides the Durable Object namespace and optional per-minute limit used by distributed exchange throttling. + * The binding is mandatory so production requests never silently fall back to a process-local or shared limiter. + */ export interface DistributedRateLimitEnv { NOEMA_RATE_LIMIT_PER_MINUTE?: string; NOEMA_RATE_LIMITER: DurableObjectNamespace; } +/** + * Describes the authoritative distributed rate-limit result for one request, including whether it is allowed, + * the configured limit, remaining capacity, and retry delay that a rejected caller should observe. + */ export type DistributedRateLimitDecision = { allowed: boolean; limit: number; @@ -39,6 +47,10 @@ type AlarmDecision = | { action: "delete" } | { action: "reschedule"; reset_at_ms: number }; +/** + * Signals that the distributed rate-limit authority cannot return a trustworthy decision and the caller must fail closed. + * This includes malformed decisions, missing trusted client identity, transport errors, and Durable Object failures. + */ export class DistributedRateLimitUnavailable extends Error { constructor(message: string) { super(message); @@ -59,11 +71,21 @@ function jsonResponse(body: unknown, status = 200): Response { }); } +/** + * Tests whether a response Content-Type identifies JSON while tolerating ordinary media-type parameters. + * @param raw Raw Content-Type header value from the trusted internal rate-limit response. + * @returns `true` only when the normalized media type is exactly `application/json`. + */ export function isJsonMediaType(raw: string | null): boolean { const mediaType = (raw ?? "").split(";", 1)[0]!.trim().toLowerCase(); return mediaType === "application/json"; } +/** + * Normalizes an operator-supplied per-minute request limit into the bounded production configuration range. + * @param raw Optional textual limit from deployment configuration. + * @returns A positive integer no greater than the hard maximum, or the safe default when input is invalid. + */ export function configuredDistributedRateLimit(raw: string | undefined): number { const parsed = Number(raw ?? String(DEFAULT_RATE_LIMIT_PER_MINUTE)); if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_RATE_LIMIT_PER_MINUTE; @@ -101,6 +123,11 @@ function canonicalIpv6(candidate: string): string | undefined { } } +/** + * Extracts a canonical trusted client identifier only from Cloudflare's `CF-Connecting-IP` request header. + * @param request Edge request whose Cloudflare-supplied client address is used for distributed bucketing. + * @returns A canonical IPv4 or IPv6 address, or `undefined` when the trusted header is missing or malformed. + */ export function trustedClientIdentifier(request: Request): string | undefined { const candidate = request.headers.get("cf-connecting-ip")?.trim() ?? ""; if (!candidate || candidate.length > MAX_CLIENT_IDENTIFIER_LENGTH) { @@ -114,6 +141,12 @@ async function sha256Hex(value: string): Promise { return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); } +/** + * Derives the stable privacy-preserving Durable Object name for the trusted client represented by a request. + * @param request Edge request carrying the trusted Cloudflare client-address header. + * @returns A SHA-256 hash-derived bucket name that does not expose the raw client identifier. + * @throws {DistributedRateLimitUnavailable} When no trustworthy client identifier can be established. + */ export async function distributedRateLimitObjectName(request: Request): Promise { const identifier = trustedClientIdentifier(request); if (!identifier) { @@ -268,6 +301,13 @@ async function readBoundedRateLimitDecision(response: Response): Promise { const url = new URL(request.url); if (request.method !== "POST" || url.pathname !== "/check") { @@ -382,6 +431,10 @@ export class NoemaRateLimiter { return jsonResponse(publicDecision); } + /** + * Deletes an expired rate-limit bucket or reschedules cleanup when the active fixed window has not ended yet. + * @returns A promise that resolves after cleanup or the required alarm reschedule is durably requested. + */ async alarm(): Promise { const now = Date.now(); const decision = await this.state.storage.transaction(async (transaction) => { diff --git a/src/runtime-entrypoint.ts b/src/runtime-entrypoint.ts index 67f4467d7..2006bd199 100644 --- a/src/runtime-entrypoint.ts +++ b/src/runtime-entrypoint.ts @@ -6,6 +6,12 @@ import entrypoint, { import { evaluateRuntimeReadiness } from "./runtime-readiness"; export { NoemaOidcReplayGuard, NoemaRateLimiter }; + +/** + * Runtime bindings required by Noema's production worker entrypoint. + * This interface inherits the credential-exchange, replay-guard, and rate-limit bindings + * consumed by the delegated application entrypoint and the readiness evaluation path. + */ export interface Env extends BaseEnv {} function readinessHeaders( @@ -84,6 +90,11 @@ async function runtimeReadinessResponse(request: Request, env: Env): Promise { const url = new URL(request.url); diff --git a/src/worker.ts b/src/worker.ts index 69b5bedf3..141cd3d55 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -16,6 +16,11 @@ import { export { NoemaOidcReplayGuard, NoemaRateLimiter }; +/** + * Runtime configuration for the protected Worker layer. It composes the base GitHub + * credential-exchange environment with distributed rate-limit and OIDC replay bindings + * so every credential-bearing exchange can fail closed when shared controls are unavailable. + */ export interface Env extends BaseEnv, DistributedRateLimitEnv, OidcReplayProtectionEnv {} const trustedTracePattern = /^[A-Za-z0-9._:-]+$/; @@ -260,6 +265,11 @@ function withDistributedRateLimitHeaders( }); } +/** + * Protected public Worker entrypoint layered over the base exchange worker. It applies + * distributed rate limiting, exact reusable-workflow trust, and single-use OIDC replay + * semantics before returning any successful credential exchange with security headers. + */ export default { async fetch(request: Request, env: Env): Promise { const url = new URL(request.url); diff --git a/test/public-api-diagnostic-bounds.test.ts b/test/public-api-diagnostic-bounds.test.ts new file mode 100644 index 000000000..5a61d80ba --- /dev/null +++ b/test/public-api-diagnostic-bounds.test.ts @@ -0,0 +1,53 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; + +const rateLimitSource = readFileSync(new URL("../src/rate-limit.ts", import.meta.url), "utf8"); +const oidcReplaySource = readFileSync(new URL("../src/oidc-replay.ts", import.meta.url), "utf8"); + +/** + * Verifies that a public constructor only promises bounded diagnostic messages + * when its class implementation contains an observable message-bounding rule. + */ +function expectBoundedDiagnosticClaimImplemented( + source: string, + className: string, + boundedClaim: string, +): void { + const classStart = source.indexOf(`export class ${className}`); + expect(classStart, `${className} must remain a public class`).toBeGreaterThanOrEqual(0); + + const docStart = source.lastIndexOf("/**", classStart); + const docEnd = docStart >= 0 ? source.indexOf("*/", docStart) : -1; + const adjacent = docEnd >= 0 && source.slice(docEnd + 2, classStart).trim() === ""; + const sliceStart = adjacent ? docStart : classStart; + + const nextClass = source.indexOf("\nexport class ", classStart + 1); + const nextDoc = nextClass >= 0 ? source.lastIndexOf("/**", nextClass) : -1; + const sliceEnd = nextDoc > classStart + ? nextDoc + : nextClass >= 0 + ? nextClass + : source.length; + const classSource = source.slice(sliceStart, sliceEnd); + if (!classSource.includes(boundedClaim)) return; + + expect( + classSource, + `${className} documents a bounded diagnostic but does not bound message input`, + ).toMatch(/(?:MAX_[A-Z0-9_]*MESSAGE|message\.length|message\.slice\(|message\.substring\()/); +} + +describe("public error diagnostic documentation", () => { + it("does not promise an unimplemented diagnostic-message bound", () => { + expectBoundedDiagnosticClaimImplemented( + rateLimitSource, + "DistributedRateLimitUnavailable", + "bounded diagnostic message", + ); + expectBoundedDiagnosticClaimImplemented( + oidcReplaySource, + "OidcReplayUnavailable", + "bounded diagnostic reason", + ); + }); +}); diff --git a/test/rate-limit-public-api-docs.test.ts b/test/rate-limit-public-api-docs.test.ts new file mode 100644 index 000000000..5120b493a --- /dev/null +++ b/test/rate-limit-public-api-docs.test.ts @@ -0,0 +1,484 @@ +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +const require = createRequire(import.meta.url); +const ts = require("typescript") as typeof import("typescript"); +type TsNode = import("typescript").Node; +type TsSourceFile = import("typescript").SourceFile; +type TsStatement = import("typescript").Statement; +type TsExportDeclaration = import("typescript").ExportDeclaration; +type TsSymbol = import("typescript").Symbol; +type TsSyntaxKind = import("typescript").SyntaxKind; + +const repositoryRoot = fileURLToPath(new URL("../", import.meta.url)); +const sourceRoot = fileURLToPath(new URL("../src/", import.meta.url)); +const tsconfigPath = join(repositoryRoot, "tsconfig.json"); + +function sourcePaths(directory: string): string[] { + return readdirSync(directory, { withFileTypes: true }) + .flatMap((entry) => { + const path = join(directory, entry.name); + if (entry.isDirectory()) return sourcePaths(path); + return entry.isFile() && entry.name.endsWith(".ts") ? [path] : []; + }) + .sort(); +} + +function projectCompilerOptions(): import("typescript").CompilerOptions { + const config = ts.readConfigFile(tsconfigPath, ts.sys.readFile); + if (config.error) { + throw new Error( + ts.flattenDiagnosticMessageText(config.error.messageText, "\n"), + ); + } + const parsed = ts.parseJsonConfigFileContent( + config.config, + ts.sys, + repositoryRoot, + undefined, + tsconfigPath, + ); + if (parsed.errors.length > 0) { + throw new Error( + parsed.errors + .map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")) + .join("\n"), + ); + } + return parsed.options; +} + +function jsdocImmediatelyBefore(source: string, node: TsNode): string | undefined { + const prefix = source.slice(node.getFullStart(), node.getStart()); + return prefix.match(/(\/\*\*[\s\S]*?\*\/)\s*$/)?.[1]; +} + +function meaningfulJSDoc(doc: string | undefined): boolean { + return Boolean(doc && doc.length > 80 && !/\b(?:TODO|TBD)\b/i.test(doc)); +} + +function hasModifier(node: TsNode, kind: TsSyntaxKind): boolean { + return Boolean( + ts.canHaveModifiers(node) + && ts.getModifiers(node)?.some((modifier) => modifier.kind === kind), + ); +} + +function exported(node: TsNode): boolean { + return hasModifier(node, ts.SyntaxKind.ExportKeyword); +} + +type ParsedSource = { + path: string; + source: string; + file: TsSourceFile; +}; + +type DirectExport = { + name: string; + path: string; + source: string; + file: TsSourceFile; + node: TsNode; + callable: boolean; + parameterCount: number; +}; + +type ResolvedReexport = { + exposedName: string; + path: string; + source: string; + file: TsSourceFile; + node: TsExportDeclaration; + targetNodes: TsNode[]; + resolved: boolean; +}; + +type PublicApiInventory = { + parsedSources: ParsedSource[]; + directExports: DirectExport[]; + reexports: ResolvedReexport[]; +}; + +function declarationNames(statement: TsStatement): Array<{ + name: string; + node: TsNode; + callable: boolean; + parameterCount: number; +}> { + if ( + ts.isInterfaceDeclaration(statement) + || ts.isTypeAliasDeclaration(statement) + || ts.isClassDeclaration(statement) + || ts.isEnumDeclaration(statement) + || ts.isModuleDeclaration(statement) + ) { + return statement.name + ? [{ name: statement.name.text, node: statement, callable: false, parameterCount: 0 }] + : []; + } + + if (ts.isFunctionDeclaration(statement)) { + return statement.name + ? [{ + name: statement.name.text, + node: statement, + callable: true, + parameterCount: statement.parameters.length, + }] + : []; + } + + if (ts.isVariableStatement(statement)) { + return statement.declarationList.declarations.flatMap((declaration) => + ts.isIdentifier(declaration.name) + ? [{ name: declaration.name.text, node: statement, callable: false, parameterCount: 0 }] + : [] + ); + } + + return []; +} + +function documentationNode(node: TsNode): TsNode { + let current: TsNode | undefined = node; + while (current && !ts.isSourceFile(current)) { + if ( + ts.isVariableStatement(current) + || ts.isFunctionDeclaration(current) + || ts.isClassDeclaration(current) + || ts.isInterfaceDeclaration(current) + || ts.isTypeAliasDeclaration(current) + || ts.isEnumDeclaration(current) + || ts.isModuleDeclaration(current) + ) { + return current; + } + current = current.parent; + } + return node; +} + +function collectPublicApi(directory: string): PublicApiInventory { + const rootNames = sourcePaths(directory); + const program = ts.createProgram(rootNames, projectCompilerOptions()); + const checker = program.getTypeChecker(); + const parsedSources = rootNames.map((path) => { + const file = program.getSourceFile(path); + if (!file) throw new Error(`TypeScript program did not load ${path}`); + return { + path: relative(directory, path).replaceAll("\\", "/"), + source: file.text, + file, + }; + }); + const sourceByFileName = new Map( + parsedSources.map((parsed) => [parsed.file.fileName, parsed] as const), + ); + + function resolveAlias(symbol: TsSymbol | undefined): TsSymbol | undefined { + if (!symbol) return undefined; + if (!(symbol.flags & ts.SymbolFlags.Alias)) return symbol; + try { + return checker.getAliasedSymbol(symbol); + } catch { + return undefined; + } + } + + function ownedDocumentationNodes(symbol: TsSymbol | undefined): TsNode[] { + const resolved = resolveAlias(symbol); + if (!resolved) return []; + const unique = new Map(); + for (const declaration of resolved.declarations ?? []) { + const parsed = sourceByFileName.get(declaration.getSourceFile().fileName); + if (!parsed) continue; + const node = documentationNode(declaration); + const key = `${parsed.path}:${node.getStart(parsed.file)}`; + unique.set(key, node); + } + return [...unique.values()]; + } + + function moduleExports(statement: TsExportDeclaration): TsSymbol[] | undefined { + if (!statement.moduleSpecifier) return undefined; + const moduleSymbol = checker.getSymbolAtLocation(statement.moduleSpecifier); + if (!moduleSymbol) return undefined; + try { + return checker.getExportsOfModule(moduleSymbol); + } catch { + return undefined; + } + } + + const directExports: DirectExport[] = []; + const reexports: ResolvedReexport[] = []; + + for (const parsed of parsedSources) { + for (const statement of parsed.file.statements) { + if (ts.isExportAssignment(statement)) { + directExports.push({ + name: "default", + path: parsed.path, + source: parsed.source, + file: parsed.file, + node: statement, + callable: false, + parameterCount: 0, + }); + continue; + } + + if (ts.isExportDeclaration(statement)) { + const clause = statement.exportClause; + if (clause && ts.isNamedExports(clause)) { + for (const element of clause.elements) { + const symbol = checker.getSymbolAtLocation(element.name); + const targetNodes = ownedDocumentationNodes(symbol); + reexports.push({ + exposedName: element.name.text, + path: parsed.path, + source: parsed.source, + file: parsed.file, + node: statement, + targetNodes, + resolved: targetNodes.length > 0, + }); + } + continue; + } + + const exportedSymbols = moduleExports(statement); + if (clause && ts.isNamespaceExport(clause)) { + const targetNodes = (exportedSymbols ?? []).flatMap((symbol) => + ownedDocumentationNodes(symbol) + ); + reexports.push({ + exposedName: clause.name.text, + path: parsed.path, + source: parsed.source, + file: parsed.file, + node: statement, + targetNodes, + resolved: Boolean(exportedSymbols?.length) && targetNodes.length > 0, + }); + continue; + } + + if (!clause) { + if (!exportedSymbols) { + reexports.push({ + exposedName: "*", + path: parsed.path, + source: parsed.source, + file: parsed.file, + node: statement, + targetNodes: [], + resolved: false, + }); + continue; + } + for (const symbol of exportedSymbols.filter((candidate) => candidate.name !== "default")) { + const targetNodes = ownedDocumentationNodes(symbol); + reexports.push({ + exposedName: symbol.name, + path: parsed.path, + source: parsed.source, + file: parsed.file, + node: statement, + targetNodes, + resolved: targetNodes.length > 0, + }); + } + } + continue; + } + + if (!exported(statement)) continue; + for (const declaration of declarationNames(statement)) { + directExports.push({ + ...declaration, + path: parsed.path, + source: parsed.source, + file: parsed.file, + }); + } + } + } + + return { parsedSources, directExports, reexports }; +} + +function reexportFailures(items: ResolvedReexport[]): string[] { + return items.flatMap((item) => { + const localDoc = jsdocImmediatelyBefore(item.source, item.node); + if (meaningfulJSDoc(localDoc)) return []; + if (!item.resolved || item.targetNodes.length === 0) { + return [`${item.path} re-export ${item.exposedName}: module target is unresolved or ambiguous`]; + } + const undocumented = item.targetNodes.filter((node) => { + const sourceFile = node.getSourceFile(); + const source = sourceFile.text; + return !meaningfulJSDoc(jsdocImmediatelyBefore(source, node)); + }); + if (undocumented.length === 0) return []; + return [ + `${item.path} re-export ${item.exposedName}: ${undocumented.length} resolved declaration(s) lack meaningful JSDoc`, + ]; + }); +} + +const inventory = collectPublicApi(sourceRoot); +const { parsedSources, directExports, reexports } = inventory; + +function location(item: { path: string; file: TsSourceFile; node: TsNode }): string { + const line = item.file.getLineAndCharacterOfPosition(item.node.getStart(item.file)).line + 1; + return `${item.path}:${line}`; +} + +function expectPublicDoc(source: string, marker: string, requiredTerms: string[]): void { + const markerIndex = source.indexOf(marker); + expect(markerIndex, `missing source marker: ${marker}`).toBeGreaterThanOrEqual(0); + const prefix = source.slice(0, markerIndex); + const commentStart = prefix.lastIndexOf("/**"); + expect(commentStart, `${marker} must have a preceding JSDoc block`).toBeGreaterThanOrEqual(0); + const commentEnd = prefix.indexOf("*/", commentStart); + expect(commentEnd, `${marker} JSDoc must be terminated`).toBeGreaterThan(commentStart); + expect( + prefix.slice(commentEnd + 2).trim(), + `${marker} JSDoc must be immediately adjacent to the documented symbol`, + ).toBe(""); + + const doc = prefix.slice(commentStart, commentEnd + 2); + expect(doc.length, `${marker} JSDoc must explain behavior rather than act as a label`).toBeGreaterThan(80); + expect(doc).not.toMatch(/\b(?:TODO|TBD)\b/i); + for (const term of requiredTerms) { + expect(doc.toLowerCase(), `${marker} JSDoc must explain ${term}`).toContain(term.toLowerCase()); + } +} + +describe("repository-wide TypeScript public API inventory", () => { + it("discovers every owned production TypeScript module recursively", () => { + expect(parsedSources.length).toBeGreaterThan(0); + expect(parsedSources.map(({ path }) => path)).toEqual( + [...parsedSources.map(({ path }) => path)].sort(), + ); + }); + + it("requires meaningful adjacent JSDoc for every direct public export", () => { + const failures = directExports.flatMap((item) => { + const doc = jsdocImmediatelyBefore(item.source, item.node); + const reasons: string[] = []; + if (!meaningfulJSDoc(doc)) reasons.push("missing or non-meaningful adjacent JSDoc"); + if (item.callable && item.parameterCount > 0 && !doc?.includes("@param")) { + reasons.push("callable export does not document parameters"); + } + if (item.callable && !doc?.includes("@returns")) { + reasons.push("callable export does not document its return contract"); + } + return reasons.map((reason) => `${location(item)} ${item.name}: ${reason}`); + }); + + expect(failures, failures.join("\n")).toEqual([]); + }); + + it("resolves named, star, and namespace re-exports to their actual module declarations", () => { + const failures = reexportFailures(reexports); + expect(failures, failures.join("\n")).toEqual([]); + }); + + it("does not let an unrelated same-name declaration satisfy a re-export", () => { + const directory = mkdtempSync(join(tmpdir(), "noema-public-api-")); + try { + writeFileSync( + join(directory, "documented.ts"), + "/** This unrelated Credential is intentionally well documented so name-only matching would produce a false pass. */\nexport interface Credential { documented: true }\n", + ); + writeFileSync( + join(directory, "undocumented.ts"), + "export interface Credential { documented: false }\nexport interface Other { value: string }\n", + ); + writeFileSync( + join(directory, "barrel.ts"), + "export { Credential as PublicCredential } from './undocumented';\nexport * from './undocumented';\nexport * as UndocumentedNamespace from './undocumented';\n", + ); + + const failures = reexportFailures(collectPublicApi(directory).reexports).join("\n"); + expect(failures).toContain("PublicCredential"); + expect(failures).toContain("Other"); + expect(failures).toContain("UndocumentedNamespace"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + + it("treats a named merged declaration as resolved when every owned declaration is documented", () => { + const directory = mkdtempSync(join(tmpdir(), "noema-public-api-merged-")); + try { + writeFileSync( + join(directory, "merged.ts"), + "/** First half of a merged public contract with enough detail to qualify as meaningful adjacent API documentation. */\nexport interface MergedContract { first: string }\n/** Second half of the merged public contract with enough detail to qualify as meaningful adjacent API documentation. */\nexport interface MergedContract { second: string }\n", + ); + writeFileSync( + join(directory, "barrel.ts"), + "export { MergedContract } from './merged';\n", + ); + + const merged = collectPublicApi(directory).reexports.find( + (item) => item.exposedName === "MergedContract", + ); + expect(merged?.resolved).toBe(true); + expect(merged?.targetNodes.length).toBe(2); + expect(reexportFailures(merged ? [merged] : [])).toEqual([]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); +}); + +const rateLimitSource = readFileSync(new URL("../src/rate-limit.ts", import.meta.url), "utf8"); +const entrypointSource = readFileSync(new URL("../src/entrypoint.ts", import.meta.url), "utf8"); +const runtimeEntrypointSource = readFileSync(new URL("../src/runtime-entrypoint.ts", import.meta.url), "utf8"); +const outboundFetchPolicySource = readFileSync(new URL("../src/outbound-fetch-policy.ts", import.meta.url), "utf8"); +const oidcReplaySource = readFileSync(new URL("../src/oidc-replay.ts", import.meta.url), "utf8"); + +describe("credential-boundary public API semantics", () => { + it("documents rate-limit trust, failures, and Durable Object methods", () => { + expectPublicDoc(rateLimitSource, "export interface DistributedRateLimitEnv", ["Durable Object", "limit"]); + expectPublicDoc(rateLimitSource, "export type DistributedRateLimitDecision", ["allowed", "remaining", "retry"]); + expectPublicDoc(rateLimitSource, "export class DistributedRateLimitUnavailable", ["fail", "rate-limit"]); + expectPublicDoc(rateLimitSource, "export function trustedClientIdentifier", ["CF-Connecting-IP", "trusted"]); + expectPublicDoc(rateLimitSource, "export async function distributedRateLimitObjectName", ["@throws", "hash"]); + expectPublicDoc(rateLimitSource, "export async function checkDistributedRateLimit", ["@throws", "Durable Object"]); + expectPublicDoc(rateLimitSource, " async fetch(request: Request): Promise", ["@param", "@returns", "fail"]); + expectPublicDoc(rateLimitSource, " async alarm(): Promise", ["@returns", "cleanup", "reschedule"]); + }); + + it("documents request-edge, runtime-readiness, and credential-egress boundaries", () => { + expectPublicDoc(entrypointSource, "export function isTrustedGithubApiBase", ["exact", "origin"]); + expectPublicDoc(entrypointSource, "export function isBoundedOidcBearer", ["credential"]); + expectPublicDoc(entrypointSource, "export async function boundExchangeJsonBody", ["byte", "stream"]); + expectPublicDoc(entrypointSource, "export default {", ["Worker", "/exchange", "fail"]); + expectPublicDoc(runtimeEntrypointSource, "export default {", ["/ready", "Worker", "readiness"]); + expectPublicDoc(outboundFetchPolicySource, "export function isTrustedCredentialEgress", ["allowlist"]); + expectPublicDoc(outboundFetchPolicySource, "export function isTrustedCredentialEgressRequest", ["credential"]); + expectPublicDoc(outboundFetchPolicySource, "export function createFailClosedFetch", ["redirect", "timeout"]); + expectPublicDoc(outboundFetchPolicySource, "export function ensureGlobalOutboundFetchPolicy", ["tamper"]); + }); + + it("documents OIDC replay authority, failures, and Durable Object methods", () => { + expectPublicDoc(oidcReplaySource, "export interface OidcReplayProtectionEnv", ["Durable Object", "binding"]); + expectPublicDoc(oidcReplaySource, "export type OidcReplayClaimDecision", ["accepted", "expiry"]); + expectPublicDoc(oidcReplaySource, "export class OidcReplayDetected", ["replay", "expiry"]); + expectPublicDoc(oidcReplaySource, "export class OidcReplayUnavailable", ["fail", "replay"]); + expectPublicDoc(oidcReplaySource, "export async function oidcReplayObjectName", ["@throws", "hash"]); + expectPublicDoc(oidcReplaySource, "export async function claimOidcTokenUsage", ["@throws", "replay"]); + expectPublicDoc(oidcReplaySource, "export class NoemaOidcReplayGuard", ["Durable Object", "atomic"]); + expectPublicDoc(oidcReplaySource, " async fetch(request: Request): Promise", ["@param", "@returns", "replay"]); + expectPublicDoc(oidcReplaySource, " async alarm(): Promise", ["@returns", "cleanup", "reschedule"]); + }); +}); \ No newline at end of file