@shieldfive/crypto 1.0.0-alpha.11

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 (124) hide show
  1. package/CHANGELOG.md +228 -0
  2. package/LICENSE +201 -0
  3. package/README.md +275 -0
  4. package/SECURITY.md +130 -0
  5. package/dist/format/header.d.ts +73 -0
  6. package/dist/format/header.d.ts.map +1 -0
  7. package/dist/format/header.js +230 -0
  8. package/dist/format/header.js.map +1 -0
  9. package/dist/identity/index.d.ts +119 -0
  10. package/dist/identity/index.d.ts.map +1 -0
  11. package/dist/identity/index.js +217 -0
  12. package/dist/identity/index.js.map +1 -0
  13. package/dist/identity/sign.d.ts +92 -0
  14. package/dist/identity/sign.d.ts.map +1 -0
  15. package/dist/identity/sign.js +182 -0
  16. package/dist/identity/sign.js.map +1 -0
  17. package/dist/index.d.ts +58 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +146 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/internal/encoding.d.ts +33 -0
  22. package/dist/internal/encoding.d.ts.map +1 -0
  23. package/dist/internal/encoding.js +135 -0
  24. package/dist/internal/encoding.js.map +1 -0
  25. package/dist/internal/hkdf.d.ts +14 -0
  26. package/dist/internal/hkdf.d.ts.map +1 -0
  27. package/dist/internal/hkdf.js +27 -0
  28. package/dist/internal/hkdf.js.map +1 -0
  29. package/dist/internal/hmac.d.ts +9 -0
  30. package/dist/internal/hmac.d.ts.map +1 -0
  31. package/dist/internal/hmac.js +18 -0
  32. package/dist/internal/hmac.js.map +1 -0
  33. package/dist/internal/runtime.d.ts +29 -0
  34. package/dist/internal/runtime.d.ts.map +1 -0
  35. package/dist/internal/runtime.js +67 -0
  36. package/dist/internal/runtime.js.map +1 -0
  37. package/dist/internal/sodium.d.ts +12 -0
  38. package/dist/internal/sodium.d.ts.map +1 -0
  39. package/dist/internal/sodium.js +34 -0
  40. package/dist/internal/sodium.js.map +1 -0
  41. package/dist/internal/types.d.ts +98 -0
  42. package/dist/internal/types.d.ts.map +1 -0
  43. package/dist/internal/types.js +70 -0
  44. package/dist/internal/types.js.map +1 -0
  45. package/dist/kdf/argon2id.d.ts +72 -0
  46. package/dist/kdf/argon2id.d.ts.map +1 -0
  47. package/dist/kdf/argon2id.js +98 -0
  48. package/dist/kdf/argon2id.js.map +1 -0
  49. package/dist/migration/v0-bridge.d.ts +94 -0
  50. package/dist/migration/v0-bridge.d.ts.map +1 -0
  51. package/dist/migration/v0-bridge.js +203 -0
  52. package/dist/migration/v0-bridge.js.map +1 -0
  53. package/dist/streams/aes-gcm-v1.d.ts +144 -0
  54. package/dist/streams/aes-gcm-v1.d.ts.map +1 -0
  55. package/dist/streams/aes-gcm-v1.js +456 -0
  56. package/dist/streams/aes-gcm-v1.js.map +1 -0
  57. package/dist/streams/pq-hybrid-v1.d.ts +219 -0
  58. package/dist/streams/pq-hybrid-v1.d.ts.map +1 -0
  59. package/dist/streams/pq-hybrid-v1.js +473 -0
  60. package/dist/streams/pq-hybrid-v1.js.map +1 -0
  61. package/dist/suites/aes-gcm-v0/api.d.ts +48 -0
  62. package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -0
  63. package/dist/suites/aes-gcm-v0/api.js +110 -0
  64. package/dist/suites/aes-gcm-v0/api.js.map +1 -0
  65. package/dist/suites/aes-gcm-v1/api.d.ts +54 -0
  66. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -0
  67. package/dist/suites/aes-gcm-v1/api.js +181 -0
  68. package/dist/suites/aes-gcm-v1/api.js.map +1 -0
  69. package/dist/suites/aes-gcm-v1/index.d.ts +59 -0
  70. package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -0
  71. package/dist/suites/aes-gcm-v1/index.js +177 -0
  72. package/dist/suites/aes-gcm-v1/index.js.map +1 -0
  73. package/dist/suites/aes-gcm-v2/api.d.ts +44 -0
  74. package/dist/suites/aes-gcm-v2/api.d.ts.map +1 -0
  75. package/dist/suites/aes-gcm-v2/api.js +162 -0
  76. package/dist/suites/aes-gcm-v2/api.js.map +1 -0
  77. package/dist/suites/aes-gcm-v2/index.d.ts +63 -0
  78. package/dist/suites/aes-gcm-v2/index.d.ts.map +1 -0
  79. package/dist/suites/aes-gcm-v2/index.js +193 -0
  80. package/dist/suites/aes-gcm-v2/index.js.map +1 -0
  81. package/dist/suites/pq-hybrid-v1/api.d.ts +67 -0
  82. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -0
  83. package/dist/suites/pq-hybrid-v1/api.js +190 -0
  84. package/dist/suites/pq-hybrid-v1/api.js.map +1 -0
  85. package/dist/suites/pq-hybrid-v1/index.d.ts +101 -0
  86. package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -0
  87. package/dist/suites/pq-hybrid-v1/index.js +225 -0
  88. package/dist/suites/pq-hybrid-v1/index.js.map +1 -0
  89. package/dist/suites/xchacha-v1/api.d.ts +29 -0
  90. package/dist/suites/xchacha-v1/api.d.ts.map +1 -0
  91. package/dist/suites/xchacha-v1/api.js +154 -0
  92. package/dist/suites/xchacha-v1/api.js.map +1 -0
  93. package/dist/suites/xchacha-v1/index.d.ts +50 -0
  94. package/dist/suites/xchacha-v1/index.d.ts.map +1 -0
  95. package/dist/suites/xchacha-v1/index.js +133 -0
  96. package/dist/suites/xchacha-v1/index.js.map +1 -0
  97. package/package.json +124 -0
  98. package/spec/format-v0.md +81 -0
  99. package/spec/format-v1.md +400 -0
  100. package/spec/key-derivation.md +167 -0
  101. package/spec/threat-model.md +242 -0
  102. package/src/format/header.ts +316 -0
  103. package/src/identity/index.ts +371 -0
  104. package/src/identity/sign.ts +221 -0
  105. package/src/index.ts +224 -0
  106. package/src/internal/encoding.ts +152 -0
  107. package/src/internal/hkdf.ts +47 -0
  108. package/src/internal/hmac.ts +33 -0
  109. package/src/internal/runtime.ts +80 -0
  110. package/src/internal/sodium.ts +38 -0
  111. package/src/internal/types.ts +134 -0
  112. package/src/kdf/argon2id.ts +165 -0
  113. package/src/migration/v0-bridge.ts +347 -0
  114. package/src/streams/aes-gcm-v1.ts +647 -0
  115. package/src/streams/pq-hybrid-v1.ts +722 -0
  116. package/src/suites/aes-gcm-v0/api.ts +155 -0
  117. package/src/suites/aes-gcm-v1/api.ts +292 -0
  118. package/src/suites/aes-gcm-v1/index.ts +269 -0
  119. package/src/suites/aes-gcm-v2/api.ts +268 -0
  120. package/src/suites/aes-gcm-v2/index.ts +289 -0
  121. package/src/suites/pq-hybrid-v1/api.ts +299 -0
  122. package/src/suites/pq-hybrid-v1/index.ts +343 -0
  123. package/src/suites/xchacha-v1/api.ts +254 -0
  124. package/src/suites/xchacha-v1/index.ts +213 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"argon2id.d.ts","sourceRoot":"","sources":["../../src/kdf/argon2id.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,cAAc,GAAG,UAAU,GAAG,WAAW,CAAA;AAErD,eAAO,MAAM,mBAAmB,KAAK,CAAA;AACrC,eAAO,MAAM,mBAAmB,KAAK,CAAA;AA4BrC,MAAM,WAAW,uBAAuB;IACtC,iDAAiD;IACjD,UAAU,EAAE,MAAM,CAAA;IAClB,mEAAmE;IACnE,IAAI,CAAC,EAAE,UAAU,CAAA;IACjB,qDAAqD;IACrD,MAAM,CAAC,EAAE,cAAc,CAAA;CACxB;AAED,MAAM,WAAW,wBAAwB;IACvC,8EAA8E;IAC9E,YAAY,EAAE,UAAU,CAAA;IACxB,8DAA8D;IAC9D,IAAI,EAAE,UAAU,CAAA;IAChB,4EAA4E;IAC5E,MAAM,EAAE,cAAc,CAAA;CACvB;AAED;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,uBAAuB,GAC7B,OAAO,CAAC,wBAAwB,CAAC,CA2CnC;AAED;;;;GAIG;AACH,wBAAsB,oBAAoB,CAAC,KAAK,EAAE;IAChD,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,UAAU,CAAA;IAChB,MAAM,EAAE,cAAc,CAAA;CACvB,GAAG,OAAO,CAAC,UAAU,CAAC,CAGtB;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,KAAK,EAAE;IAC5C,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,UAAU,CAAA;IAChB,MAAM,EAAE,cAAc,CAAA;IACtB,oBAAoB,EAAE,UAAU,CAAA;CACjC,GAAG,OAAO,CAAC,OAAO,CAAC,CAQnB"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Argon2id-based key derivation for password-derived master secrets.
3
+ *
4
+ * The library does not require its callers to use this module — the host
5
+ * application can produce a 32-byte master secret any way it likes. But
6
+ * for the common case of "stretch a user passphrase into a master key,"
7
+ * this module gives a vetted default with explicit parameter choices.
8
+ *
9
+ * Backed by libsodium-wrappers-sumo (loaded lazily). Requires the
10
+ * optional peer dependency to be installed.
11
+ */
12
+ import { getSodium } from '../internal/sodium.js';
13
+ import { hkdfSha256 } from '../internal/hkdf.js';
14
+ import { randomBytes } from '../internal/runtime.js';
15
+ import { HKDF_INFO } from '../internal/types.js';
16
+ export const ARGON2ID_SALT_BYTES = 16;
17
+ export const MASTER_SECRET_BYTES = 32;
18
+ /** Resolve a preset name to (opslimit, memlimit) using libsodium constants. */
19
+ async function resolvePreset(preset) {
20
+ const sodium = await getSodium();
21
+ switch (preset) {
22
+ case 'moderate':
23
+ return {
24
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_MODERATE,
25
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_MODERATE,
26
+ };
27
+ case 'sensitive':
28
+ return {
29
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_SENSITIVE,
30
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_SENSITIVE,
31
+ };
32
+ default: {
33
+ const _exhaustive = preset;
34
+ throw new Error(`unknown Argon2id preset: ${String(_exhaustive)}`);
35
+ }
36
+ }
37
+ }
38
+ /**
39
+ * Derive a 32-byte master secret from a passphrase using Argon2id.
40
+ *
41
+ * The host application MUST persist `salt` and `preset` alongside the
42
+ * user's account so that future logins can reproduce the same master
43
+ * secret. The passphrase itself MUST NOT be stored.
44
+ */
45
+ export async function deriveMasterSecret(input) {
46
+ const sodium = await getSodium();
47
+ if (typeof input.passphrase !== 'string' || input.passphrase.length === 0) {
48
+ throw new Error('deriveMasterSecret: passphrase must be a non-empty string');
49
+ }
50
+ const salt = input.salt ?? randomBytes(ARGON2ID_SALT_BYTES);
51
+ if (salt.length < ARGON2ID_SALT_BYTES) {
52
+ throw new RangeError(`deriveMasterSecret: salt must be at least ${ARGON2ID_SALT_BYTES} bytes`);
53
+ }
54
+ // libsodium expects exactly SALTBYTES; if a longer salt is supplied,
55
+ // we domain-separate it through HKDF first to land on 16 bytes.
56
+ let usableSalt = salt;
57
+ if (salt.length > ARGON2ID_SALT_BYTES) {
58
+ usableSalt = await hkdfSha256({
59
+ ikm: salt,
60
+ info: HKDF_INFO.ARGON2ID_SALT_COMPRESSION,
61
+ length: ARGON2ID_SALT_BYTES,
62
+ });
63
+ }
64
+ const preset = input.preset ?? 'moderate';
65
+ const { opslimit, memlimit } = await resolvePreset(preset);
66
+ const passphraseBytes = new TextEncoder().encode(input.passphrase);
67
+ const derived = sodium.crypto_pwhash(MASTER_SECRET_BYTES, passphraseBytes, usableSalt, opslimit, memlimit, sodium.crypto_pwhash_ALG_ARGON2ID13);
68
+ return {
69
+ masterSecret: new Uint8Array(derived),
70
+ salt,
71
+ preset,
72
+ };
73
+ }
74
+ /**
75
+ * Re-derive the same master secret given the previously stored salt and
76
+ * preset. Convenience wrapper; exactly equivalent to deriveMasterSecret
77
+ * called with the saved parameters.
78
+ */
79
+ export async function reDeriveMasterSecret(input) {
80
+ const result = await deriveMasterSecret(input);
81
+ return result.masterSecret;
82
+ }
83
+ /**
84
+ * Verify a passphrase against a previously derived master secret without
85
+ * exposing whether the input was wrong before the constant-time compare.
86
+ * Returns true iff the rederived master secret matches.
87
+ */
88
+ export async function verifyPassphrase(input) {
89
+ const computed = await reDeriveMasterSecret(input);
90
+ if (computed.length !== input.expectedMasterSecret.length)
91
+ return false;
92
+ let diff = 0;
93
+ for (let i = 0; i < computed.length; i += 1) {
94
+ diff |= computed[i] ^ input.expectedMasterSecret[i];
95
+ }
96
+ return diff === 0;
97
+ }
98
+ //# sourceMappingURL=argon2id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"argon2id.js","sourceRoot":"","sources":["../../src/kdf/argon2id.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAA;AAgBhD,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAA;AACrC,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAA;AAOrC,+EAA+E;AAC/E,KAAK,UAAU,aAAa,CAAC,MAAsB;IACjD,MAAM,MAAM,GAAG,MAAM,SAAS,EAAE,CAAA;IAChC,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,UAAU;YACb,OAAO;gBACL,QAAQ,EAAE,MAAM,CAAC,+BAA+B;gBAChD,QAAQ,EAAE,MAAM,CAAC,+BAA+B;aACjD,CAAA;QACH,KAAK,WAAW;YACd,OAAO;gBACL,QAAQ,EAAE,MAAM,CAAC,gCAAgC;gBACjD,QAAQ,EAAE,MAAM,CAAC,gCAAgC;aAClD,CAAA;QACH,OAAO,CAAC,CAAC,CAAC;YACR,MAAM,WAAW,GAAU,MAAM,CAAA;YACjC,MAAM,IAAI,KAAK,CAAC,4BAA4B,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;QACpE,CAAC;IACH,CAAC;AACH,CAAC;AAoBD;;;;;;GAMG;AACH,MAAM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CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,KAI1C;IACC,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC,KAAK,CAAC,CAAA;IAC9C,OAAO,MAAM,CAAC,YAAY,CAAA;AAC5B,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,KAKtC;IACC,MAAM,QAAQ,GAAG,MAAM,oBAAoB,CAAC,KAAK,CAAC,CAAA;IAClD,IAAI,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,oBAAoB,CAAC,MAAM;QAAE,OAAO,KAAK,CAAA;IACvE,IAAI,IAAI,GAAG,CAAC,CAAA;IACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5C,IAAI,IAAI,QAAQ,CAAC,CAAC,CAAE,GAAG,KAAK,CAAC,oBAAoB,CAAC,CAAC,CAAE,CAAA;IACvD,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,CAAA;AACnB,CAAC"}
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Phase 1 migration bridge: v0 (legacy) format encrypt/decrypt.
3
+ *
4
+ * ⚠️ THIS MODULE EXISTS SOLELY FOR THE PHASE 1 SHIELDFIVE MIGRATION ⚠️
5
+ *
6
+ * The on-disk file format here is the legacy "v0" format documented in
7
+ * `spec/format-v0.md` — concatenated AES-256-GCM chunks, no header, no
8
+ * AAD, IV = 4-byte file-prefix || uint64_be(counter), all metadata stored
9
+ * out-of-band in the application database.
10
+ *
11
+ * v0 has documented structural weaknesses (no truncation detection at
12
+ * the AEAD layer, no chunk-index AAD, etc.) that v1 fixes. We expose a
13
+ * v0 *writer* in this bridge module ONLY so that ShieldFive can swap the
14
+ * inline crypto in the main repository for library calls **without**
15
+ * changing the on-disk format in the same release. Once Phase 2 ships
16
+ * (writers default to suite 0x01 / v1), this module is deprecated; once
17
+ * all v0 files have been migrated to v1, this module is deleted.
18
+ *
19
+ * Outside the ShieldFive main-repo migration, callers SHOULD NOT use
20
+ * `legacyV0Writer.encryptV0`. Use one of the v1 suites instead.
21
+ *
22
+ * The decrypt path delegates straight to `suites/aes-gcm-v0/api.ts`
23
+ * (which is the supported, public legacy reader).
24
+ */
25
+ import { decryptV0, decryptV0ToBytes, V0_IV_BYTES, V0_KEY_BYTES, V0_NONCE_PREFIX_BYTES, V0_TAG_BYTES, type V0DecryptOptions } from '../suites/aes-gcm-v0/api.js';
26
+ export { decryptV0, decryptV0ToBytes, V0_IV_BYTES, V0_KEY_BYTES, V0_NONCE_PREFIX_BYTES, V0_TAG_BYTES, type V0DecryptOptions, };
27
+ export interface V0EncryptOptions {
28
+ /** Plaintext blob. */
29
+ blob: Blob;
30
+ /** 32-byte AES-256 content key. Must already be unwrapped. */
31
+ contentKey: Uint8Array;
32
+ /** 4-byte per-file random nonce prefix. Generated if omitted. */
33
+ noncePrefix?: Uint8Array;
34
+ /** Plaintext bytes per chunk. Production uses 5 MiB or 8 MiB. */
35
+ chunkSize: number;
36
+ /** Optional progress callback (0..1). */
37
+ onProgress?: (progress: number) => void;
38
+ /**
39
+ * If true, also computes per-chunk SHA-1 hashes for storage-layer
40
+ * integrity checks (matching the production worker's behavior).
41
+ */
42
+ computeChunkHashes?: boolean;
43
+ }
44
+ export interface V0EncryptResult {
45
+ /** Encrypted blob (concatenated chunks, no header). */
46
+ blob: Blob;
47
+ /** Number of chunks emitted. */
48
+ totalChunks: number;
49
+ /** Plaintext byte count. */
50
+ plaintextSize: number;
51
+ /** Nonce prefix used (caller MUST persist this in the database). */
52
+ noncePrefix: Uint8Array;
53
+ /** SHA-1 hashes per chunk if requested; otherwise omitted. */
54
+ chunkHashes?: string[];
55
+ }
56
+ /**
57
+ * Encrypt a blob in the legacy v0 format. Drop-in replacement for the
58
+ * inline AES-GCM calls in `public/workers/sf-crypto-worker.js`.
59
+ *
60
+ * **Wire format:** identical to current production. Bit-for-bit
61
+ * compatible.
62
+ *
63
+ * **Key handling:** the caller must bring their own pre-unwrapped 32-byte
64
+ * content key. This module does not wrap or unwrap keys.
65
+ */
66
+ export declare function encryptV0(options: V0EncryptOptions): Promise<V0EncryptResult>;
67
+ /**
68
+ * Web Worker message handler shaped to match the existing production
69
+ * worker contract at `public/workers/sf-crypto-worker.js`. Lets the main
70
+ * repo replace the worker file's body with `installV0WorkerHandler(self)`
71
+ * during Phase 1 of the migration — no API changes for callers.
72
+ *
73
+ * Message shape (matches production):
74
+ * { type: 'init', mode: 'encrypt' | 'decrypt', key: ArrayBuffer,
75
+ * noncePrefix: ArrayBuffer, chunkSize: number, blob: Blob }
76
+ * { type: 'process', index: number }
77
+ * (also accepted: { type: 'chunk_request', index: number } — alias)
78
+ * { type: 'clear' }
79
+ *
80
+ * Responses:
81
+ * { type: 'inited', totalChunks: number }
82
+ * { type: 'chunk', mode: 'encrypt', index, data: ArrayBuffer, sha1: string }
83
+ * { type: 'chunk', mode: 'decrypt', index, data: ArrayBuffer }
84
+ * { type: 'cleared' }
85
+ * { type: 'error', error: string }
86
+ */
87
+ export interface WorkerLike {
88
+ onmessage: ((event: {
89
+ data: unknown;
90
+ }) => void | Promise<void>) | null;
91
+ postMessage: (msg: unknown) => void;
92
+ }
93
+ export declare function installV0WorkerHandler(scope: WorkerLike): void;
94
+ //# sourceMappingURL=v0-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"v0-bridge.d.ts","sourceRoot":"","sources":["../../src/migration/v0-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,WAAW,EACX,YAAY,EACZ,qBAAqB,EACrB,YAAY,EACZ,KAAK,gBAAgB,EACtB,MAAM,6BAA6B,CAAA;AAEpC,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,WAAW,EACX,YAAY,EACZ,qBAAqB,EACrB,Y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IVE MIGRATION ⚠️
5
+ *
6
+ * The on-disk file format here is the legacy "v0" format documented in
7
+ * `spec/format-v0.md` — concatenated AES-256-GCM chunks, no header, no
8
+ * AAD, IV = 4-byte file-prefix || uint64_be(counter), all metadata stored
9
+ * out-of-band in the application database.
10
+ *
11
+ * v0 has documented structural weaknesses (no truncation detection at
12
+ * the AEAD layer, no chunk-index AAD, etc.) that v1 fixes. We expose a
13
+ * v0 *writer* in this bridge module ONLY so that ShieldFive can swap the
14
+ * inline crypto in the main repository for library calls **without**
15
+ * changing the on-disk format in the same release. Once Phase 2 ships
16
+ * (writers default to suite 0x01 / v1), this module is deprecated; once
17
+ * all v0 files have been migrated to v1, this module is deleted.
18
+ *
19
+ * Outside the ShieldFive main-repo migration, callers SHOULD NOT use
20
+ * `legacyV0Writer.encryptV0`. Use one of the v1 suites instead.
21
+ *
22
+ * The decrypt path delegates straight to `suites/aes-gcm-v0/api.ts`
23
+ * (which is the supported, public legacy reader).
24
+ */
25
+ import { uint64BE } from '../internal/encoding.js';
26
+ import { getSubtle, randomBytes } from '../internal/runtime.js';
27
+ import { decryptV0, decryptV0ToBytes, V0_IV_BYTES, V0_KEY_BYTES, V0_NONCE_PREFIX_BYTES, V0_TAG_BYTES, } from '../suites/aes-gcm-v0/api.js';
28
+ export { decryptV0, decryptV0ToBytes, V0_IV_BYTES, V0_KEY_BYTES, V0_NONCE_PREFIX_BYTES, V0_TAG_BYTES, };
29
+ function buildV0Iv(prefix, counter) {
30
+ const iv = new Uint8Array(V0_IV_BYTES);
31
+ iv.set(prefix, 0);
32
+ iv.set(uint64BE(counter), 4);
33
+ return iv;
34
+ }
35
+ async function sha1Hex(bytes) {
36
+ const subtle = getSubtle();
37
+ const digest = await subtle.digest('SHA-1', bytes);
38
+ const arr = new Uint8Array(digest);
39
+ let out = '';
40
+ for (let i = 0; i < arr.length; i += 1) {
41
+ out += arr[i].toString(16).padStart(2, '0');
42
+ }
43
+ return out;
44
+ }
45
+ /**
46
+ * Encrypt a blob in the legacy v0 format. Drop-in replacement for the
47
+ * inline AES-GCM calls in `public/workers/sf-crypto-worker.js`.
48
+ *
49
+ * **Wire format:** identical to current production. Bit-for-bit
50
+ * compatible.
51
+ *
52
+ * **Key handling:** the caller must bring their own pre-unwrapped 32-byte
53
+ * content key. This module does not wrap or unwrap keys.
54
+ */
55
+ export async function encryptV0(options) {
56
+ const { blob, contentKey, chunkSize, onProgress } = options;
57
+ if (!(blob instanceof Blob)) {
58
+ throw new TypeError('encryptV0: blob must be a Blob or File');
59
+ }
60
+ if (contentKey.length !== V0_KEY_BYTES) {
61
+ throw new RangeError('encryptV0: contentKey must be 32 bytes');
62
+ }
63
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
64
+ throw new RangeError('encryptV0: chunkSize must be a positive integer');
65
+ }
66
+ const noncePrefix = options.noncePrefix ?? randomBytes(V0_NONCE_PREFIX_BYTES);
67
+ if (noncePrefix.length !== V0_NONCE_PREFIX_BYTES) {
68
+ throw new RangeError('encryptV0: noncePrefix must be 4 bytes');
69
+ }
70
+ const plaintextSize = blob.size;
71
+ if (plaintextSize === 0) {
72
+ return {
73
+ blob: new Blob([], { type: 'application/octet-stream' }),
74
+ totalChunks: 0,
75
+ plaintextSize: 0,
76
+ noncePrefix,
77
+ ...(options.computeChunkHashes ? { chunkHashes: [] } : {}),
78
+ };
79
+ }
80
+ const totalChunks = Math.ceil(plaintextSize / chunkSize);
81
+ const subtle = getSubtle();
82
+ const key = await subtle.importKey('raw', contentKey, { name: 'AES-GCM' }, false, ['encrypt']);
83
+ const parts = [];
84
+ const chunkHashes = [];
85
+ for (let i = 0; i < totalChunks; i += 1) {
86
+ const start = i * chunkSize;
87
+ const end = Math.min(start + chunkSize, plaintextSize);
88
+ const slice = new Uint8Array(await blob.slice(start, end).arrayBuffer());
89
+ const iv = buildV0Iv(noncePrefix, i);
90
+ const ct = new Uint8Array(await subtle.encrypt({
91
+ name: 'AES-GCM',
92
+ iv: iv,
93
+ tagLength: 128,
94
+ }, key, slice));
95
+ parts.push(ct);
96
+ if (options.computeChunkHashes) {
97
+ chunkHashes.push(await sha1Hex(ct));
98
+ }
99
+ onProgress?.((i + 1) / totalChunks);
100
+ }
101
+ const result = {
102
+ blob: new Blob(parts, { type: 'application/octet-stream' }),
103
+ totalChunks,
104
+ plaintextSize,
105
+ noncePrefix,
106
+ };
107
+ if (options.computeChunkHashes) {
108
+ result.chunkHashes = chunkHashes;
109
+ }
110
+ return result;
111
+ }
112
+ export function installV0WorkerHandler(scope) {
113
+ let state = null;
114
+ scope.onmessage = async (event) => {
115
+ const msg = (event.data ?? {});
116
+ try {
117
+ if (msg.type === 'init') {
118
+ const mode = msg.mode === 'decrypt' ? 'decrypt' : 'encrypt';
119
+ const rawKeyBuf = msg.key;
120
+ const rawPrefixBuf = msg.noncePrefix;
121
+ const blob = msg.blob;
122
+ const chunkSize = Number(msg.chunkSize ?? 0);
123
+ if (!rawKeyBuf || !rawPrefixBuf || !blob || !chunkSize || chunkSize <= 0) {
124
+ throw new Error('worker_init_invalid');
125
+ }
126
+ const rawKey = new Uint8Array(rawKeyBuf);
127
+ const noncePrefix = new Uint8Array(rawPrefixBuf);
128
+ if (rawKey.length !== V0_KEY_BYTES) {
129
+ throw new Error('worker_init_key_invalid');
130
+ }
131
+ if (noncePrefix.length !== V0_NONCE_PREFIX_BYTES) {
132
+ throw new Error('worker_init_nonce_prefix_invalid');
133
+ }
134
+ const key = await getSubtle().importKey('raw', rawKey, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
135
+ const ctChunkSize = chunkSize + V0_TAG_BYTES;
136
+ const totalChunks = mode === 'encrypt'
137
+ ? Math.ceil(blob.size / chunkSize)
138
+ : Math.ceil(blob.size / ctChunkSize);
139
+ state = {
140
+ mode,
141
+ key,
142
+ noncePrefix,
143
+ chunkSize,
144
+ blob,
145
+ totalChunks,
146
+ };
147
+ scope.postMessage({ type: 'inited', totalChunks });
148
+ return;
149
+ }
150
+ if (msg.type === 'process' || msg.type === 'chunk_request') {
151
+ if (!state)
152
+ throw new Error('worker_not_inited');
153
+ const index = Number(msg.index ?? -1);
154
+ if (!Number.isInteger(index) || index < 0 || index >= state.totalChunks) {
155
+ throw new Error('worker_chunk_index_invalid');
156
+ }
157
+ const iv = buildV0Iv(state.noncePrefix, index);
158
+ if (state.mode === 'encrypt') {
159
+ const start = index * state.chunkSize;
160
+ const end = Math.min(start + state.chunkSize, state.blob.size);
161
+ const slice = new Uint8Array(await state.blob.slice(start, end).arrayBuffer());
162
+ const ciphertext = await getSubtle().encrypt({ name: 'AES-GCM', iv: iv, tagLength: 128 }, state.key, slice);
163
+ const ctBytes = new Uint8Array(ciphertext);
164
+ const sha1 = await sha1Hex(ctBytes);
165
+ scope.postMessage({
166
+ type: 'chunk',
167
+ mode: 'encrypt',
168
+ index,
169
+ data: ciphertext,
170
+ sha1,
171
+ });
172
+ }
173
+ else {
174
+ const ctChunk = state.chunkSize + V0_TAG_BYTES;
175
+ const start = index * ctChunk;
176
+ const end = Math.min(start + ctChunk, state.blob.size);
177
+ const slice = new Uint8Array(await state.blob.slice(start, end).arrayBuffer());
178
+ const plaintext = await getSubtle().decrypt({ name: 'AES-GCM', iv: iv, tagLength: 128 }, state.key, slice);
179
+ scope.postMessage({
180
+ type: 'chunk',
181
+ mode: 'decrypt',
182
+ index,
183
+ data: plaintext,
184
+ });
185
+ }
186
+ return;
187
+ }
188
+ if (msg.type === 'clear') {
189
+ state = null;
190
+ scope.postMessage({ type: 'cleared' });
191
+ return;
192
+ }
193
+ throw new Error('worker_unknown_message_type');
194
+ }
195
+ catch (err) {
196
+ scope.postMessage({
197
+ type: 'error',
198
+ error: err.message ?? 'unknown_error',
199
+ });
200
+ }
201
+ };
202
+ }
203
+ //# sourceMappingURL=v0-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"v0-bridge.js","sourceRoot":"","sources":["../../src/migration/v0-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GA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A;oBACD,MAAM,SAAS,GAAG,MAAM,SAAS,EAAE,CAAC,OAAO,CACzC,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,EAA6B,EAAE,SAAS,EAAE,GAAG,EAAE,EACtE,KAAK,CAAC,GAAG,EACT,KAAgC,CACjC,CAAA;oBACD,KAAK,CAAC,WAAW,CAAC;wBAChB,IAAI,EAAE,OAAO;wBACb,IAAI,EAAE,SAAS;wBACf,KAAK;wBACL,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAA;gBACJ,CAAC;gBACD,OAAM;YACR,CAAC;YAED,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBACzB,KAAK,GAAG,IAAI,CAAA;gBACZ,KAAK,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;gBACtC,OAAM;YACR,CAAC;YAED,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;QAChD,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,KAAK,CAAC,WAAW,CAAC;gBAChB,IAAI,EAAE,OAAO;gBACb,KAAK,EAAG,GAAa,CAAC,OAAO,IAAI,eAAe;aACjD,CAAC,CAAA;QACJ,CAAC;IACH,CAAC,CAAA;AACH,CAAC"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Streaming encrypt/decrypt for the v1 wire format.
3
+ *
4
+ * The whole-blob APIs in `suites/<name>/api.ts` materialize entire files in
5
+ * memory. That's fine for small files; for multi-gigabyte files on a
6
+ * mobile device it isn't.
7
+ *
8
+ * This module exposes a WHATWG TransformStream factory that ingests
9
+ * plaintext (or ciphertext) chunks from any ReadableStream and emits the
10
+ * other side, without ever holding more than one chunk-plus-header in
11
+ * memory at once.
12
+ *
13
+ * Currently implemented:
14
+ * - Suite 0x01 (aes-256-gcm-v1) encrypt
15
+ * - Suite 0x01 (aes-256-gcm-v1) decrypt
16
+ *
17
+ * The XChaCha and PQ-hybrid suites use the same chunk format and AAD;
18
+ * adding them is a copy of the AES module with the suite primitive
19
+ * swapped, but we ship one suite first to lock the streaming contract.
20
+ */
21
+ export interface AesGcmV1EncryptStreamOptions {
22
+ /** Total plaintext byte count. Required because the header carries it. */
23
+ plaintextSize: number;
24
+ /** Plaintext bytes per chunk. Default 4 MiB. */
25
+ chunkSize?: number;
26
+ /** Pre-existing 32-byte content key, or generated if omitted. */
27
+ contentKey?: Uint8Array;
28
+ /** Pre-existing 16-byte file_id, or generated if omitted. */
29
+ fileId?: Uint8Array;
30
+ /** Optional embedded suite payload (60-byte wrapped key + 12-byte IV). */
31
+ suitePayloadOverride?: Uint8Array;
32
+ /**
33
+ * Optional 32-byte Ed25519 secret seed. When provided, the stream
34
+ * appends a signature block over `header_unauthenticated_bytes ||
35
+ * concat(chunk_macs)` after the final chunk. When omitted, no block
36
+ * is emitted and the file decrypts as unsigned (legacy behavior).
37
+ */
38
+ ed25519SecretKey?: Uint8Array;
39
+ }
40
+ export interface AesGcmV1EncryptStreamResult {
41
+ /** TransformStream<Uint8Array, Uint8Array> emitting the v1 wire format. */
42
+ stream: TransformStream<Uint8Array, Uint8Array>;
43
+ /** The content key used (for envelope wrapping by the caller). */
44
+ contentKey: Uint8Array;
45
+ /** The file_id used (for application-level metadata storage). */
46
+ fileId: Uint8Array;
47
+ }
48
+ /**
49
+ * Build a TransformStream that encrypts plaintext into v1 wire-format
50
+ * ciphertext on the fly. The stream emits the header first, then each
51
+ * chunk as it arrives.
52
+ *
53
+ * The caller MUST pass `plaintextSize` because the header records it.
54
+ * If the caller doesn't know the size up front, they must accumulate
55
+ * the plaintext into a buffer first — there is no way to write a
56
+ * self-describing header otherwise.
57
+ */
58
+ export declare function createAesGcmV1EncryptStream(options: AesGcmV1EncryptStreamOptions): AesGcmV1EncryptStreamResult;
59
+ export interface AesGcmV1DecryptStreamOptions {
60
+ contentKey: Uint8Array;
61
+ /**
62
+ * If provided, a trailing signature block (if present) is verified
63
+ * against this Ed25519 public key, and the resolved metadata's
64
+ * `signature.verified` reflects the outcome. If omitted, a present
65
+ * block is parsed and surfaced but not verified; `verified` is null.
66
+ */
67
+ expectedSignerPublicKey?: Uint8Array;
68
+ }
69
+ /**
70
+ * Verified signature metadata surfaced by the decrypt stream.
71
+ *
72
+ * - `algorithm`, `publicKey`, `signature` come from the parsed block.
73
+ * - `verified` is `true` if the caller passed `expectedSignerPublicKey`
74
+ * AND it matched the embedded pubkey AND the signature verifies; it
75
+ * is `false` if the check ran and failed; it is `null` if the caller
76
+ * passed no `expectedSignerPublicKey` (the application policy layer
77
+ * is expected to do its own verification using the surfaced bytes).
78
+ */
79
+ export interface VerifiedSignature {
80
+ algorithm: number;
81
+ publicKey: Uint8Array;
82
+ signature: Uint8Array;
83
+ verified: boolean | null;
84
+ }
85
+ export interface DecryptionMetadata {
86
+ /** Null when the file has no signature block (legacy / unsigned). */
87
+ signature: VerifiedSignature | null;
88
+ }
89
+ export interface AesGcmV1DecryptStreamResult {
90
+ stream: TransformStream<Uint8Array, Uint8Array>;
91
+ /**
92
+ * Resolves once the stream finishes flushing. Rejects if the stream
93
+ * errored — callers awaiting metadata MUST handle rejection (or await
94
+ * the plaintext drain first, which surfaces the same error).
95
+ */
96
+ metadata: Promise<DecryptionMetadata>;
97
+ }
98
+ /**
99
+ * Build a TransformStream that decrypts a v1 ciphertext stream into
100
+ * plaintext. Unlike the whole-blob decryptor, this version processes
101
+ * input incrementally — useful for very large files or when ciphertext
102
+ * arrives chunked over the network.
103
+ *
104
+ * Files written by an older library version (no signature block) decrypt
105
+ * unchanged: `metadata.signature` resolves to `null`. Files with a
106
+ * trailing signature block are parsed; if `expectedSignerPublicKey` is
107
+ * supplied, the signature is verified and `metadata.signature.verified`
108
+ * reflects the outcome.
109
+ */
110
+ export declare function createAesGcmV1DecryptStream(options: AesGcmV1DecryptStreamOptions): AesGcmV1DecryptStreamResult;
111
+ /**
112
+ * Pipe a ReadableStream<Uint8Array> through the AES-GCM-v1 encrypt
113
+ * transform and return the resulting ReadableStream + key material.
114
+ */
115
+ export declare function encryptStreamAesGcmV1(source: ReadableStream<Uint8Array>, options: AesGcmV1EncryptStreamOptions): {
116
+ ciphertext: ReadableStream<Uint8Array>;
117
+ contentKey: Uint8Array;
118
+ fileId: Uint8Array;
119
+ };
120
+ /**
121
+ * Pipe a ReadableStream<Uint8Array> through the AES-GCM-v1 decrypt
122
+ * transform and return the resulting plaintext ReadableStream alongside
123
+ * a `metadata` Promise that resolves at end-of-stream with the parsed
124
+ * signature block (or `signature: null` for unsigned / legacy files).
125
+ */
126
+ export declare function decryptStreamAesGcmV1(source: ReadableStream<Uint8Array>, options: AesGcmV1DecryptStreamOptions): {
127
+ plaintext: ReadableStream<Uint8Array>;
128
+ metadata: Promise<DecryptionMetadata>;
129
+ };
130
+ /**
131
+ * Parse a trailing signature block (if any) from the decrypt stream's
132
+ * residual buffer, optionally verifying it against the caller's
133
+ * trusted public key.
134
+ *
135
+ * Shared between the AES-GCM and PQ-hybrid stream decoders so the
136
+ * signature semantics live in one place.
137
+ */
138
+ export declare function finalizeSignatureMetadata(input: {
139
+ trailingBytes: Uint8Array;
140
+ header: Uint8Array;
141
+ chunkMacs: ReadonlyArray<Uint8Array>;
142
+ expectedSignerPublicKey: Uint8Array | undefined;
143
+ }): VerifiedSignature | null;
144
+ //# sourceMappingURL=aes-gcm-v1.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aes-gcm-v1.d.ts","sourceRoot":"","sources":["../../src/streams/aes-gcm-v1.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AA0CH,MAAM,WAAW,4BAA4B;IAC3C,0EAA0E;IAC1E,aAAa,EAAE,MAAM,CAAA;IACrB,gDAAgD;IAChD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,iEAAiE;IACjE,UAAU,CAAC,EAAE,UAAU,CAAA;IACvB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,0EAA0E;IAC1E,oBAAoB,CA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