raz-encrypt 1.1.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.
Files changed (49) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +442 -212
  3. package/dist/canonicalJson.d.ts +15 -0
  4. package/dist/canonicalJson.js +73 -13
  5. package/dist/canonicalJson.js.map +1 -1
  6. package/dist/core.d.ts +4 -2
  7. package/dist/core.js +3 -1
  8. package/dist/core.js.map +1 -1
  9. package/dist/crypto/classical.d.ts +2 -0
  10. package/dist/crypto/classical.js +4 -0
  11. package/dist/crypto/classical.js.map +1 -1
  12. package/dist/crypto/confirmedSession.d.ts +47 -0
  13. package/dist/crypto/confirmedSession.js +84 -0
  14. package/dist/crypto/confirmedSession.js.map +1 -0
  15. package/dist/crypto/frameCipher.js +8 -2
  16. package/dist/crypto/frameCipher.js.map +1 -1
  17. package/dist/crypto/frameSession.d.ts +40 -0
  18. package/dist/crypto/frameSession.js +96 -0
  19. package/dist/crypto/frameSession.js.map +1 -0
  20. package/dist/crypto/hybrid.d.ts +95 -8
  21. package/dist/crypto/hybrid.js +374 -49
  22. package/dist/crypto/hybrid.js.map +1 -1
  23. package/dist/crypto/nodeHybrid.d.ts +6 -4
  24. package/dist/crypto/nodeHybrid.js +3 -2
  25. package/dist/crypto/nodeHybrid.js.map +1 -1
  26. package/dist/crypto/pqc.d.ts +7 -2
  27. package/dist/crypto/pqc.js +13 -4
  28. package/dist/crypto/pqc.js.map +1 -1
  29. package/dist/crypto/ratchet.js +5 -0
  30. package/dist/crypto/ratchet.js.map +1 -1
  31. package/dist/fileCrypto.d.ts +44 -2
  32. package/dist/fileCrypto.js +197 -28
  33. package/dist/fileCrypto.js.map +1 -1
  34. package/dist/identity.d.ts +69 -4
  35. package/dist/identity.js +111 -12
  36. package/dist/identity.js.map +1 -1
  37. package/dist/index.d.ts +8 -7
  38. package/dist/index.js +4 -4
  39. package/dist/index.js.map +1 -1
  40. package/dist/passphrase.d.ts +27 -0
  41. package/dist/passphrase.js +69 -0
  42. package/dist/passphrase.js.map +1 -0
  43. package/dist/store.d.ts +42 -5
  44. package/dist/store.js +254 -22
  45. package/dist/store.js.map +1 -1
  46. package/dist/trust.d.ts +143 -2
  47. package/dist/trust.js +376 -27
  48. package/dist/trust.js.map +1 -1
  49. package/package.json +62 -48
package/dist/identity.js CHANGED
@@ -1,9 +1,34 @@
1
1
  import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { generateClassicalKeypair } from "./crypto/classical.js";
5
- import { decryptFromFile, encryptToFile } from "./fileCrypto.js";
6
- import { generatePqcKemKeypair, generatePqcSignKeypair } from "./crypto/pqc.js";
4
+ import { generateClassicalKeypair, isValidClassicalKeypairShape } from "./crypto/classical.js";
5
+ import { signCore } from "./crypto/hybrid.js";
6
+ import { decryptFileWithFormat, DecryptionFailedError, encryptToFile, upgradeLegacyFile } from "./fileCrypto.js";
7
+ import { assertAcceptablePassphrase, MIN_PASSPHRASE_LENGTH, normalizePassphrase } from "./passphrase.js";
8
+ import { generatePqcKemKeypair, generatePqcSignKeypair, isValidPqcKemKeypairShape, isValidPqcSignKeypairShape, } from "./crypto/pqc.js";
9
+ function isHex(value) {
10
+ return typeof value === "string" && value.length % 2 === 0 && /^[0-9a-f]*$/i.test(value);
11
+ }
12
+ function isValidKeypairShape(value) {
13
+ if (typeof value !== "object" || value === null)
14
+ return false;
15
+ const v = value;
16
+ return isHex(v.publicKey) && isHex(v.secretKey);
17
+ }
18
+ /**
19
+ * Structural shape check for a decrypted identity file's plaintext. In
20
+ * normal operation AEAD authentication already guarantees this shape, so a
21
+ * malformed value here would mean a wrong/corrupted ciphertext slipped past
22
+ * decryption (practically impossible without the passphrase) — this exists
23
+ * so that case fails closed with DecryptionFailedError instead of crashing
24
+ * on a missing/non-hex field (found by fuzzing, issue #42).
25
+ */
26
+ function isValidSerializedIdentityShape(data) {
27
+ if (typeof data !== "object" || data === null)
28
+ return false;
29
+ const d = data;
30
+ return typeof d.alias === "string" && isValidKeypairShape(d.classical) && isValidKeypairShape(d.pqcSign) && isValidKeypairShape(d.pqcKem);
31
+ }
7
32
  function identityFilePath(storageDir) {
8
33
  return join(storageDir, "identity.enc.json");
9
34
  }
