@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.
241 lines • 11.9 kB
JavaScript
;
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Keyset = void 0;
const errors_js_1 = require("./errors.js");
const jwt_decode_js_1 = require("./jwt-decode.js");
const util_js_1 = require("./util.js");
const extractPrivateJwk = (key) => key.privateJwk;
const extractPublicJwk = (key) => key.publicJwk;
let Keyset = (() => {
var _a;
let _instanceExtraInitializers = [];
let _get_signAlgorithms_decorators;
let _get_publicJwks_decorators;
let _get_privateJwks_decorators;
return _a = class Keyset {
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
_a
? [...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',
]) {
Object.defineProperty(this, "preferredSigningAlgorithms", {
enumerable: true,
configurable: true,
writable: true,
value: (__runInitializers(this, _instanceExtraInitializers), preferredSigningAlgorithms)
});
Object.defineProperty(this, "keys", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
const keys = [];
const kids = new Set();
for (const key of iterable) {
if (!key)
continue;
keys.push(key);
if (key.kid) {
if (kids.has(key.kid))
throw new errors_js_1.JwkError(`Duplicate key: ${key.kid}`);
else
kids.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((0, util_js_1.preferredOrderCmp)(this.preferredSigningAlgorithms)));
}
get publicJwks() {
return {
keys: Array.from(this, extractPublicJwk).filter(util_js_1.isDefined),
};
}
get privateJwks() {
return {
keys: Array.from(this, extractPrivateJwk).filter(util_js_1.isDefined),
};
}
has(kid) {
return this.keys.some((key) => key.kid === kid);
}
get(search) {
for (const key of this.list(search)) {
return key;
}
throw new errors_js_1.JwkError(`Key not found ${search.kid || search.alg || '<unknown>'}`, errors_js_1.ERR_JWK_NOT_FOUND);
}
*list(search) {
// Optimization: Empty string or empty array will not match any key
if (search.kid?.length === 0)
return;
if (search.alg?.length === 0)
return;
for (const key of this) {
if (search.use && key.use !== search.use)
continue;
if (Array.isArray(search.kid)) {
if (!key.kid || !search.kid.includes(key.kid))
continue;
}
else if (search.kid) {
if (key.kid !== search.kid)
continue;
}
if (Array.isArray(search.alg)) {
if (!search.alg.some((a) => key.algorithms.includes(a)))
continue;
}
else if (typeof search.alg === 'string') {
if (!key.algorithms.includes(search.alg))
continue;
}
yield key;
}
}
findKey({ kid, alg, use }) {
const matchingKeys = [];
for (const key of this.list({ kid, alg, use })) {
// Not a signing key
if (!key.isPrivate)
continue;
// Skip negotiation if a specific "alg" was provided
if (typeof alg === 'string')
return [key, alg];
matchingKeys.push(key);
}
const isAllowedAlg = (0, util_js_1.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 [matchingKey, prefAlg];
}
}
// Return any candidate
for (const [matchingKey, matchingAlgs] of candidates) {
for (const alg of matchingAlgs) {
return [matchingKey, alg];
}
}
throw new errors_js_1.JwkError(`No singing key found for ${kid || alg || use || '<unknown>'}`, errors_js_1.ERR_JWK_NOT_FOUND);
}
[(_get_signAlgorithms_decorators = [util_js_1.cachedGetter], _get_publicJwks_decorators = [util_js_1.cachedGetter], _get_privateJwks_decorators = [util_js_1.cachedGetter], Symbol.iterator)]() {
return this.keys.values();
}
async createJwt({ alg: sAlg, kid: sKid, ...header }, payload) {
try {
const [key, alg] = this.findKey({ alg: sAlg, kid: sKid, use: 'sig' });
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 errors_js_1.JwtCreateError.from(err);
}
}
async verifyJwt(token, options) {
const { header } = (0, jwt_decode_js_1.unsafeDecodeJwt)(token);
const { kid, alg } = header;
const errors = [];
for (const key of this.list({ kid, alg })) {
try {
const result = await key.verifyJwt(token, options);
return { ...result, key };
}
catch (err) {
errors.push(err);
}
}
switch (errors.length) {
case 0:
throw new errors_js_1.JwtVerifyError('No key matched', errors_js_1.ERR_JWKS_NO_MATCHING_KEY);
case 1:
throw errors_js_1.JwtVerifyError.from(errors[0], errors_js_1.ERR_JWT_INVALID);
default:
throw errors_js_1.JwtVerifyError.from(errors, errors_js_1.ERR_JWT_INVALID);
}
}
toJSON() {
// Make a copy to prevent mutation of the original keyset
return structuredClone(this.publicJwks);
}
},
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
__esDecorate(_a, 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(_a, 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(_a, 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(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
})(),
_a;
})();
exports.Keyset = Keyset;
//# sourceMappingURL=keyset.js.map