import { createRemoteJWKSet, customFetch, jwtVerify } from 'jose'; import { boundedBody, failure } from './http.mjs'; // Access JWTs and owner-issued opaque credentials are different, explicit contracts. // Only the configured issuer receives credentials; active-token results are never cached. export function createPrincipalVerifier(config, fetcher = fetch) { const keys = createRemoteJWKSet(new URL(config.jwks), { timeoutDuration: 5000, [customFetch]: async (url, init) => { const response = await fetcher(url, { ...init, redirect: 'error' }); const body = await boundedBody(response, 65536, 5000); return new Response(body, { status: response.status, headers: response.headers }); }, }); return async (authorization, write = false) => { const bearer = /^Bearer ([A-Za-z0-9._~-]{1,4096})$/.exec(authorization ?? '')?.[1]; if (!bearer) throw failure('invalid_token', 401); const signed = config.authMode === 'owner-signed'; let payload; if (!signed) { try { payload = ( await jwtVerify(bearer, keys, { issuer: config.issuer, audience: config.resource, requiredClaims: ['sub', 'exp', 'iat', 'organization_id', 'scope'], algorithms: ['EdDSA', 'ES256', 'RS256'], clockTolerance: 0, }) ).payload; } catch { throw failure('invalid_token', 401); } } const response = await fetcher(config.introspection, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(5000), headers: { Authorization: `Basic ${Buffer.from(`${encodeURIComponent(config.clientId)}:${encodeURIComponent(config.secret)}`).toString('base64')}`, 'Content-Type': 'application/x-www-form-urlencoded', Accept: signed ? 'application/token-introspection+jwt' : 'application/json', }, body: new URLSearchParams({ token: bearer, token_type_hint: 'access_token' }), }); if (!response.ok) throw failure('authorization_unavailable', 503); let info; try { const body = await boundedBody(response, 16384, 5000); if (signed) { if (response.headers.get('content-type')?.split(';')[0] !== 'application/token-introspection+jwt') throw new Error('Signed response required'); const verified = await jwtVerify(body, keys, { issuer: config.issuer, audience: config.clientId, algorithms: ['ES256'], requiredClaims: ['iss', 'aud', 'iat'], maxTokenAge: '60s', clockTolerance: 0, }); if (verified.protectedHeader.typ !== 'token-introspection+jwt') throw new Error('Invalid type'); info = verified.payload.token_introspection; const now = Date.now() / 1000; if ( !info || typeof info !== 'object' || Array.isArray(info) || info.active !== true || info.iss !== config.issuer || (info.aud !== config.resource && !(Array.isArray(info.aud) && info.aud.length === 1 && info.aud[0] === config.resource)) || !Number.isSafeInteger(info.iat) || info.iat > now || now - info.iat > 300 || !Number.isSafeInteger(info.exp) || info.exp <= now || info.exp <= info.iat || info.exp - info.iat > 300 || (info.nbf !== undefined && (!Number.isSafeInteger(info.nbf) || info.nbf > now)) || info.token_type !== 'Bearer' || info.observe_workspace !== config.workspace || typeof info.scope !== 'string' || info.scope.length > 512 || info.scope .split(' ') .some( scope => !['observe:connections:read', 'observe:connections:write', 'openid', 'offline_access'].includes(scope), ) ) throw new Error('Invalid bound active token'); payload = { sub: info.sub, organization_id: config.workspace, scope: info.scope }; } else { info = JSON.parse(body); if ( info.active !== true || info.sub !== payload.sub || info.organization_id !== payload.organization_id || info.iss !== config.issuer || (info.aud !== config.resource && !(Array.isArray(info.aud) && info.aud.includes(config.resource))) ) throw new Error('Invalid active token'); } if ( typeof payload.sub !== 'string' || payload.sub.length < 1 || payload.sub.length > 128 || typeof payload.organization_id !== 'string' || payload.organization_id.length < 1 || payload.organization_id.length > 128 ) throw new Error('Invalid principal'); } catch { throw failure('invalid_token', 401); } const issued = typeof payload.scope === 'string' ? payload.scope.split(' ') : []; const scopes = typeof info.scope === 'string' ? info.scope.split(' ').filter(scope => issued.includes(scope)) : []; if (!scopes.includes(config.readScope) || (write && !scopes.includes(config.writeScope))) throw failure('insufficient_scope'); return { tenant: payload.organization_id, account: payload.sub, scopes }; }; }