raz-encrypt 0.3.0 → 2.1.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 +21 -21
- package/README.md +442 -212
- package/dist/canonicalJson.d.ts +15 -0
- package/dist/canonicalJson.js +73 -13
- package/dist/canonicalJson.js.map +1 -1
- package/dist/core.d.ts +6 -2
- package/dist/core.js +4 -1
- package/dist/core.js.map +1 -1
- package/dist/crypto/classical.d.ts +2 -0
- package/dist/crypto/classical.js +4 -0
- package/dist/crypto/classical.js.map +1 -1
- package/dist/crypto/confirmedSession.d.ts +47 -0
- package/dist/crypto/confirmedSession.js +84 -0
- package/dist/crypto/confirmedSession.js.map +1 -0
- package/dist/crypto/frameCipher.js +8 -2
- package/dist/crypto/frameCipher.js.map +1 -1
- package/dist/crypto/frameSession.d.ts +40 -0
- package/dist/crypto/frameSession.js +96 -0
- package/dist/crypto/frameSession.js.map +1 -0
- package/dist/crypto/hybrid.d.ts +186 -25
- package/dist/crypto/hybrid.js +512 -54
- package/dist/crypto/hybrid.js.map +1 -1
- package/dist/crypto/nodeHybrid.d.ts +6 -4
- package/dist/crypto/nodeHybrid.js +3 -2
- package/dist/crypto/nodeHybrid.js.map +1 -1
- package/dist/crypto/pqc.d.ts +7 -2
- package/dist/crypto/pqc.js +13 -4
- package/dist/crypto/pqc.js.map +1 -1
- package/dist/crypto/ratchet.d.ts +68 -0
- package/dist/crypto/ratchet.js +94 -0
- package/dist/crypto/ratchet.js.map +1 -0
- package/dist/fileCrypto.d.ts +44 -2
- package/dist/fileCrypto.js +197 -28
- package/dist/fileCrypto.js.map +1 -1
- package/dist/identity.d.ts +69 -4
- package/dist/identity.js +111 -12
- package/dist/identity.js.map +1 -1
- package/dist/index.d.ts +8 -7
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/passphrase.d.ts +27 -0
- package/dist/passphrase.js +69 -0
- package/dist/passphrase.js.map +1 -0
- package/dist/store.d.ts +42 -5
- package/dist/store.js +254 -22
- package/dist/store.js.map +1 -1
- package/dist/trust.d.ts +143 -2
- package/dist/trust.js +376 -27
- package/dist/trust.js.map +1 -1
- package/package.json +62 -48
package/dist/trust.d.ts
CHANGED
|
@@ -1,16 +1,62 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Certificate, type VerifyResult } from "./crypto/hybrid.js";
|
|
2
|
+
import { type Identity, type PublicCard } from "./identity.js";
|
|
2
3
|
export interface TrustRecord {
|
|
3
4
|
card: PublicCard;
|
|
4
5
|
trustedAt: string;
|
|
5
6
|
/** Set when this party was later revoked (see untrustParty). Absent = still trusted. */
|
|
6
7
|
revokedAt?: string;
|
|
8
|
+
/**
|
|
9
|
+
* Set alongside revokedAt when this record was tombstoned by a verified
|
|
10
|
+
* rotation (applyRotation), not an ordinary revocation: the fingerprint of
|
|
11
|
+
* the card this party rotated TO. Informational only — verify() still
|
|
12
|
+
* reports "revoked-signer" for this record either way (ADR 0023/issue
|
|
13
|
+
* #37); nothing reads this field to change verification behavior.
|
|
14
|
+
*/
|
|
15
|
+
rotatedTo?: string;
|
|
7
16
|
}
|
|
17
|
+
type Entries = Record<string, TrustRecord>;
|
|
18
|
+
/**
|
|
19
|
+
* Thrown when trust.json cannot be trusted: its MAC does not verify (edited,
|
|
20
|
+
* truncated, copied from another identity), it is not valid JSON, or it is an
|
|
21
|
+
* unauthenticated legacy file that was never explicitly adopted with
|
|
22
|
+
* `migrateLegacyTrustStore`. Everything that consults the trust list fails
|
|
23
|
+
* closed on this rather than reading a file anyone with filesystem access
|
|
24
|
+
* could have written.
|
|
25
|
+
*/
|
|
26
|
+
export declare class TrustStoreIntegrityError extends Error {
|
|
27
|
+
constructor(message: string);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Exported (ADR 0026) so the timing-safety test can exercise this exact
|
|
31
|
+
* compare in isolation, without the file I/O its only internal callers do.
|
|
32
|
+
*/
|
|
33
|
+
export declare function macMatches(identity: Identity, entries: Entries, mac: unknown): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* One-time, explicit opt-in (issue #43/ADR 0027) to encrypt `trust.json`'s
|
|
36
|
+
* entries, so filesystem access alone no longer reveals who this identity
|
|
37
|
+
* trusts. A no-op if the store is already v4. A legacy (unauthenticated) file
|
|
38
|
+
* is not implicitly adopted here — call `migrateLegacyTrustStore` first, same
|
|
39
|
+
* as reading it would require.
|
|
40
|
+
*/
|
|
41
|
+
export declare function migrateTrustStoreToEncrypted(identity: Identity): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* One-time, explicit adoption of a trust.json written before trust-store
|
|
44
|
+
* MACs existed (a v1 alias map or a v2 fingerprint-keyed file). Those files
|
|
45
|
+
* carry no proof of who wrote them, so they are never read implicitly (an
|
|
46
|
+
* attacker could otherwise plant one and bypass the MAC). Calling this says
|
|
47
|
+
* "I have reviewed the current file and it is mine": its records are kept
|
|
48
|
+
* and the file is rewritten authenticated. Returns the number of records
|
|
49
|
+
* adopted; returns 0 and changes nothing if the file is missing or already
|
|
50
|
+
* authenticated (a modified authenticated file still throws).
|
|
51
|
+
*/
|
|
52
|
+
export declare function migrateLegacyTrustStore(identity: Identity): Promise<number>;
|
|
8
53
|
/**
|
|
9
54
|
* Records another party's public card as trusted, keyed by the card's
|
|
10
55
|
* fingerprint (not alias — two different real parties could otherwise pick
|
|
11
56
|
* the same alias and silently overwrite each other). Public keys are not
|
|
12
57
|
* secret, so this file is plain JSON (unlike identity.enc.json), though it's
|
|
13
|
-
*
|
|
58
|
+
* permission-restricted to the owning user and, since ADR 0015, carries an
|
|
59
|
+
* HMAC (keyed from the Identity's secret keys) so edits are detected.
|
|
14
60
|
*
|
|
15
61
|
* Trusting a card again after it was revoked reinstates it (clears revokedAt).
|
|
16
62
|
*/
|
|
@@ -23,6 +69,14 @@ export declare function trustParty(identity: Identity, card: PublicCard): Promis
|
|
|
23
69
|
* "untrusted-signer" (never trusted at all).
|
|
24
70
|
*/
|
|
25
71
|
export declare function untrustParty(identity: Identity, alias: string): Promise<void>;
|
|
72
|
+
/**
|
|
73
|
+
* Revokes exactly one card, identified by its `fingerprint(card)` string
|
|
74
|
+
* (spaces and case are ignored). Unlike `untrustParty`, parties that merely
|
|
75
|
+
* share an alias are untouched — alias is a non-unique display label.
|
|
76
|
+
* Returns true if a currently-trusted record was revoked, false if no such
|
|
77
|
+
* trusted record exists (a typo'd fingerprint is reported, not ignored).
|
|
78
|
+
*/
|
|
79
|
+
export declare function untrustFingerprint(identity: Identity, fingerprintValue: string): Promise<boolean>;
|
|
26
80
|
/** Every currently-trusted (non-revoked) card. */
|
|
27
81
|
export declare function listTrustedParties(identity: Identity): Promise<PublicCard[]>;
|
|
28
82
|
/** Every trust record ever made, revoked or not — for audit/history purposes. */
|
|
@@ -39,3 +93,90 @@ export declare function getTrustedParty(identity: Identity, alias: string): Prom
|
|
|
39
93
|
export declare function getTrustedPartiesByAlias(identity: Identity, alias: string): Promise<PublicCard[]>;
|
|
40
94
|
/** All trust records (revoked or not) recorded under this alias. */
|
|
41
95
|
export declare function getTrustRecordsByAlias(identity: Identity, alias: string): Promise<TrustRecord[]>;
|
|
96
|
+
/**
|
|
97
|
+
* Verifies a self-signed card (from `exportSignedCard`) — checks the
|
|
98
|
+
* signature is self-consistent (the certificate's signer IS the card it's
|
|
99
|
+
* attached to) and, if the card carries an `expiresAt`, that it hasn't
|
|
100
|
+
* passed. Only on success does this call the ordinary `trustParty` to
|
|
101
|
+
* actually record it — self-signing proves the card is authentic and
|
|
102
|
+
* current, not that you've decided to trust it (Fingerprint confirmation
|
|
103
|
+
* is still the human-level trust decision, same as a bare card).
|
|
104
|
+
*/
|
|
105
|
+
export declare function trustSignedCard(identity: Identity, card: PublicCard, certificate: Certificate): Promise<VerifyResult>;
|
|
106
|
+
export interface RotationDocument {
|
|
107
|
+
oldCard: PublicCard;
|
|
108
|
+
newCard: PublicCard;
|
|
109
|
+
rotatedAt: string;
|
|
110
|
+
}
|
|
111
|
+
export interface RotationStatement {
|
|
112
|
+
document: RotationDocument;
|
|
113
|
+
oldCertificate: Certificate;
|
|
114
|
+
newCertificate: Certificate;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Starts a key rotation: the OLD identity signs a statement naming `newCard`
|
|
118
|
+
* as its successor. Hand the result to `completeRotation`, called with the
|
|
119
|
+
* NEW identity, to get a complete, dual-signed RotationStatement — a single
|
|
120
|
+
* signature from the old key alone is never enough to redirect a peer's
|
|
121
|
+
* trust (see `applyRotation`), so this function's output is not yet usable
|
|
122
|
+
* on its own.
|
|
123
|
+
*/
|
|
124
|
+
export declare function beginRotation(oldIdentity: Identity, newCard: PublicCard, options?: {
|
|
125
|
+
rotatedAt?: string;
|
|
126
|
+
}): Promise<{
|
|
127
|
+
document: RotationDocument;
|
|
128
|
+
oldCertificate: Certificate;
|
|
129
|
+
}>;
|
|
130
|
+
/**
|
|
131
|
+
* Finishes a key rotation: the NEW identity signs the SAME document
|
|
132
|
+
* `beginRotation` produced, proving the new key exists and agrees to be
|
|
133
|
+
* named as successor — not just asserted unilaterally by whoever holds the
|
|
134
|
+
* old key (which could be an attacker who compromised it alone).
|
|
135
|
+
*/
|
|
136
|
+
export declare function completeRotation(newIdentity: Identity, draft: {
|
|
137
|
+
document: RotationDocument;
|
|
138
|
+
oldCertificate: Certificate;
|
|
139
|
+
}): Promise<RotationStatement>;
|
|
140
|
+
/**
|
|
141
|
+
* Verifies a RotationStatement (both signatures self-consistent, both
|
|
142
|
+
* certificates over the identical document) and, only if `oldCard` already
|
|
143
|
+
* has an existing Trust Record, moves trust to `newCard` and tombstones
|
|
144
|
+
* `oldCard`'s record (revokedAt set, plus rotatedTo pointing at newCard's
|
|
145
|
+
* fingerprint). A statement for a card you never trusted is a no-op — this
|
|
146
|
+
* is not a way to seed your trust store with a card you never decided to
|
|
147
|
+
* trust in the first place.
|
|
148
|
+
*/
|
|
149
|
+
export declare function applyRotation(identity: Identity, statement: RotationStatement): Promise<VerifyResult>;
|
|
150
|
+
export interface RevocationDocument {
|
|
151
|
+
revokedCard: PublicCard;
|
|
152
|
+
revokedAt: string;
|
|
153
|
+
reason?: string;
|
|
154
|
+
}
|
|
155
|
+
/** A Certificate only stores its document's HASH, not the document itself (same as everywhere else in this codebase) — so a revocation notice bundles the document alongside its certificate, the same shape RotationStatement already uses for the same reason. */
|
|
156
|
+
export interface RevocationNotice {
|
|
157
|
+
document: RevocationDocument;
|
|
158
|
+
certificate: Certificate;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Produces a self-signed, portable revocation notice for `identity`'s own
|
|
162
|
+
* card — verifiable by any peer independently of their (or your) local
|
|
163
|
+
* trust-store state. The same function works whether called reactively
|
|
164
|
+
* (retiring a key now) or right after createIdentity, to be stored
|
|
165
|
+
* separately and used later if this identity becomes inaccessible — that's
|
|
166
|
+
* what actually makes "recovery" possible for a lost passphrase or a lost
|
|
167
|
+
* identity file (ADR 0023): there is no special "pre-generated" mode, it's
|
|
168
|
+
* the same notice either way.
|
|
169
|
+
*/
|
|
170
|
+
export declare function createRevocationNotice(identity: Identity, options?: {
|
|
171
|
+
reason?: string;
|
|
172
|
+
}): Promise<RevocationNotice>;
|
|
173
|
+
/**
|
|
174
|
+
* Verifies a revocation notice (self-consistent, well-formed, `revokedAt`
|
|
175
|
+
* a valid ISO instant) and, only if the named card already has an existing
|
|
176
|
+
* Trust Record, tombstones it (revokedAt set) — exactly like
|
|
177
|
+
* `untrustFingerprint`. A notice for a card you never trusted is a no-op,
|
|
178
|
+
* for the same reason `applyRotation` is: this is not a pre-emptive
|
|
179
|
+
* denylist feature.
|
|
180
|
+
*/
|
|
181
|
+
export declare function applyRevocationNotice(identity: Identity, notice: RevocationNotice): Promise<VerifyResult>;
|
|
182
|
+
export {};
|
package/dist/trust.js
CHANGED
|
@@ -1,50 +1,250 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { gcm } from "@noble/ciphers/aes.js";
|
|
2
|
+
import { equalBytes } from "@noble/ciphers/utils.js";
|
|
3
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
4
|
+
import { hmac } from "@noble/hashes/hmac.js";
|
|
5
|
+
import { sha384 } from "@noble/hashes/sha2.js";
|
|
6
|
+
import { bytesToHex, concatBytes, hexToBytes, randomBytes, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
7
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
8
|
import { join } from "node:path";
|
|
9
|
+
import { canonicalize } from "./canonicalJson.js";
|
|
10
|
+
import { isValidIsoInstant, signCore, verifyCore } from "./crypto/hybrid.js";
|
|
3
11
|
import { fingerprint } from "./fingerprint.js";
|
|
12
|
+
import { exportPublicIdentity } from "./identity.js";
|
|
13
|
+
/**
|
|
14
|
+
* Thrown when trust.json cannot be trusted: its MAC does not verify (edited,
|
|
15
|
+
* truncated, copied from another identity), it is not valid JSON, or it is an
|
|
16
|
+
* unauthenticated legacy file that was never explicitly adopted with
|
|
17
|
+
* `migrateLegacyTrustStore`. Everything that consults the trust list fails
|
|
18
|
+
* closed on this rather than reading a file anyone with filesystem access
|
|
19
|
+
* could have written.
|
|
20
|
+
*/
|
|
21
|
+
export class TrustStoreIntegrityError extends Error {
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "TrustStoreIntegrityError";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const TRUST_STORE_HMAC_INFO = utf8ToBytes("raz-encrypt-trust-store-v1|hmac-key");
|
|
28
|
+
// A separate key from the MAC key, same reason the audit log's head key is
|
|
29
|
+
// separate from its entry key (ADR 0019) — independent HKDF outputs per use
|
|
30
|
+
// (ADR 0027).
|
|
31
|
+
const TRUST_STORE_ENC_INFO = utf8ToBytes("raz-encrypt-trust-store-v1|enc-key");
|
|
4
32
|
function trustFilePath(storageDir) {
|
|
5
33
|
return join(storageDir, "trust.json");
|
|
6
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* HKDF-derived from BOTH the classical and PQC signing secrets, same
|
|
37
|
+
* composition as the audit log's key (ADR 0009) but under its own info label
|
|
38
|
+
* so the two MAC keys are independent. Recomputed on every use, never persisted.
|
|
39
|
+
*/
|
|
40
|
+
function deriveTrustStoreKey(identity) {
|
|
41
|
+
return hkdf(sha384, concatBytes(identity.classical.secretKey, identity.pqcSign.secretKey), undefined, TRUST_STORE_HMAC_INFO, 32);
|
|
42
|
+
}
|
|
43
|
+
/** Same derivation shape as deriveTrustStoreKey, under its own info label (ADR 0027) — never derived from a passphrase, since trustParty/etc. only ever receive an Identity. */
|
|
44
|
+
function deriveTrustStoreEncKey(identity) {
|
|
45
|
+
return hkdf(sha384, concatBytes(identity.classical.secretKey, identity.pqcSign.secretKey), undefined, TRUST_STORE_ENC_INFO, 32);
|
|
46
|
+
}
|
|
47
|
+
function computeMac(identity, entries) {
|
|
48
|
+
return bytesToHex(hmac(sha384, deriveTrustStoreKey(identity), utf8ToBytes(canonicalize({ version: 3, entries }))));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Exported (ADR 0026) so the timing-safety test can exercise this exact
|
|
52
|
+
* compare in isolation, without the file I/O its only internal callers do.
|
|
53
|
+
*/
|
|
54
|
+
export function macMatches(identity, entries, mac) {
|
|
55
|
+
if (typeof mac !== "string" || !/^[0-9a-f]{96}$/.test(mac))
|
|
56
|
+
return false;
|
|
57
|
+
return equalBytes(hexToBytes(mac), hexToBytes(computeMac(identity, entries)));
|
|
58
|
+
}
|
|
59
|
+
/** v4's MAC covers the ciphertext blob instead of the plaintext entries (ADR 0027) — same chain-authentication mechanism, different bytes underneath it. */
|
|
60
|
+
function computeMacV4(identity, nonce, ciphertext) {
|
|
61
|
+
return bytesToHex(hmac(sha384, deriveTrustStoreKey(identity), utf8ToBytes(canonicalize({ version: 4, nonce, ciphertext }))));
|
|
62
|
+
}
|
|
63
|
+
function macMatchesV4(identity, nonce, ciphertext, mac) {
|
|
64
|
+
if (typeof mac !== "string" || !/^[0-9a-f]{96}$/.test(mac))
|
|
65
|
+
return false;
|
|
66
|
+
return equalBytes(hexToBytes(mac), hexToBytes(computeMacV4(identity, nonce, ciphertext)));
|
|
67
|
+
}
|
|
68
|
+
/** Associated data for the entries AEAD: binds the ciphertext to the format version and its own nonce, same pattern as fileCrypto.ts's headerAad. */
|
|
69
|
+
function entriesAad(version, nonce) {
|
|
70
|
+
return utf8ToBytes(canonicalize({ version, nonce }));
|
|
71
|
+
}
|
|
72
|
+
function encryptEntries(identity, entries) {
|
|
73
|
+
const nonce = randomBytes(12);
|
|
74
|
+
const nonceHex = bytesToHex(nonce);
|
|
75
|
+
const ciphertext = gcm(deriveTrustStoreEncKey(identity), nonce, entriesAad(4, nonceHex)).encrypt(utf8ToBytes(canonicalize(entries)));
|
|
76
|
+
return { nonce: nonceHex, ciphertext: bytesToHex(ciphertext) };
|
|
77
|
+
}
|
|
78
|
+
/** Throws TrustStoreIntegrityError (never a raw AEAD error) if the ciphertext doesn't authenticate or doesn't decode as entries. */
|
|
79
|
+
function decryptEntries(identity, nonce, ciphertext) {
|
|
80
|
+
try {
|
|
81
|
+
const plaintext = gcm(deriveTrustStoreEncKey(identity), hexToBytes(nonce), entriesAad(4, nonce)).decrypt(hexToBytes(ciphertext));
|
|
82
|
+
const entries = JSON.parse(new TextDecoder().decode(plaintext));
|
|
83
|
+
if (typeof entries !== "object" || entries === null || Array.isArray(entries))
|
|
84
|
+
throw new Error("decrypted trust store is not an entries object");
|
|
85
|
+
return entries;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
throw new TrustStoreIntegrityError("trust.json failed its integrity check: it was modified, truncated, or belongs to a different identity.");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function isV3(data) {
|
|
92
|
+
if (typeof data !== "object" || data === null || data.version !== 3)
|
|
93
|
+
return false;
|
|
94
|
+
const entries = data.entries;
|
|
95
|
+
return typeof entries === "object" && entries !== null && !Array.isArray(entries);
|
|
96
|
+
}
|
|
97
|
+
function isHex96(value) {
|
|
98
|
+
return typeof value === "string" && /^[0-9a-f]{96}$/.test(value);
|
|
99
|
+
}
|
|
100
|
+
function isV4(data) {
|
|
101
|
+
if (typeof data !== "object" || data === null || data.version !== 4)
|
|
102
|
+
return false;
|
|
103
|
+
const d = data;
|
|
104
|
+
return typeof d.nonce === "string" && /^[0-9a-f]{24}$/.test(d.nonce) && typeof d.ciphertext === "string" && /^[0-9a-f]*$/.test(d.ciphertext) && isHex96(d.mac);
|
|
105
|
+
}
|
|
7
106
|
function isV2(data) {
|
|
8
107
|
return typeof data === "object" && data !== null && data.version === 2;
|
|
9
108
|
}
|
|
10
|
-
/**
|
|
11
|
-
function
|
|
109
|
+
/** Converts an unauthenticated legacy file (v1 alias map, or v2 without a MAC) to fingerprint-keyed entries. */
|
|
110
|
+
function legacyEntries(data) {
|
|
111
|
+
if (isV2(data))
|
|
112
|
+
return data.entries;
|
|
113
|
+
if (typeof data !== "object" || data === null) {
|
|
114
|
+
// Object.values(null) throws TypeError; fail closed with the same error
|
|
115
|
+
// every other unauthenticated-shape rejection in this module uses,
|
|
116
|
+
// rather than crashing the caller (found by fuzzing, issue #42).
|
|
117
|
+
throw new TrustStoreIntegrityError("trust.json is not a valid legacy trust-store shape (expected an object).");
|
|
118
|
+
}
|
|
12
119
|
const entries = {};
|
|
13
|
-
for (const card of Object.values(
|
|
120
|
+
for (const card of Object.values(data)) {
|
|
14
121
|
entries[fingerprint(card)] = { card, trustedAt: new Date().toISOString() };
|
|
15
122
|
}
|
|
16
|
-
return
|
|
123
|
+
return entries;
|
|
17
124
|
}
|
|
18
|
-
async function
|
|
19
|
-
let raw;
|
|
125
|
+
async function readRaw(storageDir) {
|
|
20
126
|
try {
|
|
21
|
-
|
|
127
|
+
return await readFile(trustFilePath(storageDir), "utf8");
|
|
22
128
|
}
|
|
23
129
|
catch (err) {
|
|
24
130
|
if (err.code === "ENOENT")
|
|
25
|
-
return
|
|
131
|
+
return undefined;
|
|
26
132
|
throw err;
|
|
27
133
|
}
|
|
28
|
-
const data = JSON.parse(raw);
|
|
29
|
-
return isV2(data) ? data : migrateLegacy(data);
|
|
30
134
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
135
|
+
function parse(raw) {
|
|
136
|
+
try {
|
|
137
|
+
return JSON.parse(raw);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
throw new TrustStoreIntegrityError("trust.json is not valid JSON; refusing to use it.");
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Reads and AUTHENTICATES the trust store, transparently decrypting a v4 (issue #43) file. Missing file = empty store. Anything unauthenticated throws TrustStoreIntegrityError. */
|
|
144
|
+
async function readTrustStore(identity) {
|
|
145
|
+
const raw = await readRaw(identity.storageDir);
|
|
146
|
+
if (raw === undefined)
|
|
147
|
+
return {};
|
|
148
|
+
const data = parse(raw);
|
|
149
|
+
if (isV4(data)) {
|
|
150
|
+
if (!macMatchesV4(identity, data.nonce, data.ciphertext, data.mac)) {
|
|
151
|
+
throw new TrustStoreIntegrityError("trust.json failed its integrity check: it was modified, truncated, or belongs to a different identity.");
|
|
152
|
+
}
|
|
153
|
+
return decryptEntries(identity, data.nonce, data.ciphertext);
|
|
154
|
+
}
|
|
155
|
+
if (!isV3(data)) {
|
|
156
|
+
throw new TrustStoreIntegrityError("trust.json is an unauthenticated legacy file (written before trust-store MACs). Review it, then call migrateLegacyTrustStore(identity) to adopt it.");
|
|
157
|
+
}
|
|
158
|
+
if (!macMatches(identity, data.entries, data.mac)) {
|
|
159
|
+
throw new TrustStoreIntegrityError("trust.json failed its integrity check: it was modified, truncated, or belongs to a different identity.");
|
|
160
|
+
}
|
|
161
|
+
return data.entries;
|
|
162
|
+
}
|
|
163
|
+
async function writeStoreFile(identity, store) {
|
|
164
|
+
await mkdir(identity.storageDir, { recursive: true, mode: 0o700 });
|
|
165
|
+
const finalPath = trustFilePath(identity.storageDir);
|
|
166
|
+
const tmpPath = `${finalPath}.${process.pid}.${Date.now()}.tmp`;
|
|
167
|
+
try {
|
|
168
|
+
await writeFile(tmpPath, JSON.stringify(store, null, 2), { mode: 0o600 });
|
|
169
|
+
await rename(tmpPath, finalPath);
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
await rm(tmpPath, { force: true });
|
|
173
|
+
throw err;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Writes the store with a fresh MAC, atomically (temp file in the same
|
|
178
|
+
* directory, then rename), mode 0o600. Preserves whatever format is
|
|
179
|
+
* currently on disk (issue #43): once `migrateTrustStoreToEncrypted` has
|
|
180
|
+
* been called, every subsequent write here stays v4; a brand-new or
|
|
181
|
+
* never-migrated store stays v3, exactly as before this issue.
|
|
182
|
+
*/
|
|
183
|
+
async function writeTrustStore(identity, entries) {
|
|
184
|
+
const raw = await readRaw(identity.storageDir);
|
|
185
|
+
const current = raw === undefined ? undefined : parse(raw);
|
|
186
|
+
if (isV4(current)) {
|
|
187
|
+
await writeTrustStore4(identity, entries);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
await writeStoreFile(identity, { version: 3, entries, mac: computeMac(identity, entries) });
|
|
191
|
+
}
|
|
192
|
+
async function writeTrustStore4(identity, entries) {
|
|
193
|
+
const { nonce, ciphertext } = encryptEntries(identity, entries);
|
|
194
|
+
await writeStoreFile(identity, { version: 4, nonce, ciphertext, mac: computeMacV4(identity, nonce, ciphertext) });
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* One-time, explicit opt-in (issue #43/ADR 0027) to encrypt `trust.json`'s
|
|
198
|
+
* entries, so filesystem access alone no longer reveals who this identity
|
|
199
|
+
* trusts. A no-op if the store is already v4. A legacy (unauthenticated) file
|
|
200
|
+
* is not implicitly adopted here — call `migrateLegacyTrustStore` first, same
|
|
201
|
+
* as reading it would require.
|
|
202
|
+
*/
|
|
203
|
+
export async function migrateTrustStoreToEncrypted(identity) {
|
|
204
|
+
const raw = await readRaw(identity.storageDir);
|
|
205
|
+
const current = raw === undefined ? undefined : parse(raw);
|
|
206
|
+
const entries = await readTrustStore(identity); // verifies/decrypts whichever format; throws on a legacy or tampered file
|
|
207
|
+
if (isV4(current))
|
|
208
|
+
return; // already encrypted — true no-op, same spirit as migrateLegacyTrustStore's
|
|
209
|
+
await writeTrustStore4(identity, entries);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* One-time, explicit adoption of a trust.json written before trust-store
|
|
213
|
+
* MACs existed (a v1 alias map or a v2 fingerprint-keyed file). Those files
|
|
214
|
+
* carry no proof of who wrote them, so they are never read implicitly (an
|
|
215
|
+
* attacker could otherwise plant one and bypass the MAC). Calling this says
|
|
216
|
+
* "I have reviewed the current file and it is mine": its records are kept
|
|
217
|
+
* and the file is rewritten authenticated. Returns the number of records
|
|
218
|
+
* adopted; returns 0 and changes nothing if the file is missing or already
|
|
219
|
+
* authenticated (a modified authenticated file still throws).
|
|
220
|
+
*/
|
|
221
|
+
export async function migrateLegacyTrustStore(identity) {
|
|
222
|
+
const raw = await readRaw(identity.storageDir);
|
|
223
|
+
if (raw === undefined)
|
|
224
|
+
return 0;
|
|
225
|
+
const data = parse(raw);
|
|
226
|
+
if (isV3(data) || isV4(data)) {
|
|
227
|
+
await readTrustStore(identity); // verifies (and decrypts, for v4); throws if tampered
|
|
228
|
+
return 0;
|
|
229
|
+
}
|
|
230
|
+
const entries = legacyEntries(data);
|
|
231
|
+
await writeTrustStore(identity, entries);
|
|
232
|
+
return Object.keys(entries).length;
|
|
34
233
|
}
|
|
35
234
|
/**
|
|
36
235
|
* Records another party's public card as trusted, keyed by the card's
|
|
37
236
|
* fingerprint (not alias — two different real parties could otherwise pick
|
|
38
237
|
* the same alias and silently overwrite each other). Public keys are not
|
|
39
238
|
* secret, so this file is plain JSON (unlike identity.enc.json), though it's
|
|
40
|
-
*
|
|
239
|
+
* permission-restricted to the owning user and, since ADR 0015, carries an
|
|
240
|
+
* HMAC (keyed from the Identity's secret keys) so edits are detected.
|
|
41
241
|
*
|
|
42
242
|
* Trusting a card again after it was revoked reinstates it (clears revokedAt).
|
|
43
243
|
*/
|
|
44
244
|
export async function trustParty(identity, card) {
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
await writeTrustStore(identity
|
|
245
|
+
const entries = await readTrustStore(identity);
|
|
246
|
+
entries[fingerprint(card)] = { card, trustedAt: new Date().toISOString() };
|
|
247
|
+
await writeTrustStore(identity, entries);
|
|
48
248
|
}
|
|
49
249
|
/**
|
|
50
250
|
* Revokes every currently-trusted card recorded under `alias` — e.g. after a
|
|
@@ -54,25 +254,42 @@ export async function trustParty(identity, card) {
|
|
|
54
254
|
* "untrusted-signer" (never trusted at all).
|
|
55
255
|
*/
|
|
56
256
|
export async function untrustParty(identity, alias) {
|
|
57
|
-
const
|
|
257
|
+
const entries = await readTrustStore(identity);
|
|
58
258
|
const revokedAt = new Date().toISOString();
|
|
59
|
-
for (const record of Object.values(
|
|
259
|
+
for (const record of Object.values(entries)) {
|
|
60
260
|
if (record.card.alias === alias && !record.revokedAt)
|
|
61
261
|
record.revokedAt = revokedAt;
|
|
62
262
|
}
|
|
63
|
-
await writeTrustStore(identity
|
|
263
|
+
await writeTrustStore(identity, entries);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Revokes exactly one card, identified by its `fingerprint(card)` string
|
|
267
|
+
* (spaces and case are ignored). Unlike `untrustParty`, parties that merely
|
|
268
|
+
* share an alias are untouched — alias is a non-unique display label.
|
|
269
|
+
* Returns true if a currently-trusted record was revoked, false if no such
|
|
270
|
+
* trusted record exists (a typo'd fingerprint is reported, not ignored).
|
|
271
|
+
*/
|
|
272
|
+
export async function untrustFingerprint(identity, fingerprintValue) {
|
|
273
|
+
const normalize = (value) => value.replace(/\s+/g, "").toUpperCase();
|
|
274
|
+
const wanted = normalize(fingerprintValue);
|
|
275
|
+
const entries = await readTrustStore(identity);
|
|
276
|
+
const key = Object.keys(entries).find((candidate) => normalize(candidate) === wanted);
|
|
277
|
+
if (key === undefined || entries[key].revokedAt)
|
|
278
|
+
return false;
|
|
279
|
+
entries[key].revokedAt = new Date().toISOString();
|
|
280
|
+
await writeTrustStore(identity, entries);
|
|
281
|
+
return true;
|
|
64
282
|
}
|
|
65
283
|
/** Every currently-trusted (non-revoked) card. */
|
|
66
284
|
export async function listTrustedParties(identity) {
|
|
67
|
-
const
|
|
68
|
-
return Object.values(
|
|
285
|
+
const entries = await readTrustStore(identity);
|
|
286
|
+
return Object.values(entries)
|
|
69
287
|
.filter((record) => !record.revokedAt)
|
|
70
288
|
.map((record) => record.card);
|
|
71
289
|
}
|
|
72
290
|
/** Every trust record ever made, revoked or not — for audit/history purposes. */
|
|
73
291
|
export async function listTrustRecords(identity) {
|
|
74
|
-
|
|
75
|
-
return Object.values(store.entries);
|
|
292
|
+
return Object.values(await readTrustStore(identity));
|
|
76
293
|
}
|
|
77
294
|
/** The first currently-trusted (non-revoked) card recorded under this alias, if any. */
|
|
78
295
|
export async function getTrustedParty(identity, alias) {
|
|
@@ -92,7 +309,139 @@ export async function getTrustedPartiesByAlias(identity, alias) {
|
|
|
92
309
|
}
|
|
93
310
|
/** All trust records (revoked or not) recorded under this alias. */
|
|
94
311
|
export async function getTrustRecordsByAlias(identity, alias) {
|
|
95
|
-
|
|
96
|
-
|
|
312
|
+
return Object.values(await readTrustStore(identity)).filter((record) => record.card.alias === alias);
|
|
313
|
+
}
|
|
314
|
+
// --- Authenticated key lifecycle (issue #37 / ADR 0023) -----------------
|
|
315
|
+
//
|
|
316
|
+
// Everything below is an ordinary Certificate over a new document shape,
|
|
317
|
+
// verified by reusing verifyCore — never a new signing or verification
|
|
318
|
+
// primitive. The common trick: a SELF-signed document's trust basis isn't a
|
|
319
|
+
// trust-store lookup, it's self-consistency (does the certificate's signer
|
|
320
|
+
// match the card it's attached to?), so `cardMatchesSigner` stands in for
|
|
321
|
+
// checkTrust wherever one of these functions verifies a self-signed card.
|
|
322
|
+
/** True iff `signer` (a Certificate's signer fields) is the SAME party `card` claims to be — not a trust-store lookup, a self-consistency check. */
|
|
323
|
+
function cardMatchesSigner(card, signer) {
|
|
324
|
+
return card.alias === signer.alias && card.classicalPublicKey === signer.classicalPublicKey && card.pqcSignPublicKey === signer.pqcSignPublicKey;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Verifies a self-signed card (from `exportSignedCard`) — checks the
|
|
328
|
+
* signature is self-consistent (the certificate's signer IS the card it's
|
|
329
|
+
* attached to) and, if the card carries an `expiresAt`, that it hasn't
|
|
330
|
+
* passed. Only on success does this call the ordinary `trustParty` to
|
|
331
|
+
* actually record it — self-signing proves the card is authentic and
|
|
332
|
+
* current, not that you've decided to trust it (Fingerprint confirmation
|
|
333
|
+
* is still the human-level trust decision, same as a bare card).
|
|
334
|
+
*/
|
|
335
|
+
export async function trustSignedCard(identity, card, certificate) {
|
|
336
|
+
const result = await verifyCore(identity, card, certificate, {
|
|
337
|
+
checkTrust: async (signer) => (cardMatchesSigner(card, signer) ? "trusted" : "untrusted"),
|
|
338
|
+
});
|
|
339
|
+
if (result.valid)
|
|
340
|
+
await trustParty(identity, card);
|
|
341
|
+
return result;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Starts a key rotation: the OLD identity signs a statement naming `newCard`
|
|
345
|
+
* as its successor. Hand the result to `completeRotation`, called with the
|
|
346
|
+
* NEW identity, to get a complete, dual-signed RotationStatement — a single
|
|
347
|
+
* signature from the old key alone is never enough to redirect a peer's
|
|
348
|
+
* trust (see `applyRotation`), so this function's output is not yet usable
|
|
349
|
+
* on its own.
|
|
350
|
+
*/
|
|
351
|
+
export async function beginRotation(oldIdentity, newCard, options = {}) {
|
|
352
|
+
const rotatedAt = options.rotatedAt ?? new Date().toISOString();
|
|
353
|
+
if (!isValidIsoInstant(rotatedAt))
|
|
354
|
+
throw new Error(`rotatedAt must be a valid ISO-8601 instant in the exact format new Date().toISOString() produces; got ${JSON.stringify(rotatedAt)}.`);
|
|
355
|
+
const document = { oldCard: exportPublicIdentity(oldIdentity), newCard, rotatedAt };
|
|
356
|
+
const oldCertificate = await signCore(oldIdentity, document);
|
|
357
|
+
return { document, oldCertificate };
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Finishes a key rotation: the NEW identity signs the SAME document
|
|
361
|
+
* `beginRotation` produced, proving the new key exists and agrees to be
|
|
362
|
+
* named as successor — not just asserted unilaterally by whoever holds the
|
|
363
|
+
* old key (which could be an attacker who compromised it alone).
|
|
364
|
+
*/
|
|
365
|
+
export async function completeRotation(newIdentity, draft) {
|
|
366
|
+
const newCertificate = await signCore(newIdentity, draft.document);
|
|
367
|
+
return { document: draft.document, oldCertificate: draft.oldCertificate, newCertificate };
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Verifies a RotationStatement (both signatures self-consistent, both
|
|
371
|
+
* certificates over the identical document) and, only if `oldCard` already
|
|
372
|
+
* has an existing Trust Record, moves trust to `newCard` and tombstones
|
|
373
|
+
* `oldCard`'s record (revokedAt set, plus rotatedTo pointing at newCard's
|
|
374
|
+
* fingerprint). A statement for a card you never trusted is a no-op — this
|
|
375
|
+
* is not a way to seed your trust store with a card you never decided to
|
|
376
|
+
* trust in the first place.
|
|
377
|
+
*/
|
|
378
|
+
export async function applyRotation(identity, statement) {
|
|
379
|
+
const { document, oldCertificate, newCertificate } = statement;
|
|
380
|
+
const oldResult = await verifyCore(identity, document, oldCertificate, {
|
|
381
|
+
checkTrust: async (signer) => (cardMatchesSigner(document.oldCard, signer) ? "trusted" : "untrusted"),
|
|
382
|
+
});
|
|
383
|
+
if (!oldResult.valid)
|
|
384
|
+
return oldResult;
|
|
385
|
+
const newResult = await verifyCore(identity, document, newCertificate, {
|
|
386
|
+
checkTrust: async (signer) => (cardMatchesSigner(document.newCard, signer) ? "trusted" : "untrusted"),
|
|
387
|
+
});
|
|
388
|
+
if (!newResult.valid)
|
|
389
|
+
return newResult;
|
|
390
|
+
const entries = await readTrustStore(identity);
|
|
391
|
+
const oldKey = fingerprint(document.oldCard);
|
|
392
|
+
const existing = entries[oldKey];
|
|
393
|
+
if (!existing || existing.revokedAt)
|
|
394
|
+
return { valid: true }; // nothing trusted to migrate from — no-op
|
|
395
|
+
const revokedAt = new Date().toISOString();
|
|
396
|
+
entries[oldKey] = { ...existing, revokedAt, rotatedTo: fingerprint(document.newCard) };
|
|
397
|
+
entries[fingerprint(document.newCard)] = { card: document.newCard, trustedAt: revokedAt };
|
|
398
|
+
await writeTrustStore(identity, entries);
|
|
399
|
+
return { valid: true };
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Produces a self-signed, portable revocation notice for `identity`'s own
|
|
403
|
+
* card — verifiable by any peer independently of their (or your) local
|
|
404
|
+
* trust-store state. The same function works whether called reactively
|
|
405
|
+
* (retiring a key now) or right after createIdentity, to be stored
|
|
406
|
+
* separately and used later if this identity becomes inaccessible — that's
|
|
407
|
+
* what actually makes "recovery" possible for a lost passphrase or a lost
|
|
408
|
+
* identity file (ADR 0023): there is no special "pre-generated" mode, it's
|
|
409
|
+
* the same notice either way.
|
|
410
|
+
*/
|
|
411
|
+
export async function createRevocationNotice(identity, options = {}) {
|
|
412
|
+
const revokedAt = new Date().toISOString();
|
|
413
|
+
const document = {
|
|
414
|
+
revokedCard: exportPublicIdentity(identity),
|
|
415
|
+
revokedAt,
|
|
416
|
+
...(options.reason !== undefined ? { reason: options.reason } : {}),
|
|
417
|
+
};
|
|
418
|
+
const certificate = await signCore(identity, document);
|
|
419
|
+
return { document, certificate };
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Verifies a revocation notice (self-consistent, well-formed, `revokedAt`
|
|
423
|
+
* a valid ISO instant) and, only if the named card already has an existing
|
|
424
|
+
* Trust Record, tombstones it (revokedAt set) — exactly like
|
|
425
|
+
* `untrustFingerprint`. A notice for a card you never trusted is a no-op,
|
|
426
|
+
* for the same reason `applyRotation` is: this is not a pre-emptive
|
|
427
|
+
* denylist feature.
|
|
428
|
+
*/
|
|
429
|
+
export async function applyRevocationNotice(identity, notice) {
|
|
430
|
+
const { document, certificate } = notice;
|
|
431
|
+
if (!isValidIsoInstant(document.revokedAt))
|
|
432
|
+
return { valid: false, reason: "malformed-certificate" };
|
|
433
|
+
const result = await verifyCore(identity, document, certificate, {
|
|
434
|
+
checkTrust: async (signer) => (cardMatchesSigner(document.revokedCard, signer) ? "trusted" : "untrusted"),
|
|
435
|
+
});
|
|
436
|
+
if (!result.valid)
|
|
437
|
+
return result;
|
|
438
|
+
const entries = await readTrustStore(identity);
|
|
439
|
+
const key = fingerprint(document.revokedCard);
|
|
440
|
+
const existing = entries[key];
|
|
441
|
+
if (!existing || existing.revokedAt)
|
|
442
|
+
return { valid: true }; // nothing trusted to revoke — no-op
|
|
443
|
+
entries[key] = { ...existing, revokedAt: document.revokedAt };
|
|
444
|
+
await writeTrustStore(identity, entries);
|
|
445
|
+
return { valid: true };
|
|
97
446
|
}
|
|
98
447
|
//# sourceMappingURL=trust.js.map
|