@astratra/security 1.11.0 → 1.12.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 +1 -1
- package/README.md +44 -0
- package/package.json +1 -1
- package/src/idTokens.js +214 -0
- package/src/index.d.ts +54 -0
- package/src/index.js +2 -1
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -820,6 +820,50 @@ déconnexion. Garde le secret d'appareil sous sa propre clé (non effacée par
|
|
|
820
820
|
`clear()`), et fonde l'offre « se connecter avec Face ID » sur la présence de ce
|
|
821
821
|
secret et sur `gate.read().supported`, pas sur `enabled`.
|
|
822
822
|
|
|
823
|
+
## Se connecter avec Google ou Apple (jetons d'identité)
|
|
824
|
+
|
|
825
|
+
L'app obtient un **jeton d'identité** OpenID Connect (Sign in with Apple,
|
|
826
|
+
Google Sign-In) et l'envoie au serveur, qui seul décide : il vérifie la
|
|
827
|
+
signature avec les clés publiées par le fournisseur (JWKS), l'émetteur,
|
|
828
|
+
l'audience (tes identifiants de client) et l'expiration. Aucune dépendance
|
|
829
|
+
JOSE : Node lit les JWK, `jsonwebtoken` vérifie.
|
|
830
|
+
|
|
831
|
+
```js
|
|
832
|
+
const { createGoogleIdTokenVerifier, createAppleIdTokenVerifier, hashNonce, IdTokenError } = require('@astratra/security');
|
|
833
|
+
|
|
834
|
+
const google = createGoogleIdTokenVerifier({ audiences: [IOS_CLIENT_ID, WEB_CLIENT_ID] });
|
|
835
|
+
const apple = createAppleIdTokenVerifier({ audiences: ['com.example.app', 'com.example.web'] });
|
|
836
|
+
|
|
837
|
+
try {
|
|
838
|
+
// Apple : l'app a demandé la connexion avec SHA-256(nonceBrut) ; le jeton porte cette empreinte.
|
|
839
|
+
const profile = await apple(req.body.idToken, { nonce: hashNonce(nonceBrutGardeParLeServeur) });
|
|
840
|
+
// { subject, email, emailVerified, relayEmail, audience, claims }
|
|
841
|
+
} catch (error) {
|
|
842
|
+
if (error instanceof IdTokenError) return res.status(error.statusCode).json({ code: error.code });
|
|
843
|
+
throw error;
|
|
844
|
+
}
|
|
845
|
+
```
|
|
846
|
+
|
|
847
|
+
Ce qui est garanti, et testé :
|
|
848
|
+
|
|
849
|
+
- **RS256 seulement** : `none` et HS256 sont refusés avant toute lecture.
|
|
850
|
+
- **Rotation bornée** : un `kid` inconnu recharge les clés une fois, jamais
|
|
851
|
+
plus d'une fois par `minRefreshMs` (60 s) ; les vérifications simultanées
|
|
852
|
+
partagent le chargement ; un fournisseur muet donne `keys_unavailable` (503).
|
|
853
|
+
- **Nonce** : s'il est donné, il doit être exactement celui du jeton
|
|
854
|
+
(comparaison à temps constant).
|
|
855
|
+
- **L'adresse n'est pas une preuve** : `emailVerified` n'est vrai que si le
|
|
856
|
+
fournisseur l'affirme (`email_verified`, booléen ou texte chez Apple), et
|
|
857
|
+
l'adresse relais d'Apple est signalée par `relayEmail`. Lie un compte au
|
|
858
|
+
fournisseur par `subject` (le `sub`), jamais par l'adresse.
|
|
859
|
+
- Les codes d'erreur sont stables : `malformed`, `unknown_key`,
|
|
860
|
+
`keys_unavailable`, `expired`, `invalid`, `nonce_mismatch` ; le message ne
|
|
861
|
+
contient jamais le jeton.
|
|
862
|
+
|
|
863
|
+
`createIdTokenVerifier({ jwksUrl, issuers, audiences })` sert tout autre
|
|
864
|
+
fournisseur OpenID Connect ; `fetch` et `now` s'injectent pour les tests (faux
|
|
865
|
+
JWKS signé localement, jamais le vrai réseau).
|
|
866
|
+
|
|
823
867
|
## Tests
|
|
824
868
|
|
|
825
869
|
```bash
|
package/package.json
CHANGED
package/src/idTokens.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vérifier un jeton d'identité OpenID Connect (Google, Apple, tout fournisseur
|
|
3
|
+
* qui publie ses clés en JWKS) sans dépendance JOSE : Node transforme chaque
|
|
4
|
+
* JWK en KeyObject, jsonwebtoken vérifie la signature, l'émetteur, l'audience
|
|
5
|
+
* et l'expiration.
|
|
6
|
+
*
|
|
7
|
+
* Ce que le module garantit, chaque point testé :
|
|
8
|
+
*
|
|
9
|
+
* RS256 SEULEMENT. Un jeton qui annonce « none » ou HS256 est refusé avant
|
|
10
|
+
* toute lecture de ses champs : la clé publique ne devient jamais un secret
|
|
11
|
+
* HMAC.
|
|
12
|
+
*
|
|
13
|
+
* ROTATION BORNÉE. Un `kid` inconnu déclenche UN rechargement des clés
|
|
14
|
+
* (les fournisseurs les font tourner), jamais plus d'une fois par
|
|
15
|
+
* `minRefreshMs` : un flot de jetons forgés ne transforme pas le serveur en
|
|
16
|
+
* relais qui martèle le fournisseur. Deux vérifications simultanées
|
|
17
|
+
* partagent le même rechargement.
|
|
18
|
+
*
|
|
19
|
+
* NONCE. Quand l'appelant donne le nonce attendu, le jeton doit porter
|
|
20
|
+
* exactement celui-là : un jeton capturé ailleurs ne se rejoue pas.
|
|
21
|
+
*
|
|
22
|
+
* L'ADRESSE N'EST PAS UNE PREUVE. `emailVerified` n'est vrai que si le
|
|
23
|
+
* fournisseur l'affirme ; l'adresse relais d'Apple (« Masquer mon
|
|
24
|
+
* adresse ») est signalée par `relayEmail`. Le lien durable entre un compte
|
|
25
|
+
* et le fournisseur est `subject` (le `sub`), jamais l'adresse.
|
|
26
|
+
*
|
|
27
|
+
* Toute erreur est une IdTokenError avec un code stable ; son message ne
|
|
28
|
+
* contient jamais le jeton.
|
|
29
|
+
*/
|
|
30
|
+
const crypto = require('crypto');
|
|
31
|
+
const jwt = require('jsonwebtoken');
|
|
32
|
+
|
|
33
|
+
const DEFAULT_CACHE_MS = 60 * 60 * 1000;
|
|
34
|
+
const DEFAULT_MIN_REFRESH_MS = 60 * 1000;
|
|
35
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
36
|
+
const MAX_KEYS = 50;
|
|
37
|
+
const MAX_TOKEN_LENGTH = 16 * 1024;
|
|
38
|
+
|
|
39
|
+
const GOOGLE_JWKS_URL = 'https://www.googleapis.com/oauth2/v3/certs';
|
|
40
|
+
const GOOGLE_ISSUERS = ['https://accounts.google.com', 'accounts.google.com'];
|
|
41
|
+
const APPLE_JWKS_URL = 'https://appleid.apple.com/auth/keys';
|
|
42
|
+
const APPLE_ISSUERS = ['https://appleid.apple.com'];
|
|
43
|
+
|
|
44
|
+
const ID_TOKEN_ERROR_CODES = ['malformed', 'unknown_key', 'keys_unavailable', 'expired', 'invalid', 'nonce_mismatch'];
|
|
45
|
+
|
|
46
|
+
class IdTokenError extends Error {
|
|
47
|
+
constructor(code, message) {
|
|
48
|
+
super(message || `ID token rejected (${code}).`);
|
|
49
|
+
this.name = 'IdTokenError';
|
|
50
|
+
this.code = code;
|
|
51
|
+
this.statusCode = code === 'keys_unavailable' ? 503 : 401;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const truthy = (value) => value === true || value === 'true';
|
|
56
|
+
|
|
57
|
+
/** L'empreinte d'un nonce telle qu'Apple la place dans le jeton : SHA-256 en hexadécimal. */
|
|
58
|
+
function hashNonce(rawNonce) {
|
|
59
|
+
return crypto.createHash('sha256').update(String(rawNonce)).digest('hex');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @param {object} options
|
|
64
|
+
* @param {string} options.jwksUrl
|
|
65
|
+
* @param {string[]} options.issuers
|
|
66
|
+
* @param {string[]} options.audiences identifiants de client acceptés (jamais vide).
|
|
67
|
+
* @param {Function} [options.fetch]
|
|
68
|
+
* @param {Function} [options.now] millisecondes (sert aussi à juger l'expiration).
|
|
69
|
+
* @param {number} [options.cacheMs]
|
|
70
|
+
* @param {number} [options.minRefreshMs]
|
|
71
|
+
* @param {number} [options.timeoutMs]
|
|
72
|
+
* @param {number} [options.clockToleranceSec]
|
|
73
|
+
*/
|
|
74
|
+
function createIdTokenVerifier(options = {}) {
|
|
75
|
+
const {
|
|
76
|
+
jwksUrl,
|
|
77
|
+
issuers,
|
|
78
|
+
audiences,
|
|
79
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
80
|
+
now = Date.now,
|
|
81
|
+
cacheMs = DEFAULT_CACHE_MS,
|
|
82
|
+
minRefreshMs = DEFAULT_MIN_REFRESH_MS,
|
|
83
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
84
|
+
clockToleranceSec = 0
|
|
85
|
+
} = options;
|
|
86
|
+
|
|
87
|
+
if (typeof jwksUrl !== 'string' || !jwksUrl || !Array.isArray(issuers) || issuers.length === 0
|
|
88
|
+
|| !Array.isArray(audiences) || audiences.filter((a) => typeof a === 'string' && a).length === 0) {
|
|
89
|
+
throw new Error('createIdTokenVerifier requires jwksUrl, issuers and audiences.');
|
|
90
|
+
}
|
|
91
|
+
if (typeof fetchImpl !== 'function') throw new Error('createIdTokenVerifier requires a fetch implementation.');
|
|
92
|
+
const audienceList = audiences.filter((a) => typeof a === 'string' && a);
|
|
93
|
+
|
|
94
|
+
let keys = new Map();
|
|
95
|
+
let fetchedAt = -Infinity;
|
|
96
|
+
let attemptedAt = -Infinity;
|
|
97
|
+
let inflight = null;
|
|
98
|
+
|
|
99
|
+
async function load() {
|
|
100
|
+
attemptedAt = now();
|
|
101
|
+
let body;
|
|
102
|
+
try {
|
|
103
|
+
const signal = typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : undefined;
|
|
104
|
+
const response = await fetchImpl(jwksUrl, signal ? { signal } : undefined);
|
|
105
|
+
if (!response || !response.ok) throw new Error('status');
|
|
106
|
+
body = await response.json();
|
|
107
|
+
} catch (_error) {
|
|
108
|
+
throw new IdTokenError('keys_unavailable', 'The identity provider keys could not be loaded.');
|
|
109
|
+
}
|
|
110
|
+
const next = new Map();
|
|
111
|
+
for (const jwk of (body && Array.isArray(body.keys) ? body.keys : []).slice(0, MAX_KEYS)) {
|
|
112
|
+
if (!jwk || typeof jwk.kid !== 'string' || jwk.kty !== 'RSA') continue;
|
|
113
|
+
if (jwk.use && jwk.use !== 'sig') continue;
|
|
114
|
+
try {
|
|
115
|
+
next.set(jwk.kid, crypto.createPublicKey({ key: jwk, format: 'jwk' }));
|
|
116
|
+
} catch (_error) { /* une clé illisible est ignorée, les autres restent */ }
|
|
117
|
+
}
|
|
118
|
+
keys = next;
|
|
119
|
+
fetchedAt = now();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function refresh() {
|
|
123
|
+
if (!inflight) inflight = load().finally(() => { inflight = null; });
|
|
124
|
+
return inflight;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function keyFor(kid) {
|
|
128
|
+
if (now() - fetchedAt >= cacheMs) {
|
|
129
|
+
/* Un fournisseur muet n'est pas réinterrogé à chaque jeton : on garde les anciennes clés jusqu'au prochain essai permis. */
|
|
130
|
+
if (now() - attemptedAt >= minRefreshMs || keys.size === 0) {
|
|
131
|
+
try { await refresh(); } catch (error) { if (keys.size === 0) throw error; }
|
|
132
|
+
}
|
|
133
|
+
} else if (!keys.has(kid) && now() - attemptedAt >= minRefreshMs) {
|
|
134
|
+
await refresh();
|
|
135
|
+
}
|
|
136
|
+
return keys.get(kid) || null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {string} idToken
|
|
141
|
+
* @param {object} [expected]
|
|
142
|
+
* @param {string|string[]} [expected.nonce] la valeur exacte attendue dans le jeton (ou les valeurs acceptées).
|
|
143
|
+
*/
|
|
144
|
+
return async function verifyIdToken(idToken, expected = {}) {
|
|
145
|
+
if (typeof idToken !== 'string' || !idToken || idToken.length > MAX_TOKEN_LENGTH) {
|
|
146
|
+
throw new IdTokenError('malformed');
|
|
147
|
+
}
|
|
148
|
+
const decoded = jwt.decode(idToken, { complete: true });
|
|
149
|
+
const header = decoded && decoded.header;
|
|
150
|
+
if (!header || header.alg !== 'RS256' || typeof header.kid !== 'string' || !header.kid) {
|
|
151
|
+
throw new IdTokenError('malformed');
|
|
152
|
+
}
|
|
153
|
+
const key = await keyFor(header.kid);
|
|
154
|
+
if (!key) throw new IdTokenError('unknown_key');
|
|
155
|
+
|
|
156
|
+
let claims;
|
|
157
|
+
try {
|
|
158
|
+
claims = jwt.verify(idToken, key, {
|
|
159
|
+
algorithms: ['RS256'],
|
|
160
|
+
issuer: issuers,
|
|
161
|
+
audience: audienceList,
|
|
162
|
+
clockTimestamp: Math.floor(now() / 1000),
|
|
163
|
+
clockTolerance: clockToleranceSec
|
|
164
|
+
});
|
|
165
|
+
} catch (error) {
|
|
166
|
+
throw new IdTokenError(error && error.name === 'TokenExpiredError' ? 'expired' : 'invalid');
|
|
167
|
+
}
|
|
168
|
+
if (!claims || typeof claims !== 'object' || typeof claims.sub !== 'string' || !claims.sub) {
|
|
169
|
+
throw new IdTokenError('invalid');
|
|
170
|
+
}
|
|
171
|
+
if (expected && expected.nonce !== undefined && expected.nonce !== null) {
|
|
172
|
+
/* Plusieurs valeurs acceptées : le nonce brut et son empreinte, quand l'appelant ne sait pas
|
|
173
|
+
si la bibliothèque de l'app a haché le nonce avant de le donner au fournisseur. */
|
|
174
|
+
const accepted = (Array.isArray(expected.nonce) ? expected.nonce : [expected.nonce]).map(String).filter(Boolean);
|
|
175
|
+
const got = Buffer.from(typeof claims.nonce === 'string' ? claims.nonce : '');
|
|
176
|
+
const matches = accepted.some((value) => {
|
|
177
|
+
const want = Buffer.from(value);
|
|
178
|
+
return want.length === got.length && crypto.timingSafeEqual(want, got);
|
|
179
|
+
});
|
|
180
|
+
if (!matches) throw new IdTokenError('nonce_mismatch');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const email = typeof claims.email === 'string' && claims.email.includes('@') ? claims.email.trim().toLowerCase() : null;
|
|
184
|
+
return {
|
|
185
|
+
subject: claims.sub,
|
|
186
|
+
email,
|
|
187
|
+
emailVerified: Boolean(email) && truthy(claims.email_verified),
|
|
188
|
+
relayEmail: truthy(claims.is_private_email) || (email ? email.endsWith('@privaterelay.appleid.com') : false),
|
|
189
|
+
audience: Array.isArray(claims.aud) ? claims.aud[0] : claims.aud,
|
|
190
|
+
claims
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function createGoogleIdTokenVerifier({ audiences, ...options } = {}) {
|
|
196
|
+
return createIdTokenVerifier({ jwksUrl: GOOGLE_JWKS_URL, issuers: GOOGLE_ISSUERS, audiences, ...options });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function createAppleIdTokenVerifier({ audiences, ...options } = {}) {
|
|
200
|
+
return createIdTokenVerifier({ jwksUrl: APPLE_JWKS_URL, issuers: APPLE_ISSUERS, audiences, ...options });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
module.exports = {
|
|
204
|
+
createIdTokenVerifier,
|
|
205
|
+
createGoogleIdTokenVerifier,
|
|
206
|
+
createAppleIdTokenVerifier,
|
|
207
|
+
hashNonce,
|
|
208
|
+
IdTokenError,
|
|
209
|
+
ID_TOKEN_ERROR_CODES,
|
|
210
|
+
GOOGLE_JWKS_URL,
|
|
211
|
+
GOOGLE_ISSUERS,
|
|
212
|
+
APPLE_JWKS_URL,
|
|
213
|
+
APPLE_ISSUERS
|
|
214
|
+
};
|
package/src/index.d.ts
CHANGED
|
@@ -894,3 +894,57 @@ export function createTrustedDeviceService(options: {
|
|
|
894
894
|
|
|
895
895
|
export const TRUSTED_DEVICE_ID_PATTERN: RegExp;
|
|
896
896
|
export const TRUSTED_DEVICE_SECRET_PATTERN: RegExp;
|
|
897
|
+
|
|
898
|
+
export const DEFAULT_PERMISSIONS_POLICY: 'geolocation=(), camera=(), microphone=(), payment=()';
|
|
899
|
+
export const DEFAULT_CSRF_COOKIE_NAME: 'astratra_csrf';
|
|
900
|
+
|
|
901
|
+
/* ────────────────────────── Jetons d'identité (OpenID Connect) ────────────────────────── */
|
|
902
|
+
|
|
903
|
+
export type IdTokenErrorCode = 'malformed' | 'unknown_key' | 'keys_unavailable' | 'expired' | 'invalid' | 'nonce_mismatch';
|
|
904
|
+
export const ID_TOKEN_ERROR_CODES: IdTokenErrorCode[];
|
|
905
|
+
|
|
906
|
+
export class IdTokenError extends Error {
|
|
907
|
+
name: 'IdTokenError';
|
|
908
|
+
code: IdTokenErrorCode;
|
|
909
|
+
/** 503 quand les clés du fournisseur sont injoignables, 401 sinon. */
|
|
910
|
+
statusCode: 401 | 503;
|
|
911
|
+
constructor(code: IdTokenErrorCode, message?: string);
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
export interface IdTokenProfile {
|
|
915
|
+
/** Le `sub` : le seul lien durable entre un compte et le fournisseur. */
|
|
916
|
+
subject: string;
|
|
917
|
+
/** En minuscules, ou null. */
|
|
918
|
+
email: string | null;
|
|
919
|
+
/** Vrai seulement si le fournisseur affirme avoir vérifié l'adresse. */
|
|
920
|
+
emailVerified: boolean;
|
|
921
|
+
/** Adresse relais d'Apple (« Masquer mon adresse »). */
|
|
922
|
+
relayEmail: boolean;
|
|
923
|
+
/** Le client pour lequel le jeton a été émis. */
|
|
924
|
+
audience: string;
|
|
925
|
+
claims: Record<string, unknown>;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
export interface IdTokenVerifierOptions {
|
|
929
|
+
jwksUrl: string;
|
|
930
|
+
issuers: string[];
|
|
931
|
+
audiences: string[];
|
|
932
|
+
fetch?: (url: string, init?: { signal?: AbortSignal }) => Promise<{ ok: boolean; status?: number; json(): Promise<unknown> }>;
|
|
933
|
+
now?: () => number;
|
|
934
|
+
cacheMs?: number;
|
|
935
|
+
minRefreshMs?: number;
|
|
936
|
+
timeoutMs?: number;
|
|
937
|
+
clockToleranceSec?: number;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
export type IdTokenVerifier = (idToken: string, expected?: { nonce?: string | string[] | null }) => Promise<IdTokenProfile>;
|
|
941
|
+
|
|
942
|
+
export function createIdTokenVerifier(options: IdTokenVerifierOptions): IdTokenVerifier;
|
|
943
|
+
export function createGoogleIdTokenVerifier(options: Omit<IdTokenVerifierOptions, 'jwksUrl' | 'issuers'>): IdTokenVerifier;
|
|
944
|
+
export function createAppleIdTokenVerifier(options: Omit<IdTokenVerifierOptions, 'jwksUrl' | 'issuers'>): IdTokenVerifier;
|
|
945
|
+
/** SHA-256 en hexadécimal, comme Apple place le nonce dans le jeton. */
|
|
946
|
+
export function hashNonce(rawNonce: string): string;
|
|
947
|
+
export const GOOGLE_JWKS_URL: string;
|
|
948
|
+
export const GOOGLE_ISSUERS: string[];
|
|
949
|
+
export const APPLE_JWKS_URL: string;
|
|
950
|
+
export const APPLE_ISSUERS: string[];
|