@@ -42,20 +67,28 @@ function deserialize(storageDir, data) {
42
67
  },
43
68
  };
44
69
  }
45
- export const MIN_PASSPHRASE_LENGTH = 12;
70
+ export { MIN_PASSPHRASE_LENGTH };
46
71
  /**
47
72
  * Generates a new hybrid classical+post-quantum identity (one ECDSA/ECDH-P384
48
73
  * keypair, one ML-DSA-87 signing keypair, one ML-KEM-1024 key-exchange
49
74
  * keypair) and persists it encrypted-at-rest under `storageDir`.
50
75
  *
51
- * Requires a passphrase of at least MIN_PASSPHRASE_LENGTH characters — this
52
- * check only applies here, not to loadIdentity, so an identity created
53
- * before this check existed can still be loaded with its original passphrase.
76
+ * The passphrase is normalized to Unicode NFKC, must be at least
77
+ * MIN_PASSPHRASE_LENGTH characters (counted as code points after
78
+ * normalization), must not be a single repeated character, and must not be
79
+ * on a small blocklist of very common passphrases (ADR 0017). These checks
80
+ * only apply here, not to loadIdentity, so an identity created before they
81
+ * existed can still be loaded with its original passphrase.
82
+ *
83
+ * `options.checkPassphrase`, if supplied, runs after all of the above pass
84
+ * (ADR 0021) — this is where real breach-corpus checking belongs, not in
85
+ * this library's own, deliberately small, blocklist.
54
86
  */
