UNPKG

@atproto/jwk

Version:

A library for working with JSON Web Keys (JWKs) in TypeScript. This is meant to be extended by environment-specific libraries like @atproto/jwk-jose.

216 lines 10.2 kB
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; import { ERR_JWKS_NO_MATCHING_KEY, ERR_JWK_NOT_FOUND, ERR_JWT_INVALID, JwkError, JwtCreateError, JwtVerifyError, } from './errors.js'; import { unsafeDecodeJwt } from './jwt-decode.js'; import { cachedGetter, isDefined, matchesAny, preferredOrderCmp, } from './util.js'; const extractPrivateJwk = (key) => key.privateJwk; const extractPublicJwk = (key) => key.publicJwk; let Keyset = (() => { let _instanceExtraInitializers = []; let _get_signAlgorithms_decorators; let _get_publicJwks_decorators; let _get_privateJwks_decorators; return class Keyset { static { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; __esDecorate(this, null, _get_signAlgorithms_decorators, { kind: "getter", name: "signAlgorithms", static: false, private: false, access: { has: obj => "signAlgorithms" in obj, get: obj => obj.signAlgorithms }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(this, null, _get_publicJwks_decorators, { kind: "getter", name: "publicJwks", static: false, private: false, access: { has: obj => "publicJwks" in obj, get: obj => obj.publicJwks }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(this, null, _get_privateJwks_decorators, { kind: "getter", name: "privateJwks", static: false, private: false, access: { has: obj => "privateJwks" in obj, get: obj => obj.privateJwks }, metadata: _metadata }, null, _instanceExtraInitializers); if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); } constructor(iterable, /** * The preferred algorithms to use when signing a JWT using this keyset. * * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-3.1} */ preferredSigningAlgorithms = iterable instanceof Keyset ? [...iterable.preferredSigningAlgorithms] : [ // Prefer elliptic curve algorithms 'EdDSA', 'ES256K', 'ES256', // https://datatracker.ietf.org/doc/html/rfc7518#section-3.5 'PS256', 'PS384', 'PS512', 'HS256', 'HS384', 'HS512', ]) { this.preferredSigningAlgorithms = (__runInitializers(this, _instanceExtraInitializers), preferredSigningAlgorithms); const keys = []; const keyIds = new Set(); for (const key of iterable) { if (!key) continue; keys.push(key); if (key.kid) { if (keyIds.has(key.kid)) throw new JwkError(`Duplicate key: ${key.kid}`); else keyIds.add(key.kid); } } this.keys = Object.freeze(keys); } get size() { return this.keys.length; } get signAlgorithms() { const algorithms = new Set(); for (const key of this) { if (key.use !== 'sig') continue; for (const alg of key.algorithms) { algorithms.add(alg); } } return Object.freeze([...algorithms].sort(preferredOrderCmp(this.preferredSigningAlgorithms))); } get publicJwks() { return Object.freeze({ keys: Object.freeze(Array.from(this, extractPublicJwk).filter(isDefined)), }); } get privateJwks() { return Object.freeze({ keys: Object.freeze(Array.from(this, extractPrivateJwk).filter(isDefined)), }); } has(kid) { return this.keys.some((key) => key.kid === kid); } get(options) { const key = this.find(options); if (key) return key; throw new JwkError(`Key not found ${options.kid ?? options.alg ?? options.usage ?? '<unknown>'}`, ERR_JWK_NOT_FOUND); } find(options) { for (const key of this.list(options)) { return key; } return undefined; } *list(options) { for (const key of this) { if (key.isActive(options) && key.matches(options)) { yield key; } } } findPrivateKey({ kid, alg, usage, ...options }) { const matchingKeys = []; // Allow the loop bellow to return early when a single "alg" is provided if (Array.isArray(alg) && alg.length === 1) alg = alg[0]; for (const key of this.list({ ...options, kid, alg, usage })) { // Skip negotiation if a single "alg" was provided if (typeof alg === 'string') return { key, alg }; matchingKeys.push(key); } const isAllowedAlg = matchesAny(alg); const candidates = matchingKeys.map((key) => [key, key.algorithms.filter(isAllowedAlg)]); // Return the first candidates that matches the preferred algorithms for (const prefAlg of this.preferredSigningAlgorithms) { for (const [matchingKey, matchingAlgs] of candidates) { if (matchingAlgs.includes(prefAlg)) { return { key: matchingKey, alg: prefAlg }; } } } // Return any candidate for (const [matchingKey, matchingAlgs] of candidates) { for (const alg of matchingAlgs) { return { key: matchingKey, alg }; } } throw new JwkError(`No private key found for ${kid || alg || usage}`, ERR_JWK_NOT_FOUND); } [(_get_signAlgorithms_decorators = [cachedGetter], _get_publicJwks_decorators = [cachedGetter], _get_privateJwks_decorators = [cachedGetter], Symbol.iterator)]() { return this.keys.values(); } async createJwt({ alg: sAlg, kid: sKid, ...header }, payload) { try { const { key, alg } = this.findPrivateKey({ alg: sAlg, kid: sKid, usage: 'sign', allowRevoked: false, // For explicitness (default value is false) }); const protectedHeader = { ...header, alg, kid: key.kid }; if (typeof payload === 'function') { payload = await payload(protectedHeader, key); } return await key.createJwt(protectedHeader, payload); } catch (err) { throw JwtCreateError.from(err); } } async verifyJwt(token, options) { const { header } = unsafeDecodeJwt(token); const { kid, alg } = header; const errors = []; for (const key of this.list({ ...options, kid, alg, usage: 'verify' })) { try { const result = await key.verifyJwt(token, options); return { ...result, key }; } catch (err) { errors.push(err); } } switch (errors.length) { case 0: throw new JwtVerifyError('No key matched', ERR_JWKS_NO_MATCHING_KEY); case 1: throw JwtVerifyError.from(errors[0], ERR_JWT_INVALID); default: throw JwtVerifyError.from(errors, ERR_JWT_INVALID); } } toJSON() { // Make a copy to allow mutation of the result return structuredClone(this.publicJwks); } }; })(); export { Keyset }; //# sourceMappingURL=keyset.js.map