@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.
- package/LICENSE +203 -0
- package/NOTICE +5 -0
- package/README.md +59 -2
- package/dist/client.d.ts +152 -0
- package/dist/client.js +523 -0
- package/dist/common.d.ts +33 -0
- package/dist/common.js +6 -0
- package/dist/discovery.d.ts +15 -0
- package/dist/discovery.js +90 -0
- package/dist/dpop.d.ts +28 -0
- package/dist/dpop.js +94 -0
- package/dist/errors.d.ts +69 -0
- package/dist/errors.js +146 -0
- package/dist/express.d.ts +34 -0
- package/dist/express.js +155 -0
- package/dist/fastify.d.ts +66 -0
- package/dist/fastify.js +108 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +7 -0
- package/dist/jwks.d.ts +43 -0
- package/dist/jwks.js +170 -0
- package/dist/refresh.d.ts +11 -0
- package/dist/refresh.js +29 -0
- package/dist/server/cookie.d.ts +9 -0
- package/dist/server/cookie.js +30 -0
- package/dist/server/crypto.d.ts +20 -0
- package/dist/server/crypto.js +71 -0
- package/dist/server/returnTo.d.ts +6 -0
- package/dist/server/returnTo.js +20 -0
- package/dist/server/routes.d.ts +86 -0
- package/dist/server/routes.js +513 -0
- package/dist/server/session.d.ts +120 -0
- package/dist/server/session.js +268 -0
- package/dist/transaction.d.ts +52 -0
- package/dist/transaction.js +104 -0
- package/dist/userinfo.d.ts +7 -0
- package/dist/userinfo.js +32 -0
- package/dist/verifier.d.ts +53 -0
- package/dist/verifier.js +193 -0
- package/package.json +63 -4
package/dist/fastify.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { PRIVATE_NO_STORE, createServerCore, formFields, varyWithCookie } from './server/routes.js';
|
|
2
|
+
const resolvedByRequest = new WeakMap();
|
|
3
|
+
function coreRequest(request) {
|
|
4
|
+
return { method: request.method, url: request.raw.url ?? request.url, headers: request.headers };
|
|
5
|
+
}
|
|
6
|
+
/** Réponses qui portent un cookie du SDK : `onSend` y impose `Cache-Control: private, no-store` et `Vary: Cookie` (M1). */
|
|
7
|
+
const privateReplies = new WeakSet();
|
|
8
|
+
function addCookies(reply, cookies) {
|
|
9
|
+
if (cookies.length === 0)
|
|
10
|
+
return;
|
|
11
|
+
privateReplies.add(reply);
|
|
12
|
+
const prev = reply.getHeader('set-cookie');
|
|
13
|
+
const list = Array.isArray(prev) ? prev : typeof prev === 'string' ? [prev] : [];
|
|
14
|
+
reply.header('set-cookie', [...list, ...cookies]);
|
|
15
|
+
}
|
|
16
|
+
function send(reply, out) {
|
|
17
|
+
reply.code(out.status);
|
|
18
|
+
for (const [k, v] of Object.entries(out.headers))
|
|
19
|
+
reply.header(k, v);
|
|
20
|
+
addCookies(reply, out.setCookies);
|
|
21
|
+
return reply.send(out.body ?? '');
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Plugin Fastify (4 et 5) du mode serveur : routes `{basePath}/login`, `/callback`, `/logout` (POST), `/me` (journalisées
|
|
25
|
+
* au niveau `warn` seulement : l'URL de retour porte un code), `request.passport` sur toutes les requêtes,
|
|
26
|
+
* `fastify.passport.requireUser` et `fastify.passport.requireAccessToken(...)` (crochets `preHandler`). Les décorations
|
|
27
|
+
* valent pour toute l'appli (`skip-override`) ; les routes du SDK, et leur analyseur de formulaire vide, restent
|
|
28
|
+
* encapsulées.
|
|
29
|
+
*/
|
|
30
|
+
const plugin = async (fastify, opts) => {
|
|
31
|
+
const core = await createServerCore(opts);
|
|
32
|
+
const logoutUrl = `${core.basePath}/logout`;
|
|
33
|
+
const anonymous = () => ({ logoutUrl, accessToken: () => Promise.reject(new Error('passport.lgbt: no session')) });
|
|
34
|
+
fastify.decorateRequest('passport', null);
|
|
35
|
+
// au dernier moment, après les en-têtes de l'appli : une session ne va jamais dans un cache partagé
|
|
36
|
+
fastify.addHook('onSend', async (_request, reply, payload) => {
|
|
37
|
+
if (privateReplies.has(reply)) {
|
|
38
|
+
reply.header('cache-control', PRIVATE_NO_STORE);
|
|
39
|
+
reply.header('vary', varyWithCookie(reply.getHeader('vary')));
|
|
40
|
+
}
|
|
41
|
+
return payload;
|
|
42
|
+
});
|
|
43
|
+
fastify.addHook('onRequest', async (request, reply) => {
|
|
44
|
+
let resolved;
|
|
45
|
+
try {
|
|
46
|
+
resolved = await core.resolve(coreRequest(request));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
resolved = { state: 'none', setCookies: [], view: anonymous() };
|
|
50
|
+
}
|
|
51
|
+
resolvedByRequest.set(request, resolved);
|
|
52
|
+
request.passport = resolved.view;
|
|
53
|
+
addCookies(reply, resolved.setCookies);
|
|
54
|
+
// retour de l'émetteur après une déconnexion avec `returnTo` (route de l'appli)
|
|
55
|
+
const back = core.intercept(coreRequest(request));
|
|
56
|
+
if (back)
|
|
57
|
+
return send(reply, back);
|
|
58
|
+
return undefined;
|
|
59
|
+
});
|
|
60
|
+
await fastify.register(async (child) => {
|
|
61
|
+
// un formulaire de déconnexion (POST sans corps utile) ne doit pas finir en 415
|
|
62
|
+
const form = 'application/x-www-form-urlencoded';
|
|
63
|
+
if (!child.hasContentTypeParser(form))
|
|
64
|
+
child.addContentTypeParser(form, { parseAs: 'string', bodyLimit: 4096 }, (_req, body, done) => done(null, formFields(body)));
|
|
65
|
+
const handler = async (request, reply) => {
|
|
66
|
+
const resolved = resolvedByRequest.get(request) ?? { state: 'none', setCookies: [], view: anonymous() };
|
|
67
|
+
try {
|
|
68
|
+
const creq = coreRequest(request);
|
|
69
|
+
if (request.method === 'POST')
|
|
70
|
+
creq.body = formFields(request.body);
|
|
71
|
+
const out = await core.handle(creq, resolved);
|
|
72
|
+
return send(reply, out ?? { status: 404, headers: { 'cache-control': 'no-store' }, setCookies: [] });
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return send(reply, core.internalError());
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
for (const route of ['login', 'callback', 'me'])
|
|
79
|
+
child.route({ method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], url: `${core.basePath}/${route}`, logLevel: 'warn', handler });
|
|
80
|
+
child.route({ method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], url: logoutUrl, logLevel: 'warn', handler });
|
|
81
|
+
});
|
|
82
|
+
const passport = {
|
|
83
|
+
requireUser: async (request, reply) => {
|
|
84
|
+
const resolved = resolvedByRequest.get(request);
|
|
85
|
+
const out = resolved ? core.guard(coreRequest(request), resolved) : core.internalError();
|
|
86
|
+
return out ? send(reply, out) : undefined;
|
|
87
|
+
},
|
|
88
|
+
requireAccessToken: (v) => {
|
|
89
|
+
const check = core.accessTokenGuard(v);
|
|
90
|
+
return async (request, reply) => {
|
|
91
|
+
const r = await check(coreRequest(request)).catch(() => ({ response: core.internalError() }));
|
|
92
|
+
if ('response' in r)
|
|
93
|
+
return send(reply, r.response);
|
|
94
|
+
request.passport = { ...(request.passport ?? anonymous()), token: r.token };
|
|
95
|
+
return undefined;
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
fastify.decorate('passport', passport);
|
|
100
|
+
};
|
|
101
|
+
// sans fastify-plugin : les décorations et le crochet `onRequest` valent pour l'appli entière
|
|
102
|
+
Object.defineProperty(plugin, Symbol.for('skip-override'), { value: true });
|
|
103
|
+
Object.defineProperty(plugin, Symbol.for('fastify.display-name'), { value: '@passport.lgbt/node' });
|
|
104
|
+
/**
|
|
105
|
+
* Plugin Fastify 4 et 5 : `await app.register(passportFastify, options)`. Le type est celui de Fastify ; l'implémentation
|
|
106
|
+
* n'en dépend que structurellement (aucune importation à l'exécution).
|
|
107
|
+
*/
|
|
108
|
+
export const passportFastify = plugin;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { ACR } from './common.js';
|
|
2
|
+
export type { Acr, Locale, PassportUser, Scope } from './common.js';
|
|
3
|
+
export { PassportError } from './errors.js';
|
|
4
|
+
export type { PassportErrorCode } from './errors.js';
|
|
5
|
+
export { createPassportClient } from './client.js';
|
|
6
|
+
export type { IntrospectionResult, PassportClient, PassportClientOptions, ResourceTokenSet, TokenSet } from './client.js';
|
|
7
|
+
export type { AuthTransaction, AuthorizationOptions } from './transaction.js';
|
|
8
|
+
export { AccessTokenError, createAccessTokenVerifier } from './verifier.js';
|
|
9
|
+
export type { AccessTokenErrorCode, AccessTokenVerifierOptions, VerifiableRequest, VerifiedAccessToken } from './verifier.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @passport.lgbt/node : client OIDC serveur de passport.lgbt et vérification des jetons d'accès d'une API ressource.
|
|
2
|
+
// Mode serveur (session chiffrée, routes /login, /callback, /logout, /me) : sous-chemins `@passport.lgbt/node/express` et
|
|
3
|
+
// `@passport.lgbt/node/fastify`.
|
|
4
|
+
export { ACR } from './common.js';
|
|
5
|
+
export { PassportError } from './errors.js';
|
|
6
|
+
export { createPassportClient } from './client.js';
|
|
7
|
+
export { AccessTokenError, createAccessTokenVerifier } from './verifier.js';
|
package/dist/jwks.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { KeyObject } from 'node:crypto';
|
|
2
|
+
export interface DecodedJws {
|
|
3
|
+
header: Record<string, unknown>;
|
|
4
|
+
payload: Record<string, unknown>;
|
|
5
|
+
/** `en-tête.charge` tel que reçu (entrée de la signature). */
|
|
6
|
+
signingInput: string;
|
|
7
|
+
signature: Buffer;
|
|
8
|
+
}
|
|
9
|
+
/** Découpe un JWS compact ; `undefined` s'il n'en est pas un (trois segments base64url, en-tête et charge JSON objets). */
|
|
10
|
+
export declare function decodeJws(token: string): DecodedJws | undefined;
|
|
11
|
+
/** Algorithmes de signature pris en charge (jetons d'accès : ES256 seul ; preuves DPoP : selon la découverte). */
|
|
12
|
+
export type JwsAlg = 'ES256' | 'EdDSA' | 'RS256';
|
|
13
|
+
export declare const SUPPORTED_ALGS: ReadonlySet<string>;
|
|
14
|
+
/** La clé publique convient-elle à l'algorithme ? (pas de clé privée, type et courbe attendus, RSA ≥ 2048 bits) */
|
|
15
|
+
export declare function keyFitsAlg(jwk: Record<string, unknown>, alg: string): boolean;
|
|
16
|
+
/** Clé publique tirée d'une JWK ; `undefined` si elle ne convient pas à l'algorithme. */
|
|
17
|
+
export declare function importKey(jwk: Record<string, unknown>, alg: string): KeyObject | undefined;
|
|
18
|
+
export declare function verifyJws(jws: DecodedJws, alg: string, key: KeyObject): boolean;
|
|
19
|
+
/** Empreinte JWK (RFC 7638, SHA-256, base64url) d'une clé publique EC, OKP ou RSA. */
|
|
20
|
+
export declare function jwkThumbprint(jwk: Record<string, unknown>): string | undefined;
|
|
21
|
+
/** Durée de fraîcheur du JWKS. */
|
|
22
|
+
export declare const JWKS_TTL_MS: number;
|
|
23
|
+
/** Délai minimal entre deux lectures (kid inconnu, ou relecture après échéance). */
|
|
24
|
+
export declare const JWKS_COOLDOWN_MS = 30000;
|
|
25
|
+
/** Clés gardées après la dernière lecture réussie si l'émetteur est injoignable. */
|
|
26
|
+
export declare const JWKS_STALE_MS: number;
|
|
27
|
+
export interface JwksOptions {
|
|
28
|
+
/** Rend l'URL du JWKS (découverte, lue à la demande). */
|
|
29
|
+
uri: () => Promise<string>;
|
|
30
|
+
fetch: typeof fetch;
|
|
31
|
+
signal: () => AbortSignal;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Clés de signature des jetons d'accès (EC P-256, ES256) : JWKS gardé 10 min ; `kid` inconnu → une relecture, au plus une
|
|
35
|
+
* toutes les 30 s (lectures simultanées partagées) ; émetteur injoignable → dernières clés gardées jusqu'à 1 h après la
|
|
36
|
+
* dernière lecture réussie, puis `PassportError('network')`.
|
|
37
|
+
*/
|
|
38
|
+
export declare class JwksCache {
|
|
39
|
+
#private;
|
|
40
|
+
constructor(o: JwksOptions);
|
|
41
|
+
/** Clé du `kid`, ou `undefined` si l'émetteur ne la publie pas. */
|
|
42
|
+
key(kid: string): Promise<KeyObject | undefined>;
|
|
43
|
+
}
|
package/dist/jwks.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { createHash, createPublicKey, verify as verifySignature } from 'node:crypto';
|
|
2
|
+
import { PassportError } from './errors.js';
|
|
3
|
+
const B64U = /^[A-Za-z0-9_-]*$/;
|
|
4
|
+
function jsonPart(part) {
|
|
5
|
+
if (!B64U.test(part) || part.length === 0)
|
|
6
|
+
return undefined;
|
|
7
|
+
try {
|
|
8
|
+
const v = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'));
|
|
9
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Découpe un JWS compact ; `undefined` s'il n'en est pas un (trois segments base64url, en-tête et charge JSON objets). */
|
|
16
|
+
export function decodeJws(token) {
|
|
17
|
+
const parts = token.split('.');
|
|
18
|
+
if (parts.length !== 3)
|
|
19
|
+
return undefined;
|
|
20
|
+
const [h, p, s] = parts;
|
|
21
|
+
const header = jsonPart(h);
|
|
22
|
+
const payload = jsonPart(p);
|
|
23
|
+
if (!header || !payload || !B64U.test(s) || s.length === 0)
|
|
24
|
+
return undefined;
|
|
25
|
+
return { header, payload, signingInput: `${h}.${p}`, signature: Buffer.from(s, 'base64url') };
|
|
26
|
+
}
|
|
27
|
+
export const SUPPORTED_ALGS = new Set(['ES256', 'EdDSA', 'RS256']);
|
|
28
|
+
/** La clé publique convient-elle à l'algorithme ? (pas de clé privée, type et courbe attendus, RSA ≥ 2048 bits) */
|
|
29
|
+
export function keyFitsAlg(jwk, alg) {
|
|
30
|
+
if ('d' in jwk || 'p' in jwk || 'k' in jwk)
|
|
31
|
+
return false;
|
|
32
|
+
if (alg === 'ES256')
|
|
33
|
+
return jwk.kty === 'EC' && jwk.crv === 'P-256' && typeof jwk.x === 'string' && typeof jwk.y === 'string';
|
|
34
|
+
if (alg === 'EdDSA')
|
|
35
|
+
return jwk.kty === 'OKP' && jwk.crv === 'Ed25519' && typeof jwk.x === 'string';
|
|
36
|
+
if (alg === 'RS256')
|
|
37
|
+
return jwk.kty === 'RSA' && typeof jwk.n === 'string' && typeof jwk.e === 'string' && Buffer.from(jwk.n, 'base64url').length >= 256;
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
/** Clé publique tirée d'une JWK ; `undefined` si elle ne convient pas à l'algorithme. */
|
|
41
|
+
export function importKey(jwk, alg) {
|
|
42
|
+
if (!keyFitsAlg(jwk, alg))
|
|
43
|
+
return undefined;
|
|
44
|
+
const members = jwk.kty === 'EC' ? { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y } : jwk.kty === 'OKP' ? { kty: jwk.kty, crv: jwk.crv, x: jwk.x } : { kty: jwk.kty, n: jwk.n, e: jwk.e };
|
|
45
|
+
try {
|
|
46
|
+
return createPublicKey({ key: members, format: 'jwk' });
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function verifyJws(jws, alg, key) {
|
|
53
|
+
try {
|
|
54
|
+
const data = Buffer.from(jws.signingInput, 'ascii');
|
|
55
|
+
if (alg === 'ES256')
|
|
56
|
+
return jws.signature.length === 64 && verifySignature('sha256', data, { key, dsaEncoding: 'ieee-p1363' }, jws.signature);
|
|
57
|
+
if (alg === 'EdDSA')
|
|
58
|
+
return verifySignature(null, data, key, jws.signature);
|
|
59
|
+
if (alg === 'RS256')
|
|
60
|
+
return verifySignature('sha256', data, key, jws.signature);
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** Empreinte JWK (RFC 7638, SHA-256, base64url) d'une clé publique EC, OKP ou RSA. */
|
|
68
|
+
export function jwkThumbprint(jwk) {
|
|
69
|
+
let members;
|
|
70
|
+
if (jwk.kty === 'EC')
|
|
71
|
+
members = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
|
|
72
|
+
else if (jwk.kty === 'OKP')
|
|
73
|
+
members = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
|
|
74
|
+
else if (jwk.kty === 'RSA')
|
|
75
|
+
members = { e: jwk.e, kty: jwk.kty, n: jwk.n };
|
|
76
|
+
else
|
|
77
|
+
return undefined;
|
|
78
|
+
if (!Object.values(members).every((v) => typeof v === 'string'))
|
|
79
|
+
return undefined;
|
|
80
|
+
return createHash('sha256').update(JSON.stringify(members), 'utf8').digest('base64url');
|
|
81
|
+
}
|
|
82
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
83
|
+
// JWKS de l'émetteur, en cache
|
|
84
|
+
/** Durée de fraîcheur du JWKS. */
|
|
85
|
+
export const JWKS_TTL_MS = 10 * 60_000;
|
|
86
|
+
/** Délai minimal entre deux lectures (kid inconnu, ou relecture après échéance). */
|
|
87
|
+
export const JWKS_COOLDOWN_MS = 30_000;
|
|
88
|
+
/** Clés gardées après la dernière lecture réussie si l'émetteur est injoignable. */
|
|
89
|
+
export const JWKS_STALE_MS = 60 * 60_000;
|
|
90
|
+
/**
|
|
91
|
+
* Clés de signature des jetons d'accès (EC P-256, ES256) : JWKS gardé 10 min ; `kid` inconnu → une relecture, au plus une
|
|
92
|
+
* toutes les 30 s (lectures simultanées partagées) ; émetteur injoignable → dernières clés gardées jusqu'à 1 h après la
|
|
93
|
+
* dernière lecture réussie, puis `PassportError('network')`.
|
|
94
|
+
*/
|
|
95
|
+
export class JwksCache {
|
|
96
|
+
#o;
|
|
97
|
+
#keys = new Map();
|
|
98
|
+
#fetchedAt = -Infinity;
|
|
99
|
+
#attemptedAt = -Infinity;
|
|
100
|
+
#missReadAt = -Infinity;
|
|
101
|
+
#failedAt = -Infinity;
|
|
102
|
+
#inFlight;
|
|
103
|
+
constructor(o) {
|
|
104
|
+
this.#o = o;
|
|
105
|
+
}
|
|
106
|
+
/** Clé du `kid`, ou `undefined` si l'émetteur ne la publie pas. */
|
|
107
|
+
async key(kid) {
|
|
108
|
+
const now = Date.now();
|
|
109
|
+
// après une lecture en échec, aucune nouvelle lecture pendant 30 s (pas un appel à l'émetteur par requête)
|
|
110
|
+
const backoff = now - this.#failedAt < JWKS_COOLDOWN_MS;
|
|
111
|
+
const stale = now - this.#fetchedAt > JWKS_TTL_MS && now - this.#attemptedAt >= JWKS_COOLDOWN_MS;
|
|
112
|
+
const miss = !this.#keys.has(kid) && now - this.#missReadAt >= JWKS_COOLDOWN_MS;
|
|
113
|
+
if (this.#inFlight || (!backoff && (stale || miss))) {
|
|
114
|
+
// la première lecture n'entame pas le délai des relectures pour kid inconnu
|
|
115
|
+
if (miss && !this.#inFlight && this.#fetchedAt !== -Infinity)
|
|
116
|
+
this.#missReadAt = now;
|
|
117
|
+
try {
|
|
118
|
+
await this.#read();
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// clés gardées jusqu'à 1 h après la dernière lecture réussie
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (Date.now() - this.#fetchedAt > JWKS_STALE_MS)
|
|
125
|
+
throw new PassportError('network');
|
|
126
|
+
return this.#keys.get(kid);
|
|
127
|
+
}
|
|
128
|
+
#read() {
|
|
129
|
+
if (this.#inFlight)
|
|
130
|
+
return this.#inFlight;
|
|
131
|
+
this.#attemptedAt = Date.now();
|
|
132
|
+
const p = (async () => {
|
|
133
|
+
try {
|
|
134
|
+
const res = await this.#o.fetch(await this.#o.uri(), { method: 'GET', headers: { accept: 'application/json' }, redirect: 'manual', signal: this.#o.signal() });
|
|
135
|
+
if (res.status !== 200)
|
|
136
|
+
throw new PassportError('network');
|
|
137
|
+
const doc = (await res.json());
|
|
138
|
+
if (!doc || !Array.isArray(doc.keys))
|
|
139
|
+
throw new PassportError('invalid_response');
|
|
140
|
+
const keys = new Map();
|
|
141
|
+
for (const k of doc.keys) {
|
|
142
|
+
if (!k || typeof k !== 'object')
|
|
143
|
+
continue;
|
|
144
|
+
const jwk = k;
|
|
145
|
+
if (typeof jwk.kid !== 'string' || keys.has(jwk.kid))
|
|
146
|
+
continue;
|
|
147
|
+
if (jwk.use !== undefined && jwk.use !== 'sig')
|
|
148
|
+
continue;
|
|
149
|
+
if (jwk.alg !== undefined && jwk.alg !== 'ES256')
|
|
150
|
+
continue;
|
|
151
|
+
const key = importKey(jwk, 'ES256');
|
|
152
|
+
if (key)
|
|
153
|
+
keys.set(jwk.kid, key);
|
|
154
|
+
}
|
|
155
|
+
this.#keys = keys;
|
|
156
|
+
this.#fetchedAt = Date.now();
|
|
157
|
+
this.#failedAt = -Infinity;
|
|
158
|
+
}
|
|
159
|
+
catch (e) {
|
|
160
|
+
this.#failedAt = Date.now();
|
|
161
|
+
throw e;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
this.#inFlight = undefined;
|
|
165
|
+
}
|
|
166
|
+
})();
|
|
167
|
+
this.#inFlight = p;
|
|
168
|
+
return p;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Empreinte SHA-256 d'un refresh token : seule clé gardée en mémoire, jamais le jeton lui-même. */
|
|
2
|
+
export declare function fingerprint(token: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Une seule opération en vol par refresh token dans le processus : les appels simultanés partagent la même promesse
|
|
5
|
+
* (la rotation des refresh tokens révoque toute la famille au moindre rejeu). L'entrée disparaît dès que l'opération se
|
|
6
|
+
* termine ; un appel ultérieur avec le même jeton repart vers l'émetteur (et y est refusé s'il a déjà tourné).
|
|
7
|
+
*/
|
|
8
|
+
export declare class RefreshQueue<T> {
|
|
9
|
+
#private;
|
|
10
|
+
run(token: string, op: () => Promise<T>): Promise<T>;
|
|
11
|
+
}
|
package/dist/refresh.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/** Empreinte SHA-256 d'un refresh token : seule clé gardée en mémoire, jamais le jeton lui-même. */
|
|
3
|
+
export function fingerprint(token) {
|
|
4
|
+
return createHash('sha256').update(token, 'utf8').digest('base64url');
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Une seule opération en vol par refresh token dans le processus : les appels simultanés partagent la même promesse
|
|
8
|
+
* (la rotation des refresh tokens révoque toute la famille au moindre rejeu). L'entrée disparaît dès que l'opération se
|
|
9
|
+
* termine ; un appel ultérieur avec le même jeton repart vers l'émetteur (et y est refusé s'il a déjà tourné).
|
|
10
|
+
*/
|
|
11
|
+
export class RefreshQueue {
|
|
12
|
+
#inFlight = new Map();
|
|
13
|
+
run(token, op) {
|
|
14
|
+
const key = fingerprint(token);
|
|
15
|
+
const current = this.#inFlight.get(key);
|
|
16
|
+
if (current)
|
|
17
|
+
return current;
|
|
18
|
+
const p = (async () => {
|
|
19
|
+
try {
|
|
20
|
+
return await op();
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
this.#inFlight.delete(key);
|
|
24
|
+
}
|
|
25
|
+
})();
|
|
26
|
+
this.#inFlight.set(key, p);
|
|
27
|
+
return p;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Préfixe imposé : cookie lié à l'hôte, `Secure`, `Path=/`, sans `Domain`. */
|
|
2
|
+
export declare const HOST_PREFIX = "__Host-";
|
|
3
|
+
/** Taille maximale d'un cookie (`nom=valeur`), sous la limite des navigateurs (4096). */
|
|
4
|
+
export declare const MAX_COOKIE_BYTES = 3800;
|
|
5
|
+
/** Cookies de l'en-tête `Cookie` ; la première occurrence d'un nom l'emporte. */
|
|
6
|
+
export declare function parseCookies(header: string | string[] | undefined): Map<string, string>;
|
|
7
|
+
export declare function serializeCookie(name: string, value: string, maxAgeSeconds: number): string;
|
|
8
|
+
export declare function clearCookie(name: string): string;
|
|
9
|
+
export declare function cookieBytes(name: string, value: string): number;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Préfixe imposé : cookie lié à l'hôte, `Secure`, `Path=/`, sans `Domain`. */
|
|
2
|
+
export const HOST_PREFIX = '__Host-';
|
|
3
|
+
/** Taille maximale d'un cookie (`nom=valeur`), sous la limite des navigateurs (4096). */
|
|
4
|
+
export const MAX_COOKIE_BYTES = 3800;
|
|
5
|
+
/** Cookies de l'en-tête `Cookie` ; la première occurrence d'un nom l'emporte. */
|
|
6
|
+
export function parseCookies(header) {
|
|
7
|
+
const out = new Map();
|
|
8
|
+
const lines = Array.isArray(header) ? header : header ? [header] : [];
|
|
9
|
+
for (const line of lines) {
|
|
10
|
+
for (const part of line.split(';')) {
|
|
11
|
+
const eq = part.indexOf('=');
|
|
12
|
+
if (eq <= 0)
|
|
13
|
+
continue;
|
|
14
|
+
const name = part.slice(0, eq).trim();
|
|
15
|
+
const value = part.slice(eq + 1).trim();
|
|
16
|
+
if (name && !out.has(name))
|
|
17
|
+
out.set(name, value);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
export function serializeCookie(name, value, maxAgeSeconds) {
|
|
23
|
+
return `${name}=${value}; Path=/; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}; HttpOnly; Secure; SameSite=Lax`;
|
|
24
|
+
}
|
|
25
|
+
export function clearCookie(name) {
|
|
26
|
+
return `${name}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`;
|
|
27
|
+
}
|
|
28
|
+
export function cookieBytes(name, value) {
|
|
29
|
+
return Buffer.byteLength(`${name}=${value}`, 'utf8');
|
|
30
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Usage d'une valeur chiffrée : transaction de connexion, session, ou `state` de déconnexion (porte `returnTo`). */
|
|
2
|
+
export type CookieUsage = 'tx' | 'session' | 'logout';
|
|
3
|
+
/**
|
|
4
|
+
* Chiffrement des cookies du mode serveur : AES-256-GCM, **une clé par secret, par cookie et par usage**, dérivée par
|
|
5
|
+
* HKDF-SHA256 (`info` = `pp:<émetteur>|<client>:<nom du cookie>:<usage>`), nom du cookie en données associées (AAD) et champ `typ` vérifié
|
|
6
|
+
* après déchiffrement. Une valeur de la transaction recopiée dans le cookie de session ne se déchiffre donc pas. Le premier
|
|
7
|
+
* secret chiffre ; tous déchiffrent (rotation).
|
|
8
|
+
*/
|
|
9
|
+
export declare class CookieSealer {
|
|
10
|
+
#private;
|
|
11
|
+
private readonly context;
|
|
12
|
+
/** `context` : émetteur et client de l'appli, mêlés à la dérivation : le cookie d'une autre appli ne s'ouvre pas. */
|
|
13
|
+
constructor(secrets: unknown, context: string);
|
|
14
|
+
seal(name: string, usage: CookieUsage, data: Record<string, unknown>): string;
|
|
15
|
+
/** Contenu du cookie, ou `undefined` (altéré, autre secret, autre cookie, autre usage). `secretIndex` > 0 : à réécrire. */
|
|
16
|
+
open(name: string, usage: CookieUsage, value: string | undefined): {
|
|
17
|
+
data: Record<string, unknown>;
|
|
18
|
+
secretIndex: number;
|
|
19
|
+
} | undefined;
|
|
20
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto';
|
|
2
|
+
import { DETAILS, configError } from '../errors.js';
|
|
3
|
+
const VERSION = 'v1';
|
|
4
|
+
const IV_BYTES = 12;
|
|
5
|
+
const TAG_BYTES = 16;
|
|
6
|
+
const MIN_SECRET_BYTES = 32;
|
|
7
|
+
/**
|
|
8
|
+
* Chiffrement des cookies du mode serveur : AES-256-GCM, **une clé par secret, par cookie et par usage**, dérivée par
|
|
9
|
+
* HKDF-SHA256 (`info` = `pp:<émetteur>|<client>:<nom du cookie>:<usage>`), nom du cookie en données associées (AAD) et champ `typ` vérifié
|
|
10
|
+
* après déchiffrement. Une valeur de la transaction recopiée dans le cookie de session ne se déchiffre donc pas. Le premier
|
|
11
|
+
* secret chiffre ; tous déchiffrent (rotation).
|
|
12
|
+
*/
|
|
13
|
+
export class CookieSealer {
|
|
14
|
+
context;
|
|
15
|
+
#secrets;
|
|
16
|
+
#keys = new Map();
|
|
17
|
+
/** `context` : émetteur et client de l'appli, mêlés à la dérivation : le cookie d'une autre appli ne s'ouvre pas. */
|
|
18
|
+
constructor(secrets, context) {
|
|
19
|
+
this.context = context;
|
|
20
|
+
if (!Array.isArray(secrets) || secrets.length === 0)
|
|
21
|
+
throw configError(DETAILS.sessionSecrets);
|
|
22
|
+
for (const s of secrets)
|
|
23
|
+
if (typeof s !== 'string' || Buffer.byteLength(s, 'utf8') < MIN_SECRET_BYTES)
|
|
24
|
+
throw configError(DETAILS.sessionSecrets);
|
|
25
|
+
this.#secrets = secrets.map((s) => Buffer.from(s, 'utf8'));
|
|
26
|
+
}
|
|
27
|
+
#key(index, name, usage) {
|
|
28
|
+
const id = `${index}:${name}:${usage}`;
|
|
29
|
+
let key = this.#keys.get(id);
|
|
30
|
+
if (!key) {
|
|
31
|
+
key = Buffer.from(hkdfSync('sha256', this.#secrets[index] ?? Buffer.alloc(0), Buffer.alloc(0), `pp:${this.context}:${name}:${usage}`, 32));
|
|
32
|
+
this.#keys.set(id, key);
|
|
33
|
+
}
|
|
34
|
+
return key;
|
|
35
|
+
}
|
|
36
|
+
seal(name, usage, data) {
|
|
37
|
+
const iv = randomBytes(IV_BYTES);
|
|
38
|
+
const cipher = createCipheriv('aes-256-gcm', this.#key(0, name, usage), iv);
|
|
39
|
+
cipher.setAAD(Buffer.from(name, 'utf8'));
|
|
40
|
+
const plain = Buffer.from(JSON.stringify({ ...data, typ: usage }), 'utf8');
|
|
41
|
+
const out = Buffer.concat([iv, cipher.update(plain), cipher.final(), cipher.getAuthTag()]);
|
|
42
|
+
return `${VERSION}.${out.toString('base64url')}`;
|
|
43
|
+
}
|
|
44
|
+
/** Contenu du cookie, ou `undefined` (altéré, autre secret, autre cookie, autre usage). `secretIndex` > 0 : à réécrire. */
|
|
45
|
+
open(name, usage, value) {
|
|
46
|
+
if (typeof value !== 'string' || !value.startsWith(`${VERSION}.`) || value.length > 8192)
|
|
47
|
+
return undefined;
|
|
48
|
+
const raw = Buffer.from(value.slice(VERSION.length + 1), 'base64url');
|
|
49
|
+
if (raw.length < IV_BYTES + TAG_BYTES + 2)
|
|
50
|
+
return undefined;
|
|
51
|
+
const iv = raw.subarray(0, IV_BYTES);
|
|
52
|
+
const tag = raw.subarray(raw.length - TAG_BYTES);
|
|
53
|
+
const body = raw.subarray(IV_BYTES, raw.length - TAG_BYTES);
|
|
54
|
+
for (let i = 0; i < this.#secrets.length; i++) {
|
|
55
|
+
try {
|
|
56
|
+
const decipher = createDecipheriv('aes-256-gcm', this.#key(i, name, usage), iv);
|
|
57
|
+
decipher.setAAD(Buffer.from(name, 'utf8'));
|
|
58
|
+
decipher.setAuthTag(tag);
|
|
59
|
+
const plain = Buffer.concat([decipher.update(body), decipher.final()]);
|
|
60
|
+
const data = JSON.parse(plain.toString('utf8'));
|
|
61
|
+
if (!data || typeof data !== 'object' || Array.isArray(data) || data.typ !== usage)
|
|
62
|
+
return undefined;
|
|
63
|
+
return { data: data, secretIndex: i };
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// secret suivant
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `returnTo` du mode serveur : chemin local de l'appli (règle de `safeReturnTo` : sortie normalisée contrôlée), sous le
|
|
3
|
+
* chemin de `appBaseUrl`, **hors des routes du SDK** (`{basePath}` et en dessous : une connexion qui renverrait vers
|
|
4
|
+
* `/login` bouclerait) ; sinon la racine de l'appli.
|
|
5
|
+
*/
|
|
6
|
+
export declare function appReturnTo(value: unknown, appBase: URL, callbackPath: string): string;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { safeReturnTo } from '../transaction.js';
|
|
2
|
+
/**
|
|
3
|
+
* `returnTo` du mode serveur : chemin local de l'appli (règle de `safeReturnTo` : sortie normalisée contrôlée), sous le
|
|
4
|
+
* chemin de `appBaseUrl`, **hors des routes du SDK** (`{basePath}` et en dessous : une connexion qui renverrait vers
|
|
5
|
+
* `/login` bouclerait) ; sinon la racine de l'appli.
|
|
6
|
+
*/
|
|
7
|
+
export function appReturnTo(value, appBase, callbackPath) {
|
|
8
|
+
const root = appBase.pathname.endsWith('/') ? appBase.pathname : `${appBase.pathname}/`;
|
|
9
|
+
const reference = new URL(callbackPath, appBase.origin);
|
|
10
|
+
const path = safeReturnTo(value, reference);
|
|
11
|
+
if (path === '/')
|
|
12
|
+
return root;
|
|
13
|
+
const basePath = callbackPath.replace(/\/callback$/, '');
|
|
14
|
+
const pathname = path.split('?')[0] ?? '';
|
|
15
|
+
if (basePath && (pathname === basePath || pathname.startsWith(`${basePath}/`)))
|
|
16
|
+
return root;
|
|
17
|
+
if (root !== '/' && !(path === root.slice(0, -1) || path.startsWith(root)))
|
|
18
|
+
return root;
|
|
19
|
+
return path;
|
|
20
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { PassportClientOptions } from '../client.js';
|
|
2
|
+
import type { Acr, PassportUser } from '../common.js';
|
|
3
|
+
import type { AccessTokenVerifierOptions, VerifiedAccessToken } from '../verifier.js';
|
|
4
|
+
import type { SessionStore, StoredSession } from './session.js';
|
|
5
|
+
export interface PassportServerOptions extends Omit<PassportClientOptions, 'onRefreshTokenRotated'> {
|
|
6
|
+
/** Défaut `/auth` : routes `/login`, `/callback`, `/logout`, `/me`. */
|
|
7
|
+
basePath?: string;
|
|
8
|
+
/** Origine publique de l'appli (`returnTo`, contrôle d'`Origin`, URL de retour) ; jamais l'en-tête `Host`. */
|
|
9
|
+
appBaseUrl: string;
|
|
10
|
+
session: {
|
|
11
|
+
/** Au moins 32 octets chacun ; le premier chiffre, tous déchiffrent (rotation). */
|
|
12
|
+
secrets: readonly string[];
|
|
13
|
+
/** Nom du cookie de session, préfixé de `__Host-` (défaut `pp_session`). */
|
|
14
|
+
cookieName?: string;
|
|
15
|
+
store?: SessionStore;
|
|
16
|
+
/** Durée de vie de la session, renouvellements compris (défaut : 7 jours). */
|
|
17
|
+
maxAgeSeconds?: number;
|
|
18
|
+
};
|
|
19
|
+
requireAcr?: readonly Acr[];
|
|
20
|
+
}
|
|
21
|
+
/** Requête vue par le cœur, indépendante du cadriciel. `url` : chemin et requête tels que reçus. */
|
|
22
|
+
export interface CoreRequest {
|
|
23
|
+
method: string;
|
|
24
|
+
url: string;
|
|
25
|
+
headers: Record<string, string | string[] | undefined>;
|
|
26
|
+
/** Corps de formulaire déjà lu (`POST {basePath}/logout`), champs texte seulement. */
|
|
27
|
+
body?: Record<string, string>;
|
|
28
|
+
}
|
|
29
|
+
export interface CoreResponse {
|
|
30
|
+
status: number;
|
|
31
|
+
headers: Record<string, string>;
|
|
32
|
+
setCookies: string[];
|
|
33
|
+
body?: string;
|
|
34
|
+
}
|
|
35
|
+
/** `req.passport` (Express) et `request.passport` (Fastify). */
|
|
36
|
+
export interface PassportRequestState {
|
|
37
|
+
/** Personne connectée ; absent sans session valable. */
|
|
38
|
+
user?: PassportUser;
|
|
39
|
+
/** Jeton pour appeler l'API (`resource` si configurée, sinon jeton de profil) ; rejette `session_ended` sans session. */
|
|
40
|
+
accessToken(): Promise<string>;
|
|
41
|
+
/** Route de déconnexion (`POST`). */
|
|
42
|
+
logoutUrl: string;
|
|
43
|
+
/** Jeton d'accès vérifié par `requireAccessToken`. */
|
|
44
|
+
token?: VerifiedAccessToken;
|
|
45
|
+
}
|
|
46
|
+
export type SessionState = 'none' | 'active' | 'expired' | 'unavailable';
|
|
47
|
+
export interface Resolved {
|
|
48
|
+
state: SessionState;
|
|
49
|
+
setCookies: string[];
|
|
50
|
+
view: PassportRequestState;
|
|
51
|
+
/** Session lue (même expirée), pour la déconnexion. */
|
|
52
|
+
session?: StoredSession;
|
|
53
|
+
storeId?: string;
|
|
54
|
+
/** `unavailable` parce que l'émetteur a répondu `429` : secondes d'attente (`Retry-After`). */
|
|
55
|
+
retryAfter?: number;
|
|
56
|
+
}
|
|
57
|
+
/** Champs texte d'un corps de formulaire (`application/x-www-form-urlencoded`), 4 Kio au plus ; sinon `{}`. */
|
|
58
|
+
export declare function formFields(body: unknown): Record<string, string>;
|
|
59
|
+
/** En-têtes de toute réponse qui porte (ou pourrait porter) une session : jamais en cache partagé (M1). */
|
|
60
|
+
export declare const PRIVATE_NO_STORE = "private, no-store";
|
|
61
|
+
/** `Vary` complété de `Cookie` (sans doublon). */
|
|
62
|
+
export declare function varyWithCookie(current: unknown): string;
|
|
63
|
+
/** Navigation de page (et non `fetch`) : `GET`, `Accept: text/html`, `Sec-Fetch-Mode` absent ou `navigate`. */
|
|
64
|
+
export declare function isNavigation(req: CoreRequest): boolean;
|
|
65
|
+
export interface ServerCore {
|
|
66
|
+
basePath: string;
|
|
67
|
+
resolve(req: CoreRequest): Promise<Resolved>;
|
|
68
|
+
/** Retour de l'émetteur après une déconnexion avec `returnTo` (sur `postLogoutRedirectUri`) ; sinon `undefined`. */
|
|
69
|
+
intercept(req: CoreRequest): CoreResponse | undefined;
|
|
70
|
+
/** Routes du SDK ; `undefined` si la requête n'en est pas une. */
|
|
71
|
+
handle(req: CoreRequest, resolved: Resolved): Promise<CoreResponse | undefined>;
|
|
72
|
+
/** `requireUser` : `undefined` si la personne est connectée, sinon la réponse (401, 302 `prompt=none`, 503). */
|
|
73
|
+
guard(req: CoreRequest, resolved: Resolved): CoreResponse | undefined;
|
|
74
|
+
/** `requireAccessToken` : jeton vérifié, ou réponse de refus (401, 403, 503). */
|
|
75
|
+
accessTokenGuard(v: Omit<AccessTokenVerifierOptions, 'issuer'>): (req: CoreRequest) => Promise<{
|
|
76
|
+
token: VerifiedAccessToken;
|
|
77
|
+
} | {
|
|
78
|
+
response: CoreResponse;
|
|
79
|
+
}>;
|
|
80
|
+
internalError(): CoreResponse;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Cœur du mode serveur, sans cadriciel : session dans un cookie `__Host-` chiffré (ou un `store`), renouvellement unique
|
|
84
|
+
* par refresh token, `onRefreshTokenRotated` **toujours** branché sur la session.
|
|
85
|
+
*/
|
|
86
|
+
export declare function createServerCore(o: PassportServerOptions): Promise<ServerCore>;
|