@astratra/core 1.2.0 → 1.3.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
@@ -22,11 +22,16 @@ const {
22
22
  errorMiddleware, // gestionnaire d'erreurs Express — masque message/stack en production, logge les 5xx via req.log ou console
23
23
  notFoundMiddleware, // gestionnaire 404 Express via apiResponse
24
24
  requestIdMiddleware, // attache req.requestId (header X-Request-Id, respecte un id entrant)
25
- validateMiddleware, // (validations) => exécute des validations express-validator, 400 si échec
25
+ validateMiddleware, // (validations) => lance des chaînes de validation, 400 si échec
26
+ body, param, query, header, cookie, check, // chaînes de validation, comme express-validator
27
+ validationResult, matchedData,
26
28
  loadEnv, // (schema) => lit process.env avec valeurs par défaut/requis/transform/validate
27
29
  idempotencyMiddleware, // (options) => une écriture rejouée avec la même clé ne s'exécute qu'une fois
28
30
  createIdempotency, // (options) => le même moteur, hors HTTP (tâches, files, RPC)
29
- createMemoryIdempotencyStore
31
+ createMemoryIdempotencyStore,
32
+ createGoogleServiceAccountAuth, // ({ credentials, scopes }) => { getAccessToken, request } — jeton d'un compte de service Google
33
+ createUpload, // ({ limits, fileFilter }) => { single, array, fields, none, any } — téléversements, sans multer
34
+ detectFileType // (buffer) => { ext, mime } | null — le vrai type d'un fichier, par ses premiers octets
30
35
  } = require('@astratra/core');
