@leed-ai/git-gateway-auth-jwt 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +24 -2
- package/dist/base64url.d.ts +5 -0
- package/dist/base64url.js +17 -0
- package/dist/base64url.js.map +1 -0
- package/dist/jwks-Bk8zq_xG.d.ts +48 -0
- package/dist/jwks-source.d.ts +30 -0
- package/dist/jwks-source.js +84 -0
- package/dist/jwks-source.js.map +1 -0
- package/dist/jwt-authenticator.d.ts +25 -0
- package/dist/jwt-authenticator.js +72 -0
- package/dist/jwt-authenticator.js.map +1 -0
- package/dist/jwt-verify.d.ts +18 -0
- package/dist/jwt-verify.js +157 -0
- package/dist/jwt-verify.js.map +1 -0
- package/dist/package-name.d.ts +3 -0
- package/dist/package-name.js +6 -0
- package/dist/package-name.js.map +1 -0
- package/dist/schemas/jwks.d.ts +2 -0
- package/dist/schemas/jwks.js +67 -0
- package/dist/schemas/jwks.js.map +1 -0
- package/dist/schemas/jwt-algorithm.d.ts +17 -0
- package/dist/schemas/jwt-algorithm.js +35 -0
- package/dist/schemas/jwt-algorithm.js.map +1 -0
- package/dist/schemas/jwt-authenticator-config.d.ts +41 -0
- package/dist/schemas/jwt-authenticator-config.js +57 -0
- package/dist/schemas/jwt-authenticator-config.js.map +1 -0
- package/dist/schemas/jwt-parts.d.ts +20 -0
- package/dist/schemas/jwt-parts.js +40 -0
- package/dist/schemas/jwt-parts.js.map +1 -0
- package/package.json +103 -4
- package/src/base64url.ts +16 -0
- package/src/jwks-source.ts +109 -0
- package/src/jwt-authenticator.ts +100 -0
- package/src/jwt-verify.ts +135 -0
- package/src/package-name.ts +4 -0
- package/src/schemas/jwks.ts +96 -0
- package/src/schemas/jwt-algorithm.ts +28 -0
- package/src/schemas/jwt-authenticator-config.ts +111 -0
- package/src/schemas/jwt-parts.ts +60 -0
package/src/base64url.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
/** Decodes unpadded base64url (RFC 4648 §5) into bytes; throws on characters outside the alphabet. */
|
|
4
|
+
export function decodeBase64Url(text: string): Uint8Array {
|
|
5
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error('not base64url');
|
|
6
|
+
const base64 = text.replaceAll('-', '+').replaceAll('_', '/');
|
|
7
|
+
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
|
8
|
+
return Uint8Array.from(atob(padded), (char) => char.codePointAt(0) ?? 0);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Encodes bytes as unpadded base64url. */
|
|
12
|
+
export function encodeBase64Url(bytes: Uint8Array): string {
|
|
13
|
+
let binary = '';
|
|
14
|
+
for (const byte of bytes) binary += String.fromCodePoint(byte);
|
|
15
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
16
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { JwkSet, OidcDiscovery, type Jwk } from './schemas/jwks.ts';
|
|
3
|
+
|
|
4
|
+
/** Fetches over HTTP; the global `fetch` by default. */
|
|
5
|
+
export type JwksFetch = (request: Request) => Promise<Response>;
|
|
6
|
+
|
|
7
|
+
/** Options of a {@link JwksSource}. */
|
|
8
|
+
export interface JwksSourceOptions {
|
|
9
|
+
readonly issuer: string;
|
|
10
|
+
/** The JWK Set URL, or null to discover it from the issuer's OpenID configuration. */
|
|
11
|
+
readonly jwksUrl: string | null;
|
|
12
|
+
/** Seconds keys are reused. */
|
|
13
|
+
readonly cacheSeconds: number;
|
|
14
|
+
readonly fetch: JwksFetch;
|
|
15
|
+
/** The clock in milliseconds since the epoch. */
|
|
16
|
+
readonly now: () => number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The issuer is asked at most this often (an unknown key id, or a retry after a failed fetch), so
|
|
21
|
+
* bad tokens or an issuer outage cannot hammer it.
|
|
22
|
+
*/
|
|
23
|
+
const MIN_REFRESH_MS = 10_000;
|
|
24
|
+
|
|
25
|
+
async function getJson(fetcher: JwksFetch, url: string): Promise<unknown> {
|
|
26
|
+
const response = await fetcher(new Request(url, { headers: { Accept: 'application/json' } }));
|
|
27
|
+
if (!response.ok) throw new Error(`GET ${url} answered ${response.status}`);
|
|
28
|
+
return response.json();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The issuer's signing keys, fetched (through OIDC discovery when no JWKS URL is configured) and
|
|
33
|
+
* cached for `cacheSeconds`. A key id not in the cached set triggers one early refetch, so key
|
|
34
|
+
* rotation is picked up without waiting for the cache to expire. Every fetch attempt, failed or
|
|
35
|
+
* not, starts a {@link MIN_REFRESH_MS} window in which the issuer is not asked again. When a
|
|
36
|
+
* refresh fails the last keys fetched are served (stale on error), so an issuer outage does not
|
|
37
|
+
* stop authentication; only with no keys ever fetched does the failure surface. Concurrent
|
|
38
|
+
* callers share one fetch.
|
|
39
|
+
*/
|
|
40
|
+
export class JwksSource {
|
|
41
|
+
readonly #options: JwksSourceOptions;
|
|
42
|
+
#keys: readonly Jwk[] | null = null;
|
|
43
|
+
/** When the keys were last fetched successfully. */
|
|
44
|
+
#fetchedAt = Number.NEGATIVE_INFINITY;
|
|
45
|
+
/** When the issuer was last asked, whatever the outcome. */
|
|
46
|
+
#attemptedAt = Number.NEGATIVE_INFINITY;
|
|
47
|
+
/** Why the last attempt failed, while no keys have ever been fetched. */
|
|
48
|
+
#lastError: unknown = null;
|
|
49
|
+
#pending: Promise<readonly Jwk[]> | null = null;
|
|
50
|
+
/** The JWK Set URL once known (configured, or discovered once). */
|
|
51
|
+
#jwksUrl: string | null;
|
|
52
|
+
|
|
53
|
+
constructor(options: JwksSourceOptions) {
|
|
54
|
+
this.#options = options;
|
|
55
|
+
this.#jwksUrl = options.jwksUrl;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The keys that may have signed a token naming `kid` (every key when the token names none). */
|
|
59
|
+
async keysFor(kid: string | undefined): Promise<readonly Jwk[]> {
|
|
60
|
+
const fresh = this.#options.now() - this.#fetchedAt < this.#options.cacheSeconds * 1000;
|
|
61
|
+
let keys = this.#keys !== null && fresh ? this.#keys : await this.#refresh();
|
|
62
|
+
const matching = (set: readonly Jwk[]): readonly Jwk[] =>
|
|
63
|
+
kid === undefined ? set : set.filter((key) => key.kid === kid);
|
|
64
|
+
if (matching(keys).length === 0 && kid !== undefined) keys = await this.#refresh();
|
|
65
|
+
return matching(keys);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Fetches the keys unless the issuer was asked less than {@link MIN_REFRESH_MS} ago; serves the
|
|
70
|
+
* cached keys when it was, or when the fetch fails.
|
|
71
|
+
*/
|
|
72
|
+
async #refresh(): Promise<readonly Jwk[]> {
|
|
73
|
+
if (this.#pending !== null) return this.#pending;
|
|
74
|
+
if (this.#options.now() - this.#attemptedAt < MIN_REFRESH_MS) {
|
|
75
|
+
if (this.#keys !== null) return this.#keys;
|
|
76
|
+
throw this.#lastError ?? new Error('the issuer keys are not available yet');
|
|
77
|
+
}
|
|
78
|
+
this.#attemptedAt = this.#options.now();
|
|
79
|
+
this.#pending = this.#load()
|
|
80
|
+
.catch((error: unknown) => {
|
|
81
|
+
if (this.#keys !== null) return this.#keys;
|
|
82
|
+
this.#lastError = error;
|
|
83
|
+
throw error;
|
|
84
|
+
})
|
|
85
|
+
.finally(() => {
|
|
86
|
+
this.#pending = null;
|
|
87
|
+
});
|
|
88
|
+
return this.#pending;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async #load(): Promise<readonly Jwk[]> {
|
|
92
|
+
const { issuer, fetch: fetcher } = this.#options;
|
|
93
|
+
let url = this.#jwksUrl;
|
|
94
|
+
if (url === null) {
|
|
95
|
+
const discovery = OidcDiscovery.parse(
|
|
96
|
+
await getJson(fetcher, `${issuer.replace(/\/$/, '')}/.well-known/openid-configuration`),
|
|
97
|
+
);
|
|
98
|
+
if (discovery.issuer !== issuer)
|
|
99
|
+
throw new Error(`the discovery document names issuer ${discovery.issuer}`);
|
|
100
|
+
url = discovery.jwks_uri;
|
|
101
|
+
this.#jwksUrl = url;
|
|
102
|
+
}
|
|
103
|
+
const set = JwkSet.parse(await getJson(fetcher, url));
|
|
104
|
+
this.#keys = set.keys;
|
|
105
|
+
this.#fetchedAt = this.#options.now();
|
|
106
|
+
this.#lastError = null;
|
|
107
|
+
return set.keys;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import type { Authenticator } from '@leed-ai/git-gateway-contract/proxy/gateway-hooks';
|
|
3
|
+
import { Role, type PrincipalInput } from '@leed-ai/git-gateway-contract/proxy/principal';
|
|
4
|
+
import { readCredential } from '@leed-ai/git-gateway-contract/proxy/request-credential';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
|
|
7
|
+
import { JwksSource, type JwksFetch } from './jwks-source.ts';
|
|
8
|
+
import { decodeJwt, verifySignature, type DecodedJwt } from './jwt-verify.ts';
|
|
9
|
+
import { JwtAlgorithm } from './schemas/jwt-algorithm.ts';
|
|
10
|
+
import {
|
|
11
|
+
JwtAuthenticatorConfig,
|
|
12
|
+
type JwtAuthenticatorConfigInput,
|
|
13
|
+
} from './schemas/jwt-authenticator-config.ts';
|
|
14
|
+
|
|
15
|
+
/** Options beyond the configuration: how keys are fetched and the clock (both injectable for tests). */
|
|
16
|
+
export interface JwtAuthenticatorOptions {
|
|
17
|
+
/** Fetches the discovery document and JWK Set; default the global `fetch`. */
|
|
18
|
+
readonly fetch?: JwksFetch;
|
|
19
|
+
/** The clock; default the system clock. */
|
|
20
|
+
readonly now?: () => Date;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const SingleLine = z
|
|
24
|
+
.string()
|
|
25
|
+
.min(1)
|
|
26
|
+
.max(255)
|
|
27
|
+
.regex(/^[^\n\0]+$/);
|
|
28
|
+
const Email = z.email().max(255);
|
|
29
|
+
|
|
30
|
+
function rolesOf(value: unknown): string[] {
|
|
31
|
+
const names = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\s,]+/) : [];
|
|
32
|
+
return names.filter((name): name is string => Role.safeParse(name).success).slice(0, 100);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The reference {@link Authenticator}: the bearer credential (a Bearer header, or the password of
|
|
37
|
+
* the HTTP Basic credentials git sends, so a credential helper can supply the token) must be a JWT
|
|
38
|
+
* signed by one of the issuer's keys (JWKS, discovered through OIDC unless a URL is configured)
|
|
39
|
+
* with an accepted algorithm, carry the configured issuer and an accepted audience, and be
|
|
40
|
+
* within its "nbf"/"exp" window. Its claims are mapped to a principal whose `expiresAt` is the
|
|
41
|
+
* token's expiry, so no cached decision outlives the token. Anything else is null — a 401.
|
|
42
|
+
*/
|
|
43
|
+
export class JwtAuthenticator implements Authenticator {
|
|
44
|
+
readonly #config: JwtAuthenticatorConfig;
|
|
45
|
+
readonly #keys: JwksSource;
|
|
46
|
+
readonly #now: () => Date;
|
|
47
|
+
|
|
48
|
+
constructor(config: JwtAuthenticatorConfigInput, options: JwtAuthenticatorOptions = {}) {
|
|
49
|
+
this.#config = JwtAuthenticatorConfig.parse(config);
|
|
50
|
+
this.#now = options.now ?? (() => new Date());
|
|
51
|
+
this.#keys = new JwksSource({
|
|
52
|
+
issuer: this.#config.issuer,
|
|
53
|
+
jwksUrl: this.#config.jwksUrl,
|
|
54
|
+
cacheSeconds: this.#config.jwksCacheSeconds,
|
|
55
|
+
fetch: options.fetch ?? (async (request) => fetch(request)),
|
|
56
|
+
now: () => this.#now().getTime(),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async authenticate(request: Request): Promise<PrincipalInput | null> {
|
|
61
|
+
const credential = readCredential(request);
|
|
62
|
+
const jwt = credential === null ? null : decodeJwt(credential.secret);
|
|
63
|
+
if (jwt === null || !this.#claimsValid(jwt)) return null;
|
|
64
|
+
const algorithm = JwtAlgorithm.safeParse(jwt.header.alg);
|
|
65
|
+
if (!algorithm.success || !this.#config.algorithms.includes(algorithm.data)) return null;
|
|
66
|
+
const keys = await this.#keys.keysFor(jwt.header.kid);
|
|
67
|
+
for (const key of keys) {
|
|
68
|
+
if (await verifySignature(jwt, algorithm.data, key)) return this.#principal(jwt);
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#claimsValid({ claims }: DecodedJwt): boolean {
|
|
74
|
+
const now = this.#now().getTime() / 1000;
|
|
75
|
+
const tolerance = this.#config.clockToleranceSeconds;
|
|
76
|
+
if (claims.iss !== this.#config.issuer) return false;
|
|
77
|
+
const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
78
|
+
if (!audiences.some((audience) => this.#config.audience.includes(audience))) return false;
|
|
79
|
+
if (claims.exp + tolerance <= now) return false;
|
|
80
|
+
return claims.nbf === undefined || claims.nbf - tolerance <= now;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
#principal({ claims }: DecodedJwt): PrincipalInput | null {
|
|
84
|
+
const mapping = this.#config.claims;
|
|
85
|
+
const subject = SingleLine.safeParse(claims[mapping.subject]);
|
|
86
|
+
if (!subject.success) return null;
|
|
87
|
+
const name = SingleLine.safeParse(claims[mapping.name]);
|
|
88
|
+
const email = Email.safeParse(claims[mapping.email]);
|
|
89
|
+
return {
|
|
90
|
+
subject: subject.data,
|
|
91
|
+
name: name.success ? name.data : null,
|
|
92
|
+
email: email.success ? email.data : null,
|
|
93
|
+
roles: rolesOf(claims[mapping.roles]),
|
|
94
|
+
// The token is accepted until exp plus the clock tolerance, so the principal lasts as long.
|
|
95
|
+
expiresAt: new Date(
|
|
96
|
+
Math.min((claims.exp + this.#config.clockToleranceSeconds) * 1000, 8.64e15),
|
|
97
|
+
).toISOString(),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { decodeBase64Url } from './base64url.ts';
|
|
3
|
+
import type { Jwk } from './schemas/jwks.ts';
|
|
4
|
+
import type { JwtAlgorithm } from './schemas/jwt-algorithm.ts';
|
|
5
|
+
import { JwtClaims, JwtHeader } from './schemas/jwt-parts.ts';
|
|
6
|
+
|
|
7
|
+
/** A JWT split into its parts, the header and claims parsed but nothing verified yet. */
|
|
8
|
+
export interface DecodedJwt {
|
|
9
|
+
readonly header: JwtHeader;
|
|
10
|
+
readonly claims: JwtClaims;
|
|
11
|
+
/** The bytes the signature covers: "<header>.<payload>" as sent. */
|
|
12
|
+
readonly signingInput: Uint8Array;
|
|
13
|
+
readonly signature: Uint8Array;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A base64url JSON segment, parsed. */
|
|
17
|
+
const segment = (part: string): unknown => JSON.parse(new TextDecoder().decode(decodeBase64Url(part)));
|
|
18
|
+
|
|
19
|
+
/** Splits and parses a compact JWS JWT; null when it is not one. */
|
|
20
|
+
export function decodeJwt(token: string): DecodedJwt | null {
|
|
21
|
+
const parts = token.split('.');
|
|
22
|
+
if (parts.length !== 3) return null;
|
|
23
|
+
const [header = '', payload = '', signature = ''] = parts;
|
|
24
|
+
try {
|
|
25
|
+
const parsedHeader = JwtHeader.safeParse(segment(header));
|
|
26
|
+
const parsedClaims = JwtClaims.safeParse(segment(payload));
|
|
27
|
+
if (!parsedHeader.success || !parsedClaims.success) return null;
|
|
28
|
+
return {
|
|
29
|
+
header: parsedHeader.data,
|
|
30
|
+
claims: parsedClaims.data,
|
|
31
|
+
signingInput: new TextEncoder().encode(`${header}.${payload}`),
|
|
32
|
+
signature: decodeBase64Url(signature),
|
|
33
|
+
};
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Web Crypto parameters for importing a key and verifying with it. */
|
|
40
|
+
interface Algorithms {
|
|
41
|
+
readonly kty: Jwk['kty'];
|
|
42
|
+
readonly import: { readonly name: string; readonly hash?: string; readonly namedCurve?: string };
|
|
43
|
+
readonly verify: { readonly name: string; readonly hash?: string; readonly saltLength?: number };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The public members of a key Web Crypto imports, without the ones the authenticator ignores. */
|
|
47
|
+
interface PublicJwk {
|
|
48
|
+
kty: string;
|
|
49
|
+
ext: boolean;
|
|
50
|
+
n?: string;
|
|
51
|
+
e?: string;
|
|
52
|
+
crv?: string;
|
|
53
|
+
x?: string;
|
|
54
|
+
y?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function publicJwk(key: Jwk): PublicJwk {
|
|
58
|
+
const jwk: PublicJwk = { kty: key.kty, ext: true };
|
|
59
|
+
for (const member of ['n', 'e', 'crv', 'x', 'y'] as const) {
|
|
60
|
+
const value = key[member];
|
|
61
|
+
if (value !== undefined) jwk[member] = value;
|
|
62
|
+
}
|
|
63
|
+
return jwk;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const ALGORITHMS: Readonly<Record<JwtAlgorithm, Algorithms>> = {
|
|
67
|
+
RS256: {
|
|
68
|
+
kty: 'RSA',
|
|
69
|
+
import: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
|
70
|
+
verify: { name: 'RSASSA-PKCS1-v1_5' },
|
|
71
|
+
},
|
|
72
|
+
RS384: {
|
|
73
|
+
kty: 'RSA',
|
|
74
|
+
import: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-384' },
|
|
75
|
+
verify: { name: 'RSASSA-PKCS1-v1_5' },
|
|
76
|
+
},
|
|
77
|
+
RS512: {
|
|
78
|
+
kty: 'RSA',
|
|
79
|
+
import: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-512' },
|
|
80
|
+
verify: { name: 'RSASSA-PKCS1-v1_5' },
|
|
81
|
+
},
|
|
82
|
+
PS256: {
|
|
83
|
+
kty: 'RSA',
|
|
84
|
+
import: { name: 'RSA-PSS', hash: 'SHA-256' },
|
|
85
|
+
verify: { name: 'RSA-PSS', saltLength: 32 },
|
|
86
|
+
},
|
|
87
|
+
PS384: {
|
|
88
|
+
kty: 'RSA',
|
|
89
|
+
import: { name: 'RSA-PSS', hash: 'SHA-384' },
|
|
90
|
+
verify: { name: 'RSA-PSS', saltLength: 48 },
|
|
91
|
+
},
|
|
92
|
+
PS512: {
|
|
93
|
+
kty: 'RSA',
|
|
94
|
+
import: { name: 'RSA-PSS', hash: 'SHA-512' },
|
|
95
|
+
verify: { name: 'RSA-PSS', saltLength: 64 },
|
|
96
|
+
},
|
|
97
|
+
ES256: {
|
|
98
|
+
kty: 'EC',
|
|
99
|
+
import: { name: 'ECDSA', namedCurve: 'P-256' },
|
|
100
|
+
verify: { name: 'ECDSA', hash: 'SHA-256' },
|
|
101
|
+
},
|
|
102
|
+
ES384: {
|
|
103
|
+
kty: 'EC',
|
|
104
|
+
import: { name: 'ECDSA', namedCurve: 'P-384' },
|
|
105
|
+
verify: { name: 'ECDSA', hash: 'SHA-384' },
|
|
106
|
+
},
|
|
107
|
+
EdDSA: { kty: 'OKP', import: { name: 'Ed25519' }, verify: { name: 'Ed25519' } },
|
|
108
|
+
Ed25519: { kty: 'OKP', import: { name: 'Ed25519' }, verify: { name: 'Ed25519' } },
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/** The two names of EdDSA on Ed25519: the polymorphic "EdDSA" and the fully-specified "Ed25519". */
|
|
112
|
+
const OKP_NAMES: ReadonlySet<string> = new Set(['EdDSA', 'Ed25519']);
|
|
113
|
+
|
|
114
|
+
/** Whether `key` may verify a token signed with `algorithm` (key type, curve and any "alg"/"use" agree). */
|
|
115
|
+
export function keyFits(key: Jwk, algorithm: JwtAlgorithm): boolean {
|
|
116
|
+
const spec = ALGORITHMS[algorithm];
|
|
117
|
+
if (key.kty !== spec.kty) return false;
|
|
118
|
+
if (key.alg !== undefined && key.alg !== algorithm && !(OKP_NAMES.has(key.alg) && OKP_NAMES.has(algorithm)))
|
|
119
|
+
return false;
|
|
120
|
+
if (key.use !== undefined && key.use !== 'sig') return false;
|
|
121
|
+
if (spec.import.namedCurve !== undefined && key.crv !== spec.import.namedCurve) return false;
|
|
122
|
+
return !OKP_NAMES.has(algorithm) || key.crv === 'Ed25519';
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Verifies a decoded JWT's signature with one public key; false on any mismatch or import failure. */
|
|
126
|
+
export async function verifySignature(jwt: DecodedJwt, algorithm: JwtAlgorithm, key: Jwk): Promise<boolean> {
|
|
127
|
+
if (!keyFits(key, algorithm)) return false;
|
|
128
|
+
const spec = ALGORITHMS[algorithm];
|
|
129
|
+
try {
|
|
130
|
+
const imported = await crypto.subtle.importKey('jwk', publicJwk(key), spec.import, false, ['verify']);
|
|
131
|
+
return await crypto.subtle.verify(spec.verify, imported, jwt.signature, jwt.signingInput);
|
|
132
|
+
} catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
const base64url = z.string().regex(/^[A-Za-z0-9_-]+$/);
|
|
5
|
+
|
|
6
|
+
/** One public key of a JWK Set. */
|
|
7
|
+
export const Jwk = z
|
|
8
|
+
.looseObject({
|
|
9
|
+
kty: z.enum(['RSA', 'EC', 'OKP']).meta({
|
|
10
|
+
description: 'Key type.',
|
|
11
|
+
enumDescriptions: {
|
|
12
|
+
RSA: 'An RSA public key (n, e).',
|
|
13
|
+
EC: 'An elliptic-curve public key (crv, x, y).',
|
|
14
|
+
OKP: 'An Ed25519 public key (crv, x).',
|
|
15
|
+
},
|
|
16
|
+
}),
|
|
17
|
+
kid: z
|
|
18
|
+
.string()
|
|
19
|
+
.min(1)
|
|
20
|
+
.max(255)
|
|
21
|
+
.optional()
|
|
22
|
+
.describe('Key id, matched against a token header\'s "kid"; absent on single-key sets.'),
|
|
23
|
+
alg: z
|
|
24
|
+
.string()
|
|
25
|
+
.min(1)
|
|
26
|
+
.max(20)
|
|
27
|
+
.optional()
|
|
28
|
+
.describe('The algorithm the key is for; when present a token must use it.'),
|
|
29
|
+
use: z
|
|
30
|
+
.string()
|
|
31
|
+
.min(1)
|
|
32
|
+
.max(20)
|
|
33
|
+
.optional()
|
|
34
|
+
.describe('Intended use; keys whose use is not "sig" are ignored. Absent means any.'),
|
|
35
|
+
n: base64url.optional().describe('RSA modulus, base64url.'),
|
|
36
|
+
e: base64url.optional().describe('RSA public exponent, base64url.'),
|
|
37
|
+
crv: z.string().min(1).max(20).optional().describe('Curve: P-256 or P-384 for EC, Ed25519 for OKP.'),
|
|
38
|
+
x: base64url.optional().describe('Curve point x coordinate (EC) or public key (OKP), base64url.'),
|
|
39
|
+
y: base64url.optional().describe('Curve point y coordinate (EC), base64url.'),
|
|
40
|
+
})
|
|
41
|
+
.meta({
|
|
42
|
+
id: 'Jwk',
|
|
43
|
+
title: 'JSON Web Key',
|
|
44
|
+
description:
|
|
45
|
+
'One public signing key from a JWK Set (RFC 7517). Members the authenticator does not use are kept but ignored.',
|
|
46
|
+
examples: [
|
|
47
|
+
{
|
|
48
|
+
kty: 'EC',
|
|
49
|
+
kid: 'key-1',
|
|
50
|
+
alg: 'ES256',
|
|
51
|
+
use: 'sig',
|
|
52
|
+
crv: 'P-256',
|
|
53
|
+
x: 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
|
|
54
|
+
y: 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/** A JSON Web Key, inferred from {@link Jwk}. */
|
|
60
|
+
export type Jwk = z.infer<typeof Jwk>;
|
|
61
|
+
|
|
62
|
+
/** A JWK Set document. */
|
|
63
|
+
export const JwkSet = z
|
|
64
|
+
.looseObject({
|
|
65
|
+
keys: z.array(Jwk).max(100).describe("The issuer's public keys, at most 100."),
|
|
66
|
+
})
|
|
67
|
+
.meta({
|
|
68
|
+
id: 'JwkSet',
|
|
69
|
+
title: 'JWK Set',
|
|
70
|
+
description: "The document at an issuer's jwks_uri (RFC 7517 §5): its public signing keys.",
|
|
71
|
+
examples: [
|
|
72
|
+
{ keys: [{ kty: 'RSA', kid: 'rsa-1', n: 'sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri', e: 'AQAB' }] },
|
|
73
|
+
],
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** A JWK Set, inferred from {@link JwkSet}. */
|
|
77
|
+
export type JwkSet = z.infer<typeof JwkSet>;
|
|
78
|
+
|
|
79
|
+
/** The part of an OpenID Provider configuration the authenticator reads. */
|
|
80
|
+
export const OidcDiscovery = z
|
|
81
|
+
.looseObject({
|
|
82
|
+
issuer: z.string().min(1).describe("The provider's issuer identifier; must equal the configured issuer."),
|
|
83
|
+
jwks_uri: z.url({ protocol: /^https?$/ }).describe('Where the provider publishes its JWK Set.'),
|
|
84
|
+
})
|
|
85
|
+
.meta({
|
|
86
|
+
id: 'OidcDiscovery',
|
|
87
|
+
title: 'OIDC discovery document',
|
|
88
|
+
description:
|
|
89
|
+
'The fields of <issuer>/.well-known/openid-configuration (OpenID Connect Discovery 1.0) the authenticator uses.',
|
|
90
|
+
examples: [
|
|
91
|
+
{ issuer: 'https://auth.example.com', jwks_uri: 'https://auth.example.com/.well-known/jwks.json' },
|
|
92
|
+
],
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
/** An OIDC discovery document, inferred from {@link OidcDiscovery}. */
|
|
96
|
+
export type OidcDiscovery = z.infer<typeof OidcDiscovery>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
/** A JWS signature algorithm the authenticator can verify with Web Crypto. */
|
|
5
|
+
export const JwtAlgorithm = z
|
|
6
|
+
.enum(['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'EdDSA', 'Ed25519'])
|
|
7
|
+
.meta({
|
|
8
|
+
id: 'JwtAlgorithm',
|
|
9
|
+
title: 'JWT algorithm',
|
|
10
|
+
description:
|
|
11
|
+
'A JWS "alg" the JWT authenticator verifies with Web Crypto. Symmetric algorithms (HS*) and "none" are never accepted.',
|
|
12
|
+
enumDescriptions: {
|
|
13
|
+
RS256: 'RSASSA-PKCS1-v1_5 with SHA-256 (RSA key).',
|
|
14
|
+
RS384: 'RSASSA-PKCS1-v1_5 with SHA-384 (RSA key).',
|
|
15
|
+
RS512: 'RSASSA-PKCS1-v1_5 with SHA-512 (RSA key).',
|
|
16
|
+
PS256: 'RSASSA-PSS with SHA-256 (RSA key).',
|
|
17
|
+
PS384: 'RSASSA-PSS with SHA-384 (RSA key).',
|
|
18
|
+
PS512: 'RSASSA-PSS with SHA-512 (RSA key).',
|
|
19
|
+
ES256: 'ECDSA on P-256 with SHA-256 (EC key).',
|
|
20
|
+
ES384: 'ECDSA on P-384 with SHA-384 (EC key).',
|
|
21
|
+
EdDSA: 'EdDSA with an Ed25519 key (OKP key, crv Ed25519).',
|
|
22
|
+
Ed25519: 'Ed25519, the fully-specified name of EdDSA on Ed25519 (RFC 9864); same keys as EdDSA.',
|
|
23
|
+
},
|
|
24
|
+
examples: ['RS256', 'ES256'],
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/** A JWS algorithm, inferred from {@link JwtAlgorithm}. */
|
|
28
|
+
export type JwtAlgorithm = z.infer<typeof JwtAlgorithm>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
import { JwtAlgorithm } from './jwt-algorithm.ts';
|
|
5
|
+
|
|
6
|
+
const claimName = (what: string, fallback: string) =>
|
|
7
|
+
z
|
|
8
|
+
.string()
|
|
9
|
+
.min(1)
|
|
10
|
+
.max(100)
|
|
11
|
+
.default(fallback)
|
|
12
|
+
.describe(`Name of the claim holding ${what}; default "${fallback}".`);
|
|
13
|
+
|
|
14
|
+
/** Which JWT claims become which Principal fields. */
|
|
15
|
+
export const JwtClaimMapping = z
|
|
16
|
+
.object({
|
|
17
|
+
subject: claimName('the principal subject (a non-empty string; required in every token)', 'sub'),
|
|
18
|
+
name: claimName('the display name (optional; ignored unless a non-empty single-line string)', 'name'),
|
|
19
|
+
email: claimName('the email address (optional; ignored unless a valid address)', 'email'),
|
|
20
|
+
roles: claimName(
|
|
21
|
+
'the roles: an array of strings, or one string of space- or comma-separated names (optional; names with whitespace are dropped)',
|
|
22
|
+
'roles',
|
|
23
|
+
),
|
|
24
|
+
})
|
|
25
|
+
.strict()
|
|
26
|
+
.meta({
|
|
27
|
+
id: 'JwtClaimMapping',
|
|
28
|
+
title: 'JWT claim mapping',
|
|
29
|
+
description: 'Which claims of a verified JWT fill which Principal fields.',
|
|
30
|
+
examples: [{ subject: 'sub', name: 'name', email: 'email', roles: 'roles' }],
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** A claim mapping as written (defaults optional). */
|
|
34
|
+
export type JwtClaimMappingInput = z.input<typeof JwtClaimMapping>;
|
|
35
|
+
|
|
36
|
+
/** Configuration of the JWT (JWKS/OIDC) authenticator. */
|
|
37
|
+
export const JwtAuthenticatorConfig = z
|
|
38
|
+
.object({
|
|
39
|
+
issuer: z
|
|
40
|
+
.url({ protocol: /^https?$/ })
|
|
41
|
+
.describe(
|
|
42
|
+
'The required "iss" claim, compared exactly; also the base of OIDC discovery when `jwksUrl` is null.',
|
|
43
|
+
),
|
|
44
|
+
audience: z
|
|
45
|
+
.array(z.string().min(1).max(255).describe('One accepted audience value.'))
|
|
46
|
+
.min(1)
|
|
47
|
+
.max(20)
|
|
48
|
+
.describe(
|
|
49
|
+
'Accepted "aud" values: a token is accepted when its audience (a string or an array) contains any of them.',
|
|
50
|
+
),
|
|
51
|
+
jwksUrl: z
|
|
52
|
+
.url({ protocol: /^https?$/ })
|
|
53
|
+
.nullable()
|
|
54
|
+
.default(null)
|
|
55
|
+
.describe(
|
|
56
|
+
'Where the signing keys (a JWK Set) are fetched; null (the default) discovers them from <issuer>/.well-known/openid-configuration ("jwks_uri").',
|
|
57
|
+
),
|
|
58
|
+
algorithms: z
|
|
59
|
+
.array(JwtAlgorithm)
|
|
60
|
+
.min(1)
|
|
61
|
+
.max(10)
|
|
62
|
+
.default(['RS256', 'ES256'])
|
|
63
|
+
.describe(
|
|
64
|
+
'Signature algorithms accepted; a token signed otherwise is refused. Default ["RS256", "ES256"].',
|
|
65
|
+
),
|
|
66
|
+
clockToleranceSeconds: z
|
|
67
|
+
.int()
|
|
68
|
+
.min(0)
|
|
69
|
+
.max(300)
|
|
70
|
+
.default(60)
|
|
71
|
+
.describe(
|
|
72
|
+
'Seconds of clock skew allowed when checking "exp" and "nbf"; the principal expires this long after "exp" too. 0–300, default 60.',
|
|
73
|
+
),
|
|
74
|
+
jwksCacheSeconds: z
|
|
75
|
+
.int()
|
|
76
|
+
.min(10)
|
|
77
|
+
.max(86_400)
|
|
78
|
+
.default(600)
|
|
79
|
+
.describe(
|
|
80
|
+
'Seconds fetched keys are reused before being fetched again; a token naming an unknown "kid" refetches sooner. The issuer is asked at most every 10 seconds, and when a refetch fails the last keys fetched keep being used. 10–86400, default 600.',
|
|
81
|
+
),
|
|
82
|
+
claims: JwtClaimMapping.default({
|
|
83
|
+
subject: 'sub',
|
|
84
|
+
name: 'name',
|
|
85
|
+
email: 'email',
|
|
86
|
+
roles: 'roles',
|
|
87
|
+
}).describe('Which claims fill which Principal fields; defaults to sub, name, email and roles.'),
|
|
88
|
+
})
|
|
89
|
+
.strict()
|
|
90
|
+
.meta({
|
|
91
|
+
id: 'JwtAuthenticatorConfig',
|
|
92
|
+
title: 'JWT authenticator configuration',
|
|
93
|
+
description:
|
|
94
|
+
'Configuration of the reference JWT authenticator: tokens (as a Bearer header or the HTTP Basic password git sends) are verified against the issuer\'s JWKS, and must carry the issuer, an accepted audience and an unexpired "exp".',
|
|
95
|
+
examples: [
|
|
96
|
+
{
|
|
97
|
+
issuer: 'https://auth.example.com',
|
|
98
|
+
audience: ['git.example.com'],
|
|
99
|
+
jwksUrl: null,
|
|
100
|
+
algorithms: ['RS256', 'ES256'],
|
|
101
|
+
clockToleranceSeconds: 60,
|
|
102
|
+
jwksCacheSeconds: 600,
|
|
103
|
+
claims: { subject: 'sub', name: 'name', email: 'email', roles: 'roles' },
|
|
104
|
+
},
|
|
105
|
+
],
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
/** A JWT authenticator configuration as written (defaults optional). */
|
|
109
|
+
export type JwtAuthenticatorConfigInput = z.input<typeof JwtAuthenticatorConfig>;
|
|
110
|
+
/** A complete JWT authenticator configuration, inferred from {@link JwtAuthenticatorConfig}. */
|
|
111
|
+
export type JwtAuthenticatorConfig = z.output<typeof JwtAuthenticatorConfig>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
/** The protected header of a JWS-signed JWT. */
|
|
5
|
+
export const JwtHeader = z
|
|
6
|
+
.looseObject({
|
|
7
|
+
alg: z.string().min(1).max(20).describe('Signature algorithm; must be one the authenticator accepts.'),
|
|
8
|
+
kid: z
|
|
9
|
+
.string()
|
|
10
|
+
.min(1)
|
|
11
|
+
.max(255)
|
|
12
|
+
.optional()
|
|
13
|
+
.describe("Id of the signing key in the issuer's JWK Set; absent when the set has one key."),
|
|
14
|
+
typ: z.string().max(50).optional().describe('Media type, usually "JWT"; not checked.'),
|
|
15
|
+
})
|
|
16
|
+
.meta({
|
|
17
|
+
id: 'JwtHeader',
|
|
18
|
+
title: 'JWT header',
|
|
19
|
+
description: 'The protected header of a signed JWT (RFC 7515 §4). Other members are allowed and ignored.',
|
|
20
|
+
examples: [{ alg: 'RS256', kid: 'rsa-1', typ: 'JWT' }],
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** A JWT header, inferred from {@link JwtHeader}. */
|
|
24
|
+
export type JwtHeader = z.infer<typeof JwtHeader>;
|
|
25
|
+
|
|
26
|
+
const numericDate = (what: string) =>
|
|
27
|
+
z.number().finite().nonnegative().describe(`${what}, as seconds since the epoch (a JSON number).`);
|
|
28
|
+
|
|
29
|
+
/** The registered claims of a JWT the authenticator checks; all other claims pass through. */
|
|
30
|
+
export const JwtClaims = z
|
|
31
|
+
.looseObject({
|
|
32
|
+
iss: z.string().min(1).describe('Issuer; must equal the configured issuer.'),
|
|
33
|
+
aud: z
|
|
34
|
+
.union([
|
|
35
|
+
z.string().min(1).describe('A single audience.'),
|
|
36
|
+
z.array(z.string().min(1).describe('One audience.')).min(1).describe('Several audiences.'),
|
|
37
|
+
])
|
|
38
|
+
.describe('Audience; must contain one of the configured audiences.'),
|
|
39
|
+
exp: numericDate('Expiry; required, and must be in the future (with clock tolerance)'),
|
|
40
|
+
nbf: numericDate('Not before; when present, must not be in the future (with clock tolerance)').optional(),
|
|
41
|
+
iat: numericDate('Issued at; informational').optional(),
|
|
42
|
+
})
|
|
43
|
+
.meta({
|
|
44
|
+
id: 'JwtClaims',
|
|
45
|
+
title: 'JWT claims',
|
|
46
|
+
description:
|
|
47
|
+
'The payload of a JWT: the registered claims the authenticator checks (iss, aud, exp, nbf), plus any others, from which the principal is mapped.',
|
|
48
|
+
examples: [
|
|
49
|
+
{
|
|
50
|
+
iss: 'https://auth.example.com',
|
|
51
|
+
aud: 'git.example.com',
|
|
52
|
+
exp: 1_795_000_000,
|
|
53
|
+
sub: 'user:42',
|
|
54
|
+
roles: ['maintainer'],
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/** JWT claims, inferred from {@link JwtClaims}. */
|
|
60
|
+
export type JwtClaims = z.infer<typeof JwtClaims>;
|