codeburn/src/sync/discovery.ts
Andrew Lee d8a7b2a95f fix(sync): address PR review — https enforcement, keychain test isolation, golden ID pins
Before-merge items:
1. HTTPS enforced on every remote endpoint (RFC 8252 §8.3): baseUrl,
   issuer, authorization/token/revocation endpoints, and the traces
   endpoint all reject non-https, with a loopback (127.0.0.1/::1/
   localhost) exception for offline tests and local dev. Enforcement is
   central (assertHttps) — the browser-open guard is no longer the only
   check whose failure was swallowed.
2. Credential store test isolation: CODEBURN_SYNC_TOKEN_STORE=file
   forces the file store (honors HOME) so the offline suite never
   touches the real macOS login keychain. Set in the e2e suite.
3. Golden pins for deriveSpanId/deriveTraceId/deriveDeviceId with fixed
   inputs and expected hex — the idempotency contract depends on these
   encodings being stable across releases; a green-tests encoding change
   would silently double-count history on span-ID-keyed backends.
   getDeviceId refactored over a pure deriveDeviceId(host, user).

Smaller review items:
- Callback server: ready promise resolves the actually-bound port from
  the listening event (kills the 100ms-sleep race after port fallback);
  Connection: close on all responses + closeAllConnections() on
  shutdown (pooled keep-alive sockets from a closed server could
  swallow requests aimed at a later server on the same port); error
  handler guarded so a post-bind error can never rebind to a different
  port than advertised; optional ports param ([0] = ephemeral) removes
  fixed-port contention between parallel test workers.
- fetchOidcConfig verifies the issuer claim matches the fetch origin
  (OIDC Discovery §4.3 mix-up defense).
- partialSuccess.rejectedSpans wrapped in Number() — proto3 int64 JSON
  mapping sends strings from strict protojson servers; += would
  concatenate.
- Ledger writes are atomic (temp + rename); corrupt-ledger recovery and
  no-tmp-left-behind tests added; XDG_CACHE_HOME honored (ledger is
  reconstructible state, not config).
- Mock IdP now implements /oauth2/authorize (registers PKCE challenge,
  302s to redirect_uri) and verifies S256 code_verifier + single-use
  codes at the token endpoint. The e2e drives the real redirect flow
  and asserts wrong-verifier and code-reuse are rejected — PKCE binding
  is now exercised end to end.
- sync reset calls clearLedger() instead of reimplementing the path.
- push sets exit code 1 on rate-limited/server-error outcomes so cron
  and script callers can detect incomplete pushes.

Deferred (noted for fast-follow): macOS 'security -i' stdin mode
(untestable on this Linux box), ai.cost_estimated as a real
ParsedApiCall flag (touches core parser types).

Sync suite: 81 passing (5x stable), 5 developer-only.

AI-Origin: human
2026-07-13 16:45:39 +00:00

119 lines
3.3 KiB
TypeScript

/**
* codeburn sync — discovery document parser.
*
* Fetches and validates {baseUrl}/.well-known/codeburn-export.json
*/
export interface CodeburnDiscoveryDoc {
version: number
issuer: string
client_id: string
scopes: string[]
traces_path: string
max_batch_size: number
}
export class DiscoveryError extends Error {
constructor(message: string) {
super(message)
this.name = 'DiscoveryError'
}
}
const LOOPBACK_HOSTS = new Set(['127.0.0.1', '[::1]', 'localhost'])
/**
* Enforce https on remote endpoints (RFC 8252 §8.3). Refresh tokens and
* bearer tokens travel on these URLs — plaintext http is only permitted
* for loopback addresses (local development and offline tests).
*/
export function assertHttps(url: string, label: string): void {
let parsed: URL
try {
parsed = new URL(url)
} catch {
throw new DiscoveryError(`${label} is not a valid URL: ${url}`)
}
if (parsed.protocol === 'https:') return
if (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname)) return
throw new DiscoveryError(
`${label} must use https (got ${parsed.protocol}//${parsed.host}). ` +
`Plain http is only allowed for loopback (127.0.0.1).`
)
}
const SUPPORTED_VERSION = 1
export function parseDiscoveryDoc(raw: unknown): CodeburnDiscoveryDoc {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new DiscoveryError('Discovery doc must be a JSON object')
}
const doc = raw as Record<string, unknown>
// Version check
const version = typeof doc.version === 'number' ? doc.version : 1
if (version > SUPPORTED_VERSION) {
throw new DiscoveryError(
`This endpoint requires codeburn sync v${version}. Please update codeburn.`
)
}
// Required fields
const issuer = doc.issuer
if (typeof issuer !== 'string' || !issuer) {
throw new DiscoveryError('Discovery doc missing required field: issuer')
}
const client_id = doc.client_id
if (typeof client_id !== 'string' || !client_id) {
throw new DiscoveryError('Discovery doc missing required field: client_id')
}
// Format validation after presence checks (clearer errors)
assertHttps(issuer, 'Issuer')
// Optional with defaults
const scopes = Array.isArray(doc.scopes)
? doc.scopes.filter((s): s is string => typeof s === 'string')
: ['openid']
const traces_path = typeof doc.traces_path === 'string' ? doc.traces_path : '/v1/traces'
const max_batch_size = typeof doc.max_batch_size === 'number' && doc.max_batch_size > 0
? doc.max_batch_size
: 1000
return { version, issuer, client_id, scopes, traces_path, max_batch_size }
}
export async function fetchDiscoveryDoc(baseUrl: string): Promise<CodeburnDiscoveryDoc> {
assertHttps(baseUrl, 'Base URL')
const url = `${baseUrl.replace(/\/$/, '')}/.well-known/codeburn-export.json`
let response: Response
try {
response = await fetch(url)
} catch (err) {
throw new DiscoveryError(`Cannot reach ${url}: ${(err as Error).message}`)
}
if (response.status === 404) {
throw new DiscoveryError(
`Server does not support codeburn sync.\n${url} returned 404.`
)
}
if (!response.ok) {
throw new DiscoveryError(`${url} returned HTTP ${response.status}`)
}
let body: unknown
try {
body = await response.json()
} catch {
throw new DiscoveryError(`${url} returned invalid JSON`)
}
return parseDiscoveryDoc(body)
}