/**
* Decodes a JWT segment without verifying the signature. Verification, where
* this SDK needs it, stays in `Auth#verify` (the one place that actually
* checks a signature against a JWKS) — this module is only for reading
* claims out of a token whose signature is either irrelevant to the caller
* (it'll be verified server-side when the request lands) or already been
* checked elsewhere.
*
* Shared by `Auth` (decodes tokens obtained from OAuth flows) and
* `InsightsService` (a script-scoped client decodes its own token to read
* its `sourceId`/`permissions` claims). `Buffer` is used deliberately over
* `atob` — it's UTF-8-aware (claims like a tenant's display name can contain
* non-ASCII characters) and, confirmed via a live check, is available as a
* global in Deno as well as Node, so this stays usable from either runtime.
*
* @module jwt
*/
const decodeJwtSegment = (token, index) => {
const parts = typeof token === 'string' ? token.split('.') : []
if (parts.length !== 3) throw new Error('sdk/invalid-token-format')
try {
return JSON.parse(Buffer.from(parts[index], 'base64url').toString('utf8'))
} catch (e) {
throw new Error('sdk/invalid-token-format')
}
}
export const decodeJwtHeader = token => decodeJwtSegment(token, 0)
export const decodeJwtPayload = token => decodeJwtSegment(token, 1)
Source