@astratra/security 1.12.1 → 1.14.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/README.md CHANGED
@@ -407,6 +407,20 @@ app.use('/auth', createLoginLimiter({
407
407
  app.use('/auth/login', createAccountLimiter({ onBlocked: ({ identifier }) => { /* ... */ } }));
408
408
  ```
409
409
 
410
+ Un compteur par zone, pour qu'un dépassement sur une page ne bloque pas les autres. Les noms forment une liste fermée, jamais une valeur tirée librement de l'adresse demandée :
411
+
412
+ ```js
413
+ const ZONES = new Set(['notes', 'reunions']);
414
+ app.use(createApiLimiter({
415
+ max: 300,
416
+ area: (req) => {
417
+ const premier = req.path.split('/')[1];
418
+ if (req.path.endsWith('/chapitres')) return { name: 'chapitres', max: 2000 };
419
+ return { name: ZONES.has(premier) ? premier : 'autres' };
420
+ }
421
+ }));
422
+ ```
423
+
410
424
  `createAccountLimiter()` identifie le compte via `req.body.email` par défaut : comme
411
425
  `createWafMiddleware()`, il doit être monté APRÈS `express.json()`/`express.urlencoded()`.
412
426
  Avant, `req.body` vaut `undefined` et toutes les tentatives retombent sur la clé
@@ -864,6 +878,89 @@ Ce qui est garanti, et testé :
864
878
  fournisseur OpenID Connect ; `fetch` et `now` s'injectent pour les tests (faux
865
879
  JWKS signé localement, jamais le vrai réseau).
866
880
 
881
+ ## Requêtes signées par la puce du téléphone (sans connexion)
882
+
883
+ Une app qui s'ouvre **sans écran de connexion**, mais ne répond qu'aux
884
+ téléphones qu'elle connaît. Le téléphone crée une paire de clés P-256 **dans sa
885
+ puce de sécurité** (Secure Enclave sur iPhone) : la clé privée n'en sort
886
+ jamais. Chaque requête porte une signature de ce qu'elle dit (méthode, chemin,
887
+ heure, nonce, empreinte du corps). Le serveur ne garde que la clé publique :
888
+ une copie de sa base ne signe rien.
889
+
890
+ Deux clés par appareil :
891
+
892
+ - la **clé d'appareil** signe chaque requête, sans rien demander ;
893
+ - la **clé Face ID** est créée par l'app avec un contrôle d'accès qui fait
894
+ refuser à la puce toute signature sans Face ID ou empreinte. Une route qui
895
+ l'exige reçoit une signature que la puce n'a produite qu'après la
896
+ vérification. Le serveur vérifie la clé, le téléphone garantit le contrôle.
897
+
898
+ ```js
899
+ const { createDeviceSignatureVerifier, createMemoryDeviceStore } = require('@astratra/security');
900
+
901
+ const appareils = createDeviceSignatureVerifier({
902
+ store: monStoreEnBase, // getDevice, countDevices, addDevice, revokeDevice, spendNonce (atomique)
903
+ maxDevices: 1 // le premier téléphone devient le seul ; l'enregistrement se ferme
904
+ });
905
+
906
+ app.use(express.raw({ type: '*/*' })); // la signature porte sur le corps BRUT
907
+ app.post('/appareil', async (req, res) => {
908
+ const { id, publicKey, biometricPublicKey, biometricSignature } = JSON.parse(req.body);
909
+ try {
910
+ await appareils.enroll({ method: req.method, path: req.originalUrl, headers: req.headers, body: req.body },
911
+ { id, publicKey, biometricPublicKey, biometricSignature });
912
+ res.status(201).json({ ok: true });
913
+ } catch { res.status(404).end(); }
914
+ });
915
+ app.get('/conversation', appareils.middleware({ rejectStatus: 404 }), lireConversation);
916
+ app.post('/arret-urgence', appareils.middleware({ requireBiometric: true, rejectStatus: 404 }), arreter);
917
+ ```
918
+
919
+ Les en-têtes : `x-device-id`, `x-device-time` (millisecondes), `x-device-nonce`
920
+ (16 à 128 caractères), `x-device-signature` (base64, DER ou brut 64 octets),
921
+ `x-device-key` (`device` ou `biometric`). Le texte signé est
922
+ `MÉTHODE\nchemin\nheure\nnonce\nsha256(corps) en base64url` — donné par
923
+ `canonicalDeviceRequest`.
924
+
925
+ Côté iPhone (Swift), les deux clés et une signature :
926
+
927
+ ```swift
928
+ import Security
929
+ import LocalAuthentication
930
+
931
+ func cleDansLaPuce(tag: String, faceID: Bool) throws -> SecKey {
932
+ var flags: SecAccessControlCreateFlags = [.privateKeyUsage]
933
+ if faceID { flags.insert(.biometryCurrentSet) }
934
+ let acces = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, flags, nil)!
935
+ let attributs: [String: Any] = [
936
+ kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
937
+ kSecAttrKeySizeInBits as String: 256,
938
+ kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
939
+ kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: true,
940
+ kSecAttrApplicationTag as String: Data(tag.utf8),
941
+ kSecAttrAccessControl as String: acces]
942
+ ]
943
+ var erreur: Unmanaged<CFError>?
944
+ guard let cle = SecKeyCreateRandomKey(attributs as CFDictionary, &erreur) else { throw erreur!.takeRetainedValue() }
945
+ return cle
946
+ }
947
+
948
+ // Clé publique à envoyer à l'enregistrement : les 65 octets bruts, en base64.
949
+ let publique = SecKeyCopyExternalRepresentation(SecKeyCopyPublicKey(cle)!, nil)! as Data
950
+
951
+ // Signature d'une requête (DER, ce que le serveur attend).
952
+ let signature = SecKeyCreateSignature(cle, .ecdsaSignatureMessageX962SHA256, Data(texteSigne.utf8) as CFData, nil)! as Data
953
+ ```
954
+
955
+ Les règles, chacune vérifiée par les tests : une signature de plus de
956
+ `maxSkewMs` (60 s) est refusée ; un nonce ne sert qu'une fois, même une seconde
957
+ après ; un octet changé dans le corps casse la signature ; l'enregistrement
958
+ prouve qu'on détient les clés ; une fausse signature ne grille pas le nonce du
959
+ vrai téléphone ; un appareil révoqué est refusé ; et chaque refus a la **même**
960
+ réponse, pour qu'un curieux n'apprenne rien. En production, `spendNonce` doit
961
+ être atomique (une insertion qui échoue sur un doublon), sinon deux serveurs
962
+ acceptent chacun le même rejeu.
963
+
867
964
  ## Tests
868
965
 
869
966
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/security",
3
- "version": "1.12.1",
3
+ "version": "1.14.0",
4
4
  "description": "Generic authentication and security middleware for Astratra workspaces.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Requests signed by a phone's secure chip (Secure Enclave on iPhone, StrongBox
3
+ * on Android): an app that opens without any sign-in screen, yet answers only
4
+ * the devices it knows.
5
+ *
6
+ * The phone makes a P-256 key pair INSIDE its chip; the private key never
7
+ * leaves it. Every request carries a signature of what it says (method, path,
8
+ * time, a nonce, a fingerprint of the body). The server keeps only the public
9
+ * key, so a copy of its database signs nothing.
10
+ *
11
+ * Two keys per device:
12
+ * - the DEVICE key signs every request, silently;
13
+ * - the BIOMETRIC key is created by the app with an access control that makes
14
+ * the chip refuse to sign without Face ID / a fingerprint. A route that
15
+ * requires it gets a signature the chip produced only after a biometric
16
+ * check. The server verifies the key, the phone guarantees the check.
17
+ *
18
+ * The rules, each one enforced below:
19
+ * - a signature older (or further in the future) than `maxSkewMs` is refused;
20
+ * - a nonce is spent once (`store.spendNonce`, atomic): a captured request
21
+ * replayed even a second later is refused;
22
+ * - the body is part of what is signed: a changed byte breaks the signature;
23
+ * - enrolment can be capped (`maxDevices`): with 1, the first phone becomes
24
+ * the only one and enrolment closes for good — "the one device" pattern;
25
+ * - enrolment proves possession: the new keys must sign the enrolment itself;
26
+ * - every refusal is the SAME answer, so a prober learns nothing.
27
+ */
28
+ const crypto = require('crypto');
29
+
30
+ const HEADER = {
31
+ device: 'x-device-id',
32
+ time: 'x-device-time',
33
+ nonce: 'x-device-nonce',
34
+ signature: 'x-device-signature',
35
+ key: 'x-device-key'
36
+ };
37
+ /* The DER header of a P-256 SubjectPublicKeyInfo: prepended to the 65-byte raw point iOS exports. */
38
+ const P256_SPKI_PREFIX = Buffer.from('3059301306072a8648ce3d020106082a8648ce3d030107034200', 'hex');
39
+ const NONCE = /^[A-Za-z0-9_-]{16,128}$/;
40
+ const DEVICE_ID = /^[A-Za-z0-9_-]{8,128}$/;
41
+
42
+ class DeviceSignatureError extends Error {
43
+ constructor(code) { super(code); this.code = code; this.name = 'DeviceSignatureError'; }
44
+ }
45
+
46
+ /**
47
+ * A public key as a phone hands it over: the raw uncompressed point (65 bytes,
48
+ * what SecKeyCopyExternalRepresentation gives), an SPKI DER, or a PEM.
49
+ */
50
+ function importPublicKey(value) {
51
+ if (typeof value !== 'string' || !value.trim()) throw new DeviceSignatureError('bad_key');
52
+ let key;
53
+ try {
54
+ if (value.includes('BEGIN PUBLIC KEY')) key = crypto.createPublicKey(value);
55
+ else {
56
+ const bytes = Buffer.from(value, 'base64');
57
+ const der = bytes.length === 65 && bytes[0] === 0x04 ? Buffer.concat([P256_SPKI_PREFIX, bytes]) : bytes;
58
+ key = crypto.createPublicKey({ key: der, format: 'der', type: 'spki' });
59
+ }
60
+ } catch {
61
+ throw new DeviceSignatureError('bad_key');
62
+ }
63
+ if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') throw new DeviceSignatureError('bad_key');
64
+ return key.export({ type: 'spki', format: 'pem' }).toString();
65
+ }
66
+
67
+ /** What is signed, byte for byte the same on the phone and on the server. */
68
+ function canonicalRequest({ method, path, time, nonce, body }) {
69
+ const digest = crypto.createHash('sha256').update(body === undefined || body === null ? '' : body).digest('base64url');
70
+ return [String(method).toUpperCase(), path, String(time), nonce, digest].join('\n');
71
+ }
72
+
73
+ /** Accepts the chip's DER (X9.62) signature, or the 64-byte raw form. */
74
+ function verifySignature(publicKeyPem, data, signatureB64) {
75
+ let signature;
76
+ try { signature = Buffer.from(String(signatureB64), 'base64'); } catch { return false; }
77
+ if (!signature.length) return false;
78
+ const dsaEncoding = signature.length === 64 ? 'ieee-p1363' : 'der';
79
+ try {
80
+ return crypto.verify('sha256', Buffer.from(data), { key: publicKeyPem, dsaEncoding }, signature);
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * In-memory store: one process, for development and tests. In production give
88
+ * a store backed by your database — `spendNonce` MUST be atomic (an INSERT
89
+ * that fails on a duplicate), or two servers each accept the same replay.
90
+ */
91
+ function createMemoryDeviceStore() {
92
+ const devices = new Map();
93
+ const nonces = new Map();
94
+ return {
95
+ async getDevice(id) { return devices.get(id) || null; },
96
+ async countDevices() { return [...devices.values()].filter((d) => !d.revokedAt).length; },
97
+ async addDevice(device) { if (devices.has(device.id)) return false; devices.set(device.id, { ...device }); return true; },
98
+ async revokeDevice(id, at) { const d = devices.get(id); if (d) d.revokedAt = at; return Boolean(d); },
99
+ async spendNonce(deviceId, nonce, expiresAt) {
100
+ const now = Date.now();
101
+ for (const [k, exp] of nonces) if (exp < now) nonces.delete(k);
102
+ const key = `${deviceId}:${nonce}`;
103
+ if (nonces.has(key)) return false;
104
+ nonces.set(key, expiresAt);
105
+ return true;
106
+ }
107
+ };
108
+ }
109
+
110
+ /**
111
+ * @param {object} options
112
+ * @param {object} options.store getDevice, countDevices, addDevice, revokeDevice, spendNonce (see createMemoryDeviceStore).
113
+ * @param {number} [options.maxSkewMs=60000] How far a signature's time may be from the server's.
114
+ * @param {number|null} [options.maxDevices=null] Cap on enrolled devices (1: the one-device pattern).
115
+ * @param {Function} [options.now]
116
+ */
117
+ function createDeviceSignatureVerifier(options = {}) {
118
+ const store = options.store;
119
+ for (const method of ['getDevice', 'countDevices', 'addDevice', 'revokeDevice', 'spendNonce']) {
120
+ if (!store || typeof store[method] !== 'function') throw new Error(`createDeviceSignatureVerifier requires options.store.${method}.`);
121
+ }
122
+ const maxSkewMs = options.maxSkewMs ?? 60_000;
123
+ const maxDevices = options.maxDevices ?? null;
124
+ const now = options.now || Date.now;
125
+
126
+ function readHeaders(headers) {
127
+ const get = (name) => {
128
+ const v = headers?.[name] ?? headers?.[name.toLowerCase()];
129
+ return Array.isArray(v) ? v[0] : v;
130
+ };
131
+ return {
132
+ deviceId: get(HEADER.device), time: Number(get(HEADER.time)), nonce: get(HEADER.nonce),
133
+ signature: get(HEADER.signature), keyKind: get(HEADER.key) === 'biometric' ? 'biometric' : 'device'
134
+ };
135
+ }
136
+
137
+ async function checkFreshness(deviceId, time, nonce) {
138
+ if (!Number.isFinite(time) || Math.abs(now() - time) > maxSkewMs) throw new DeviceSignatureError('stale');
139
+ if (typeof nonce !== 'string' || !NONCE.test(nonce)) throw new DeviceSignatureError('bad_nonce');
140
+ if (!(await store.spendNonce(deviceId, nonce, now() + 2 * maxSkewMs))) throw new DeviceSignatureError('replay');
141
+ }
142
+
143
+ /**
144
+ * Verifies one request. Returns { device, biometric } or throws DeviceSignatureError
145
+ * (code: unknown_device, stale, bad_nonce, replay, bad_signature, biometric_required, revoked).
146
+ * @param {{ method: string, path: string, headers: object, body?: string|Buffer }} request body: the RAW bytes.
147
+ * @param {{ requireBiometric?: boolean }} [rules]
148
+ */
149
+ async function verify(request, rules = {}) {
150
+ const h = readHeaders(request.headers);
151
+ if (typeof h.deviceId !== 'string' || !DEVICE_ID.test(h.deviceId)) throw new DeviceSignatureError('unknown_device');
152
+ const device = await store.getDevice(h.deviceId);
153
+ if (!device) throw new DeviceSignatureError('unknown_device');
154
+ if (device.revokedAt) throw new DeviceSignatureError('revoked');
155
+ if (rules.requireBiometric && h.keyKind !== 'biometric') throw new DeviceSignatureError('biometric_required');
156
+ const publicKey = h.keyKind === 'biometric' ? device.biometricPublicKey : device.publicKey;
157
+ if (!publicKey) throw new DeviceSignatureError('biometric_required');
158
+ const data = canonicalRequest({ method: request.method, path: request.path, time: h.time, nonce: h.nonce, body: request.body });
159
+ if (!verifySignature(publicKey, data, h.signature)) throw new DeviceSignatureError('bad_signature');
160
+ /* The nonce is spent only once the signature is good: a forger cannot burn a real phone's nonces. */
161
+ await checkFreshness(h.deviceId, h.time, h.nonce);
162
+ return { device: { id: device.id, label: device.label ?? null }, biometric: h.keyKind === 'biometric' };
163
+ }
164
+
165
+ /**
166
+ * Enrols a device. The enrolment request is itself signed by the new device key
167
+ * (and, when given, a second signature by the biometric key in `biometricSignature`):
168
+ * proof that the caller holds both private keys.
169
+ * @param {{ method: string, path: string, headers: object, body?: string|Buffer }} request
170
+ * @param {{ id: string, publicKey: string, biometricPublicKey?: string, label?: string, biometricSignature?: string }} enrolment
171
+ * @returns {Promise<{ id: string }>} or throws DeviceSignatureError (closed, exists, bad_key, bad_signature, stale, replay).
172
+ */
173
+ async function enroll(request, enrolment) {
174
+ if (!enrolment || typeof enrolment.id !== 'string' || !DEVICE_ID.test(enrolment.id)) throw new DeviceSignatureError('bad_request');
175
+ if (maxDevices !== null && (await store.countDevices()) >= maxDevices) throw new DeviceSignatureError('closed');
176
+ const publicKey = importPublicKey(enrolment.publicKey);
177
+ const biometricPublicKey = enrolment.biometricPublicKey ? importPublicKey(enrolment.biometricPublicKey) : null;
178
+ const h = readHeaders(request.headers);
179
+ if (h.deviceId !== enrolment.id) throw new DeviceSignatureError('bad_request');
180
+ const data = canonicalRequest({ method: request.method, path: request.path, time: h.time, nonce: h.nonce, body: request.body });
181
+ if (!verifySignature(publicKey, data, h.signature)) throw new DeviceSignatureError('bad_signature');
182
+ if (biometricPublicKey && !verifySignature(biometricPublicKey, data, enrolment.biometricSignature)) throw new DeviceSignatureError('bad_signature');
183
+ await checkFreshness(enrolment.id, h.time, h.nonce);
184
+ const added = await store.addDevice({ id: enrolment.id, publicKey, biometricPublicKey, label: enrolment.label ?? null, enrolledAt: now(), revokedAt: null });
185
+ if (!added) throw new DeviceSignatureError('exists');
186
+ /* Two phones racing for the last place: the store let both in; the later one is undone. */
187
+ if (maxDevices !== null && (await store.countDevices()) > maxDevices) {
188
+ await store.revokeDevice(enrolment.id, now());
189
+ throw new DeviceSignatureError('closed');
190
+ }
191
+ return { id: enrolment.id };
192
+ }
193
+
194
+ /** Whether a new device could still enrol. */
195
+ async function enrollmentOpen() {
196
+ return maxDevices === null || (await store.countDevices()) < maxDevices;
197
+ }
198
+
199
+ /**
200
+ * Express middleware: sets req.device, or answers `rejectStatus` (default 401;
201
+ * 404 to look like a service that does not exist). Needs the RAW body: mount
202
+ * express.raw() (or keep req.rawBody) before it.
203
+ */
204
+ function middleware({ requireBiometric = false, rejectStatus = 401 } = {}) {
205
+ return async (req, res, next) => {
206
+ try {
207
+ const body = Buffer.isBuffer(req.body) ? req.body : req.rawBody ?? (typeof req.body === 'string' ? req.body : '');
208
+ const result = await verify({ method: req.method, path: req.originalUrl || req.url, headers: req.headers, body }, { requireBiometric });
209
+ req.device = result.device;
210
+ req.deviceBiometric = result.biometric;
211
+ next();
212
+ } catch (error) {
213
+ if (!(error instanceof DeviceSignatureError)) return next(error);
214
+ res.status(rejectStatus).json({ message: rejectStatus === 404 ? 'Not found.' : 'Unauthorized.' });
215
+ }
216
+ };
217
+ }
218
+
219
+ return { verify, enroll, enrollmentOpen, middleware, revoke: (id) => store.revokeDevice(id, now()) };
220
+ }
221
+
222
+ module.exports = {
223
+ createDeviceSignatureVerifier,
224
+ createMemoryDeviceStore,
225
+ canonicalDeviceRequest: canonicalRequest,
226
+ importDevicePublicKey: importPublicKey,
227
+ DeviceSignatureError,
228
+ DEVICE_SIGNATURE_HEADERS: HEADER
229
+ };
package/src/index.d.ts CHANGED
@@ -304,7 +304,9 @@ export interface AccountLimiterOptions extends RateLimitOptions {
304
304
  onBlocked?: (context: AccountBlockedContext) => Awaitable<void>;
305
305
  }
306
306
 
307
- export function createApiLimiter(options?: RateLimitOptions): RequestHandler;
307
+ /** Un compteur à part pour une zone de l'application ; `max` remplace la limite générale. */
308
+ export interface RateLimitArea { name: string; max?: number }
309
+ export function createApiLimiter(options?: RateLimitOptions & { area?: (req: any) => RateLimitArea | null | undefined }): RequestHandler;
308
310
  export function createLoginLimiter(options?: LoginLimiterOptions): RequestHandler;
309
311
  export function createAccountLimiter(options?: AccountLimiterOptions): RequestHandler;
310
312
  export function skipLocalhost(req: RequestLike): boolean;
@@ -948,3 +950,46 @@ export const GOOGLE_JWKS_URL: string;
948
950
  export const GOOGLE_ISSUERS: string[];
949
951
  export const APPLE_JWKS_URL: string;
950
952
  export const APPLE_ISSUERS: string[];
953
+
954
+ /** One enrolled phone: public keys only, never a private key. */
955
+ export interface EnrolledDevice {
956
+ id: string;
957
+ publicKey: string;
958
+ biometricPublicKey: string | null;
959
+ label: string | null;
960
+ enrolledAt: number;
961
+ revokedAt: number | null;
962
+ }
963
+ export interface DeviceStore {
964
+ getDevice(id: string): Promise<EnrolledDevice | null>;
965
+ /** Devices not revoked. */
966
+ countDevices(): Promise<number>;
967
+ /** false when the id already exists. */
968
+ addDevice(device: EnrolledDevice): Promise<boolean>;
969
+ revokeDevice(id: string, at: number): Promise<boolean>;
970
+ /** MUST be atomic: false when this nonce was already spent by this device. */
971
+ spendNonce(deviceId: string, nonce: string, expiresAt: number): Promise<boolean>;
972
+ }
973
+ export interface SignedDeviceRequest {
974
+ method: string;
975
+ path: string;
976
+ headers: Record<string, string | string[] | undefined>;
977
+ /** The RAW body bytes. */
978
+ body?: string | Buffer;
979
+ }
980
+ export type DeviceSignatureErrorCode = 'unknown_device' | 'revoked' | 'stale' | 'bad_nonce' | 'replay' | 'bad_signature' | 'biometric_required' | 'closed' | 'exists' | 'bad_key' | 'bad_request';
981
+ export class DeviceSignatureError extends Error { code: DeviceSignatureErrorCode; }
982
+ export interface DeviceSignatureVerifier {
983
+ verify(request: SignedDeviceRequest, rules?: { requireBiometric?: boolean }): Promise<{ device: { id: string; label: string | null }; biometric: boolean }>;
984
+ enroll(request: SignedDeviceRequest, enrolment: { id: string; publicKey: string; biometricPublicKey?: string; biometricSignature?: string; label?: string }): Promise<{ id: string }>;
985
+ enrollmentOpen(): Promise<boolean>;
986
+ /** Sets req.device and req.deviceBiometric; needs the raw body (express.raw or req.rawBody). */
987
+ middleware(options?: { requireBiometric?: boolean; rejectStatus?: number }): RequestHandler;
988
+ revoke(id: string): Promise<boolean>;
989
+ }
990
+ export function createDeviceSignatureVerifier(options: { store: DeviceStore; maxSkewMs?: number; maxDevices?: number | null; now?: () => number }): DeviceSignatureVerifier;
991
+ export function createMemoryDeviceStore(): DeviceStore;
992
+ export function canonicalDeviceRequest(parts: { method: string; path: string; time: number | string; nonce: string; body?: string | Buffer | null }): string;
993
+ /** Raw 65-byte point (base64), SPKI DER (base64) or PEM, P-256 only; returns the SPKI PEM. */
994
+ export function importDevicePublicKey(value: string): string;
995
+ export const DEVICE_SIGNATURE_HEADERS: { device: string; time: string; nonce: string; signature: string; key: string };
package/src/index.js CHANGED
@@ -21,5 +21,6 @@ module.exports = {
21
21
  ...require('./privateFileLinks'),
22
22
  ...require('./loginDevices'),
23
23
  ...require('./trustedDevices'),
24
- ...require('./idTokens')
24
+ ...require('./idTokens'),
25
+ ...require('./deviceSignatures')
25
26
  };
@@ -174,15 +174,27 @@ const withOptionalStore = (limiterOptions, store) => {
174
174
 
175
175
  const defaultApiSkip = () => (process.env.NODE_ENV === 'production' ? undefined : skipLocalhost);
176
176
 
177
- const createApiLimiter = (options = {}) => rateLimit(withOptionalStore({
178
- windowMs: options.windowMs || 15 * 60 * 1000,
179
- max: options.max || 300,
180
- skip: options.skip ?? defaultApiSkip(),
181
- standardHeaders: options.standardHeaders ?? true,
182
- legacyHeaders: options.legacyHeaders ?? false,
183
- validate: options.validate || { ip: false },
184
- message: options.message || DEFAULT_API_MESSAGE
185
- }, resolveStore(options)));
177
+ /**
178
+ * `area(req)` sépare les compteurs : chaque zone rendue (`{ name, max }`) a le
179
+ * sien, par adresse. Avec un seul compteur, une boucle ou un gros téléchargement
180
+ * sur une page rendait toutes les autres indisponibles. L'application donne une
181
+ * liste fermée de noms : un nom tiré librement de l'adresse demandée offrirait
182
+ * un compteur neuf à chaque requête, donc plus aucune limite.
183
+ */
184
+ const createApiLimiter = (options = {}) => {
185
+ const fallback = options.max || 300;
186
+ const { area } = options;
187
+ return rateLimit(withOptionalStore({
188
+ windowMs: options.windowMs || 15 * 60 * 1000,
189
+ max: area ? (req) => area(req)?.max || fallback : fallback,
190
+ ...(area ? { keyGenerator: (req) => `${area(req)?.name || 'default'}:${getIp(req)}` } : {}),
191
+ skip: options.skip ?? defaultApiSkip(),
192
+ standardHeaders: options.standardHeaders ?? true,
193
+ legacyHeaders: options.legacyHeaders ?? false,
194
+ validate: options.validate || { ip: false },
195
+ message: options.message || DEFAULT_API_MESSAGE
196
+ }, resolveStore(options)));
197
+ };
186
198
 
187
199
  const createLoginLimiter = (options = {}) => rateLimit(withOptionalStore({
188
200
  windowMs: options.windowMs || 15 * 60 * 1000,