31
36
  ```
32
37
 
@@ -143,6 +148,106 @@ partagé entre instances.
143
148
  - Il ne protège pas les webhooks d'un prestataire de paiement : voir
144
149
  `@astratra/payments`, qui les reconnaît par l'identifiant d'événement.
145
150
 
151
+ ## Jeton d'un compte de service Google
152
+
153
+ Le jeton d'accès d'un compte de service Google (Wallet, Play, Firebase…), sans
154
+ google-auth-library : un JWT signé en RS256 avec la clé du compte, échangé contre
155
+ un jeton d'accès (RFC 7523).
156
+
157
+ ```js
158
+ const { createGoogleServiceAccountAuth } = require('@astratra/core');
159
+
160
+ const google = createGoogleServiceAccountAuth({
161
+ credentials: JSON.parse(process.env.GOOGLE_SERVICE_ACCOUNT_JSON),
162
+ scopes: ['https://www.googleapis.com/auth/wallet_object.issuer']
163
+ });
164
+ const token = await google.getAccessToken();
165
+ const { data } = await google.request({ method: 'GET', url: 'https://walletobjects.googleapis.com/walletobjects/v1/issuer' });
166
+ ```
167
+
168
+ - Le jeton est gardé jusqu'à cinq minutes avant son échéance ; des demandes
169
+ simultanées partagent un seul échange. `request()` rejoue une fois après un 401
170
+ avec un jeton neuf ; une réponse d'erreur lève `GoogleAuthError`
171
+ (`GOOGLE_API_ERROR`, avec `response.status` et `response.data`).
172
+ - L'adresse d'échange (`token_uri`) n'est acceptée qu'en https sur
173
+ `googleapis.com` : un fichier de compte de service modifié ne peut pas envoyer
174
+ l'assertion signée ailleurs. `allowedTokenUris` en permet une autre (émulateur).
175
+ - Une clé collée avec des `\n` écrits en toutes lettres est acceptée. Aucun
176
+ message d'erreur ne reprend la clé, l'assertion ou le jeton ; chaque appel à
177
+ Google a un délai (`timeoutMs`, 15 s).
178
+
179
+ ## Téléversement de fichiers
180
+
181
+ Le téléversement (`multipart/form-data`), lu au fil du flux et gardé en mémoire,
182
+ sans multer ni busboy. Les mêmes usages que multer en mémoire, les mêmes codes
183
+ d'erreur (`LIMIT_FILE_SIZE`, `LIMIT_UNEXPECTED_FILE`…, avec `status` 400 ou 413) :
184
+
185
+ ```js
186
+ const { createUpload, detectFileType } = require('@astratra/core');
187
+
188
+ const upload = createUpload({ limits: { fileSize: 5 * 1024 * 1024, files: 1 } });
189
+ app.post('/photos', upload.single('photo'), (req, res) => {
190
+ const type = detectFileType(req.file.buffer); // le type annoncé (req.file.mimetype) n'est pas une preuve
191
+ if (!type || !['jpg', 'png', 'webp'].includes(type.ext)) return res.status(400).end();
192
+ // req.file : fieldname, originalname (sans chemin), safeName, mimetype, size, buffer ; req.body : les autres champs
193
+ });
194
+ ```
195
+
196
+ - Des limites par défaut (multer n'en avait aucune) : 10 Mio par fichier, 10
197
+ fichiers, 100 champs, 1 Mio par champ, 200 parties, 50 Mio au total.
198
+ - Comparé à multer 2.4.0 sur 191 formulaires enregistrés : quand les deux
199
+ acceptent, mêmes champs et mêmes fichiers, octet pour octet. Écarts voulus :
200
+ noms lus en UTF-8 (multer donnait « élève »), champ `__proto__`,
201
+ `constructor` ou `prototype` refusé, en-tête répété dans une partie refusé,
202
+ partie sans `Content-Disposition` refusée, et rien n'est lu après la
203
+ frontière finale (busboy continuait).
204
+ - Un corps interrompu, des en-têtes trop longs ou une frontière absente sont des
205
+ erreurs 400, jamais une attente sans fin ; au-delà de la limite totale, le
206
+ reste du corps n'est pas gardé.
207
+
208
+ ## Valider une requête
209
+
210
+ Les chaînes de validation, à la manière d'express-validator 7, sans dépendance : mêmes méthodes, mêmes erreurs,
211
+ mêmes nettoyages écrits dans la requête. Un projet qui utilisait express-validator change seulement son `require`.
212
+
213
+ ```js
214
+ const { body, param, validationResult, matchedData, validateMiddleware } = require('@astratra/core');
215
+
216
+ router.post('/inscription',
217
+ body('email').trim().isEmail().normalizeEmail().withMessage('Adresse invalide'),
218
+ body('age').optional().isInt({ min: 13 }).toInt(),
219
+ body('password').isLength({ min: 12 }).hide(), // l'erreur ne renvoie pas le mot de passe
220
+ body('enfants.*.nom').trim().notEmpty(), // chaque élément d'un tableau
221
+ (req, res) => {
222
+ const result = validationResult(req);
223
+ if (!result.isEmpty()) return res.status(400).json({ errors: result.array() });
224
+ return res.json(matchedData(req)); // seulement les champs validés
225
+ });
226
+
227
+ router.patch('/reglages/:key', validateMiddleware([param('key').trim().notEmpty().isLength({ max: 200 })]), handler);
228
+ ```
229
+
230
+ Vérifications : `exists`, `notEmpty`, `isEmpty`, `isString`, `isArray`, `isObject`, `isBoolean`, `isEmail`,
231
+ `isLength`, `isInt`, `isFloat`, `isNumeric`, `isIn`, `isMongoId`, `isUUID`, `isHexadecimal`, `isIP`, `isFQDN`,
232
+ `isByteLength`, `contains`, `equals`, `matches`, `custom`. Nettoyages : `trim`, `ltrim`, `rtrim`, `escape`,
233
+ `unescape`, `normalizeEmail`, `toInt`, `toFloat`, `toBoolean`, `toDate`, `toLowerCase`, `toUpperCase`, `stripLow`,
234
+ `blacklist`, `whitelist`, `toArray`, `default`, `replace`, `customSanitizer`. Et `optional`, `not`, `bail`, `if`,
235
+ `withMessage`, `hide`. Une méthode absente (`isURL`…) échoue au démarrage de l'application, pas à la première
236
+ requête.
237
+
238
+ Plus sûr qu'express-validator :
239
+
240
+ - **Aucune écriture sur un prototype** : un champ ou un joker vers `__proto__`, `constructor` ou `prototype`
241
+ n'est jamais lu ni écrit, et seules les propriétés propres de la requête sont lues.
242
+ - **Aucune requête ne fait planter la validation** : un corps JSON comme `{"v":{"toString":0}}` ou
243
+ `{"v":[[{"toString":1}]]}`, ou un texte avec un demi-caractère Unicode, faisait lever une exception à
244
+ express-validator (une erreur 500) ; ici la valeur est simplement invalide.
245
+
246
+ Dans Express 5, `req.query` est recalculé à chaque lecture : un nettoyage ne s'y écrit pas (pas plus qu'avec
247
+ express-validator). La valeur nettoyée se lit dans `matchedData(req)`.
248
+
249
+ Le code vient en partie de validator.js et d'express-validator (licence MIT) : voir `THIRD-PARTY-NOTICES.md`.
250
+
146
251
  ## Tests
147
252
 
148
253
  ```bash
