@passport.lgbt/node 0.0.0-stage → 1.0.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.
@@ -0,0 +1,193 @@
1
+ import { discover, parseIssuer } from './discovery.js';
2
+ import { JtiCache, verifyDpopProof } from './dpop.js';
3
+ import { DETAILS, configError } from './errors.js';
4
+ import { JWKS_COOLDOWN_MS, JwksCache, SUPPORTED_ALGS, decodeJws, verifyJws } from './jwks.js';
5
+ const ERROR_MESSAGES = {
6
+ missing_token: 'passport.lgbt: an access token is required',
7
+ invalid_token: 'passport.lgbt: the access token is invalid',
8
+ insufficient_scope: 'passport.lgbt: the access token lacks a required scope',
9
+ invalid_dpop_proof: 'passport.lgbt: the DPoP proof is invalid',
10
+ };
11
+ const OPAQUE_MESSAGE = 'passport.lgbt: the access token is not a JWT. Declare the API as a resource (RFC 8707) so that clients obtain a JWT access token for it (see the @passport.lgbt/node documentation)';
12
+ /**
13
+ * Refus d'un jeton d'accès, à rendre tel quel par l'API : `status` (401 ou 403) et `wwwAuthenticate` (défi `Bearer` ou
14
+ * `DPoP`) sont fixes ; le message ne contient jamais le jeton ni une valeur reçue.
15
+ */
16
+ export class AccessTokenError extends Error {
17
+ code;
18
+ status;
19
+ wwwAuthenticate;
20
+ constructor(code, scheme, algs, o = {}) {
21
+ super(o.opaque ? OPAQUE_MESSAGE : ERROR_MESSAGES[code]);
22
+ this.name = 'AccessTokenError';
23
+ this.code = code;
24
+ this.status = code === 'insufficient_scope' ? 403 : 401;
25
+ // sans jeton : défi sans `error` (RFC 6750 §3.1) ; `realm` = URI de la ressource (configuration, jamais une valeur reçue)
26
+ const params = code === 'missing_token' ? [`realm="${o.realm ?? ''}"`] : [`error="${code}"`];
27
+ if (scheme === 'DPoP')
28
+ params.push(`algs="${algs.join(' ')}"`);
29
+ this.wwwAuthenticate = `${scheme} ${params.join(', ')}`;
30
+ }
31
+ }
32
+ const OPTION_KEYS = new Set(['issuer', 'audience', 'requiredScopes', 'dpop', 'publicUrl', 'fetch']);
33
+ const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
34
+ const TOKEN68 = /^[A-Za-z0-9\-._~+/]+=*$/;
35
+ /** Tolérance d'horloge sur `exp`, `iat` et `nbf` (secondes). */
36
+ const CLOCK_TOLERANCE_S = 30;
37
+ const REQUEST_TIMEOUT_MS = 10_000;
38
+ function header(req, name) {
39
+ const h = req.headers ?? {};
40
+ if (name in h)
41
+ return h[name];
42
+ const found = Object.keys(h).find((k) => k.toLowerCase() === name);
43
+ return found === undefined ? undefined : h[found];
44
+ }
45
+ function single(v) {
46
+ if (Array.isArray(v))
47
+ return v.length === 1 ? v[0] : null;
48
+ return v;
49
+ }
50
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1']);
51
+ /** `htu` d'une ressource en boucle locale : `url` (un chemin) sur l'origine de la ressource ; l'en-tête `Host` est ignoré. */
52
+ function loopbackPublicUrl(origin) {
53
+ return (req) => {
54
+ if (typeof req.url !== 'string' || !req.url.startsWith('/') || req.url.startsWith('//'))
55
+ throw new Error('path expected');
56
+ const u = new URL(req.url, origin);
57
+ if (u.origin !== origin)
58
+ throw new Error('origin');
59
+ return u;
60
+ };
61
+ }
62
+ /**
63
+ * Vérifie les jetons d'accès JWT d'une API déclarée comme ressource (RFC 8707, RFC 9068) : `typ` `at+jwt`, ES256, clé du
64
+ * JWKS de l'émetteur, `iss` exact, `aud` = `audience`, `exp`, `iat`, `client_id`, `scope` ⊇ `requiredScopes`, et preuve
65
+ * DPoP (RFC 9449) pour un jeton lié. Un jeton opaque est refusé : déclarez l'API comme ressource.
66
+ */
67
+ export function createAccessTokenVerifier(o) {
68
+ if (!o || typeof o !== 'object')
69
+ throw configError();
70
+ for (const k of Object.keys(o))
71
+ if (!OPTION_KEYS.has(k))
72
+ throw configError(DETAILS.unknownOption);
73
+ parseIssuer(o.issuer);
74
+ if (typeof o.audience !== 'string' || o.audience.length === 0)
75
+ throw configError(DETAILS.audience);
76
+ try {
77
+ if (new URL(o.audience).hash || o.audience.includes('#'))
78
+ throw configError(DETAILS.audience);
79
+ }
80
+ catch {
81
+ throw configError(DETAILS.audience);
82
+ }
83
+ const required = o.requiredScopes ?? [];
84
+ if (!Array.isArray(required) || !required.every((s) => typeof s === 'string' && SCOPE_TOKEN.test(s)))
85
+ throw configError(DETAILS.requiredScopes);
86
+ const mode = o.dpop ?? 'allowed';
87
+ if (mode !== 'allowed' && mode !== 'required')
88
+ throw configError(DETAILS.dpop);
89
+ if (o.publicUrl !== undefined && typeof o.publicUrl !== 'function')
90
+ throw configError(DETAILS.callback);
91
+ const audienceUrl = new URL(o.audience);
92
+ if (o.publicUrl === undefined && !LOOPBACK_HOSTS.has(audienceUrl.hostname))
93
+ throw configError(DETAILS.publicUrl);
94
+ if (o.fetch !== undefined && typeof o.fetch !== 'function')
95
+ throw configError(DETAILS.callback);
96
+ const issuer = o.issuer;
97
+ const audience = o.audience;
98
+ const doFetch = o.fetch ?? globalThis.fetch;
99
+ const signal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS);
100
+ const publicUrl = o.publicUrl ?? loopbackPublicUrl(audienceUrl.origin);
101
+ const jti = new JtiCache();
102
+ // découverte à la demande, une fois ; après un échec, le même refus pendant 30 s (pas un appel par requête)
103
+ let metadata;
104
+ let failure;
105
+ const as = () => {
106
+ if (!metadata && failure && Date.now() - failure.at < JWKS_COOLDOWN_MS)
107
+ return Promise.reject(failure.error);
108
+ metadata ??= discover(issuer, { fetch: doFetch, signal }).then((m) => {
109
+ failure = undefined;
110
+ return m;
111
+ }, (e) => {
112
+ metadata = undefined;
113
+ failure = { error: e, at: Date.now() };
114
+ throw e;
115
+ });
116
+ return metadata;
117
+ };
118
+ const jwks = new JwksCache({ uri: async () => (await as()).jwks_uri ?? '', fetch: doFetch, signal });
119
+ let dpopAlgs = new Set(['ES256']);
120
+ return {
121
+ async verify(req) {
122
+ const meta = await as();
123
+ dpopAlgs = new Set((meta.dpop_signing_alg_values_supported ?? ['ES256']).filter((a) => SUPPORTED_ALGS.has(a)));
124
+ const algs = [...dpopAlgs];
125
+ const authorization = single(header(req, 'authorization'));
126
+ const space = typeof authorization === 'string' ? authorization.indexOf(' ') : -1;
127
+ const scheme = space > 0 && typeof authorization === 'string' ? authorization.slice(0, space).toLowerCase() : '';
128
+ const challenge = scheme === 'dpop' || mode === 'required' ? 'DPoP' : 'Bearer';
129
+ const reject = (code, c = challenge, x = {}) => new AccessTokenError(code, c, algs, x);
130
+ if (authorization === undefined || authorization === '')
131
+ throw new AccessTokenError('missing_token', challenge, algs, { realm: audience });
132
+ if (typeof authorization !== 'string' || (scheme !== 'bearer' && scheme !== 'dpop'))
133
+ throw reject('invalid_token');
134
+ const token = authorization.slice(space + 1).trim();
135
+ if (!TOKEN68.test(token))
136
+ throw reject('invalid_token');
137
+ const jws = decodeJws(token);
138
+ if (!jws)
139
+ throw reject('invalid_token', challenge, { opaque: token.split('.').length !== 3 });
140
+ const { header: h, payload: p } = jws;
141
+ const typ = typeof h.typ === 'string' ? h.typ.toLowerCase() : '';
142
+ if ((typ !== 'at+jwt' && typ !== 'application/at+jwt') || h.alg !== 'ES256' || typeof h.kid !== 'string' || h.crit !== undefined)
143
+ throw reject('invalid_token');
144
+ const key = await jwks.key(h.kid);
145
+ if (!key || !verifyJws(jws, 'ES256', key))
146
+ throw reject('invalid_token');
147
+ const now = Math.floor(Date.now() / 1000);
148
+ if (p.iss !== issuer)
149
+ throw reject('invalid_token');
150
+ const aud = Array.isArray(p.aud) && p.aud.length === 1 ? p.aud[0] : p.aud;
151
+ if (aud !== audience)
152
+ throw reject('invalid_token');
153
+ if (typeof p.exp !== 'number' || now > p.exp + CLOCK_TOLERANCE_S)
154
+ throw reject('invalid_token');
155
+ if (typeof p.iat !== 'number' || p.iat > now + CLOCK_TOLERANCE_S)
156
+ throw reject('invalid_token');
157
+ if (p.nbf !== undefined && (typeof p.nbf !== 'number' || p.nbf > now + CLOCK_TOLERANCE_S))
158
+ throw reject('invalid_token');
159
+ if (typeof p.sub !== 'string' || p.sub.length === 0 || typeof p.client_id !== 'string' || p.client_id.length === 0)
160
+ throw reject('invalid_token');
161
+ if (p.scope !== undefined && typeof p.scope !== 'string')
162
+ throw reject('invalid_token');
163
+ // DPoP : un jeton lié exige le schéma DPoP et sa preuve ; le schéma DPoP exige un jeton lié
164
+ const cnf = p.cnf;
165
+ const jkt = cnf && typeof cnf === 'object' ? cnf.jkt : undefined;
166
+ if (cnf !== undefined && typeof jkt !== 'string')
167
+ throw reject('invalid_token');
168
+ const bound = typeof jkt === 'string';
169
+ if (bound && scheme !== 'dpop')
170
+ throw reject('invalid_token', 'DPoP');
171
+ if (!bound && (scheme === 'dpop' || mode === 'required'))
172
+ throw reject('invalid_token', 'DPoP');
173
+ if (bound) {
174
+ const proof = single(header(req, 'dpop'));
175
+ let url;
176
+ try {
177
+ url = publicUrl(req);
178
+ }
179
+ catch {
180
+ throw reject('invalid_dpop_proof', 'DPoP');
181
+ }
182
+ if (typeof proof !== 'string' || typeof req.method !== 'string')
183
+ throw reject('invalid_dpop_proof', 'DPoP');
184
+ if (!verifyDpopProof({ proof, method: req.method, url, accessToken: token, jkt, algs: dpopAlgs, jti }))
185
+ throw reject('invalid_dpop_proof', 'DPoP');
186
+ }
187
+ const scopes = typeof p.scope === 'string' ? p.scope.split(' ').filter(Boolean) : [];
188
+ if (!required.every((s) => scopes.includes(s)))
189
+ throw reject('insufficient_scope');
190
+ return { sub: p.sub, clientId: p.client_id, scopes, expiresAt: p.exp * 1000, dpopBound: bound };
191
+ },
192
+ };
193
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@passport.lgbt/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "passport.lgbt server OIDC client, access-token verification, Express and Fastify middleware",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/passport-lgbt/sdk-js.git",
9
+ "directory": "packages/node"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/passport-lgbt/sdk-js/issues"
13
+ },
14
+ "homepage": "https://passport.lgbt",
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./express": {
23
+ "types": "./dist/express.d.ts",
24
+ "default": "./dist/express.js"
25
+ },
26
+ "./fastify": {
27
+ "types": "./dist/fastify.d.ts",
28
+ "default": "./dist/fastify.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README*.md",
35
+ "LICENSE",
36
+ "NOTICE"
37
+ ],
38
+ "engines": {
39
+ "node": ">=20.19"
40
+ },
41
+ "scripts": {
42
+ "test": "vitest run --root ../.. --project node"
43
+ },
44
+ "dependencies": {
45
+ "oauth4webapi": "3.8.8"
46
+ },
47
+ "peerDependencies": {
48
+ "fastify": "^4.28.0 || ^5.0.0"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "fastify": {
52
+ "optional": true
53
+ }
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "20.19.43",
57
+ "express4": "npm:express@4.22.3",
58
+ "express5": "npm:express@5.3.0",
59
+ "fastify": "5.12.7",
60
+ "fastify4": "npm:fastify@4.29.1"
61
+ },
62
+ "publishConfig": {
63
+ "access": "public"
64
+ }
65
+ }