feat(jwt): load signing keys at boot as a named plugin
Extracted from patitas-peludas onto the object plugin contract. Core is a type import only, so installing the plugin never drags in a second core or a version warning; a bad key still fails boot, which the contract tests now pin. The extraction moves from jose 5 to jose 6, and that is not a version bump: jose 6 refuses a private CryptoKey in jwtVerify, where jose 5 accepted one and derived the public half itself. The original keeps a single key per signer and verifies with the key it signed with, which works on 5 and throws "CryptoKey instances must be of type public" on 6 — for every asymmetric algorithm, so ES*, RS*, PS* and EdDSA alike. Symmetric keys are unaffected, which is exactly why one HS256 test would have shipped it. importJWKKey now imports the key twice for an asymmetric pair: as given, to sign with, and with the private fields stripped, to verify with. A symmetric key has no public half, so it keeps one secret for both. The round-trip is covered per algorithm family rather than once, because one algorithm is not coverage — it is the gap the defect lived in. The get() helper in the contract tests is generic in its body: Response.json() is typed Promise<unknown>, so reaching into the payload did not typecheck. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+405
No files matched your search
@@ -0,0 +1,87 @@
|
||||
import type { Plugin } from '@green-tea/core';
|
||||
import type { JWK } from 'jose';
|
||||
|
||||
import { importJWKKey, readPublicJWK } from './keys.ts';
|
||||
import { Signer } from './signer.ts';
|
||||
import type { JwtKeyConfig, JwtOptions } from './types.ts';
|
||||
|
||||
export { Signer } from './signer.ts';
|
||||
export { importJWKKey, readPublicJWK } from './keys.ts';
|
||||
export type { ImportedJWK, JwtKeyConfig, JwtOptions, JwtSettings, KeyMaterial } from './types.ts';
|
||||
|
||||
/** The value published into the graph: every configured signer, by name. */
|
||||
export class JwtRegistry<Name extends string = string> {
|
||||
constructor(
|
||||
private readonly signers: Map<Name, Signer>,
|
||||
private readonly paths: Map<Name, string>,
|
||||
) {}
|
||||
|
||||
get(name: Name): Signer {
|
||||
const signer = this.signers.get(name);
|
||||
// Reachable only through a typo in a key name — the configured set is fixed at boot.
|
||||
if (!signer) throw new Error(`Unknown JWT signer "${name}". Configured: ${[...this.signers.keys()].join(', ')}`);
|
||||
return signer;
|
||||
}
|
||||
|
||||
names(): Name[] {
|
||||
return [...this.signers.keys()];
|
||||
}
|
||||
|
||||
/** The public half of a key, for serving at a JWKS endpoint. */
|
||||
async publicJwk(name: Name): Promise<JWK> {
|
||||
const path = this.paths.get(name);
|
||||
if (!path) throw new Error(`Unknown JWT signer "${name}"`);
|
||||
return await readPublicJWK(path);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRegistry<Name extends string>(entries: Array<[Name, JwtKeyConfig]>): Promise<JwtRegistry<Name>> {
|
||||
const signers = new Map<Name, Signer>();
|
||||
const paths = new Map<Name, string>();
|
||||
|
||||
for (const [name, config] of entries) {
|
||||
signers.set(name, new Signer(await importJWKKey(config.path), config.settings));
|
||||
paths.set(name, config.path);
|
||||
}
|
||||
|
||||
return new JwtRegistry(signers, paths);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads signing keys while providers boot and publishes them as one graph node.
|
||||
*
|
||||
* Keys are read once, in the provider's `run`, so a missing or malformed key fails `app.listen()` or
|
||||
* `app.boot()` instead of turning the first sign-in of the day into a 500. Nothing loads lazily and
|
||||
* nothing is cached in the module registry. A key read once holds nothing open, so there is no
|
||||
* `onShutdown` (convention rule 7).
|
||||
*
|
||||
* @example
|
||||
* const app = createApp({
|
||||
* modules: [AuthModule],
|
||||
* plugins: [jwt({ keys: { access: { path: '/etc/keys/access.json', settings: { maxAge: '15m' } } } })],
|
||||
* });
|
||||
*
|
||||
* @example <caption>In a handler.</caption>
|
||||
* @Post('/signin')
|
||||
* async signIn(@needs('jwt') jwt: JwtRegistry) {
|
||||
* return { token: await jwt.get('access').sign({ sub: user.id }) };
|
||||
* }
|
||||
*/
|
||||
export function jwt<Name extends string>(options: JwtOptions<Name>): Plugin {
|
||||
const provides = options.provides ?? 'jwt';
|
||||
const entries = Object.entries(options.keys) as Array<[Name, JwtKeyConfig]>;
|
||||
|
||||
return {
|
||||
// Rule 2: plugin name, node name and provided token are one string.
|
||||
name: provides,
|
||||
mount({ scope }) {
|
||||
scope.add({
|
||||
kind: 'provider',
|
||||
name: provides,
|
||||
needs: [],
|
||||
provides: [provides],
|
||||
run: async () => ({ [provides]: await loadRegistry(entries) }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
import { importJWK, type JWK } from 'jose';
|
||||
|
||||
import type { ImportedJWK, KeyMaterial } from './types.ts';
|
||||
|
||||
/**
|
||||
* Reads a JWK from disk.
|
||||
*
|
||||
* `readFile` + `JSON.parse` rather than `await import(path)`: a dynamic import of a JSON file is cached
|
||||
* by the module registry for the life of the process, resolves differently under CommonJS and ESM, and
|
||||
* puts private key material into a module cache anything in the process can read.
|
||||
*/
|
||||
async function readJWK(filePath: string): Promise<JWK> {
|
||||
return JSON.parse(await readFile(filePath, 'utf8')) as JWK;
|
||||
}
|
||||
|
||||
const PRIVATE_FIELDS = new Set(['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'key_ops']);
|
||||
|
||||
/** Whether the key is symmetric, in which case one secret both signs and verifies. */
|
||||
function isSymmetric(jwk: JWK): boolean {
|
||||
return jwk.kty === 'oct' || 'k' in jwk;
|
||||
}
|
||||
|
||||
/** The same JWK with every private field removed. */
|
||||
function publicHalf(jwk: JWK): JWK {
|
||||
return Object.fromEntries(Object.entries(jwk).filter(([field]) => !PRIVATE_FIELDS.has(field))) as JWK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and imports a JWK file, keeping the algorithm and key id it declares.
|
||||
*
|
||||
* Imports the key **twice** for an asymmetric pair: once as given, to sign with, and once with the
|
||||
* private fields stripped, to verify with. That is not redundancy — jose 6 rejects a private
|
||||
* `CryptoKey` in `jwtVerify` with `CryptoKey instances must be of type "public"`, where jose 5
|
||||
* accepted one and derived the public half itself. A signer that kept a single key therefore signed
|
||||
* fine and threw on every verification, for every asymmetric algorithm, which is all of ES*, RS*,
|
||||
* PS* and EdDSA.
|
||||
*
|
||||
* A symmetric key has no public half to derive, so it verifies with the same secret it signs with.
|
||||
*/
|
||||
export async function importJWKKey(filePath: string): Promise<ImportedJWK> {
|
||||
const jwk = await readJWK(filePath);
|
||||
const key: KeyMaterial = await importJWK(jwk, jwk.alg);
|
||||
const verifyKey: KeyMaterial = isSymmetric(jwk) ? key : await importJWK(publicHalf(jwk), jwk.alg);
|
||||
|
||||
return { key, verifyKey, alg: jwk.alg, kid: jwk.kid };
|
||||
}
|
||||
|
||||
/** Strips every private field, so the result is safe to serve at a JWKS endpoint. */
|
||||
export async function readPublicJWK(filePath: string): Promise<JWK> {
|
||||
const jwk = await readJWK(filePath);
|
||||
|
||||
if (isSymmetric(jwk)) {
|
||||
throw new Error('A JWKS endpoint requires an asymmetric key; a symmetric JWK has no public half to publish.');
|
||||
}
|
||||
|
||||
return { ...publicHalf(jwk), use: 'sig', key_ops: ['verify'] };
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { SignJWT, errors, jwtVerify, type JWTPayload } from 'jose';
|
||||
|
||||
import type { ImportedJWK, JwtSettings, KeyMaterial } from './types.ts';
|
||||
|
||||
/** Signs and verifies with one key. */
|
||||
export class Signer {
|
||||
private readonly key: KeyMaterial;
|
||||
/** Separate from `key`: jose 6 will not verify with a private one. See `importJWKKey`. */
|
||||
private readonly verifyKey: KeyMaterial;
|
||||
private readonly algorithm: string;
|
||||
private readonly kid?: string;
|
||||
|
||||
constructor(
|
||||
jwk: ImportedJWK,
|
||||
private readonly settings: JwtSettings = {},
|
||||
) {
|
||||
this.key = jwk.key;
|
||||
this.verifyKey = jwk.verifyKey;
|
||||
this.algorithm = jwk.alg ?? '';
|
||||
this.kid = jwk.kid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Issues a token, stamping `iat` and a random `jti`.
|
||||
*
|
||||
* The `jti` is what makes a token revocable — without it the only way to retire a token early is to
|
||||
* rotate the key and invalidate everyone's. `crypto.randomUUID` is the Web Crypto global, present on
|
||||
* every runtime this package declares, so nothing is imported from `node:crypto`.
|
||||
*/
|
||||
async sign<T = JWTPayload>(payload: T & JWTPayload, overrides: JwtSettings = {}): Promise<string> {
|
||||
const { audience, issuer, maxAge } = { ...this.settings, ...overrides };
|
||||
const jwt = new SignJWT(payload).setProtectedHeader({ alg: this.algorithm, kid: this.kid });
|
||||
|
||||
if (audience) jwt.setAudience(audience);
|
||||
if (issuer) jwt.setIssuer(issuer);
|
||||
jwt.setIssuedAt();
|
||||
jwt.setJti(crypto.randomUUID());
|
||||
if (maxAge) jwt.setExpirationTime(maxAge);
|
||||
|
||||
return await jwt.sign(this.key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies signature, issuer and audience.
|
||||
*
|
||||
* @param ignoreExpiration returns the payload of an expired token instead of throwing. Only for refresh
|
||||
* flows that need the claims of a token they already know has expired — never for authenticating a
|
||||
* request.
|
||||
*/
|
||||
async verify<T = JWTPayload>(token: string, ignoreExpiration = false): Promise<T> {
|
||||
const { issuer, audience } = this.settings;
|
||||
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, this.verifyKey, { issuer, audience });
|
||||
return payload as T;
|
||||
} catch (error) {
|
||||
if (ignoreExpiration && error instanceof errors.JWTExpired) return error.payload as T;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Signs with no managed claims — no audience, issuer, expiry or jti. */
|
||||
async signUnmanaged<T = JWTPayload>(payload: T & JWTPayload): Promise<string> {
|
||||
return await new SignJWT(payload).setProtectedHeader({ alg: this.algorithm, kid: this.kid }).sign(this.key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { CryptoKey, JWK } from 'jose';
|
||||
|
||||
/** What jose signs and verifies with: an imported asymmetric key, or the bytes of a symmetric one. */
|
||||
export type KeyMaterial = CryptoKey | Uint8Array;
|
||||
|
||||
/** A JWK imported from disk, with the algorithm and key id it declares. */
|
||||
export interface ImportedJWK {
|
||||
/** Signs. The private half of an asymmetric pair, or the secret of a symmetric key. */
|
||||
key: KeyMaterial;
|
||||
/**
|
||||
* Verifies. The public half for an asymmetric key, and the same secret again for a symmetric one.
|
||||
*
|
||||
* Kept separate because jose 6 refuses a private `CryptoKey` in `jwtVerify` — see `importJWKKey`.
|
||||
*/
|
||||
verifyKey: KeyMaterial;
|
||||
alg?: string;
|
||||
kid?: string;
|
||||
}
|
||||
|
||||
/** Claim defaults applied to every token a signer issues. */
|
||||
export interface JwtSettings {
|
||||
audience?: string;
|
||||
issuer?: string;
|
||||
/** Anything jose's `setExpirationTime` accepts — `'15m'`, `'1h'`, a timestamp. */
|
||||
maxAge?: string;
|
||||
}
|
||||
|
||||
export interface JwtKeyConfig {
|
||||
/** Path to a JWK file. Resolved as given, so pass an absolute path if unsure. */
|
||||
path: string;
|
||||
settings?: JwtSettings;
|
||||
}
|
||||
|
||||
export interface JwtOptions<Name extends string = string> {
|
||||
/** One entry per signing key. The names become the keys of the published registry. */
|
||||
keys: Record<Name, JwtKeyConfig>;
|
||||
/** Graph name the registry is published under, and the plugin's name. Defaults to `jwt`. */
|
||||
provides?: string;
|
||||
}
|
||||
|
||||
export type { JWK };
|
||||
Reference in new issue
Block a user