@@ -0,0 +1,56 @@
1
+ # Code repris d'autres projets
2
+
3
+ `src/validators.js` porte des fonctions de validator.js 13.15 (isEmail, isFQDN, isIP, isLength, isInt, isFloat,
4
+ normalizeEmail…), et `src/validation.js` reprend le fonctionnement des chaînes d'express-validator 7.3 (éléments de
5
+ chaîne, sélection des champs, résultats). Les deux projets sont publiés sous licence MIT ; leurs mentions suivent.
6
+
7
+ ## validator.js
8
+
9
+ ```
10
+ Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining
13
+ a copy of this software and associated documentation files (the
14
+ "Software"), to deal in the Software without restriction, including
15
+ without limitation the rights to use, copy, modify, merge, publish,
16
+ distribute, sublicense, and/or sell copies of the Software, and to
17
+ permit persons to whom the Software is furnished to do so, subject to
18
+ the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be
21
+ included in all copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
+ ```
31
+
32
+ ## express-validator
33
+
34
+ ```
35
+ The MIT License (MIT)
36
+
37
+ Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com>
38
+
39
+ Permission is hereby granted, free of charge, to any person obtaining a copy
40
+ of this software and associated documentation files (the "Software"), to deal
41
+ in the Software without restriction, including without limitation the rights
42
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
43
+ copies of the Software, and to permit persons to whom the Software is
44
+ furnished to do so, subject to the following conditions:
45
+
46
+ The above copyright notice and this permission notice shall be included in
47
+ all copies or substantial portions of the Software.
48
+
49
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
50
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
51
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
52
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
53
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
54
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
55
+ THE SOFTWARE.
56
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/core",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Generic core utilities for Astratra SaaS packages.",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -9,10 +9,17 @@
9
9
  "types": "src/index.d.ts",
10
10
  "type": "commonjs",
11
11
  "files": [
12
- "src"
12
+ "src",
13
+ "THIRD-PARTY-NOTICES.md"
13
14
  ],
15
+ "jest": {
16
+ "testMatch": [
17
+ "**/__tests__/**/*.test.js"
18
+ ]
19
+ },
14
20
  "scripts": {
15
- "test": "jest"
21
+ "test": "jest",
22
+ "verify:mutations": "node scripts/verify-google-mutations.cjs && node scripts/verify-upload-mutations.cjs && node scripts/verify-validation-mutations.cjs"
16
23
  },
17
24
  "keywords": [
18
25
  "astratra",
@@ -31,10 +38,9 @@
31
38
  "optional": true
32
39
  }
33
40
  },
34
- "dependencies": {
35
- "express-validator": "7.3.2"
36
- },
37
41
  "devDependencies": {
42
+ "@astratra/testkit": "^2.0.0",
43
+ "express": "^4.18.3 || ^5.0.0",
38
44
  "jest": "30.4.2"
39
45
  }
40
46
  }
@@ -0,0 +1,192 @@
1
+ /* global AbortSignal */
2
+ const crypto = require('node:crypto');
3
+ const { URLSearchParams } = require('node:url');
4
+
5
+ /*
6
+ * Le jeton d'accès d'un compte de service Google, sans google-auth-library : un JWT signé en RS256 avec la clé du
7
+ * compte, échangé contre un jeton d'accès (RFC 7523, « jwt-bearer »). Une seule écriture pour tous les paquets
8
+ * (Google Wallet, Google Play, Firebase…), au lieu d'une copie par projet.
9
+ *
10
+ * - Le jeton est gardé jusqu'à cinq minutes avant son échéance ; des demandes simultanées partagent un seul échange.
11
+ * - L'adresse d'échange (token_uri) n'est acceptée que chez Google, en https : un fichier de compte de service modifié
12
+ * ne peut pas envoyer l'assertion signée (valable une heure chez Google) à un autre serveur.
13
+ * - Aucun message d'erreur ne reprend la clé, l'assertion ou le jeton.
14
+ */
15
+
16
+ const DEFAULT_TOKEN_URI = 'https://oauth2.googleapis.com/token';
17
+ const ASSERTION_LIFETIME_SECONDS = 3600;
18
+ const REFRESH_MARGIN_MS = 5 * 60 * 1000;
19
+ const DEFAULT_TIMEOUT_MS = 15_000;
20
+
21
+ class GoogleAuthError extends Error {
22
+ constructor(code, message, status) {
23
+ super(message);
24
+ this.name = 'GoogleAuthError';
25
+ this.code = code;
26
+ if (status !== undefined) this.status = status;
27
+ }
28
+ }
29
+
30
+ /** Une adresse d'échange permise : https, sur googleapis.com (ou un de ses sous-domaines), sans identifiants. */
31
+ function isGoogleTokenUri(value) {
32
+ let url;
33
+ try {
34
+ url = new URL(String(value));
35
+ } catch {
36
+ return false;
37
+ }
38
+ return url.protocol === 'https:' && !url.username && !url.password && (url.hostname === 'googleapis.com' || url.hostname.endsWith('.googleapis.com')) && (url.port === '' || url.port === '443');
39
+ }
40
+
41
+ /** Le compte de service lu (objet, ou texte JSON), vérifié ; la clé privée devient un KeyObject RSA. */
42
+ function readServiceAccount(credentials, { allowedTokenUris } = {}) {
43
+ let account = credentials;
44
+ if (typeof account === 'string') {
45
+ try {
46
+ account = JSON.parse(account);
47
+ } catch {
48
+ throw new GoogleAuthError('GOOGLE_CREDENTIALS_INVALID', 'Google service account credentials are not valid JSON.');
49
+ }
50
+ }
51
+ if (!account || typeof account !== 'object' || Array.isArray(account)) {
52
+ throw new GoogleAuthError('GOOGLE_CREDENTIALS_INVALID', 'Google service account credentials must be an object.');
53
+ }
54
+ const clientEmail = account.client_email;
55
+ if (typeof clientEmail !== 'string' || !/^[^\s@]{1,128}@[^\s@]{1,253}$/.test(clientEmail)) {
56
+ throw new GoogleAuthError('GOOGLE_CREDENTIALS_INVALID', 'Google service account credentials need a client_email.');
57
+ }
58
+ if (typeof account.private_key !== 'string' || !account.private_key.includes('PRIVATE KEY')) {
59
+ throw new GoogleAuthError('GOOGLE_CREDENTIALS_INVALID', 'Google service account credentials need a PEM private_key.');
60
+ }
61
+ let privateKey;
62
+ try {
63
+ // Collée dans une variable d'environnement d'une ligne, la clé garde souvent ses « \n » écrits en toutes lettres.
64
+ privateKey = crypto.createPrivateKey(account.private_key.replace(/\\n/g, '\n'));
65
+ } catch {
66
+ throw new GoogleAuthError('GOOGLE_CREDENTIALS_INVALID', 'The private_key of the Google service account cannot be read.');
67
+ }
68
+ if (privateKey.asymmetricKeyType !== 'rsa') {
69
+ throw new GoogleAuthError('GOOGLE_CREDENTIALS_INVALID', `A Google service account key is RSA (got ${privateKey.asymmetricKeyType}).`);
70
+ }
71
+ const tokenUri = account.token_uri === undefined || account.token_uri === null || account.token_uri === '' ? DEFAULT_TOKEN_URI : account.token_uri;
72
+ const permitted = allowedTokenUris ? allowedTokenUris.includes(tokenUri) : isGoogleTokenUri(tokenUri);
73
+ if (!permitted) {
74
+ throw new GoogleAuthError('GOOGLE_TOKEN_URI_REFUSED', 'The token_uri of the Google service account is not a Google address (https on googleapis.com).');
75
+ }
76
+ return { clientEmail, privateKey, tokenUri, projectId: typeof account.project_id === 'string' ? account.project_id : undefined };
77
+ }
78
+
79
+ const base64urlJson = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
80
+
81
+ /** L'assertion signée (RS256) que Google échange contre un jeton d'accès. */
82
+ function signServiceAccountAssertion(account, { scopes, subject, nowSeconds = Math.floor(Date.now() / 1000) }) {
83
+ const header = base64urlJson({ alg: 'RS256', typ: 'JWT' });
84
+ const claims = base64urlJson({
85
+ iss: account.clientEmail,
86
+ scope: scopes.join(' '),
87
+ aud: account.tokenUri,
88
+ iat: nowSeconds,
89
+ exp: nowSeconds + ASSERTION_LIFETIME_SECONDS,
90
+ ...(subject ? { sub: subject } : {}),
91
+ });
92
+ const signature = crypto.sign('RSA-SHA256', Buffer.from(`${header}.${claims}`), account.privateKey).toString('base64url');
93
+ return `${header}.${claims}.${signature}`;
94
+ }
95
+
96
+ /**
97
+ * @param {object} options
98
+ * @param {object|string} options.credentials le JSON du compte de service (client_email, private_key, token_uri…).
99
+ * @param {string[]} options.scopes les portées demandées (au moins une).
100
+ * @param {string} [options.subject] un compte à emprunter (délégation à l'échelle du domaine).
101
+ * @param {Function} [options.fetch] remplace fetch (essais).
102
+ * @param {() => number} [options.now] l'heure en millisecondes (essais).
103
+ * @param {number} [options.timeoutMs] délai de chaque appel à Google (15 s).
104
+ * @param {string[]} [options.allowedTokenUris] adresses d'échange permises à la place de googleapis.com (essais, émulateur).
105
+ */
106
+ function createGoogleServiceAccountAuth({ credentials, scopes, subject, fetch: fetchImpl = globalThis.fetch, now = Date.now, timeoutMs = DEFAULT_TIMEOUT_MS, allowedTokenUris } = {}) {
107
+ const account = readServiceAccount(credentials, { allowedTokenUris });
108
+ if (!Array.isArray(scopes) || !scopes.length || !scopes.every((s) => typeof s === 'string' && /^https:\/\/\S+$/.test(s))) {
109
+ throw new GoogleAuthError('GOOGLE_SCOPES_INVALID', 'createGoogleServiceAccountAuth needs one or more https:// scopes.');
110
+ }
111
+ if (typeof fetchImpl !== 'function') throw new GoogleAuthError('GOOGLE_NO_FETCH', 'No fetch implementation available.');
112
+
113
+ let cached = null;
114
+ let pending = null;
115
+
116
+ const send = async (url, init) => {
117
+ try {
118
+ return await fetchImpl(url, { ...init, signal: init.signal || AbortSignal.timeout(timeoutMs) });
119
+ } catch (error) {
120
+ const reason = error && (error.name === 'TimeoutError' || error.name === 'AbortError') ? 'timed out' : error && error.code ? error.code : 'network error';
121
+ throw new GoogleAuthError('GOOGLE_UNREACHABLE', `Google could not be reached (${reason}).`, 502);
122
+ }
123
+ };
124
+
125
+ async function exchange() {
126
+ const assertion = signServiceAccountAssertion(account, { scopes, subject, nowSeconds: Math.floor(now() / 1000) });
127
+ const response = await send(account.tokenUri, {
128
+ method: 'POST',
129
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
130
+ body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString(),
131
+ });
132
+ const body = await response.json().catch(() => null);
133
+ if (!response.ok) {
134
+ // Le code d'erreur OAuth (« invalid_grant »…) aide à comprendre ; le reste de la réponse n'est pas repris.
135
+ const reason = body && typeof body.error === 'string' && /^[\w.-]{1,64}$/.test(body.error) ? `: ${body.error}` : '';
136
+ const refused = new GoogleAuthError('GOOGLE_TOKEN_REFUSED', `Google refused the service account (${response.status}${reason}).`, response.status === 400 || response.status === 401 ? 401 : 502);
137
+ refused.httpStatus = response.status;
138
+ throw refused;
139
+ }
140
+ if (!body || typeof body.access_token !== 'string' || !body.access_token) {
141
+ throw new GoogleAuthError('GOOGLE_TOKEN_REFUSED', 'Google returned no access token.', 502);
142
+ }
143
+ const lifetime = Number(body.expires_in);
144
+ const seconds = Number.isFinite(lifetime) && lifetime > 0 ? Math.min(lifetime, ASSERTION_LIFETIME_SECONDS) : ASSERTION_LIFETIME_SECONDS;
145
+ cached = { token: body.access_token, expiresAt: now() + seconds * 1000 };
146
+ return cached.token;
147
+ }
148
+
149
+ /** Le jeton d'accès, gardé jusqu'à cinq minutes avant son échéance ; un seul échange à la fois. */
150
+ async function getAccessToken({ forceRefresh = false } = {}) {
151
+ if (!forceRefresh && cached && cached.expiresAt - REFRESH_MARGIN_MS > now()) return cached.token;
152
+ if (!pending) pending = exchange().finally(() => { pending = null; });
153
+ return pending;
154
+ }
155
+
156
+ /**
157
+ * Un appel JSON à une API Google avec le jeton. Rend { status, data, headers } ; une réponse d'erreur lève une
158
+ * GoogleAuthError GOOGLE_API_ERROR avec `response = { status, data }` (comme le client de google-auth-library). Un 401
159
+ * fait renouveler le jeton et rejouer l'appel une seule fois.
160
+ */
161
+ async function request({ method = 'GET', url, data, headers = {}, signal } = {}) {
162
+ if (typeof url !== 'string' || !/^https:\/\//.test(url)) throw new GoogleAuthError('GOOGLE_URL_INVALID', 'request() needs an https:// url.');
163
+ const call = async (token) =>
164
+ send(url, {
165
+ method,
166
+ signal,
167
+ headers: { accept: 'application/json', ...(data !== undefined ? { 'content-type': 'application/json' } : {}), ...headers, authorization: `Bearer ${token}` },
168
+ ...(data !== undefined ? { body: JSON.stringify(data) } : {}),
169
+ });
170
+ let response = await call(await getAccessToken());
171
+ if (response.status === 401) response = await call(await getAccessToken({ forceRefresh: true }));
172
+ const text = await response.text().catch(() => '');
173
+ let body = text;
174
+ if (text) {
175
+ try {
176
+ body = JSON.parse(text);
177
+ } catch {
178
+ body = text;
179
+ }
180
+ }
181
+ if (!response.ok) {
182
+ const error = new GoogleAuthError('GOOGLE_API_ERROR', `Google API answered ${response.status} for ${method} ${new URL(url).pathname}.`, response.status);
183
+ error.response = { status: response.status, data: body };
184
+ throw error;
185
+ }
186
+ return { status: response.status, data: body, headers: response.headers };
187
+ }
188
+
189
+ return { getAccessToken, request, clientEmail: account.clientEmail, projectId: account.projectId };
190
+ }
191
+
192
+ module.exports = { createGoogleServiceAccountAuth, signServiceAccountAssertion, readGoogleServiceAccount: readServiceAccount, isGoogleTokenUri, GoogleAuthError, GOOGLE_TOKEN_URI: DEFAULT_TOKEN_URI };
package/src/index.d.ts CHANGED
@@ -192,3 +192,190 @@ export function decideIdempotency(input: {
192
192
  export function hashIdempotencyPayload(payload: unknown): string;
193
193
  export function isValidIdempotencyKey(key: unknown, pattern?: RegExp): boolean;
194
194
  export const IDEMPOTENCY_TTL_MS: number;
195
+
196
+ /** Le jeton d'accès d'un compte de service Google (RFC 7523), sans google-auth-library. */
197
+ export interface GoogleServiceAccountCredentials {
198
+ client_email: string;
199
+ private_key: string;
200
+ token_uri?: string;
201
+ project_id?: string;
202
+ [key: string]: unknown;
203
+ }
204
+ export interface GoogleServiceAccountAuthOptions {
205
+ credentials: GoogleServiceAccountCredentials | string;
206
+ /** Une ou plusieurs portées https://. */
207
+ scopes: string[];
208
+ /** Un compte à emprunter (délégation à l'échelle du domaine). */
209
+ subject?: string;
210
+ fetch?: typeof fetch;
211
+ now?: () => number;
212
+ /** Délai de chaque appel à Google (15 000 ms). */
213
+ timeoutMs?: number;
214
+ /** Adresses d'échange permises à la place de googleapis.com (essais, émulateur). */
215
+ allowedTokenUris?: string[];
216
+ }
217
+ export interface GoogleServiceAccountAuth {
218
+ /** Gardé jusqu'à cinq minutes avant son échéance ; des demandes simultanées partagent un seul échange. */
219
+ getAccessToken(options?: { forceRefresh?: boolean }): Promise<string>;
220
+ /** Un appel JSON à une API Google ; un 401 renouvelle le jeton et rejoue une fois. */
221
+ request<T = unknown>(options: { method?: string; url: string; data?: unknown; headers?: Record<string, string>; signal?: AbortSignal }): Promise<{ status: number; data: T; headers: unknown }>;
222
+ clientEmail: string;
223
+ projectId?: string;
224
+ }
225
+ export function createGoogleServiceAccountAuth(options: GoogleServiceAccountAuthOptions): GoogleServiceAccountAuth;
226
+ export function readGoogleServiceAccount(credentials: GoogleServiceAccountCredentials | string, options?: { allowedTokenUris?: string[] }): { clientEmail: string; privateKey: import('node:crypto').KeyObject; tokenUri: string; projectId?: string };
227
+ export function signServiceAccountAssertion(account: { clientEmail: string; privateKey: import('node:crypto').KeyObject; tokenUri: string }, options: { scopes: string[]; subject?: string; nowSeconds?: number }): string;
228
+ /** https, sur googleapis.com ou un de ses sous-domaines, sans identifiants ni autre port. */
229
+ export function isGoogleTokenUri(value: string): boolean;
230
+ export class GoogleAuthError extends Error {
231
+ code: 'GOOGLE_CREDENTIALS_INVALID' | 'GOOGLE_TOKEN_URI_REFUSED' | 'GOOGLE_SCOPES_INVALID' | 'GOOGLE_NO_FETCH' | 'GOOGLE_UNREACHABLE' | 'GOOGLE_TOKEN_REFUSED' | 'GOOGLE_URL_INVALID' | 'GOOGLE_API_ERROR';
232
+ status?: number;
233
+ httpStatus?: number;
234
+ response?: { status: number; data: unknown };
235
+ }
236
+ export const GOOGLE_TOKEN_URI: string;
237
+
238
+ /** Le téléversement de fichiers (multipart/form-data), en mémoire, sans multer ni busboy. */
239
+ export interface UploadLimits {
240
+ /** 10 Mio par défaut. */
241
+ fileSize?: number;
242
+ /** 10 par défaut. */
243
+ files?: number;
244
+ /** 100 par défaut. */
245
+ fields?: number;
246
+ /** 1 Mio par défaut. */
247
+ fieldSize?: number;
248
+ fieldNameSize?: number;
249
+ /** 200 par défaut. */
250
+ parts?: number;
251
+ headerSize?: number;
252
+ headerPairs?: number;
253
+ /** 50 Mio par défaut. */
254
+ totalSize?: number;
255
+ }
256
+ export interface UploadedFile {
257
+ fieldname: string;
258
+ /** Le nom donné par le client, sans son chemin. */
259
+ originalname: string;
260
+ /** Le même nom, sans caractère réservé, utilisable sur un disque. */
261
+ safeName: string;
262
+ encoding: string;
263
+ /** Annoncé par le client : pas une preuve (voir detectFileType). */
264
+ mimetype: string;
265
+ size: number;
266
+ buffer: Buffer;
267
+ }
268
+ export type UploadFileFilter =
269
+ | ((req: any, file: Omit<UploadedFile, 'buffer' | 'size'> & { buffer?: Buffer; size?: number }, cb: (error: Error | null, accept?: boolean) => void) => void)
270
+ | ((req: any, file: UploadedFile) => boolean | Promise<boolean>);
271
+ export interface Upload {
272
+ single(name: string): RequestHandler;
273
+ array(name: string, maxCount?: number): RequestHandler;
274
+ fields(fields: Array<{ name: string; maxCount?: number }>): RequestHandler;
275
+ none(): RequestHandler;
276
+ any(): RequestHandler;
277
+ }
278
+ export function createUpload(options?: { limits?: UploadLimits; fileFilter?: UploadFileFilter }): Upload;
279
+ /** Le vrai type d'un fichier d'après ses premiers octets, ou null. */
280
+ export function detectFileType(buffer: Buffer): { ext: string; mime: string } | null;
281
+ export function safeFileName(name: string): string;
282
+ export class UploadError extends Error {
283
+ code: 'LIMIT_PART_COUNT' | 'LIMIT_FILE_SIZE' | 'LIMIT_FILE_COUNT' | 'LIMIT_FIELD_KEY' | 'LIMIT_FIELD_VALUE' | 'LIMIT_FIELD_COUNT' | 'LIMIT_UNEXPECTED_FILE' | 'LIMIT_TOTAL_SIZE' | 'MISSING_FIELD_NAME' | 'FIELD_NAME_FORBIDDEN' | 'MALFORMED' | 'UNEXPECTED_END' | 'HEADER_TOO_LARGE';
284
+ field?: string;
285
+ status: number;
286
+ statusCode: number;
287
+ }
288
+ export const UPLOAD_DEFAULT_LIMITS: Required<UploadLimits>;
289
+
290
+ /* La validation des requêtes par chaînes (comme express-validator 7). */
291
+ export type ValidationLocation = 'body' | 'cookies' | 'headers' | 'params' | 'query';
292
+ export interface FieldValidationError {
293
+ type: 'field';
294
+ /** Absent avec hide(), remplacé avec hide(valeur). */
295
+ value?: unknown;
296
+ msg: unknown;
297
+ path: string;
298
+ location: ValidationLocation;
299
+ }
300
+ export interface FieldMeta {
301
+ req: any;
302
+ location: ValidationLocation;
303
+ path: string;
304
+ pathValues: unknown[];
305
+ }
306
+ export type FieldMessage = unknown | ((value: unknown, meta: FieldMeta) => unknown);
307
+ export interface ValidationResult {
308
+ array(options?: { onlyFirstError?: boolean }): FieldValidationError[];
309
+ mapped(): Record<string, FieldValidationError>;
310
+ formatWith<T>(formatter: (error: FieldValidationError) => T): { array(options?: { onlyFirstError?: boolean }): T[]; mapped(): Record<string, T>; isEmpty(): boolean; throw(): void };
311
+ isEmpty(): boolean;
312
+ throw(): void;
313
+ }
314
+ export interface ValidationChain {
315
+ (req: any, res: any, next: (error?: unknown) => void): Promise<void>;
316
+ run(req: any, options?: { dryRun?: boolean }): Promise<ValidationResult>;
317
+ not(): ValidationChain;
318
+ withMessage(message: FieldMessage): ValidationChain;
319
+ custom(validator: (value: any, meta: FieldMeta) => unknown): ValidationChain;
320
+ exists(options?: { values?: 'undefined' | 'null' | 'falsy'; checkNull?: boolean; checkFalsy?: boolean }): ValidationChain;
321
+ optional(options?: boolean | { values?: 'undefined' | 'null' | 'falsy'; nullable?: boolean; checkFalsy?: boolean }): ValidationChain;
322
+ bail(options?: { level?: 'chain' | 'request' }): ValidationChain;
323
+ if(condition: ValidationChain | ((value: any, meta: FieldMeta) => unknown)): ValidationChain;
324
+ hide(hiddenValue?: string): ValidationChain;
325
+ isArray(options?: { min?: number; max?: number }): ValidationChain;
326
+ isObject(options?: { strict?: boolean }): ValidationChain;
327
+ isString(): ValidationChain;
328
+ isBoolean(options?: { strict?: boolean; loose?: boolean }): ValidationChain;
329
+ notEmpty(options?: { ignore_whitespace?: boolean }): ValidationChain;
330
+ isEmpty(options?: { ignore_whitespace?: boolean }): ValidationChain;
331
+ contains(elem: unknown, options?: { ignoreCase?: boolean; minOccurrences?: number }): ValidationChain;
332
+ equals(comparison: string): ValidationChain;
333
+ isByteLength(options?: { min?: number; max?: number }): ValidationChain;
334
+ isEmail(options?: { allow_display_name?: boolean; require_display_name?: boolean; allow_utf8_local_part?: boolean; require_tld?: boolean; allow_ip_domain?: boolean; domain_specific_validation?: boolean; blacklisted_chars?: string; host_blacklist?: (string | RegExp)[]; host_whitelist?: (string | RegExp)[]; ignore_max_length?: boolean; allow_underscores?: boolean }): ValidationChain;
335
+ isFQDN(options?: { require_tld?: boolean; allow_underscores?: boolean; allow_trailing_dot?: boolean; allow_numeric_tld?: boolean; allow_wildcard?: boolean; ignore_max_length?: boolean }): ValidationChain;
336
+ isFloat(options?: { min?: number; max?: number; gt?: number; lt?: number; locale?: string }): ValidationChain;
337
+ isHexadecimal(): ValidationChain;
338
+ isIP(version?: 4 | 6 | '4' | '6'): ValidationChain;
339
+ isIn(values: readonly unknown[] | Record<string, unknown> | string): ValidationChain;
340
+ isInt(options?: { min?: number; max?: number; gt?: number; lt?: number; allow_leading_zeroes?: boolean }): ValidationChain;
341
+ isLength(options?: { min?: number; max?: number; discreteLengths?: number[] }): ValidationChain;
342
+ isMongoId(): ValidationChain;
343
+ isNumeric(options?: { no_symbols?: boolean; locale?: string }): ValidationChain;
344
+ isUUID(version?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 'all' | 'nil' | 'max' | 'loose' | string | number): ValidationChain;
345
+ matches(pattern: RegExp | string, modifiers?: string): ValidationChain;
346
+ trim(chars?: string): ValidationChain;
347
+ ltrim(chars?: string): ValidationChain;
348
+ rtrim(chars?: string): ValidationChain;
349
+ escape(): ValidationChain;
350
+ unescape(): ValidationChain;
351
+ normalizeEmail(options?: Record<string, boolean>): ValidationChain;
352
+ stripLow(keepNewLines?: boolean): ValidationChain;
353
+ toBoolean(strict?: boolean): ValidationChain;
354
+ toDate(): ValidationChain;
355
+ toFloat(): ValidationChain;
356
+ toInt(radix?: number): ValidationChain;
357
+ blacklist(chars: string): ValidationChain;
358
+ whitelist(chars: string): ValidationChain;
359
+ toLowerCase(): ValidationChain;
360
+ toUpperCase(): ValidationChain;
361
+ toArray(): ValidationChain;
362
+ default(value: unknown): ValidationChain;
363
+ replace(valuesToReplace: unknown, newValue: unknown): ValidationChain;
364
+ customSanitizer(sanitizer: (value: any, meta: FieldMeta) => unknown): ValidationChain;
365
+ }
366
+ export type ValidationChainFactory = (fields?: string | string[], message?: FieldMessage) => ValidationChain;
367
+ export const body: ValidationChainFactory;
368
+ export const param: ValidationChainFactory;
369
+ export const query: ValidationChainFactory;
370
+ export const header: ValidationChainFactory;
371
+ export const cookie: ValidationChainFactory;
372
+ export const check: ValidationChainFactory;
373
+ export const validationResult: ((req: any) => ValidationResult) & { withDefaults<T>(options?: { formatter?: (error: FieldValidationError) => T }): (req: any) => ValidationResult };
374
+ export function matchedData(req: any, options?: { onlyValidData?: boolean; includeOptionals?: boolean; locations?: ValidationLocation[] }): Record<string, any>;
375
+ export class Result implements ValidationResult {
376
+ array(options?: { onlyFirstError?: boolean }): FieldValidationError[];
377
+ mapped(): Record<string, FieldValidationError>;
378
+ formatWith<T>(formatter: (error: FieldValidationError) => T): any;
379
+ isEmpty(): boolean;
380
+ throw(): void;
381
+ }
package/src/index.js CHANGED
@@ -1,14 +1,28 @@
1
- const idempotency = require('./idempotency');
1
+ // Des noms seuls et des « ...require() » dans l'objet exporté : Node les lit sans exécuter le fichier, pour les
2
+ // imports nommés d'un module ES (import { createLogger } from '@astratra/core'). Une valeur écrite require('./x')
3
+ // arrêtait cette lecture dès la première ligne : seul apiResponse restait visible en module ES.
4
+ const apiResponse = require('./apiResponse');
5
+ const asyncHandler = require('./asyncHandler');
6
+ const createLogger = require('./logger');
7
+ const AppError = require('./AppError');
8
+ const errorMiddleware = require('./errorMiddleware');
9
+ const notFoundMiddleware = require('./notFoundMiddleware');
10
+ const requestIdMiddleware = require('./requestIdMiddleware');
11
+ const validateMiddleware = require('./validateMiddleware');
12
+ const loadEnv = require('./loadEnv');
2
13
 
3
14
  module.exports = {
4
- apiResponse: require('./apiResponse'),
5
- asyncHandler: require('./asyncHandler'),
6
- createLogger: require('./logger'),
7
- AppError: require('./AppError'),
8
- errorMiddleware: require('./errorMiddleware'),
9
- notFoundMiddleware: require('./notFoundMiddleware'),
10
- requestIdMiddleware: require('./requestIdMiddleware'),
11
- validateMiddleware: require('./validateMiddleware'),
12
- loadEnv: require('./loadEnv'),
13
- ...idempotency
15
+ apiResponse,
16
+ asyncHandler,
17
+ createLogger,
18
+ AppError,
19
+ errorMiddleware,
20
+ notFoundMiddleware,
21
+ requestIdMiddleware,
22
+ validateMiddleware,
23
+ loadEnv,
24
+ ...require('./idempotency'),
25
+ ...require('./googleServiceAccount'),
26
+ ...require('./upload'),
27
+ ...require('./validation')
14
28
  };