@shieldfive/crypto 1.0.0-alpha.2

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 (104) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/LICENSE +201 -0
  3. package/README.md +241 -0
  4. package/SECURITY.md +123 -0
  5. package/dist/format/header.d.ts +60 -0
  6. package/dist/format/header.d.ts.map +1 -0
  7. package/dist/format/header.js +203 -0
  8. package/dist/format/header.js.map +1 -0
  9. package/dist/identity/index.d.ts +117 -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/index.d.ts +52 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +124 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/internal/encoding.d.ts +33 -0
  18. package/dist/internal/encoding.d.ts.map +1 -0
  19. package/dist/internal/encoding.js +136 -0
  20. package/dist/internal/encoding.js.map +1 -0
  21. package/dist/internal/hkdf.d.ts +14 -0
  22. package/dist/internal/hkdf.d.ts.map +1 -0
  23. package/dist/internal/hkdf.js +27 -0
  24. package/dist/internal/hkdf.js.map +1 -0
  25. package/dist/internal/hmac.d.ts +9 -0
  26. package/dist/internal/hmac.d.ts.map +1 -0
  27. package/dist/internal/hmac.js +18 -0
  28. package/dist/internal/hmac.js.map +1 -0
  29. package/dist/internal/runtime.d.ts +29 -0
  30. package/dist/internal/runtime.d.ts.map +1 -0
  31. package/dist/internal/runtime.js +67 -0
  32. package/dist/internal/runtime.js.map +1 -0
  33. package/dist/internal/sodium.d.ts +12 -0
  34. package/dist/internal/sodium.d.ts.map +1 -0
  35. package/dist/internal/sodium.js +34 -0
  36. package/dist/internal/sodium.js.map +1 -0
  37. package/dist/internal/types.d.ts +94 -0
  38. package/dist/internal/types.d.ts.map +1 -0
  39. package/dist/internal/types.js +65 -0
  40. package/dist/internal/types.js.map +1 -0
  41. package/dist/kdf/argon2id.d.ts +72 -0
  42. package/dist/kdf/argon2id.d.ts.map +1 -0
  43. package/dist/kdf/argon2id.js +97 -0
  44. package/dist/kdf/argon2id.js.map +1 -0
  45. package/dist/migration/v0-bridge.d.ts +94 -0
  46. package/dist/migration/v0-bridge.d.ts.map +1 -0
  47. package/dist/migration/v0-bridge.js +203 -0
  48. package/dist/migration/v0-bridge.js.map +1 -0
  49. package/dist/streams/aes-gcm-v1.d.ts +76 -0
  50. package/dist/streams/aes-gcm-v1.d.ts.map +1 -0
  51. package/dist/streams/aes-gcm-v1.js +322 -0
  52. package/dist/streams/aes-gcm-v1.js.map +1 -0
  53. package/dist/suites/aes-gcm-v0/api.d.ts +48 -0
  54. package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -0
  55. package/dist/suites/aes-gcm-v0/api.js +110 -0
  56. package/dist/suites/aes-gcm-v0/api.js.map +1 -0
  57. package/dist/suites/aes-gcm-v1/api.d.ts +54 -0
  58. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -0
  59. package/dist/suites/aes-gcm-v1/api.js +179 -0
  60. package/dist/suites/aes-gcm-v1/api.js.map +1 -0
  61. package/dist/suites/aes-gcm-v1/index.d.ts +56 -0
  62. package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -0
  63. package/dist/suites/aes-gcm-v1/index.js +174 -0
  64. package/dist/suites/aes-gcm-v1/index.js.map +1 -0
  65. package/dist/suites/pq-hybrid-v1/api.d.ts +40 -0
  66. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -0
  67. package/dist/suites/pq-hybrid-v1/api.js +157 -0
  68. package/dist/suites/pq-hybrid-v1/api.js.map +1 -0
  69. package/dist/suites/pq-hybrid-v1/index.d.ts +101 -0
  70. package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -0
  71. package/dist/suites/pq-hybrid-v1/index.js +225 -0
  72. package/dist/suites/pq-hybrid-v1/index.js.map +1 -0
  73. package/dist/suites/xchacha-v1/api.d.ts +29 -0
  74. package/dist/suites/xchacha-v1/api.d.ts.map +1 -0
  75. package/dist/suites/xchacha-v1/api.js +151 -0
  76. package/dist/suites/xchacha-v1/api.js.map +1 -0
  77. package/dist/suites/xchacha-v1/index.d.ts +50 -0
  78. package/dist/suites/xchacha-v1/index.d.ts.map +1 -0
  79. package/dist/suites/xchacha-v1/index.js +133 -0
  80. package/dist/suites/xchacha-v1/index.js.map +1 -0
  81. package/package.json +112 -0
  82. package/spec/format-v0.md +81 -0
  83. package/spec/format-v1.md +245 -0
  84. package/spec/key-derivation.md +122 -0
  85. package/spec/threat-model.md +152 -0
  86. package/src/format/header.ts +284 -0
  87. package/src/identity/index.ts +358 -0
  88. package/src/index.ts +197 -0
  89. package/src/internal/encoding.ts +153 -0
  90. package/src/internal/hkdf.ts +47 -0
  91. package/src/internal/hmac.ts +33 -0
  92. package/src/internal/runtime.ts +80 -0
  93. package/src/internal/sodium.ts +38 -0
  94. package/src/internal/types.ts +128 -0
  95. package/src/kdf/argon2id.ts +164 -0
  96. package/src/migration/v0-bridge.ts +347 -0
  97. package/src/streams/aes-gcm-v1.ts +443 -0
  98. package/src/suites/aes-gcm-v0/api.ts +155 -0
  99. package/src/suites/aes-gcm-v1/api.ts +291 -0
  100. package/src/suites/aes-gcm-v1/index.ts +266 -0
  101. package/src/suites/pq-hybrid-v1/api.ts +259 -0
  102. package/src/suites/pq-hybrid-v1/index.ts +343 -0
  103. package/src/suites/xchacha-v1/api.ts +251 -0
  104. package/src/suites/xchacha-v1/index.ts +213 -0
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Public type definitions for the shieldfive-crypto library.
3
+ */
4
+ export type Crypto = {
5
+ subtle: SubtleCrypto;
6
+ getRandomValues<T extends ArrayBufferView>(array: T): T;
7
+ };
8
+ export type SubtleCrypto = globalThis.SubtleCrypto;
9
+ /**
10
+ * Suite identifiers as written to the on-disk format byte.
11
+ * See `spec/format-v1.md` for the canonical assignment.
12
+ */
13
+ export declare const SUITE: {
14
+ readonly AES_256_GCM_V1: 1;
15
+ readonly XCHACHA20_POLY1305_V1: 2;
16
+ readonly PQ_HYBRID_XCHACHA_MLKEM1024_V1: 3;
17
+ };
18
+ export type SuiteId = (typeof SUITE)[keyof typeof SUITE];
19
+ export type SuiteName = 'aes-256-gcm-v1' | 'xchacha20-poly1305-v1' | 'pq-hybrid-xchacha-mlkem1024-v1';
20
+ export declare const SUITE_NAMES: Record<SuiteId, SuiteName>;
21
+ /**
22
+ * Magic bytes prefixing every v1-format file: "SF5" + major(1) + minor(0).
23
+ * Treat as immutable; do not mutate.
24
+ */
25
+ export declare const FORMAT_MAGIC: Uint8Array;
26
+ export declare const FORMAT_MAGIC_LENGTH = 5;
27
+ /** Header field sizes — see spec/format-v1.md */
28
+ export declare const HEADER_SIZES: Readonly<{
29
+ MAGIC: 5;
30
+ SUITE: 1;
31
+ FLAGS: 1;
32
+ FILE_ID: 16;
33
+ CHUNK_SIZE: 4;
34
+ TOTAL_CHUNKS: 8;
35
+ PLAINTEXT_SIZE: 8;
36
+ SUITE_PAYLOAD_LEN: 2;
37
+ HEADER_MAC: 32;
38
+ }>;
39
+ /** Fixed bytes preceding the variable-length suite_payload */
40
+ export declare const HEADER_FIXED_PREFIX_LENGTH: number;
41
+ /** Default plaintext bytes per chunk for new uploads (4 MiB) */
42
+ export declare const DEFAULT_CHUNK_SIZE: number;
43
+ /** Maximum permitted chunk_size in the format (uint32 max) */
44
+ export declare const MAX_CHUNK_SIZE = 4294967295;
45
+ /** Maximum permitted total_chunks (sane upper bound, well below uint64 max) */
46
+ export declare const MAX_TOTAL_CHUNKS = 1000000000;
47
+ /** Domain separators for HKDF — never reuse a string here in another context */
48
+ export declare const HKDF_INFO: Readonly<{
49
+ HEADER_MAC: "shieldfive/v1/header-mac";
50
+ AES_GCM_CHUNK_KEY: "shieldfive/v1/aes-gcm/chunk-key";
51
+ AES_GCM_NONCE_PREFIX: "shieldfive/v1/aes-gcm/nonce-prefix";
52
+ XCHACHA_CHUNK_KEY: "shieldfive/v1/xchacha/chunk-key";
53
+ XCHACHA_NONCE_PREFIX: "shieldfive/v1/xchacha/nonce-prefix";
54
+ PQ_HYBRID_COMBINE: "shieldfive/v1/pq-hybrid/combine";
55
+ }>;
56
+ /** AAD domain string mixed into every chunk's authenticator */
57
+ export declare const CHUNK_AAD_DOMAIN = "shieldfive/v1/chunk";
58
+ export declare const CHUNK_AAD_LENGTH: number;
59
+ /**
60
+ * Header values reflecting how a particular file was encrypted.
61
+ * Returned by header parsers; consumed by chunk encrypt/decrypt loops.
62
+ */
63
+ export interface ParsedHeader {
64
+ suite: SuiteId;
65
+ flags: number;
66
+ fileId: Uint8Array;
67
+ chunkSize: number;
68
+ totalChunks: number;
69
+ plaintextSize: number;
70
+ suitePayload: Uint8Array;
71
+ /** Bytes consumed from the input — chunks start at this offset */
72
+ headerLength: number;
73
+ }
74
+ /**
75
+ * Result of encrypting a file. The blob is the on-disk form (header +
76
+ * concatenated chunks). Application metadata (file id, suite, chunk size)
77
+ * is also returned so callers can stash it in their own database if they
78
+ * want to look files up by id.
79
+ */
80
+ export interface EncryptedFile {
81
+ blob: Blob;
82
+ suite: SuiteId;
83
+ fileId: Uint8Array;
84
+ chunkSize: number;
85
+ totalChunks: number;
86
+ plaintextSize: number;
87
+ }
88
+ /**
89
+ * Progress callback shape, called after each chunk is processed. Progress
90
+ * is reported as a float in [0, 1] inclusive. The final call is always
91
+ * exactly 1.0.
92
+ */
93
+ export type ProgressCallback = (progress: number) => void;
94
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/internal/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,MAAM,MAAM,GAAG;IACnB,MAAM,EAAE,YAAY,CAAA;IACpB,eAAe,CAAC,CAAC,SAAS,eAAe,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAA;CACxD,CAAA;AAED,MAAM,MAAM,YAAY,GAAG,UAAU,CAAC,YAAY,CAAA;AAEl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E,UAAU,CAAA;IAClB,SAAS,EAAE,MAAM,CAAA;IACjB,WAAW,EAAE,MAAM,CAAA;IACnB,aAAa,EAAE,MAAM,CAAA;CACtB;AAED;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Public type definitions for the shieldfive-crypto library.
3
+ */
4
+ /**
5
+ * Suite identifiers as written to the on-disk format byte.
6
+ * See `spec/format-v1.md` for the canonical assignment.
7
+ */
8
+ export const SUITE = {
9
+ AES_256_GCM_V1: 0x01,
10
+ XCHACHA20_POLY1305_V1: 0x02,
11
+ PQ_HYBRID_XCHACHA_MLKEM1024_V1: 0x03,
12
+ };
13
+ export const SUITE_NAMES = {
14
+ [SUITE.AES_256_GCM_V1]: 'aes-256-gcm-v1',
15
+ [SUITE.XCHACHA20_POLY1305_V1]: 'xchacha20-poly1305-v1',
16
+ [SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1]: 'pq-hybrid-xchacha-mlkem1024-v1',
17
+ };
18
+ /**
19
+ * Magic bytes prefixing every v1-format file: "SF5" + major(1) + minor(0).
20
+ * Treat as immutable; do not mutate.
21
+ */
22
+ export const FORMAT_MAGIC = new Uint8Array([
23
+ 0x53, 0x46, 0x35, 0x01, 0x00,
24
+ ]);
25
+ export const FORMAT_MAGIC_LENGTH = 5;
26
+ /** Header field sizes — see spec/format-v1.md */
27
+ export const HEADER_SIZES = Object.freeze({
28
+ MAGIC: 5,
29
+ SUITE: 1,
30
+ FLAGS: 1,
31
+ FILE_ID: 16,
32
+ CHUNK_SIZE: 4,
33
+ TOTAL_CHUNKS: 8,
34
+ PLAINTEXT_SIZE: 8,
35
+ SUITE_PAYLOAD_LEN: 2,
36
+ HEADER_MAC: 32,
37
+ });
38
+ /** Fixed bytes preceding the variable-length suite_payload */
39
+ export const HEADER_FIXED_PREFIX_LENGTH = HEADER_SIZES.MAGIC +
40
+ HEADER_SIZES.SUITE +
41
+ HEADER_SIZES.FLAGS +
42
+ HEADER_SIZES.FILE_ID +
43
+ HEADER_SIZES.CHUNK_SIZE +
44
+ HEADER_SIZES.TOTAL_CHUNKS +
45
+ HEADER_SIZES.PLAINTEXT_SIZE +
46
+ HEADER_SIZES.SUITE_PAYLOAD_LEN;
47
+ /** Default plaintext bytes per chunk for new uploads (4 MiB) */
48
+ export const DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
49
+ /** Maximum permitted chunk_size in the format (uint32 max) */
50
+ export const MAX_CHUNK_SIZE = 0xffff_ffff;
51
+ /** Maximum permitted total_chunks (sane upper bound, well below uint64 max) */
52
+ export const MAX_TOTAL_CHUNKS = 1_000_000_000;
53
+ /** Domain separators for HKDF — never reuse a string here in another context */
54
+ export const HKDF_INFO = Object.freeze({
55
+ HEADER_MAC: 'shieldfive/v1/header-mac',
56
+ AES_GCM_CHUNK_KEY: 'shieldfive/v1/aes-gcm/chunk-key',
57
+ AES_GCM_NONCE_PREFIX: 'shieldfive/v1/aes-gcm/nonce-prefix',
58
+ XCHACHA_CHUNK_KEY: 'shieldfive/v1/xchacha/chunk-key',
59
+ XCHACHA_NONCE_PREFIX: 'shieldfive/v1/xchacha/nonce-prefix',
60
+ PQ_HYBRID_COMBINE: 'shieldfive/v1/pq-hybrid/combine',
61
+ });
62
+ /** AAD domain string mixed into every chunk's authenticator */
63
+ export const CHUNK_AAD_DOMAIN = 'shieldfive/v1/chunk';
64
+ export const CHUNK_AAD_LENGTH = CHUNK_AAD_DOMAIN.length + 8 + 8 + 1;
65
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/internal/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AASH;;;GAGG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG;IACnB,cAAc,EAAE,IAAI;IACpB,qBAAqB,EAAE,IAAI;IAC3B,8BAA8B,EAAE,IAAI;CAC5B,CA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,MAAM,CAAC,MAAM,CAAC;IACrC,UAAU,EAAE,0BAA0B;IACtC,iBAAiB,EAAE,iCAAiC;IACpD,oBAAoB,EAAE,oCAAoC;IAC1D,iBAAiB,EAAE,iCAAiC;IACpD,oBAAoB,EAAE,oCAAoC;IAC1D,iBAAiB,EAAE,iCAAiC;CACrD,CAAC,CAAA;AAEF,+DAA+D;AAC/D,MAAM,CAAC,MAAM,gBAAgB,GAAG,qBAAqB,CAAA;AACrD,MAAM,CAAC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA"}
@@ -0,0 +1,72 @@
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
+ /**
13
+ * Argon2id parameter presets.
14
+ *
15
+ * "interactive" is libsodium's MIN; we deliberately do not expose it.
16
+ * "moderate" is the documented default for password storage on
17
+ * contemporary devices (3 ops, 256 MiB).
18
+ * "sensitive" is appropriate for high-value secrets but requires 1 GiB
19
+ * of RAM and is unsuitable for mobile devices.
20
+ *
21
+ * The chosen preset is encoded into the output so a derived secret can be
22
+ * re-derived later without storing the parameters alongside.
23
+ */
24
+ export type Argon2idPreset = 'moderate' | 'sensitive';
25
+ export declare const ARGON2ID_SALT_BYTES = 16;
26
+ export declare const MASTER_SECRET_BYTES = 32;
27
+ export interface DeriveMasterSecretInput {
28
+ /** User passphrase. UTF-8 encoded internally. */
29
+ passphrase: string;
30
+ /** Per-user salt. Must be ≥16 bytes. Generated if not provided. */
31
+ salt?: Uint8Array;
32
+ /** Argon2id strength preset. Default: 'moderate'. */
33
+ preset?: Argon2idPreset;
34
+ }
35
+ export interface DeriveMasterSecretOutput {
36
+ /** 32-byte master secret. Treat as the highest-value secret in the system. */
37
+ masterSecret: Uint8Array;
38
+ /** Salt used (caller must persist this for re-derivation). */
39
+ salt: Uint8Array;
40
+ /** Preset used. Encoded so a future re-derivation produces the same key. */
41
+ preset: Argon2idPreset;
42
+ }
43
+ /**
44
+ * Derive a 32-byte master secret from a passphrase using Argon2id.
45
+ *
46
+ * The host application MUST persist `salt` and `preset` alongside the
47
+ * user's account so that future logins can reproduce the same master
48
+ * secret. The passphrase itself MUST NOT be stored.
49
+ */
50
+ export declare function deriveMasterSecret(input: DeriveMasterSecretInput): Promise<DeriveMasterSecretOutput>;
51
+ /**
52
+ * Re-derive the same master secret given the previously stored salt and
53
+ * preset. Convenience wrapper; exactly equivalent to deriveMasterSecret
54
+ * called with the saved parameters.
55
+ */
56
+ export declare function reDeriveMasterSecret(input: {
57
+ passphrase: string;
58
+ salt: Uint8Array;
59
+ preset: Argon2idPreset;
60
+ }): Promise<Uint8Array>;
61
+ /**
62
+ * Verify a passphrase against a previously derived master secret without
63
+ * exposing whether the input was wrong before the constant-time compare.
64
+ * Returns true iff the rederived master secret matches.
65
+ */
66
+ export declare function verifyPassphrase(input: {
67
+ passphrase: string;
68
+ salt: Uint8Array;
69
+ preset: Argon2idPreset;
70
+ expectedMasterSecret: Uint8Array;
71
+ }): Promise<boolean>;
72
+ //# sourceMappingURL=argon2id.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"argon2id.d.ts","sourceRoot":"","sources":["../../src/kdf/argon2id.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAMH;;;;;;;;;;;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,97 @@
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
+ export const ARGON2ID_SALT_BYTES = 16;
16
+ export const MASTER_SECRET_BYTES = 32;
17
+ /** Resolve a preset name to (opslimit, memlimit) using libsodium constants. */
18
+ async function resolvePreset(preset) {
19
+ const sodium = await getSodium();
20
+ switch (preset) {
21
+ case 'moderate':
22
+ return {
23
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_MODERATE,
24
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_MODERATE,
25
+ };
26
+ case 'sensitive':
27
+ return {
28
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_SENSITIVE,
29
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_SENSITIVE,
30
+ };
31
+ default: {
32
+ const _exhaustive = preset;
33
+ throw new Error(`unknown Argon2id preset: ${String(_exhaustive)}`);
34
+ }
35
+ }
36
+ }
37
+ /**
38
+ * Derive a 32-byte master secret from a passphrase using Argon2id.
39
+ *
40
+ * The host application MUST persist `salt` and `preset` alongside the
41
+ * user's account so that future logins can reproduce the same master
42
+ * secret. The passphrase itself MUST NOT be stored.
43
+ */
44
+ export async function deriveMasterSecret(input) {
45
+ const sodium = await getSodium();
46
+ if (typeof input.passphrase !== 'string' || input.passphrase.length === 0) {
47
+ throw new Error('deriveMasterSecret: passphrase must be a non-empty string');
48
+ }
49
+ const salt = input.salt ?? randomBytes(ARGON2ID_SALT_BYTES);
50
+ if (salt.length < ARGON2ID_SALT_BYTES) {
51
+ throw new RangeError(`deriveMasterSecret: salt must be at least ${ARGON2ID_SALT_BYTES} bytes`);
52
+ }
53
+ // libsodium expects exactly SALTBYTES; if a longer salt is supplied,
54
+ // we domain-separate it through HKDF first to land on 16 bytes.
55
+ let usableSalt = salt;
56
+ if (salt.length > ARGON2ID_SALT_BYTES) {
57
+ usableSalt = await hkdfSha256({
58
+ ikm: salt,
59
+ info: 'shieldfive/v1/argon2id/salt-compression',
60
+ length: ARGON2ID_SALT_BYTES,
61
+ });
62
+ }
63
+ const preset = input.preset ?? 'moderate';
64
+ const { opslimit, memlimit } = await resolvePreset(preset);
65
+ const passphraseBytes = new TextEncoder().encode(input.passphrase);
66
+ const derived = sodium.crypto_pwhash(MASTER_SECRET_BYTES, passphraseBytes, usableSalt, opslimit, memlimit, sodium.crypto_pwhash_ALG_ARGON2ID13);
67
+ return {
68
+ masterSecret: new Uint8Array(derived),
69
+ salt,
70
+ preset,
71
+ };
72
+ }
73
+ /**
74
+ * Re-derive the same master secret given the previously stored salt and
75
+ * preset. Convenience wrapper; exactly equivalent to deriveMasterSecret
76
+ * called with the saved parameters.
77
+ */
78
+ export async function reDeriveMasterSecret(input) {
79
+ const result = await deriveMasterSecret(input);
80
+ return result.masterSecret;
81
+ }
82
+ /**
83
+ * Verify a passphrase against a previously derived master secret without
84
+ * exposing whether the input was wrong before the constant-time compare.
85
+ * Returns true iff the rederived master secret matches.
86
+ */
87
+ export async function verifyPassphrase(input) {
88
+ const computed = await reDeriveMasterSecret(input);
89
+ if (computed.length !== input.expectedMasterSecret.length)
90
+ return false;
91
+ let diff = 0;
92
+ for (let i = 0; i < computed.length; i += 1) {
93
+ diff |= computed[i] ^ input.expectedMasterSecret[i];
94
+ }
95
+ return diff === 0;
96
+ }
97
+ //# 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;AAgBpD,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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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
+ //# sourceMapping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;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,GACpD,IAAI,CAAA;IACR,WAAW,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAA;CACpC;AAWD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAkH9D"}
@@ -0,0 +1,203 @@
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 { 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