55
87
  export async function createIdentity(options) {
56
- if (options.passphrase.length < MIN_PASSPHRASE_LENGTH) {
57
- throw new Error(`Passphrase must be at least ${MIN_PASSPHRASE_LENGTH} characters long.`);
58
- }
88
+ const passphrase = normalizePassphrase(options.passphrase);
89
+ assertAcceptablePassphrase(passphrase);
90
+ if (options.checkPassphrase)
91
+ await options.checkPassphrase(passphrase);
59
92
  const filePath = identityFilePath(options.storageDir);
60
93
  if (!options.overwrite && existsSync(filePath)) {
61
94
  throw new Error(`An identity already exists at ${filePath}. Pass { overwrite: true } to replace it.`);
@@ -67,14 +100,67 @@ export async function createIdentity(options) {
67
100
  pqcSign: generatePqcSignKeypair(),
68
101
  pqcKem: generatePqcKemKeypair(),
69
102
  };
70
- await encryptToFile(filePath, options.passphrase, serialize(identity));
103
+ await encryptToFile(filePath, passphrase, serialize(identity));
71
104
  return identity;
72
105
  }
73
106
  /** Loads a previously-created identity back from disk. */
74
107
  export async function loadIdentity(options) {
75
- const data = await decryptFromFile(identityFilePath(options.storageDir), options.passphrase);
108
+ const filePath = identityFilePath(options.storageDir);
109
+ const normalized = normalizePassphrase(options.passphrase);
110
+ // Normalized form first; the raw form only matters for a file written
111
+ // before normalization existed under a passphrase NFKC would change.
112
+ const candidates = normalized === options.passphrase ? [normalized] : [normalized, options.passphrase];
113
+ const { data, legacy, passphraseIndex } = await decryptFileWithFormat(filePath, candidates);
114
+ if (!isValidSerializedIdentityShape(data))
115
+ throw new DecryptionFailedError();
116
+ if (legacy || passphraseIndex > 0) {
117
+ // Upgrade a pre-versioned file (and/or re-key one made under an
118
+ // un-normalized passphrase) to the current format under the normalized
119
+ // passphrase now that the passphrase is proven correct. Best effort: a
120
+ // read-only directory or a full disk must not stop the identity from
121
+ // loading.
122
+ try {
123
+ await upgradeLegacyFile(filePath, normalized, data);
124
+ }
125
+ catch {
126
+ // The original file is untouched (see upgradeLegacyFile); try again on the next load.
127
+ }
128
+ }
76
129
  return deserialize(options.storageDir, data);
77
130
  }
131
+ /**
132
+ * Builds an Identity from a caller-supplied KeyStore instead of a
133
+ * passphrase-encrypted file — `identity.enc.json` and a passphrase are
134
+ * never part of the picture. The returned key material's shape (byte
135
+ * lengths) is validated before trusting it, so a buggy KeyStore fails
136
+ * clearly here rather than with a cryptic error the first time a signing
137
+ * call happens to touch the bad bytes. `storageDir` is still required: the
138
+ * trust store and audit log are a separate concern from where secret keys
139
+ * live, unaffected by this function.
140
+ */
141
+ export async function loadIdentityFromKeyStore(options) {
142
+ const { classical, pqcSign, pqcKem } = await options.keyStore.load();
143
+ if (!isValidClassicalKeypairShape(classical))
144
+ throw new Error("KeyStore returned a classical keypair with the wrong byte length(s) for P-384.");
145
+ if (!isValidPqcSignKeypairShape(pqcSign))
146
+ throw new Error("KeyStore returned a pqcSign keypair with the wrong byte length(s) for ML-DSA-87.");
147
+ if (!isValidPqcKemKeypairShape(pqcKem))
148
+ throw new Error("KeyStore returned a pqcKem keypair with the wrong byte length(s) for ML-KEM-1024.");
149
+ return { alias: options.alias, storageDir: options.storageDir, classical, pqcSign, pqcKem };
150
+ }
151
+ /**
152
+ * Best-effort wipe of the secret key bytes held by `identity`: overwrites
153
+ * them with zeros so they do not linger in this process's memory after you
154
+ * are done. The identity is unusable afterwards. Limits: JavaScript gives no
155
+ * guarantee about copies the engine or GC already made, and the hex strings
156
+ * produced while saving or loading an identity are immutable and cannot be
157
+ * wiped. This narrows the exposure window; it is not a secure-erase.
158
+ */
159
+ export function zeroizeIdentity(identity) {
160
+ identity.classical.secretKey.fill(0);
161
+ identity.pqcSign.secretKey.fill(0);
162
+ identity.pqcKem.secretKey.fill(0);
163
+ }
78
164
  /** The shareable public half of an identity — hand this to the other party out of band. */
79
165
  export function exportPublicIdentity(identity) {
80
166
  return {
@@ -84,4 +170,17 @@ export function exportPublicIdentity(identity) {
84
170
  pqcKemPublicKey: bytesToHex(identity.pqcKem.publicKey),
85
171
  };
86
172
  }
173
+ /**
174
+ * A self-signed, optionally time-limited version of `exportPublicIdentity`'s
175
+ * card (ADR 0023/issue #37): the identity signs its own card, so a peer can
176
+ * verify it wasn't tampered with and — if `options.expiresAt` was set —
177
+ * reject it once expired, enforcing a cryptoperiod the bare card has no way
178
+ * to carry (it has no signature at all). `exportPublicIdentity` itself is
179
+ * unchanged; this is a separate, opt-in function precisely so every
180
+ * existing caller of the bare card is unaffected. Verify and trust a
181
+ * received one with `trustSignedCard`, not `trustParty`.
182
+ */
183
+ export async function exportSignedCard(identity, options = {}) {
184
+ return signCore(identity, exportPublicIdentity(identity), options);
185
+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B,CAAC,QAAkB;IACrD,OAAO;QACL,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,kBAAkB,EAAE,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC;QAC5D,gBAAgB,EAAE,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC;QACxD,eAAe,EAAE,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC;KACvD,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,QAAkB,EAAE,UAAuB,EAAE;IAClF,OAAO,QAAQ,CAAC,QAAQ,EAAE,oBAAoB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;AACrE,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  export { canonicalize, hashDocument } from "./canonicalJson.js";
2
2
  export { fingerprint } from "./fingerprint.js";
3
- export { decryptFrom, encryptFor, sign, UntrustedPartyError, verify } from "./crypto/nodeHybrid.js";
4
- export type { Certificate, EncryptedBox, VerifyFailureReason, VerifyResult } from "./crypto/nodeHybrid.js";
5
- export { createIdentity, exportPublicIdentity, loadIdentity, MIN_PASSPHRASE_LENGTH } from "./identity.js";
6
- export type { CreateIdentityOptions, Identity, LoadIdentityOptions, PublicCard } from "./identity.js";
7
- export { readLog, verifyLogIntegrity } from "./store.js";
3
+ export { decryptFrom, DecryptionError, encryptFor, ReplayedBoxError, sign, UntrustedPartyError, verify } from "./crypto/nodeHybrid.js";
4
+ export type { BoxReplayInfo, Certificate, EncryptedBox, VerifyFailureReason, VerifyResult } from "./crypto/nodeHybrid.js";
5
+ export { createIdentity, exportPublicIdentity, exportSignedCard, loadIdentity, loadIdentityFromKeyStore, MIN_PASSPHRASE_LENGTH, zeroizeIdentity, } from "./identity.js";
6
+ export type { CreateIdentityOptions, Identity, KeyStore, LoadIdentityFromKeyStoreOptions, LoadIdentityOptions, PublicCard } from "./identity.js";
7
+ export type { PassphraseChecker } from "./passphrase.js";
8
+ export { migrateAuditLogToEncrypted, readLog, verifyLogIntegrity } from "./store.js";
8
9
  export type { LogEntry, LogIntegrityResult } from "./store.js";
9
- export { getTrustedParty, getTrustedPartiesByAlias, getTrustRecordsByAlias, listTrustedParties, listTrustRecords, trustParty, untrustParty, } from "./trust.js";
10
- export type { TrustRecord } from "./trust.js";
10
+ export { applyRevocationNotice, applyRotation, beginRotation, completeRotation, createRevocationNotice, getTrustedParty, getTrustedPartiesByAlias, getTrustRecordsByAlias, listTrustedParties, listTrustRecords, migrateLegacyTrustStore, migrateTrustStoreToEncrypted, TrustStoreIntegrityError, trustParty, trustSignedCard, untrustFingerprint, untrustParty, } from "./trust.js";
11
+ export type { RevocationDocument, RevocationNotice, RotationDocument, RotationStatement, TrustRecord } from "./trust.js";
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { canonicalize, hashDocument } from "./canonicalJson.js";
2
2
  export { fingerprint } from "./fingerprint.js";
3
- export { decryptFrom, encryptFor, sign, UntrustedPartyError, verify } from "./crypto/nodeHybrid.js";
4
- export { createIdentity, exportPublicIdentity, loadIdentity, MIN_PASSPHRASE_LENGTH } from "./identity.js";
5
- export { readLog, verifyLogIntegrity } from "./store.js";
6
- export { getTrustedParty, getTrustedPartiesByAlias, getTrustRecordsByAlias, listTrustedParties, listTrustRecords, trustParty, untrustParty, } from "./trust.js";
3
+ export { decryptFrom, DecryptionError, encryptFor, ReplayedBoxError, sign, UntrustedPartyError, verify } from "./crypto/nodeHybrid.js";
4
+ export { createIdentity, exportPublicIdentity, exportSignedCard, loadIdentity, loadIdentityFromKeyStore, MIN_PASSPHRASE_LENGTH, zeroizeIdentity, } from "./identity.js";
5
+ export { migrateAuditLogToEncrypted, readLog, verifyLogIntegrity } from "./store.js";
6
+ export { applyRevocationNotice, applyRotation, beginRotation, completeRotation, createRevocationNotice, getTrustedParty, getTrustedPartiesByAlias, getTrustRecordsByAlias, listTrustedParties, listTrustRecords, migrateLegacyTrustStore, migrateTrustStoreToEncrypted, TrustStoreIntegrityError, trustParty, trustSignedCard, untrustFingerprint, untrustParty, } from "./trust.js";
7
7
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,IAAI,EAAE,mBAAmB,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAEpG,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,YAAY,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAE1G,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEzD,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,sBAAsB,EACtB,kBAAkB,EAClB,gBAAgB,EAChB,UAAU,EACV,YAAY,GACb,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,gBAAgB,EAAE,IAAI,EAAE,mBAAmB,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAEvI,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,gBAAgB,EAChB,YAAY,EACZ,wBAAwB,EACxB,qBAAqB,EACrB,eAAe,GAChB,MAAM,eAAe,CAAC;AAGvB,OAAO,EAAE,0BAA0B,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErF,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,wBAAwB,EACxB,sBAAsB,EACtB,kBAAkB,EAClB,gBAAgB,EAChB,uBAAuB,EACvB,4BAA4B,EAC5B,wBAAwB,EACxB,UAAU,EACV,eAAe,EACf,kBAAkB,EAClB,YAAY,GACb,MAAM,YAAY,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Passphrase handling shared by every place a passphrase becomes key
3
+ * material (ADR 0017).
4
+ *
5
+ * Normalization: the same visible passphrase can be encoded as different
6
+ * Unicode code point sequences (composed vs decomposed accents, full-width
7
+ * digits, ...) depending on the keyboard, OS or app that typed it, which
8
+ * would derive different keys. Passphrases are normalized to NFKC before
9
+ * the KDF so what the user sees is what unlocks. For pure-ASCII passphrases
10
+ * NFKC is the identity, so nothing changes for them.
11
+ */
12
+ export declare function normalizePassphrase(passphrase: string): string;
13
+ export declare const MIN_PASSPHRASE_LENGTH = 12;
14
+ /**
15
+ * A caller-supplied passphrase check, run by createIdentity AFTER the
16
+ * built-in checks (length, repeated-character, the small blocklist above)
17
+ * pass. Receives the already-normalized passphrase. Throw (synchronously or
18
+ * via a rejected promise) to reject it with your own message — e.g. because
19
+ * it's found in a real breach corpus, or scores poorly under a strength
20
+ * estimator. This is the actual fix for NIST SP 800-63B's breach-check
21
+ * expectation (ADR 0021): the built-in blocklist above is deliberately not
22
+ * grown to try to meet that bar itself, and this library adds no built-in
23
+ * network-calling checker (e.g. an HIBP lookup) of its own.
24
+ */
25
+ export type PassphraseChecker = (normalized: string) => void | Promise<void>;
26
+ /** Throws if `passphrase` (already normalized) is unacceptable for a NEW identity. Loading an existing identity never calls this. */
27
+ export declare function assertAcceptablePassphrase(normalized: string): void;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Passphrase handling shared by every place a passphrase becomes key
3
+ * material (ADR 0017).
4
+ *
5
+ * Normalization: the same visible passphrase can be encoded as different
6
+ * Unicode code point sequences (composed vs decomposed accents, full-width
7
+ * digits, ...) depending on the keyboard, OS or app that typed it, which
8
+ * would derive different keys. Passphrases are normalized to NFKC before
9
+ * the KDF so what the user sees is what unlocks. For pure-ASCII passphrases
10
+ * NFKC is the identity, so nothing changes for them.
11
+ */
12
+ export function normalizePassphrase(passphrase) {
13
+ return passphrase.normalize("NFKC");
14
+ }
15
+ export const MIN_PASSPHRASE_LENGTH = 12;
16
+ /**
17
+ * A deliberately small blocklist of the passphrases that fit a 12-character
18
+ * minimum and appear at the top of every breach list. NIST SP 800-63B asks
19
+ * verifiers to compare against known-compromised values; a few dozen entries
20
+ * cannot do that job, so treat this as a floor, not a strength meter. Apps
21
+ * that care should run a real estimator (e.g. zxcvbn) before calling
22
+ * createIdentity.
23
+ */
24
+ const COMMON_PASSPHRASES = new Set([
25
+ "passwordpassword",
26
+ "password1234",
27
+ "password12345",
28
+ "password123456",
29
+ "passw0rd1234",
30
+ "123456789012",
31
+ "1234567890123",
32
+ "12345678901234",
33
+ "123456123456",
34
+ "1234512345",
35
+ "111111111111",
36
+ "000000000000",
37
+ "qwertyuiopas",
38
+ "qwertyuiop12",
39
+ "qwertyuiop123",
40
+ "qwertyqwerty",
41
+ "asdfghjklqwe",
42
+ "zxcvbnmasdfg",
43
+ "abcdefghijkl",
44
+ "abcdefghijklm",
45
+ "abcabcabcabc",
46
+ "iloveyouiloveyou",
47
+ "letmeinletmein",
48
+ "welcome12345",
49
+ "welcome123456",
50
+ "administrator",
51
+ "changemechangeme",
52
+ "trustno1trustno1",
53
+ "monkeymonkey",
54
+ "footballfootball",
55
+ ]);
56
+ /** Throws if `passphrase` (already normalized) is unacceptable for a NEW identity. Loading an existing identity never calls this. */
57
+ export function assertAcceptablePassphrase(normalized) {
58
+ const codePoints = [...normalized];
59
+ if (codePoints.length < MIN_PASSPHRASE_LENGTH) {
60
+ throw new Error(`Passphrase must be at least ${MIN_PASSPHRASE_LENGTH} characters long.`);
61
+ }
62
+ if (new Set(codePoints).size === 1) {
63
+ throw new Error("Passphrase must not be a single repeated character.");
64
+ }
65
+ if (COMMON_PASSPHRASES.has(normalized.toLowerCase().replace(/\s+/g, ""))) {
66
+ throw new Error("Passphrase is on the list of very common passphrases; choose something less guessable.");
67
+ }
68
+ }
69
+ //# sourceMappingURL=passphrase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passphrase.js","sourceRoot":"","sources":["../src/passphrase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,UAAU,mBAAmB,CAAC,UAAkB;IACpD,OAAO,UAAU,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,kBAAkB;IAClB,cAAc;IACd,eAAe;IACf,gBAAgB;IAChB,cAAc;IACd,cAAc;IACd,eAAe;IACf,gBAAgB;IAChB,cAAc;IACd,YAAY;IACZ,cAAc;IACd,cAAc;IACd,cAAc;IACd,cAAc;IACd,eAAe;IACf,cAAc;IACd,cAAc;IACd,cAAc;IACd,cAAc;IACd,eAAe;IACf,cAAc;IACd,kBAAkB;IAClB,gBAAgB;IAChB,cAAc;IACd,eAAe;IACf,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,cAAc;IACd,kBAAkB;CACnB,CAAC,CAAC;AAeH,qIAAqI;AACrI,MAAM,UAAU,0BAA0B,CAAC,UAAkB;IAC3D,MAAM,UAAU,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC;IACnC,IAAI,UAAU,CAAC,MAAM,GAAG,qBAAqB,EAAE,CAAC;QAC9C,MAAM,IAAI,KAAK,CAAC,+BAA+B,qBAAqB,mBAAmB,CAAC,CAAC;IAC3F,CAAC;IACD,IAAI,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,IAAI,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;QACzE,MAAM,IAAI,KAAK,CAAC,wFAAwF,CAAC,CAAC;IAC5G,CAAC;AACH,CAAC"}
package/dist/store.d.ts CHANGED
@@ -6,23 +6,60 @@ export interface LogEntry {
6
6
  result?: string;
7
7
  at: string;
8
8
  }
9
+ /**
10
+ * Constant-time MAC comparison (ADR 0009/0019's chain and head MACs are both
11
+ * HMAC-SHA384, so 96 lowercase hex chars). `candidate` is untrusted on-disk
12
+ * data of unknown shape: a non-string, wrong-length, or non-hex value is
13
+ * reported as a mismatch, never thrown, matching verifyKeyConfirmation's
14
+ * contract in crypto/hybrid.ts.
15
+ *
16
+ * Exported (ADR 0026) so the timing-safety test can exercise this exact
17
+ * compare in isolation, without the file I/O its only internal callers do.
18
+ */
19
+ export declare function macEquals(candidate: unknown, expected: string): boolean;
9
20
  /**
10
21
  * Appends one entry to the local, append-only audit log (public metadata
11
- * only — no secrets). Each entry is chained to the previous one's hash
12
- * (see verifyLogIntegrity) so tampering or deleting past entries is
13
- * detectable, not just theoretically append-only.
22
+ * only — no secrets). Each entry is chained to the previous one's MAC
23
+ * (see verifyLogIntegrity), keyed from identity's own secret material
24
+ * (ADR 0009) so tampering or deleting past entries is detectable by anyone
25
+ * EXCEPT someone who also holds that secret — not just theoretically
26
+ * append-only, and not forgeable by file-write access alone.
14
27
  */
15
28
  export declare function appendLogEntry(identity: Identity, entry: Omit<LogEntry, "at">): Promise<void>;
29
+ /** Transparently decrypts any v2 (encrypted, issue #43) entries alongside plaintext v1 ones. */
16
30
  export declare function readLog(identity: Identity): Promise<LogEntry[]>;
17
31
  export type LogIntegrityResult = {
18
32
  intact: true;
19
33
  } | {
20
34
  intact: false;
35
+ /** First entry whose chain link failed; for the reasons below, the number of entries actually present. */
21
36
  brokenAtIndex: number;
37
+ /** Absent for an edited or deleted entry inside the chain. "truncated": entries at the end were removed. "head-missing" / "head-invalid": the head record that would show this is gone or not authentic. */
38
+ reason?: "truncated" | "head-missing" | "head-invalid";
22
39
  };
23
40
  /**
24
- * Walks the hash chain and reports whether it's intact. If an entry was
41
+ * Walks the MAC chain and reports whether it's intact. If an entry was
25
42
  * edited or deleted, `brokenAtIndex` is the (0-based) index of the first
26
- * entry whose chain link no longer matches.
43
+ * entry whose chain link no longer matches. Recomputing a matching MAC
44
+ * requires identity's own secret material (see computeMac/deriveAuditLogKey)
45
+ * — this is what makes forging the chain require more than filesystem
46
+ * write access (ADR 0009). It also checks the authenticated head record
47
+ * (ADR 0019), so deleting the most recent entries is reported too, with
48
+ * `reason: "truncated"`.
49
+ *
50
+ * Not detectable: replacing BOTH log.jsonl and log.head.json with an older,
51
+ * consistent pair, or deleting both files outright. Keep an off-box copy of
52
+ * the head if that matters to you.
27
53
  */
28
54
  export declare function verifyLogIntegrity(identity: Identity): Promise<LogIntegrityResult>;
55
+ /**
56
+ * One-time, explicit opt-in (issue #43/ADR 0027) to encrypt the audit log's
57
+ * entry content, so filesystem access alone no longer reveals what actions
58
+ * this identity has performed. Re-encrypts every existing entry in one pass
59
+ * (there is no mixed-format file afterwards) and marks the head record so
60
+ * every later `appendLogEntry` call encrypts just the one entry it writes —
61
+ * never the whole log again. A no-op if the log is already encrypted.
62
+ * Throws if the log fails its integrity check first: there is nothing safe
63
+ * to migrate if the chain can't be trusted.
64
+ */
65
+ export declare function migrateAuditLogToEncrypted(identity: Identity): Promise<void>;