companion-oauth-pkce.mjs
sha256:65ccb454656ea5acdea0a10e559b78bcde1eb6ff753ecc2911bc99d1c3d7cadd
feat(calendar): enforce agent context tiers in retrieval AP…
Human
minor
⚠ breaking
1 day ago
| 1 | /** |
| 2 | * Companion OAuth — native/public-client PKCE protocol CORE (pure, no I/O). |
| 3 | * |
| 4 | * Phase 3 of the Companion App build plan (feat/companion-app). |
| 5 | * See docs/COMPANION-APP-PHASE-3-OAUTH-PKCE.md for the accepted design, the adversarial |
| 6 | * threat model, the RFC citations, and the contract Phase 5 must honour to bind the loopback |
| 7 | * redirect listener and perform the real network / OS-keychain I/O. |
| 8 | * |
| 9 | * WHAT THIS MODULE IS |
| 10 | * The companion app (a future tray helper) authenticates as a NATIVE / PUBLIC OAuth client |
| 11 | * using Authorization Code + PKCE (RFC 7636) with a loopback redirect (RFC 8252) and NO |
| 12 | * client secret on the device. This module is the PROTOCOL CORE for that flow: it generates |
| 13 | * the PKCE pair, the CSRF `state`, and the `nonce`; builds the authorization URL and the |
| 14 | * token-endpoint request *descriptor*; and validates the redirect URI, the authorization |
| 15 | * response, and the token response. It decides, from a clock, whether an access token is |
| 16 | * still valid, should be refreshed, or requires full re-authentication. |
| 17 | * |
| 18 | * WHAT THIS MODULE IS NOT (deferred to Phase 5 — the shared bind gate) |
| 19 | * - It binds NO socket (no loopback redirect listener). → Phase 5 |
| 20 | * - It performs NO network I/O (no TLS POST to the token endpoint). → Phase 5 sends the |
| 21 | * descriptor returned by buildTokenRequest(). |
| 22 | * - It opens NO system browser. → Phase 5 |
| 23 | * - It performs NO real OS-keychain I/O. → lib/companion-token-custody.mjs |
| 24 | * defines the custody logic against an INJECTED adapter; Phase 5 supplies the real adapter. |
| 25 | * |
| 26 | * DESIGN CONSTRAINTS (read before modifying — these are security invariants, not style): |
| 27 | * - PURE. No I/O, no process.env reads, no network, no logging, no clock reads. Every input |
| 28 | * (including `now`) is passed explicitly so the core is deterministic and exhaustively |
| 29 | * testable, and composable at any layer without environment coupling. |
| 30 | * - CSPRNG ONLY. All entropy comes from node:crypto randomBytes; never Math.random. |
| 31 | * - S256 ONLY (RFC 7636 §4.2). The 'plain' challenge method is REJECTED everywhere — a |
| 32 | * downgrade to 'plain' defeats PKCE against an attacker who can read the authorization |
| 33 | * request, so it is never built and never accepted. |
| 34 | * - CONSTANT-TIME compares for `state` and `iss` (timing-oracle resistance). |
| 35 | * - FAIL-CLOSED. Anything missing, malformed, ambiguous, or unrecognised → DENY. Validators |
| 36 | * return a discriminated { ok:false, reason } whose `reason` is a fixed constant. |
| 37 | * - NEVER LEAK A SECRET. A token / JWT / refresh token / authorization code / code_verifier / |
| 38 | * `state` value is NEVER copied into a `reason`, a value intended for logging, or a thrown |
| 39 | * error. The authorization code and code_verifier appear ONLY in the legitimate return |
| 40 | * channels (validateAuthorizationResponse().code, buildTokenRequest()). |
| 41 | * |
| 42 | * PROVIDER-AGNOSTIC (Phase 3 scope decision, owner-approved 2026-06-05) |
| 43 | * This module hardcodes NO authorization server, NO client_id, and NO scope set. The |
| 44 | * authorization/token endpoints, the client_id, and the scope list are all INJECTED inputs. |
| 45 | * Phase 3 therefore registers no OAuth client and alters no scopes (honouring the gate's |
| 46 | * "DOES NOT approve: Any change to OAuth client registration or scopes"). Whether the |
| 47 | * native/loopback client is issued web-session-equivalent scopes, and whether the PKCE |
| 48 | * provider runs on the hosted deployment, is a SEPARATE server-side OAuth gate (a Phase 5 |
| 49 | * prerequisite) — see the Phase 3 design doc. |
| 50 | * |
| 51 | * Hard constraint from docs/COMPANION-APP-MODEL-ROUTING-AND-ENRICHMENT-ARCHITECTURE.md §3/§5: |
| 52 | * OAuth itself is unchanged; the companion is a public client with PKCE + loopback redirect, |
| 53 | * no device secret, JWT stored in the OS keychain (custody module). The cloud never proxies |
| 54 | * local inference; this module only governs the companion's identity acquisition. |
| 55 | */ |
| 56 | |
| 57 | import crypto from 'node:crypto'; |
| 58 | |
| 59 | /** |
| 60 | * Fixed reason codes. These are the ONLY strings the validators ever return as a `reason`. |
| 61 | * None is derived from request/response input, so no secret or attacker-controlled value can |
| 62 | * leak through the reason channel. |
| 63 | * @readonly |
| 64 | */ |
| 65 | export const OAUTH_PKCE_REASONS = Object.freeze({ |
| 66 | OK: 'ok', |
| 67 | MALFORMED_INPUT: 'malformed_input', |
| 68 | AUTHORIZATION_SERVER_ERROR: 'authorization_server_error', |
| 69 | STATE_MISSING: 'state_missing', |
| 70 | STATE_MISMATCH: 'state_mismatch', |
| 71 | ISSUER_MISMATCH: 'issuer_mismatch', |
| 72 | MISSING_CODE: 'missing_code', |
| 73 | INVALID_REDIRECT_URI: 'invalid_redirect_uri', |
| 74 | UNSUPPORTED_PKCE_METHOD: 'unsupported_pkce_method', |
| 75 | INVALID_TOKEN_RESPONSE: 'invalid_token_response', |
| 76 | }); |
| 77 | |
| 78 | /** The one and only PKCE challenge method this client supports (RFC 7636 §4.2). */ |
| 79 | export const PKCE_METHOD_S256 = 'S256'; |
| 80 | |
| 81 | /** RFC 7636 §4.1 code_verifier length bounds (characters). */ |
| 82 | export const CODE_VERIFIER_MIN_LEN = 43; |
| 83 | export const CODE_VERIFIER_MAX_LEN = 128; |
| 84 | |
| 85 | /** Bytes of CSPRNG entropy for the code_verifier: 32 bytes → 43 base64url chars (≥ 256-bit). */ |
| 86 | const VERIFIER_ENTROPY_BYTES = 32; |
| 87 | /** Bytes of CSPRNG entropy for `state` and `nonce` (128-bit min; we use 256-bit). */ |
| 88 | const STATE_ENTROPY_BYTES = 32; |
| 89 | const NONCE_ENTROPY_BYTES = 32; |
| 90 | |
| 91 | /** |
| 92 | * RFC 7636 §4.1 unreserved code_verifier alphabet: ALPHA / DIGIT / "-" / "." / "_" / "~". |
| 93 | * base64url output (A–Z a–z 0–9 - _) is a strict subset, so a base64url(randomBytes) verifier |
| 94 | * is always valid; this regex is the validation gate for verifiers received from elsewhere. |
| 95 | */ |
| 96 | const CODE_VERIFIER_CHARSET = /^[A-Za-z0-9\-._~]+$/; |
| 97 | |
| 98 | /** |
| 99 | * RFC 6749 §4.1.2.1 authorization error codes. Only these fixed codes may be surfaced to the |
| 100 | * caller as `errorCode`; an authorization server's free-text `error_description` is NEVER |
| 101 | * surfaced (it is attacker-influenceable and could carry injected content). |
| 102 | * @type {ReadonlySet<string>} |
| 103 | */ |
| 104 | const OAUTH_ERROR_CODES = new Set([ |
| 105 | 'invalid_request', |
| 106 | 'unauthorized_client', |
| 107 | 'access_denied', |
| 108 | 'unsupported_response_type', |
| 109 | 'invalid_scope', |
| 110 | 'server_error', |
| 111 | 'temporarily_unavailable', |
| 112 | ]); |
| 113 | |
| 114 | /** Hard ceiling on any single token-response field length (defense against oversized payloads). */ |
| 115 | const MAX_TOKEN_FIELD_LEN = 8192; |
| 116 | /** Hard ceiling on a JWT/token we will accept (generous; real Knowtation JWTs are < 2 KB). */ |
| 117 | const MAX_ACCESS_TOKEN_LEN = 8192; |
| 118 | |
| 119 | /** |
| 120 | * Constant-time equality for two short ASCII strings (e.g. `state`, `iss`). |
| 121 | * |
| 122 | * Both inputs are hashed to a fixed 32-byte SHA-256 digest before comparison, so: |
| 123 | * - timingSafeEqual always receives equal-length buffers (a raw length mismatch would itself |
| 124 | * be an early-exit oracle), |
| 125 | * - the comparison time is independent of the position of the first differing byte, and |
| 126 | * - different-length inputs simply yield different digests (no length leak via timing). |
| 127 | * |
| 128 | * Non-string or empty inputs return false WITHOUT comparing — absence is not a content oracle. |
| 129 | * |
| 130 | * @param {unknown} a |
| 131 | * @param {unknown} b |
| 132 | * @returns {boolean} |
| 133 | */ |
| 134 | export function constantTimeEqual(a, b) { |
| 135 | if (typeof a !== 'string' || typeof b !== 'string') return false; |
| 136 | if (a.length === 0 || b.length === 0) return false; |
| 137 | const da = crypto.createHash('sha256').update(a, 'utf8').digest(); |
| 138 | const db = crypto.createHash('sha256').update(b, 'utf8').digest(); |
| 139 | return crypto.timingSafeEqual(da, db); |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Compute the S256 PKCE code_challenge for a given code_verifier (RFC 7636 §4.2): |
| 144 | * code_challenge = BASE64URL-ENCODE(SHA-256(ASCII(code_verifier))) |
| 145 | * |
| 146 | * S256 ONLY: there is no `method` parameter and no 'plain' path. The verifier is validated |
| 147 | * against RFC 7636 §4.1 (length + unreserved charset) before hashing; an invalid verifier |
| 148 | * throws a fixed-message error that never contains the verifier. |
| 149 | * |
| 150 | * @param {string} codeVerifier |
| 151 | * @returns {string} base64url(SHA-256(codeVerifier)) |
| 152 | * @throws {TypeError} on a structurally invalid verifier (message carries NO secret) |
| 153 | */ |
| 154 | export function computeCodeChallenge(codeVerifier) { |
| 155 | if ( |
| 156 | typeof codeVerifier !== 'string' || |
| 157 | codeVerifier.length < CODE_VERIFIER_MIN_LEN || |
| 158 | codeVerifier.length > CODE_VERIFIER_MAX_LEN || |
| 159 | !CODE_VERIFIER_CHARSET.test(codeVerifier) |
| 160 | ) { |
| 161 | throw new TypeError('computeCodeChallenge: code_verifier is not a valid RFC 7636 §4.1 verifier'); |
| 162 | } |
| 163 | return crypto.createHash('sha256').update(codeVerifier, 'ascii').digest('base64url'); |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Create a fresh PKCE pair (RFC 7636). The verifier is 32 CSPRNG bytes base64url-encoded |
| 168 | * (43 chars, ≥ 256-bit), the challenge is its S256 transform. |
| 169 | * |
| 170 | * The returned codeVerifier is a SECRET (it must be sent only to the token endpoint over TLS, |
| 171 | * and never logged); the codeChallenge is public (it travels in the authorization URL). |
| 172 | * |
| 173 | * @returns {{ codeVerifier: string, codeChallenge: string, method: 'S256' }} |
| 174 | */ |
| 175 | export function createPkcePair() { |
| 176 | const codeVerifier = crypto.randomBytes(VERIFIER_ENTROPY_BYTES).toString('base64url'); |
| 177 | const codeChallenge = computeCodeChallenge(codeVerifier); |
| 178 | return { codeVerifier, codeChallenge, method: PKCE_METHOD_S256 }; |
| 179 | } |
| 180 | |
| 181 | /** |
| 182 | * Create a high-entropy CSRF `state` value (RFC 6749 §10.12). 32 CSPRNG bytes, base64url. |
| 183 | * `state` is single-use: bind it to the pending request and discard it after one callback. |
| 184 | * @returns {string} |
| 185 | */ |
| 186 | export function createOAuthState() { |
| 187 | return crypto.randomBytes(STATE_ENTROPY_BYTES).toString('base64url'); |
| 188 | } |
| 189 | |
| 190 | /** |
| 191 | * Create a high-entropy OpenID Connect `nonce` (replay binding for an id_token, if used). |
| 192 | * 32 CSPRNG bytes, base64url. |
| 193 | * @returns {string} |
| 194 | */ |
| 195 | export function createNonce() { |
| 196 | return crypto.randomBytes(NONCE_ENTROPY_BYTES).toString('base64url'); |
| 197 | } |
| 198 | |
| 199 | /** |
| 200 | * Validate a redirect URI against RFC 8252 (OAuth 2.0 for Native Apps) loopback rules. |
| 201 | * |
| 202 | * Accepts ONLY: |
| 203 | * - scheme `http` (loopback redirects use plain http per RFC 8252 §7.3; the connection never |
| 204 | * leaves the device), |
| 205 | * - host that is a literal loopback IP — `127.0.0.1` or `[::1]` — (RFC 8252 §8.3 recommends |
| 206 | * literal IPs over the hostname `localhost`, whose resolution depends on local config); |
| 207 | * a caller may widen the allow-set via `allowedHosts` but it is matched as an exact literal |
| 208 | * list, never a wildcard or suffix, |
| 209 | * - an explicit, numeric, in-range port (the ephemeral loopback port; RFC 8252 §7.3 requires |
| 210 | * the AUTH SERVER to permit a variable port for loopback — this validator simply requires a |
| 211 | * concrete port and never a wildcard), |
| 212 | * - no userinfo, no query, no fragment (an exact-match redirect target, no smuggling). |
| 213 | * |
| 214 | * FAIL-CLOSED: anything else returns { ok:false, reason }. The reason never contains the URI. |
| 215 | * |
| 216 | * @param {string} uri |
| 217 | * @param {{ allowedHosts?: string[] }} [opts] |
| 218 | * allowedHosts: exact loopback hostnames permitted. Default ['127.0.0.1','::1']. |
| 219 | * @returns {{ ok: true, host: string, port: number, pathname: string } | { ok: false, reason: string }} |
| 220 | */ |
| 221 | export function validateRedirectUri(uri, opts = {}) { |
| 222 | const allowed = Array.isArray(opts.allowedHosts) && opts.allowedHosts.length > 0 |
| 223 | ? opts.allowedHosts.map((h) => String(h).toLowerCase()) |
| 224 | : ['127.0.0.1', '::1']; |
| 225 | if (typeof uri !== 'string' || uri.length === 0 || uri.length > MAX_TOKEN_FIELD_LEN) { |
| 226 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 227 | } |
| 228 | let parsed; |
| 229 | try { |
| 230 | parsed = new URL(uri); |
| 231 | } catch { |
| 232 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 233 | } |
| 234 | // Plain http only, and only to a loopback literal — never https-to-loopback ambiguity, never |
| 235 | // a custom scheme. (RFC 8252 also defines a private-use-scheme flow; the companion uses the |
| 236 | // loopback flow exclusively, so any non-http scheme is rejected here.) |
| 237 | if (parsed.protocol !== 'http:') { |
| 238 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 239 | } |
| 240 | if (parsed.username !== '' || parsed.password !== '') { |
| 241 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 242 | } |
| 243 | if (parsed.search !== '' || parsed.hash !== '') { |
| 244 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 245 | } |
| 246 | // URL normalises an IPv6 host to bracketed form; strip brackets for the allowlist compare. |
| 247 | const rawHost = parsed.hostname.toLowerCase(); |
| 248 | const host = rawHost.startsWith('[') && rawHost.endsWith(']') ? rawHost.slice(1, -1) : rawHost; |
| 249 | if (!allowed.includes(host)) { |
| 250 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 251 | } |
| 252 | // A concrete numeric in-range port is mandatory (no default-port ambiguity for an ephemeral |
| 253 | // loopback listener; the absence of an explicit port would make the redirect non-exact). |
| 254 | if (parsed.port === '' || !/^[0-9]+$/.test(parsed.port)) { |
| 255 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 256 | } |
| 257 | const port = Number(parsed.port); |
| 258 | if (!Number.isInteger(port) || port < 1 || port > 65535) { |
| 259 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_REDIRECT_URI }; |
| 260 | } |
| 261 | return { ok: true, host, port, pathname: parsed.pathname }; |
| 262 | } |
| 263 | |
| 264 | /** |
| 265 | * Validate a scope list: a non-empty array of non-empty, space-free strings. |
| 266 | * @param {unknown} scopes |
| 267 | * @returns {string[] | null} the cleaned list, or null if invalid |
| 268 | */ |
| 269 | function validateScopes(scopes) { |
| 270 | if (!Array.isArray(scopes) || scopes.length === 0) return null; |
| 271 | const out = []; |
| 272 | for (const s of scopes) { |
| 273 | if (typeof s !== 'string' || s.length === 0 || /\s/.test(s)) return null; |
| 274 | out.push(s); |
| 275 | } |
| 276 | return out; |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * Build the authorization-request URL (RFC 6749 §4.1.1 + RFC 7636 §4.3) for the system browser. |
| 281 | * |
| 282 | * The URL is pure data — Phase 5 hands it to the OS browser; nothing here opens it. The result |
| 283 | * ALWAYS carries `response_type=code`, `code_challenge_method=S256`, the exact (validated) |
| 284 | * loopback `redirect_uri`, the injected `client_id`, the space-joined injected `scope`, and the |
| 285 | * CSRF `state`. It NEVER carries a client secret. If `nonce` is provided it is included. |
| 286 | * |
| 287 | * S256 ONLY: `codeChallengeMethod` defaults to 'S256' and anything else is rejected (no downgrade |
| 288 | * to 'plain'). |
| 289 | * |
| 290 | * @param {{ |
| 291 | * authorizationEndpoint: string, |
| 292 | * clientId: string, |
| 293 | * redirectUri: string, |
| 294 | * scopes: string[], |
| 295 | * state: string, |
| 296 | * codeChallenge: string, |
| 297 | * codeChallengeMethod?: 'S256', |
| 298 | * nonce?: string, |
| 299 | * allowedRedirectHosts?: string[], |
| 300 | * extraParams?: Record<string, string>, |
| 301 | * }} params |
| 302 | * @returns {string} the absolute authorization URL |
| 303 | * @throws {TypeError} on invalid configuration (message carries NO secret) |
| 304 | */ |
| 305 | export function buildAuthorizationUrl(params) { |
| 306 | const { |
| 307 | authorizationEndpoint, |
| 308 | clientId, |
| 309 | redirectUri, |
| 310 | scopes, |
| 311 | state, |
| 312 | codeChallenge, |
| 313 | codeChallengeMethod = PKCE_METHOD_S256, |
| 314 | nonce, |
| 315 | allowedRedirectHosts, |
| 316 | extraParams, |
| 317 | } = params ?? {}; |
| 318 | |
| 319 | if (codeChallengeMethod !== PKCE_METHOD_S256) { |
| 320 | // Refuse to ever construct a 'plain' (or unknown) PKCE request. |
| 321 | throw new TypeError('buildAuthorizationUrl: only S256 PKCE is supported'); |
| 322 | } |
| 323 | if (typeof authorizationEndpoint !== 'string' || authorizationEndpoint.length === 0) { |
| 324 | throw new TypeError('buildAuthorizationUrl: authorizationEndpoint is required'); |
| 325 | } |
| 326 | let endpoint; |
| 327 | try { |
| 328 | endpoint = new URL(authorizationEndpoint); |
| 329 | } catch { |
| 330 | throw new TypeError('buildAuthorizationUrl: authorizationEndpoint is not a valid URL'); |
| 331 | } |
| 332 | if (endpoint.protocol !== 'https:') { |
| 333 | // The authorization endpoint must be HTTPS (the request leaves the device). Loopback http |
| 334 | // is only for the *redirect*, never the authorization server. |
| 335 | throw new TypeError('buildAuthorizationUrl: authorizationEndpoint must be https'); |
| 336 | } |
| 337 | if (typeof clientId !== 'string' || clientId.length === 0) { |
| 338 | throw new TypeError('buildAuthorizationUrl: clientId is required'); |
| 339 | } |
| 340 | const cleanScopes = validateScopes(scopes); |
| 341 | if (!cleanScopes) { |
| 342 | throw new TypeError('buildAuthorizationUrl: scopes must be a non-empty array of tokens'); |
| 343 | } |
| 344 | if (typeof state !== 'string' || state.length === 0) { |
| 345 | throw new TypeError('buildAuthorizationUrl: state is required'); |
| 346 | } |
| 347 | if (typeof codeChallenge !== 'string' || codeChallenge.length === 0) { |
| 348 | throw new TypeError('buildAuthorizationUrl: codeChallenge is required'); |
| 349 | } |
| 350 | const redirect = validateRedirectUri(redirectUri, { allowedHosts: allowedRedirectHosts }); |
| 351 | if (!redirect.ok) { |
| 352 | throw new TypeError('buildAuthorizationUrl: redirectUri is not a valid RFC 8252 loopback URI'); |
| 353 | } |
| 354 | |
| 355 | // Build query deterministically. URLSearchParams handles percent-encoding. |
| 356 | const q = new URLSearchParams(); |
| 357 | q.set('response_type', 'code'); |
| 358 | q.set('client_id', clientId); |
| 359 | q.set('redirect_uri', redirectUri); |
| 360 | q.set('scope', cleanScopes.join(' ')); |
| 361 | q.set('state', state); |
| 362 | q.set('code_challenge', codeChallenge); |
| 363 | q.set('code_challenge_method', PKCE_METHOD_S256); |
| 364 | if (typeof nonce === 'string' && nonce.length > 0) q.set('nonce', nonce); |
| 365 | if (extraParams && typeof extraParams === 'object') { |
| 366 | for (const [k, v] of Object.entries(extraParams)) { |
| 367 | // Never let an injected extra param override a security-critical parameter. |
| 368 | const key = String(k); |
| 369 | if ( |
| 370 | key === 'response_type' || key === 'client_id' || key === 'redirect_uri' || |
| 371 | key === 'scope' || key === 'state' || key === 'code_challenge' || |
| 372 | key === 'code_challenge_method' || key === 'client_secret' |
| 373 | ) { |
| 374 | continue; |
| 375 | } |
| 376 | if (typeof v === 'string') q.set(key, v); |
| 377 | } |
| 378 | } |
| 379 | endpoint.search = q.toString(); |
| 380 | return endpoint.toString(); |
| 381 | } |
| 382 | |
| 383 | /** |
| 384 | * Validate the authorization RESPONSE delivered to the loopback redirect (RFC 6749 §4.1.2, |
| 385 | * RFC 9207 issuer identification). FAIL-CLOSED. |
| 386 | * |
| 387 | * Order of checks (each must pass): |
| 388 | * 1. structural: params is an object; |
| 389 | * 2. error: if the server returned `error`, surface a fixed reason plus the RFC 6749 error |
| 390 | * CODE only when it is a known code (never the free-text error_description); |
| 391 | * 3. state: expectedState present, params.state present, constant-time match (CSRF / fixation); |
| 392 | * 4. issuer (RFC 9207): if `expectedIssuer` is given AND params.iss is present, require a |
| 393 | * constant-time match (mix-up defense). If expectedIssuer is given but iss is absent, this |
| 394 | * is TOLERATED for back-compat (documented server-side follow-up to emit `iss`); a PRESENT |
| 395 | * but mismatched iss is always rejected; |
| 396 | * 5. code: a non-empty `code` must be present; it is returned only in the success channel. |
| 397 | * |
| 398 | * The authorization code and the state value are NEVER placed in a `reason` or thrown error. |
| 399 | * |
| 400 | * @param {{ |
| 401 | * params: Record<string, unknown>, |
| 402 | * expectedState: string, |
| 403 | * expectedIssuer?: string, |
| 404 | * }} args |
| 405 | * @returns {{ ok: true, code: string } | { ok: false, reason: string, errorCode?: string }} |
| 406 | */ |
| 407 | export function validateAuthorizationResponse(args) { |
| 408 | try { |
| 409 | const { params, expectedState, expectedIssuer } = args ?? {}; |
| 410 | if (!params || typeof params !== 'object' || Array.isArray(params)) { |
| 411 | return { ok: false, reason: OAUTH_PKCE_REASONS.MALFORMED_INPUT }; |
| 412 | } |
| 413 | |
| 414 | // 2. Authorization-server error response. |
| 415 | const errRaw = params.error; |
| 416 | if (typeof errRaw === 'string' && errRaw.length > 0) { |
| 417 | const errorCode = OAUTH_ERROR_CODES.has(errRaw) ? errRaw : undefined; |
| 418 | return errorCode |
| 419 | ? { ok: false, reason: OAUTH_PKCE_REASONS.AUTHORIZATION_SERVER_ERROR, errorCode } |
| 420 | : { ok: false, reason: OAUTH_PKCE_REASONS.AUTHORIZATION_SERVER_ERROR }; |
| 421 | } |
| 422 | |
| 423 | // 3. CSRF state — constant-time compare, fail-closed on absence. |
| 424 | if (typeof expectedState !== 'string' || expectedState.length === 0) { |
| 425 | return { ok: false, reason: OAUTH_PKCE_REASONS.STATE_MISSING }; |
| 426 | } |
| 427 | const gotState = params.state; |
| 428 | if (typeof gotState !== 'string' || gotState.length === 0) { |
| 429 | return { ok: false, reason: OAUTH_PKCE_REASONS.STATE_MISSING }; |
| 430 | } |
| 431 | if (!constantTimeEqual(gotState, expectedState)) { |
| 432 | return { ok: false, reason: OAUTH_PKCE_REASONS.STATE_MISMATCH }; |
| 433 | } |
| 434 | |
| 435 | // 4. RFC 9207 issuer — optional-but-validated. |
| 436 | if (typeof expectedIssuer === 'string' && expectedIssuer.length > 0) { |
| 437 | const gotIss = params.iss; |
| 438 | if (typeof gotIss === 'string' && gotIss.length > 0) { |
| 439 | if (!constantTimeEqual(gotIss, expectedIssuer)) { |
| 440 | return { ok: false, reason: OAUTH_PKCE_REASONS.ISSUER_MISMATCH }; |
| 441 | } |
| 442 | } |
| 443 | // iss absent → tolerated (back-compat); documented server-side follow-up. |
| 444 | } |
| 445 | |
| 446 | // 5. Authorization code. |
| 447 | const code = params.code; |
| 448 | if (typeof code !== 'string' || code.length === 0 || code.length > MAX_TOKEN_FIELD_LEN) { |
| 449 | return { ok: false, reason: OAUTH_PKCE_REASONS.MISSING_CODE }; |
| 450 | } |
| 451 | |
| 452 | return { ok: true, code }; |
| 453 | } catch { |
| 454 | // Defense in depth: never let an unexpected error escape with input data attached. |
| 455 | return { ok: false, reason: OAUTH_PKCE_REASONS.MALFORMED_INPUT }; |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | /** |
| 460 | * Build the token-endpoint REQUEST descriptor (RFC 6749 §4.1.3 + RFC 7636 §4.5). PURE — it |
| 461 | * performs NO fetch; Phase 5 sends this descriptor over TLS. |
| 462 | * |
| 463 | * The body carries grant_type=authorization_code, the `code`, the `code_verifier` (this is what |
| 464 | * proves PKCE possession and binds the code to this client), the exact `redirect_uri`, and the |
| 465 | * public-client `client_id`. It NEVER carries a client_secret. |
| 466 | * |
| 467 | * @param {{ |
| 468 | * tokenEndpoint: string, |
| 469 | * clientId: string, |
| 470 | * code: string, |
| 471 | * codeVerifier: string, |
| 472 | * redirectUri: string, |
| 473 | * allowedRedirectHosts?: string[], |
| 474 | * }} params |
| 475 | * @returns {{ url: string, method: 'POST', headers: Record<string,string>, body: string, bodyParams: Record<string,string> }} |
| 476 | * @throws {TypeError} on invalid configuration (message carries NO secret) |
| 477 | */ |
| 478 | export function buildTokenRequest(params) { |
| 479 | const { tokenEndpoint, clientId, code, codeVerifier, redirectUri, allowedRedirectHosts } = params ?? {}; |
| 480 | |
| 481 | if (typeof tokenEndpoint !== 'string' || tokenEndpoint.length === 0) { |
| 482 | throw new TypeError('buildTokenRequest: tokenEndpoint is required'); |
| 483 | } |
| 484 | let endpoint; |
| 485 | try { |
| 486 | endpoint = new URL(tokenEndpoint); |
| 487 | } catch { |
| 488 | throw new TypeError('buildTokenRequest: tokenEndpoint is not a valid URL'); |
| 489 | } |
| 490 | if (endpoint.protocol !== 'https:') { |
| 491 | throw new TypeError('buildTokenRequest: tokenEndpoint must be https'); |
| 492 | } |
| 493 | if (typeof clientId !== 'string' || clientId.length === 0) { |
| 494 | throw new TypeError('buildTokenRequest: clientId is required'); |
| 495 | } |
| 496 | if (typeof code !== 'string' || code.length === 0 || code.length > MAX_TOKEN_FIELD_LEN) { |
| 497 | throw new TypeError('buildTokenRequest: code is required'); |
| 498 | } |
| 499 | if ( |
| 500 | typeof codeVerifier !== 'string' || |
| 501 | codeVerifier.length < CODE_VERIFIER_MIN_LEN || |
| 502 | codeVerifier.length > CODE_VERIFIER_MAX_LEN || |
| 503 | !CODE_VERIFIER_CHARSET.test(codeVerifier) |
| 504 | ) { |
| 505 | throw new TypeError('buildTokenRequest: code_verifier is not a valid RFC 7636 verifier'); |
| 506 | } |
| 507 | const redirect = validateRedirectUri(redirectUri, { allowedHosts: allowedRedirectHosts }); |
| 508 | if (!redirect.ok) { |
| 509 | throw new TypeError('buildTokenRequest: redirectUri is not a valid RFC 8252 loopback URI'); |
| 510 | } |
| 511 | |
| 512 | const bodyParams = { |
| 513 | grant_type: 'authorization_code', |
| 514 | code, |
| 515 | code_verifier: codeVerifier, |
| 516 | redirect_uri: redirectUri, |
| 517 | client_id: clientId, |
| 518 | }; |
| 519 | const body = new URLSearchParams(bodyParams).toString(); |
| 520 | |
| 521 | return { |
| 522 | url: endpoint.toString(), |
| 523 | method: 'POST', |
| 524 | headers: { |
| 525 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 526 | Accept: 'application/json', |
| 527 | }, |
| 528 | body, |
| 529 | bodyParams, |
| 530 | }; |
| 531 | } |
| 532 | |
| 533 | /** |
| 534 | * Build the token-endpoint REQUEST descriptor for a refresh-token grant (RFC 6749 §6). PURE. |
| 535 | * Public client → no client_secret. `scope`, if provided, must be a subset of the original grant. |
| 536 | * |
| 537 | * @param {{ |
| 538 | * tokenEndpoint: string, |
| 539 | * clientId: string, |
| 540 | * refreshToken: string, |
| 541 | * scopes?: string[], |
| 542 | * }} params |
| 543 | * @returns {{ url: string, method: 'POST', headers: Record<string,string>, body: string, bodyParams: Record<string,string> }} |
| 544 | * @throws {TypeError} on invalid configuration (message carries NO secret) |
| 545 | */ |
| 546 | export function buildRefreshRequest(params) { |
| 547 | const { tokenEndpoint, clientId, refreshToken, scopes } = params ?? {}; |
| 548 | if (typeof tokenEndpoint !== 'string' || tokenEndpoint.length === 0) { |
| 549 | throw new TypeError('buildRefreshRequest: tokenEndpoint is required'); |
| 550 | } |
| 551 | let endpoint; |
| 552 | try { |
| 553 | endpoint = new URL(tokenEndpoint); |
| 554 | } catch { |
| 555 | throw new TypeError('buildRefreshRequest: tokenEndpoint is not a valid URL'); |
| 556 | } |
| 557 | if (endpoint.protocol !== 'https:') { |
| 558 | throw new TypeError('buildRefreshRequest: tokenEndpoint must be https'); |
| 559 | } |
| 560 | if (typeof clientId !== 'string' || clientId.length === 0) { |
| 561 | throw new TypeError('buildRefreshRequest: clientId is required'); |
| 562 | } |
| 563 | if (typeof refreshToken !== 'string' || refreshToken.length === 0 || refreshToken.length > MAX_TOKEN_FIELD_LEN) { |
| 564 | throw new TypeError('buildRefreshRequest: refreshToken is required'); |
| 565 | } |
| 566 | const bodyParams = { |
| 567 | grant_type: 'refresh_token', |
| 568 | refresh_token: refreshToken, |
| 569 | client_id: clientId, |
| 570 | }; |
| 571 | if (scopes !== undefined) { |
| 572 | const cleanScopes = validateScopes(scopes); |
| 573 | if (!cleanScopes) throw new TypeError('buildRefreshRequest: scopes must be a non-empty array of tokens'); |
| 574 | bodyParams.scope = cleanScopes.join(' '); |
| 575 | } |
| 576 | const body = new URLSearchParams(bodyParams).toString(); |
| 577 | return { |
| 578 | url: endpoint.toString(), |
| 579 | method: 'POST', |
| 580 | headers: { |
| 581 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 582 | Accept: 'application/json', |
| 583 | }, |
| 584 | body, |
| 585 | bodyParams, |
| 586 | }; |
| 587 | } |
| 588 | |
| 589 | /** |
| 590 | * Validate a parsed token-endpoint RESPONSE (RFC 6749 §5.1 / §5.2). FAIL-CLOSED. |
| 591 | * |
| 592 | * Requires: token_type === 'bearer' (case-insensitive), a non-empty access_token within length |
| 593 | * bounds, and a positive-integer expires_in (the companion needs an expiry to drive refresh; |
| 594 | * the Knowtation provider always emits it). refresh_token is optional but, when present, must be |
| 595 | * a non-empty bounded string. An `error` response, a missing/blank field, a wrong token_type, or |
| 596 | * an oversized field all fail closed. The reason never carries any token value. |
| 597 | * |
| 598 | * @param {unknown} json - the already-parsed JSON object from the token endpoint |
| 599 | * @returns { |
| 600 | * { ok: true, accessToken: string, refreshToken: string | null, expiresIn: number, tokenType: 'Bearer', scope: string | null } |
| 601 | * | { ok: false, reason: string, errorCode?: string } |
| 602 | * } |
| 603 | */ |
| 604 | export function validateTokenResponse(json) { |
| 605 | try { |
| 606 | if (!json || typeof json !== 'object' || Array.isArray(json)) { |
| 607 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 608 | } |
| 609 | const obj = /** @type {Record<string, unknown>} */ (json); |
| 610 | |
| 611 | // Error response (RFC 6749 §5.2). |
| 612 | if (typeof obj.error === 'string' && obj.error.length > 0) { |
| 613 | const errorCode = OAUTH_ERROR_CODES.has(obj.error) || obj.error === 'invalid_grant' || obj.error === 'invalid_client' |
| 614 | ? obj.error |
| 615 | : undefined; |
| 616 | return errorCode |
| 617 | ? { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE, errorCode } |
| 618 | : { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 619 | } |
| 620 | |
| 621 | const tokenType = obj.token_type; |
| 622 | if (typeof tokenType !== 'string' || tokenType.toLowerCase() !== 'bearer') { |
| 623 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 624 | } |
| 625 | |
| 626 | const accessToken = obj.access_token; |
| 627 | if ( |
| 628 | typeof accessToken !== 'string' || |
| 629 | accessToken.length === 0 || |
| 630 | accessToken.length > MAX_ACCESS_TOKEN_LEN |
| 631 | ) { |
| 632 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 633 | } |
| 634 | |
| 635 | const expiresIn = obj.expires_in; |
| 636 | if (typeof expiresIn !== 'number' || !Number.isInteger(expiresIn) || expiresIn <= 0) { |
| 637 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 638 | } |
| 639 | |
| 640 | let refreshToken = null; |
| 641 | if (obj.refresh_token !== undefined) { |
| 642 | if ( |
| 643 | typeof obj.refresh_token !== 'string' || |
| 644 | obj.refresh_token.length === 0 || |
| 645 | obj.refresh_token.length > MAX_TOKEN_FIELD_LEN |
| 646 | ) { |
| 647 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 648 | } |
| 649 | refreshToken = obj.refresh_token; |
| 650 | } |
| 651 | |
| 652 | let scope = null; |
| 653 | if (obj.scope !== undefined) { |
| 654 | if (typeof obj.scope !== 'string' || obj.scope.length > MAX_TOKEN_FIELD_LEN) { |
| 655 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 656 | } |
| 657 | scope = obj.scope; |
| 658 | } |
| 659 | |
| 660 | return { ok: true, accessToken, refreshToken, expiresIn, tokenType: 'Bearer', scope }; |
| 661 | } catch { |
| 662 | return { ok: false, reason: OAUTH_PKCE_REASONS.INVALID_TOKEN_RESPONSE }; |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | /** |
| 667 | * Decide what to do with a stored access token given the current clock. PURE. |
| 668 | * |
| 669 | * - 'valid' — the access token is still good (now + skew < expiresAt). |
| 670 | * - 'refresh' — the access token is at/past its skew-adjusted expiry but a refresh is still |
| 671 | * viable (no refreshExpiresAt given, or now < refreshExpiresAt). |
| 672 | * - 'reauth' — full re-authentication is required (refresh window elapsed, or inputs are |
| 673 | * missing/malformed → fail-closed to the safest outcome: force a fresh login). |
| 674 | * |
| 675 | * Times are epoch-ms numbers; `now` is injected (never read from the clock here). |
| 676 | * |
| 677 | * @param {{ expiresAt: number, now: number, skewMs?: number, refreshExpiresAt?: number }} params |
| 678 | * @returns {'valid' | 'refresh' | 'reauth'} |
| 679 | */ |
| 680 | export function decideTokenRefresh(params) { |
| 681 | const { expiresAt, now, skewMs = 30_000, refreshExpiresAt } = params ?? {}; |
| 682 | // Fail-closed: anything we cannot reason about forces re-auth (never falsely "valid"). |
| 683 | if (typeof now !== 'number' || !Number.isFinite(now)) return 'reauth'; |
| 684 | if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return 'reauth'; |
| 685 | const skew = typeof skewMs === 'number' && Number.isFinite(skewMs) && skewMs >= 0 ? skewMs : 30_000; |
| 686 | |
| 687 | if (now + skew < expiresAt) return 'valid'; |
| 688 | |
| 689 | // Access token expired (within skew). Is a refresh still in its window? |
| 690 | if (typeof refreshExpiresAt === 'number' && Number.isFinite(refreshExpiresAt)) { |
| 691 | return now < refreshExpiresAt ? 'refresh' : 'reauth'; |
| 692 | } |
| 693 | // No explicit refresh ceiling supplied → attempt refresh (the endpoint is the source of truth). |
| 694 | return 'refresh'; |
| 695 | } |
File History
2 commits
sha256:65ccb454656ea5acdea0a10e559b78bcde1eb6ff753ecc2911bc99d1c3d7cadd
feat(calendar): enforce agent context tiers in retrieval AP…
Human
minor
⚠
1 day ago
sha256:9103f98c89257ed2b01c237cea895dabb3e85ea337dccb1161c175e4422355b6
docs: accept Calendar Events v0 spec with Phase 0 security …
Human
1 day ago