@astratra/security 1.8.0 → 1.9.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 +81 -0
- package/package.json +1 -1
- package/src/auditChain.js +152 -0
- package/src/index.d.ts +92 -0
- package/src/index.js +4 -1
- package/src/serviceSignature.js +117 -0
- package/src/stableStringify.js +20 -0
package/README.md
CHANGED
|
@@ -10,6 +10,87 @@ Partout où un vrai projet a besoin de persistance (révocation de session,
|
|
|
10
10
|
stockage de credentials WebAuthn, alerte de brute-force), c'est un
|
|
11
11
|
callback/adapter injecté, jamais un appel base de données codé en dur.
|
|
12
12
|
|
|
13
|
+
## Signer les appels entre tes propres services
|
|
14
|
+
|
|
15
|
+
La porte d'entrée est gardée — sessions, jetons, CORS. Les couloirs entre tes
|
|
16
|
+
services, eux, ne le sont généralement pas : l'un appelle l'autre sur le réseau
|
|
17
|
+
et celui qui reçoit fait confiance à ce qui arrive, parce que « c'est interne ».
|
|
18
|
+
Ça l'est jusqu'au jour où autre chose atteint ce port.
|
|
19
|
+
|
|
20
|
+
```js
|
|
21
|
+
const { createServiceSigner } = require('@astratra/security');
|
|
22
|
+
|
|
23
|
+
const signer = createServiceSigner({
|
|
24
|
+
secret: process.env.INTERNAL_SERVICE_KEY,
|
|
25
|
+
// Sans durée de validité, une charge utile capturée fonctionne pour
|
|
26
|
+
// toujours : qui observe UN appel interne signé peut le rejouer quand il
|
|
27
|
+
// veut. Mets-la.
|
|
28
|
+
maxAgeMs: 30_000,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Côté appelant
|
|
32
|
+
await fetch(url, { headers: { ...signer.headers({ id, role, tenant }) } });
|
|
33
|
+
|
|
34
|
+
// Côté appelé
|
|
35
|
+
const check = signer.verifyHeaders(req.headers);
|
|
36
|
+
if (!check.valid) return res.status(401).json({ message: 'Appel interne non signé.' });
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Trois détails qui comptent :
|
|
40
|
+
|
|
41
|
+
**L'horodatage est À L'INTÉRIEUR de la chaîne signée.** Envoyé à côté, un
|
|
42
|
+
attaquant le réécrirait simplement.
|
|
43
|
+
|
|
44
|
+
**La signature est vérifiée AVANT que la charge utile soit analysée.** Analyser
|
|
45
|
+
d'abord, c'est faire tourner ton analyseur JSON sur ce qu'un attaquant a envoyé.
|
|
46
|
+
|
|
47
|
+
**Les clés sont triées avant signature.** Un service construit `{ id, role }`,
|
|
48
|
+
l'autre reconstruit `{ role, id }` depuis une ligne de base : `JSON.stringify`
|
|
49
|
+
produirait deux chaînes différentes pour la même donnée, et la vérification
|
|
50
|
+
échouerait par intermittence d'une façon qui ressemble à un problème réseau.
|
|
51
|
+
|
|
52
|
+
## Un journal qui montre qu'on l'a modifié
|
|
53
|
+
|
|
54
|
+
Un journal ordinaire est une liste d'affirmations. Qui a accès à la base peut
|
|
55
|
+
changer une ligne ou en supprimer une, et rien dans le résultat n'a l'air faux
|
|
56
|
+
— précisément au moment où tu as le plus besoin de lui faire confiance.
|
|
57
|
+
|
|
58
|
+
Le chaînage règle ça : chaque entrée porte l'empreinte de la précédente, donc
|
|
59
|
+
elle dépend de tout l'historique derrière elle.
|
|
60
|
+
|
|
61
|
+
```js
|
|
62
|
+
const { createAuditChain } = require('@astratra/security');
|
|
63
|
+
|
|
64
|
+
const chain = createAuditChain({ store });
|
|
65
|
+
|
|
66
|
+
await chain.record({ type: 'payment.validated', actor: userId, message: '…' });
|
|
67
|
+
|
|
68
|
+
const { intact, failure } = await chain.verify();
|
|
69
|
+
// failure.reason === 'altered' -> le contenu ne correspond plus à son empreinte
|
|
70
|
+
// failure.reason === 'broken' -> une entrée a été supprimée ou insérée
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Distinguer les deux compte : un contenu réécrit est une falsification, un
|
|
74
|
+
maillon rompu veut dire qu'on a retiré ou glissé quelque chose.
|
|
75
|
+
|
|
76
|
+
Modifier une entrée **et** recalculer sa propre empreinte ne suffit pas : tout
|
|
77
|
+
ce qui suit pointe encore sur l'ancienne valeur. Cacher un changement oblige à
|
|
78
|
+
réécrire toute la suite — et si le journal est aussi copié hors machine, même
|
|
79
|
+
pas.
|
|
80
|
+
|
|
81
|
+
Une colonne ajoutée plus tard — un index, un drapeau de réplication — ne
|
|
82
|
+
casse pas la chaîne : seuls les champs signés alimentent l'empreinte.
|
|
83
|
+
|
|
84
|
+
**L'écriture ne lève jamais.** Perdre la trace est grave ; perdre le paiement
|
|
85
|
+
qu'elle enregistrait l'est davantage. L'échec est signalé, bruyamment.
|
|
86
|
+
|
|
87
|
+
`createMemoryAuditStore()` fournit une chaîne en mémoire pour les tests. En
|
|
88
|
+
production, le store est le tien — et copier le journal hors machine est ce qui
|
|
89
|
+
transforme « visible » en « irréfutable ».
|
|
90
|
+
|
|
91
|
+
Ce mécanisme rend la falsification **visible**, pas impossible. C'est la
|
|
92
|
+
promesse honnête, et c'est celle qui vaut la peine d'être faite.
|
|
93
|
+
|
|
13
94
|
## Chiffrement de champ (au repos)
|
|
14
95
|
|
|
15
96
|
Astratra ne s'intercale jamais entre ton app et ta base de données — rien
|
package/package.json
CHANGED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An audit log that shows when it has been edited.
|
|
3
|
+
*
|
|
4
|
+
* A plain log is a list of claims. Anyone with database access can change a
|
|
5
|
+
* line or delete one, and nothing about the result looks wrong — which is
|
|
6
|
+
* precisely the moment you most need the log to be trustworthy.
|
|
7
|
+
*
|
|
8
|
+
* Chaining fixes that. Each entry carries the hash of the one before it, so
|
|
9
|
+
* every entry depends on the entire history behind it. Change one field and its
|
|
10
|
+
* hash no longer matches; delete an entry and the next one points at something
|
|
11
|
+
* that is not there. Neither can be hidden without rewriting everything after
|
|
12
|
+
* it — and if the log is also copied off-machine, not even then.
|
|
13
|
+
*
|
|
14
|
+
* This makes tampering EVIDENT, not impossible. That is the honest claim, and
|
|
15
|
+
* it is the one worth making.
|
|
16
|
+
*/
|
|
17
|
+
const crypto = require('crypto');
|
|
18
|
+
const { stableStringify } = require('./stableStringify');
|
|
19
|
+
|
|
20
|
+
/** The link the first entry points at: there is nothing before it. */
|
|
21
|
+
const GENESIS_HASH = '0'.repeat(64);
|
|
22
|
+
|
|
23
|
+
const FIELDS = ['type', 'actor', 'target', 'level', 'message', 'meta', 'context', 'previousHash', 'recordedAt'];
|
|
24
|
+
|
|
25
|
+
/** Only the signed fields, in a fixed shape — extra columns must not shift it. */
|
|
26
|
+
function canonical(event) {
|
|
27
|
+
const payload = {};
|
|
28
|
+
for (const field of FIELDS) {
|
|
29
|
+
if (event[field] !== undefined) payload[field] = event[field];
|
|
30
|
+
}
|
|
31
|
+
return payload;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function hashEvent(event) {
|
|
35
|
+
return crypto.createHash('sha256').update(stableStringify(canonical(event))).digest('hex');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} options
|
|
40
|
+
* @param {object} options.store { last(), append(event) } and, to verify,
|
|
41
|
+
* { list() } returning entries oldest first.
|
|
42
|
+
* @param {Function} [options.now]
|
|
43
|
+
* @param {object} [options.logger]
|
|
44
|
+
* @param {Function} [options.onRecordFailed] (error, event) => void.
|
|
45
|
+
*/
|
|
46
|
+
function createAuditChain(options = {}) {
|
|
47
|
+
const store = options.store;
|
|
48
|
+
for (const method of ['last', 'append']) {
|
|
49
|
+
if (!store || typeof store[method] !== 'function') {
|
|
50
|
+
throw new Error(`createAuditChain requires options.store.${method}().`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const now = options.now || (() => new Date());
|
|
55
|
+
const logger = options.logger || { error() {} };
|
|
56
|
+
const onRecordFailed = options.onRecordFailed || null;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Append an entry.
|
|
60
|
+
*
|
|
61
|
+
* Never throws. An audit write that fails must not take down the operation
|
|
62
|
+
* it was recording — losing the trace is bad, losing the payment is worse.
|
|
63
|
+
* The failure is reported instead, loudly.
|
|
64
|
+
*/
|
|
65
|
+
async function record(event = {}) {
|
|
66
|
+
try {
|
|
67
|
+
const previous = await store.last();
|
|
68
|
+
const previousHash = (previous && previous.hash) || GENESIS_HASH;
|
|
69
|
+
|
|
70
|
+
const entry = {
|
|
71
|
+
...event,
|
|
72
|
+
previousHash,
|
|
73
|
+
recordedAt: (event.recordedAt || now()).toISOString
|
|
74
|
+
? (event.recordedAt || now()).toISOString()
|
|
75
|
+
: String(event.recordedAt || now())
|
|
76
|
+
};
|
|
77
|
+
entry.hash = hashEvent(entry);
|
|
78
|
+
|
|
79
|
+
return await store.append(entry);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
logger.error(`[audit] could not record "${event.type || 'event'}": ${error.message}`);
|
|
82
|
+
if (onRecordFailed) onRecordFailed(error, event);
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Walk the chain and say where, if anywhere, it stops adding up.
|
|
89
|
+
*
|
|
90
|
+
* Two failures, and telling them apart matters:
|
|
91
|
+
*
|
|
92
|
+
* altered — the entry's own hash does not match its content;
|
|
93
|
+
* broken — the entry does not point at the one before it, so something
|
|
94
|
+
* was deleted or inserted.
|
|
95
|
+
*
|
|
96
|
+
* @param {Array} [events] oldest first. Read from the store when omitted.
|
|
97
|
+
* @returns {Promise<{intact: boolean, checked: number, failure?: object}>}
|
|
98
|
+
*/
|
|
99
|
+
async function verify(events) {
|
|
100
|
+
const entries = events || (typeof store.list === 'function' ? await store.list() : null);
|
|
101
|
+
if (!entries) {
|
|
102
|
+
throw new Error('createAuditChain.verify needs events, or options.store.list().');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
let expectedPrevious = GENESIS_HASH;
|
|
106
|
+
|
|
107
|
+
for (let index = 0; index < entries.length; index += 1) {
|
|
108
|
+
const entry = entries[index];
|
|
109
|
+
|
|
110
|
+
if (entry.previousHash !== expectedPrevious) {
|
|
111
|
+
return {
|
|
112
|
+
intact: false,
|
|
113
|
+
checked: index,
|
|
114
|
+
failure: {
|
|
115
|
+
reason: 'broken', index, entry,
|
|
116
|
+
detail: 'this entry does not follow the previous one — an entry was removed or inserted'
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (entry.hash !== hashEvent(entry)) {
|
|
122
|
+
return {
|
|
123
|
+
intact: false,
|
|
124
|
+
checked: index,
|
|
125
|
+
failure: {
|
|
126
|
+
reason: 'altered', index, entry,
|
|
127
|
+
detail: 'this entry\'s content no longer matches its own hash'
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
expectedPrevious = entry.hash;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return { intact: true, checked: entries.length };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return { record, verify, hashEvent, GENESIS_HASH };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** In-process chain for tests and development. Not persistent. */
|
|
142
|
+
function createMemoryAuditStore() {
|
|
143
|
+
const entries = [];
|
|
144
|
+
return {
|
|
145
|
+
async last() { return entries[entries.length - 1] || null; },
|
|
146
|
+
async append(entry) { entries.push(entry); return entry; },
|
|
147
|
+
async list() { return [...entries]; },
|
|
148
|
+
entries
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
module.exports = { createAuditChain, createMemoryAuditStore, hashEvent, GENESIS_HASH };
|
package/src/index.d.ts
CHANGED
|
@@ -415,3 +415,95 @@ export function hashRecoveryCode(code: string, secret: string): string;
|
|
|
415
415
|
* credential store.
|
|
416
416
|
*/
|
|
417
417
|
export function createMemoryWebauthnStore(): WebauthnStore;
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* A serialisation two machines agree on: keys sorted, so a signature or a hash
|
|
421
|
+
* does not depend on the order an object happened to be built in.
|
|
422
|
+
*/
|
|
423
|
+
export function stableStringify(value: unknown): string;
|
|
424
|
+
|
|
425
|
+
export type SignatureFailure = 'missing' | 'bad-signature' | 'expired' | 'malformed';
|
|
426
|
+
|
|
427
|
+
export interface SignedPayload {
|
|
428
|
+
payload: string;
|
|
429
|
+
signature: string;
|
|
430
|
+
issuedAt: number;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export type VerificationResult<T = unknown> =
|
|
434
|
+
| { valid: true; value: T; issuedAt: number }
|
|
435
|
+
| { valid: false; reason: SignatureFailure };
|
|
436
|
+
|
|
437
|
+
export interface ServiceSigner {
|
|
438
|
+
sign(value: unknown): SignedPayload;
|
|
439
|
+
/** Checks the signature BEFORE parsing the payload. */
|
|
440
|
+
verify<T = unknown>(payload: string | null | undefined, signature: string | null | undefined): VerificationResult<T>;
|
|
441
|
+
headers(value: unknown, names?: { payload?: string; signature?: string }): Record<string, string>;
|
|
442
|
+
verifyHeaders<T = unknown>(
|
|
443
|
+
headers: Record<string, unknown>,
|
|
444
|
+
names?: { payload?: string; signature?: string }
|
|
445
|
+
): VerificationResult<T>;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export function createServiceSigner(options: {
|
|
449
|
+
secret: string;
|
|
450
|
+
algorithm?: string;
|
|
451
|
+
/** Without it, a captured payload can be replayed forever. Set it. */
|
|
452
|
+
maxAgeMs?: number;
|
|
453
|
+
now?: () => number;
|
|
454
|
+
}): ServiceSigner;
|
|
455
|
+
|
|
456
|
+
export interface AuditEntry {
|
|
457
|
+
type?: string;
|
|
458
|
+
actor?: string;
|
|
459
|
+
target?: string;
|
|
460
|
+
level?: string;
|
|
461
|
+
message?: string;
|
|
462
|
+
meta?: Record<string, unknown>;
|
|
463
|
+
context?: Record<string, unknown>;
|
|
464
|
+
previousHash: string;
|
|
465
|
+
recordedAt: string;
|
|
466
|
+
hash: string;
|
|
467
|
+
[key: string]: unknown;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export interface AuditStore {
|
|
471
|
+
last(): Promise<AuditEntry | null> | AuditEntry | null;
|
|
472
|
+
append(entry: AuditEntry): Promise<AuditEntry> | AuditEntry;
|
|
473
|
+
list?(): Promise<AuditEntry[]> | AuditEntry[];
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
export interface AuditVerification {
|
|
477
|
+
intact: boolean;
|
|
478
|
+
checked: number;
|
|
479
|
+
failure?: {
|
|
480
|
+
/** 'altered': content no longer matches its hash. 'broken': an entry was removed or inserted. */
|
|
481
|
+
reason: 'altered' | 'broken';
|
|
482
|
+
index: number;
|
|
483
|
+
entry: AuditEntry;
|
|
484
|
+
detail: string;
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export interface AuditChain {
|
|
489
|
+
/** Never throws: an audit write must not take down what it was recording. */
|
|
490
|
+
record(event?: Record<string, unknown>): Promise<AuditEntry | null>;
|
|
491
|
+
verify(events?: AuditEntry[]): Promise<AuditVerification>;
|
|
492
|
+
hashEvent(event: Record<string, unknown>): string;
|
|
493
|
+
GENESIS_HASH: string;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
export function createAuditChain(options: {
|
|
497
|
+
store: AuditStore;
|
|
498
|
+
now?: () => Date;
|
|
499
|
+
logger?: { error?(message: string): void };
|
|
500
|
+
onRecordFailed?: (error: unknown, event: Record<string, unknown>) => void;
|
|
501
|
+
}): AuditChain;
|
|
502
|
+
|
|
503
|
+
export function createMemoryAuditStore(): AuditStore & {
|
|
504
|
+
list(): Promise<AuditEntry[]>;
|
|
505
|
+
entries: AuditEntry[];
|
|
506
|
+
};
|
|
507
|
+
|
|
508
|
+
export function hashEvent(event: Record<string, unknown>): string;
|
|
509
|
+
export const GENESIS_HASH: string;
|
package/src/index.js
CHANGED
|
@@ -13,5 +13,8 @@ module.exports = {
|
|
|
13
13
|
...require('./csp'),
|
|
14
14
|
...require('./cookies'),
|
|
15
15
|
...require('./csrf'),
|
|
16
|
-
...require('./revocation')
|
|
16
|
+
...require('./revocation'),
|
|
17
|
+
...require('./stableStringify'),
|
|
18
|
+
...require('./serviceSignature'),
|
|
19
|
+
...require('./auditChain')
|
|
17
20
|
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proving a request came from your own service.
|
|
3
|
+
*
|
|
4
|
+
* The front door is guarded — sessions, tokens, CORS. The corridors between
|
|
5
|
+
* your own services usually are not: one of them calls another over the network
|
|
6
|
+
* and the callee trusts whatever arrives, because "it's internal". It is
|
|
7
|
+
* internal right up until something else reaches that port.
|
|
8
|
+
*
|
|
9
|
+
* A shared secret and an HMAC settle it: the caller signs what it sends, the
|
|
10
|
+
* callee checks the signature, and a forged or altered payload is refused.
|
|
11
|
+
*/
|
|
12
|
+
const crypto = require('crypto');
|
|
13
|
+
const { stableStringify } = require('./stableStringify');
|
|
14
|
+
|
|
15
|
+
const DEFAULT_ALGORITHM = 'sha256';
|
|
16
|
+
|
|
17
|
+
/** Compare without leaking, through timing, how much of the value was right. */
|
|
18
|
+
function sameSignature(a, b) {
|
|
19
|
+
const left = Buffer.from(String(a || ''), 'utf8');
|
|
20
|
+
const right = Buffer.from(String(b || ''), 'utf8');
|
|
21
|
+
if (left.length !== right.length) return false;
|
|
22
|
+
return crypto.timingSafeEqual(left, right);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {object} options
|
|
27
|
+
* @param {string} options.secret shared by the services that trust each other.
|
|
28
|
+
* @param {string} [options.algorithm] default 'sha256'.
|
|
29
|
+
* @param {number} [options.maxAgeMs] how long a signature stays valid.
|
|
30
|
+
* Without it a captured payload works forever — an attacker who sees ONE
|
|
31
|
+
* signed internal call can replay it whenever they like. Set it.
|
|
32
|
+
* @param {Function} [options.now]
|
|
33
|
+
*/
|
|
34
|
+
function createServiceSigner(options = {}) {
|
|
35
|
+
const secret = options.secret;
|
|
36
|
+
if (!secret || typeof secret !== 'string') {
|
|
37
|
+
throw new Error('createServiceSigner requires options.secret as a non-empty string.');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const algorithm = options.algorithm || DEFAULT_ALGORITHM;
|
|
41
|
+
const maxAgeMs = options.maxAgeMs === undefined ? null : options.maxAgeMs;
|
|
42
|
+
const now = options.now || (() => Date.now());
|
|
43
|
+
|
|
44
|
+
const digest = (payload) => crypto.createHmac(algorithm, secret).update(payload).digest('hex');
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Sign a value. Objects are serialised with sorted keys so the two ends
|
|
48
|
+
* agree whatever order they built their fields in.
|
|
49
|
+
*
|
|
50
|
+
* @returns {{payload: string, signature: string, issuedAt: number}}
|
|
51
|
+
*/
|
|
52
|
+
function sign(value) {
|
|
53
|
+
const issuedAt = now();
|
|
54
|
+
/* The timestamp is INSIDE the signed string. Sent alongside it, an
|
|
55
|
+
attacker would simply rewrite it. */
|
|
56
|
+
const payload = stableStringify({ v: value, t: issuedAt });
|
|
57
|
+
return { payload, signature: digest(payload), issuedAt };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Check a signature and give back what was signed.
|
|
62
|
+
*
|
|
63
|
+
* @returns {{valid: boolean, value?: *, reason?: "missing"|"bad-signature"|"expired"|"malformed"}}
|
|
64
|
+
*/
|
|
65
|
+
function verify(payload, signature) {
|
|
66
|
+
if (!payload || !signature) return { valid: false, reason: 'missing' };
|
|
67
|
+
|
|
68
|
+
/* Signature FIRST, parse second. Parsing an unverified payload runs your
|
|
69
|
+
JSON parser on whatever an attacker sent. */
|
|
70
|
+
if (!sameSignature(digest(payload), signature)) return { valid: false, reason: 'bad-signature' };
|
|
71
|
+
|
|
72
|
+
let parsed;
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(payload);
|
|
75
|
+
} catch {
|
|
76
|
+
return { valid: false, reason: 'malformed' };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (maxAgeMs !== null) {
|
|
80
|
+
const age = now() - Number(parsed.t);
|
|
81
|
+
/* A negative age means a clock ahead of ours, or a forged timestamp.
|
|
82
|
+
Either way it is not something to accept. */
|
|
83
|
+
if (!Number.isFinite(age) || age < 0 || age > maxAgeMs) return { valid: false, reason: 'expired' };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return { valid: true, value: parsed.v, issuedAt: parsed.t };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The same thing shaped as headers, for the common case of one HTTP service
|
|
91
|
+
* calling another.
|
|
92
|
+
*/
|
|
93
|
+
function headers(value, names = {}) {
|
|
94
|
+
const { payload, signature } = sign(value);
|
|
95
|
+
return {
|
|
96
|
+
[names.payload || 'x-service-payload']: Buffer.from(payload, 'utf8').toString('base64'),
|
|
97
|
+
[names.signature || 'x-service-signature']: signature
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function verifyHeaders(requestHeaders = {}, names = {}) {
|
|
102
|
+
const encoded = requestHeaders[names.payload || 'x-service-payload'];
|
|
103
|
+
const signature = requestHeaders[names.signature || 'x-service-signature'];
|
|
104
|
+
if (!encoded || !signature) return { valid: false, reason: 'missing' };
|
|
105
|
+
let payload;
|
|
106
|
+
try {
|
|
107
|
+
payload = Buffer.from(String(encoded), 'base64').toString('utf8');
|
|
108
|
+
} catch {
|
|
109
|
+
return { valid: false, reason: 'malformed' };
|
|
110
|
+
}
|
|
111
|
+
return verify(payload, signature);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return { sign, verify, headers, verifyHeaders };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = { createServiceSigner };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A serialisation two machines agree on.
|
|
3
|
+
*
|
|
4
|
+
* `JSON.stringify` preserves insertion order, and insertion order depends on
|
|
5
|
+
* how the object was built. Service A builds `{ id, role }`, service B rebuilds
|
|
6
|
+
* `{ role, id }` from a database row, and the two produce different strings for
|
|
7
|
+
* the same data. Anything derived from that string — a signature, a hash —
|
|
8
|
+
* then disagrees, intermittently, in a way that looks like a network problem.
|
|
9
|
+
*
|
|
10
|
+
* Sorting the keys removes the question. Used by both the service signer and
|
|
11
|
+
* the audit chain, because a signature and a hash have the same requirement.
|
|
12
|
+
*/
|
|
13
|
+
function stableStringify(value) {
|
|
14
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
15
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
|
|
16
|
+
if (value instanceof Date) return JSON.stringify(value.toISOString());
|
|
17
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
module.exports = { stableStringify };
|