@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,153 @@
1
+ /**
2
+ * Cast helper: TypeScript 5.7+ distinguishes Uint8Array<ArrayBuffer> from
3
+ * Uint8Array<ArrayBufferLike>. Blob and many Web Crypto APIs require the
4
+ * narrower variant. This helper centralizes the cast so we don't sprinkle
5
+ * `as Uint8Array<ArrayBuffer>` across the codebase.
6
+ *
7
+ * Functionally a no-op at runtime; purely a type annotation.
8
+ */
9
+ export function asBlobPart(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
10
+ return bytes as Uint8Array<ArrayBuffer>
11
+ }
12
+
13
+ /**
14
+ * Byte-level encoding helpers.
15
+ *
16
+ * All multi-byte integer functions are explicitly big-endian to match the
17
+ * v1 wire format. Callers should prefer these over hand-rolled bit-shifting.
18
+ */
19
+
20
+ export function bytesToBase64(bytes: Uint8Array): string {
21
+ if (typeof btoa === 'function') {
22
+ let binary = ''
23
+ for (let i = 0; i < bytes.length; i += 1) {
24
+ binary += String.fromCharCode(bytes[i]!)
25
+ }
26
+ return btoa(binary)
27
+ }
28
+ // Node fallback. Uses Buffer; safe in any Node version.
29
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
30
+ return Buffer.from(bytes).toString('base64')
31
+ }
32
+
33
+ export function base64ToBytes(value: string): Uint8Array {
34
+ if (typeof value !== 'string') {
35
+ throw new TypeError('base64ToBytes: input must be a string')
36
+ }
37
+ if (typeof atob === 'function') {
38
+ const binary = atob(value)
39
+ const out = new Uint8Array(binary.length)
40
+ for (let i = 0; i < binary.length; i += 1) {
41
+ out[i] = binary.charCodeAt(i)
42
+ }
43
+ return out
44
+ }
45
+ return new Uint8Array(Buffer.from(value, 'base64'))
46
+ }
47
+
48
+ export function bytesToHex(bytes: Uint8Array): string {
49
+ let out = ''
50
+ for (let i = 0; i < bytes.length; i += 1) {
51
+ out += bytes[i]!.toString(16).padStart(2, '0')
52
+ }
53
+ return out
54
+ }
55
+
56
+ const HEX_RE = /^[0-9a-f]*$/i
57
+
58
+ export function hexToBytes(hex: string): Uint8Array {
59
+ if (typeof hex !== 'string') {
60
+ throw new TypeError('hexToBytes: input must be a string')
61
+ }
62
+ if (hex.length % 2 !== 0 || !HEX_RE.test(hex)) {
63
+ throw new TypeError('hexToBytes: input must be even-length hexadecimal')
64
+ }
65
+ const out = new Uint8Array(hex.length / 2)
66
+ for (let i = 0; i < out.length; i += 1) {
67
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
68
+ }
69
+ return out
70
+ }
71
+
72
+ export function concatBytes(parts: ReadonlyArray<Uint8Array>): Uint8Array {
73
+ let total = 0
74
+ for (const part of parts) total += part.length
75
+ const out = new Uint8Array(total)
76
+ let offset = 0
77
+ for (const part of parts) {
78
+ out.set(part, offset)
79
+ offset += part.length
80
+ }
81
+ return out
82
+ }
83
+
84
+ export function uint32BE(value: number): Uint8Array {
85
+ if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff_ffff) {
86
+ throw new RangeError('uint32BE: value out of range')
87
+ }
88
+ const out = new Uint8Array(4)
89
+ new DataView(out.buffer).setUint32(0, value, false)
90
+ return out
91
+ }
92
+
93
+ export function readUint32BE(bytes: Uint8Array, offset = 0): number {
94
+ if (offset + 4 > bytes.length) {
95
+ throw new RangeError('readUint32BE: insufficient bytes')
96
+ }
97
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(
98
+ 0,
99
+ false,
100
+ )
101
+ }
102
+
103
+ export function uint16BE(value: number): Uint8Array {
104
+ if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff) {
105
+ throw new RangeError('uint16BE: value out of range')
106
+ }
107
+ const out = new Uint8Array(2)
108
+ new DataView(out.buffer).setUint16(0, value, false)
109
+ return out
110
+ }
111
+
112
+ export function readUint16BE(bytes: Uint8Array, offset = 0): number {
113
+ if (offset + 2 > bytes.length) {
114
+ throw new RangeError('readUint16BE: insufficient bytes')
115
+ }
116
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, 2).getUint16(
117
+ 0,
118
+ false,
119
+ )
120
+ }
121
+
122
+ /**
123
+ * Encode a non-negative integer as 8 big-endian bytes. The library never
124
+ * emits values exceeding Number.MAX_SAFE_INTEGER (2^53 - 1) because the
125
+ * format spec caps total_chunks at 1e9 and plaintext_size is bounded by
126
+ * what JavaScript can sensibly handle.
127
+ */
128
+ export function uint64BE(value: number): Uint8Array {
129
+ if (!Number.isSafeInteger(value) || value < 0) {
130
+ throw new RangeError('uint64BE: value must be a non-negative safe integer')
131
+ }
132
+ const out = new Uint8Array(8)
133
+ // Top 4 bytes: high uint32 (value / 2^32, truncated)
134
+ const high = Math.floor(value / 0x1_0000_0000)
135
+ const low = value >>> 0
136
+ new DataView(out.buffer).setUint32(0, high, false)
137
+ new DataView(out.buffer).setUint32(4, low, false)
138
+ return out
139
+ }
140
+
141
+ export function readUint64BE(bytes: Uint8Array, offset = 0): number {
142
+ if (offset + 8 > bytes.length) {
143
+ throw new RangeError('readUint64BE: insufficient bytes')
144
+ }
145
+ const view = new DataView(bytes.buffer, bytes.byteOffset + offset, 8)
146
+ const high = view.getUint32(0, false)
147
+ const low = view.getUint32(4, false)
148
+ // Reject values that don't fit in a safe JS integer (> 2^53 - 1).
149
+ if (high > 0x1f_ffff) {
150
+ throw new RangeError('readUint64BE: value exceeds Number.MAX_SAFE_INTEGER')
151
+ }
152
+ return high * 0x1_0000_0000 + low
153
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * HKDF-SHA-256 wrapper.
3
+ *
4
+ * Every domain-separated key the library derives from another key flows
5
+ * through this function. Domain strings are constants in `internal/types.ts`
6
+ * — never construct an `info` parameter ad-hoc at the call site.
7
+ */
8
+
9
+ import { getSubtle } from './runtime.js'
10
+
11
+ const TEXT_ENCODER = new TextEncoder()
12
+
13
+ export async function hkdfSha256(options: {
14
+ ikm: Uint8Array
15
+ salt?: Uint8Array
16
+ info: string
17
+ length: number
18
+ }): Promise<Uint8Array> {
19
+ const { ikm, info, length } = options
20
+ const salt = options.salt ?? new Uint8Array(32) // SHA-256 zero-salt fallback
21
+ if (!Number.isSafeInteger(length) || length <= 0 || length > 8160) {
22
+ // 8160 = 255 * 32, the HKDF-SHA-256 output bound.
23
+ throw new RangeError('hkdfSha256: length out of range (1..8160)')
24
+ }
25
+
26
+ const subtle = getSubtle()
27
+ const baseKey = await subtle.importKey(
28
+ 'raw',
29
+ ikm as Uint8Array<ArrayBuffer>,
30
+ 'HKDF',
31
+ false,
32
+ ['deriveBits'],
33
+ )
34
+
35
+ const bits = await subtle.deriveBits(
36
+ {
37
+ name: 'HKDF',
38
+ hash: 'SHA-256',
39
+ salt: salt as Uint8Array<ArrayBuffer>,
40
+ info: TEXT_ENCODER.encode(info) as Uint8Array<ArrayBuffer>,
41
+ },
42
+ baseKey,
43
+ length * 8,
44
+ )
45
+
46
+ return new Uint8Array(bits)
47
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * HMAC-SHA-256 wrapper.
3
+ *
4
+ * Used for the file-format header MAC and for any application-level
5
+ * authenticator the library exposes. Always verify with constantTimeEqual.
6
+ */
7
+
8
+ import { constantTimeEqual, getSubtle } from './runtime.js'
9
+
10
+ export async function hmacSha256(
11
+ key: Uint8Array,
12
+ data: Uint8Array,
13
+ ): Promise<Uint8Array> {
14
+ const subtle = getSubtle()
15
+ const hmacKey = await subtle.importKey(
16
+ 'raw',
17
+ key as Uint8Array<ArrayBuffer>,
18
+ { name: 'HMAC', hash: 'SHA-256' },
19
+ false,
20
+ ['sign'],
21
+ )
22
+ const sig = await subtle.sign('HMAC', hmacKey, data as Uint8Array<ArrayBuffer>)
23
+ return new Uint8Array(sig)
24
+ }
25
+
26
+ export async function hmacSha256Verify(
27
+ key: Uint8Array,
28
+ data: Uint8Array,
29
+ expected: Uint8Array,
30
+ ): Promise<boolean> {
31
+ const computed = await hmacSha256(key, data)
32
+ return constantTimeEqual(computed, expected)
33
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Runtime detection and validation for the host environment.
3
+ *
4
+ * This module is intentionally tiny. The library targets any environment
5
+ * exposing the WHATWG Web Crypto API at `globalThis.crypto.subtle` —
6
+ * modern browsers, Node 20+, Deno, Bun, Cloudflare Workers, and any
7
+ * compatible WebAssembly runtime.
8
+ *
9
+ * Suites that require additional primitives (Argon2id, ML-KEM,
10
+ * XChaCha20-Poly1305) load those primitives lazily from
11
+ * `libsodium-wrappers-sumo` and `@noble/post-quantum`. Consumers that
12
+ * only use the AES-GCM suite never load those WASM blobs.
13
+ */
14
+
15
+ import type { Crypto, SubtleCrypto } from './types.js'
16
+
17
+ let cachedCrypto: Crypto | null = null
18
+
19
+ export function getCrypto(): Crypto {
20
+ if (cachedCrypto) return cachedCrypto
21
+
22
+ const candidate = (globalThis as { crypto?: Crypto }).crypto
23
+ if (
24
+ !candidate ||
25
+ !candidate.subtle ||
26
+ typeof candidate.getRandomValues !== 'function'
27
+ ) {
28
+ throw new Error(
29
+ 'shieldfive-crypto: Web Crypto API is not available. ' +
30
+ 'This library requires globalThis.crypto with SubtleCrypto support. ' +
31
+ 'In Node, use Node 20 or later.',
32
+ )
33
+ }
34
+
35
+ cachedCrypto = candidate
36
+ return candidate
37
+ }
38
+
39
+ export function getSubtle(): SubtleCrypto {
40
+ return getCrypto().subtle
41
+ }
42
+
43
+ export function randomBytes(length: number): Uint8Array {
44
+ if (!Number.isSafeInteger(length) || length <= 0) {
45
+ throw new RangeError('randomBytes: length must be a positive integer')
46
+ }
47
+ if (length > 65536) {
48
+ // Web Crypto specification limits getRandomValues to 65536 bytes per call.
49
+ throw new RangeError('randomBytes: length exceeds 65536')
50
+ }
51
+ const out = new Uint8Array(length)
52
+ getCrypto().getRandomValues(out)
53
+ return out
54
+ }
55
+
56
+ /**
57
+ * Constant-time equality for byte arrays. Used wherever a comparison failure
58
+ * could leak timing information (MAC verification, key comparison).
59
+ */
60
+ export function constantTimeEqual(
61
+ a: Uint8Array | null | undefined,
62
+ b: Uint8Array | null | undefined,
63
+ ): boolean {
64
+ if (!a || !b) return false
65
+ if (a.length !== b.length) return false
66
+ let diff = 0
67
+ for (let i = 0; i < a.length; i += 1) {
68
+ diff |= a[i]! ^ b[i]!
69
+ }
70
+ return diff === 0
71
+ }
72
+
73
+ /**
74
+ * Best-effort zeroization of secret material. JavaScript engines may have
75
+ * already copied or reallocated the underlying buffer; this is a hint, not
76
+ * a guarantee. Use only for in-process hardening.
77
+ */
78
+ export function zeroize(buffer: Uint8Array): void {
79
+ buffer.fill(0)
80
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Lazy loader for libsodium-wrappers-sumo.
3
+ *
4
+ * libsodium is loaded on demand only when a suite that needs it (XChaCha,
5
+ * PQ hybrid, password-based KDF) is actually used. Consumers using only
6
+ * AES-256-GCM never load the WASM blob.
7
+ *
8
+ * libsodium is declared as an optional peer dependency in package.json.
9
+ * Bundlers should treat it as side-effect-free.
10
+ */
11
+
12
+ let cachedSodium: any | null = null
13
+ let pendingInit: Promise<any> | null = null
14
+
15
+ export async function getSodium(): Promise<any> {
16
+ if (cachedSodium) return cachedSodium
17
+
18
+ if (!pendingInit) {
19
+ pendingInit = (async () => {
20
+ let sodium: any
21
+ try {
22
+ // Dynamic import keeps libsodium out of bundles that don't use it.
23
+ sodium = (await import('libsodium-wrappers-sumo')).default
24
+ } catch (err) {
25
+ throw new Error(
26
+ 'shieldfive-crypto: libsodium-wrappers-sumo is required for ' +
27
+ 'this cipher suite. Install it as a dependency.',
28
+ { cause: err as Error },
29
+ )
30
+ }
31
+ await sodium.ready
32
+ cachedSodium = sodium
33
+ return sodium
34
+ })()
35
+ }
36
+
37
+ return pendingInit
38
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Public type definitions for the shieldfive-crypto library.
3
+ */
4
+
5
+ export type Crypto = {
6
+ subtle: SubtleCrypto
7
+ getRandomValues<T extends ArrayBufferView>(array: T): T
8
+ }
9
+
10
+ export type SubtleCrypto = globalThis.SubtleCrypto
11
+
12
+ /**
13
+ * Suite identifiers as written to the on-disk format byte.
14
+ * See `spec/format-v1.md` for the canonical assignment.
15
+ */
16
+ export const SUITE = {
17
+ AES_256_GCM_V1: 0x01,
18
+ XCHACHA20_POLY1305_V1: 0x02,
19
+ PQ_HYBRID_XCHACHA_MLKEM1024_V1: 0x03,
20
+ } as const
21
+
22
+ export type SuiteId = (typeof SUITE)[keyof typeof SUITE]
23
+
24
+ export type SuiteName =
25
+ | 'aes-256-gcm-v1'
26
+ | 'xchacha20-poly1305-v1'
27
+ | 'pq-hybrid-xchacha-mlkem1024-v1'
28
+
29
+ export const SUITE_NAMES: Record<SuiteId, SuiteName> = {
30
+ [SUITE.AES_256_GCM_V1]: 'aes-256-gcm-v1',
31
+ [SUITE.XCHACHA20_POLY1305_V1]: 'xchacha20-poly1305-v1',
32
+ [SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1]: 'pq-hybrid-xchacha-mlkem1024-v1',
33
+ }
34
+
35
+ /**
36
+ * Magic bytes prefixing every v1-format file: "SF5" + major(1) + minor(0).
37
+ * Treat as immutable; do not mutate.
38
+ */
39
+ export const FORMAT_MAGIC: Uint8Array = new Uint8Array([
40
+ 0x53, 0x46, 0x35, 0x01, 0x00,
41
+ ])
42
+
43
+ export const FORMAT_MAGIC_LENGTH = 5
44
+
45
+ /** Header field sizes — see spec/format-v1.md */
46
+ export const HEADER_SIZES = Object.freeze({
47
+ MAGIC: 5,
48
+ SUITE: 1,
49
+ FLAGS: 1,
50
+ FILE_ID: 16,
51
+ CHUNK_SIZE: 4,
52
+ TOTAL_CHUNKS: 8,
53
+ PLAINTEXT_SIZE: 8,
54
+ SUITE_PAYLOAD_LEN: 2,
55
+ HEADER_MAC: 32,
56
+ })
57
+
58
+ /** Fixed bytes preceding the variable-length suite_payload */
59
+ export const HEADER_FIXED_PREFIX_LENGTH =
60
+ HEADER_SIZES.MAGIC +
61
+ HEADER_SIZES.SUITE +
62
+ HEADER_SIZES.FLAGS +
63
+ HEADER_SIZES.FILE_ID +
64
+ HEADER_SIZES.CHUNK_SIZE +
65
+ HEADER_SIZES.TOTAL_CHUNKS +
66
+ HEADER_SIZES.PLAINTEXT_SIZE +
67
+ HEADER_SIZES.SUITE_PAYLOAD_LEN
68
+
69
+ /** Default plaintext bytes per chunk for new uploads (4 MiB) */
70
+ export const DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024
71
+
72
+ /** Maximum permitted chunk_size in the format (uint32 max) */
73
+ export const MAX_CHUNK_SIZE = 0xffff_ffff
74
+
75
+ /** Maximum permitted total_chunks (sane upper bound, well below uint64 max) */
76
+ export const MAX_TOTAL_CHUNKS = 1_000_000_000
77
+
78
+ /** Domain separators for HKDF — never reuse a string here in another context */
79
+ export const HKDF_INFO = Object.freeze({
80
+ HEADER_MAC: 'shieldfive/v1/header-mac',
81
+ AES_GCM_CHUNK_KEY: 'shieldfive/v1/aes-gcm/chunk-key',
82
+ AES_GCM_NONCE_PREFIX: 'shieldfive/v1/aes-gcm/nonce-prefix',
83
+ XCHACHA_CHUNK_KEY: 'shieldfive/v1/xchacha/chunk-key',
84
+ XCHACHA_NONCE_PREFIX: 'shieldfive/v1/xchacha/nonce-prefix',
85
+ PQ_HYBRID_COMBINE: 'shieldfive/v1/pq-hybrid/combine',
86
+ })
87
+
88
+ /** AAD domain string mixed into every chunk's authenticator */
89
+ export const CHUNK_AAD_DOMAIN = 'shieldfive/v1/chunk'
90
+ export const CHUNK_AAD_LENGTH = CHUNK_AAD_DOMAIN.length + 8 + 8 + 1
91
+
92
+ /**
93
+ * Header values reflecting how a particular file was encrypted.
94
+ * Returned by header parsers; consumed by chunk encrypt/decrypt loops.
95
+ */
96
+ export interface ParsedHeader {
97
+ suite: SuiteId
98
+ flags: number
99
+ fileId: Uint8Array
100
+ chunkSize: number
101
+ totalChunks: number
102
+ plaintextSize: number
103
+ suitePayload: Uint8Array
104
+ /** Bytes consumed from the input — chunks start at this offset */
105
+ headerLength: number
106
+ }
107
+
108
+ /**
109
+ * Result of encrypting a file. The blob is the on-disk form (header +
110
+ * concatenated chunks). Application metadata (file id, suite, chunk size)
111
+ * is also returned so callers can stash it in their own database if they
112
+ * want to look files up by id.
113
+ */
114
+ export interface EncryptedFile {
115
+ blob: Blob
116
+ suite: SuiteId
117
+ fileId: Uint8Array
118
+ chunkSize: number
119
+ totalChunks: number
120
+ plaintextSize: number
121
+ }
122
+
123
+ /**
124
+ * Progress callback shape, called after each chunk is processed. Progress
125
+ * is reported as a float in [0, 1] inclusive. The final call is always
126
+ * exactly 1.0.
127
+ */
128
+ export type ProgressCallback = (progress: number) => void
@@ -0,0 +1,164 @@
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
+ import { getSodium } from '../internal/sodium.js'
14
+ import { hkdfSha256 } from '../internal/hkdf.js'
15
+ import { randomBytes } from '../internal/runtime.js'
16
+
17
+ /**
18
+ * Argon2id parameter presets.
19
+ *
20
+ * "interactive" is libsodium's MIN; we deliberately do not expose it.
21
+ * "moderate" is the documented default for password storage on
22
+ * contemporary devices (3 ops, 256 MiB).
23
+ * "sensitive" is appropriate for high-value secrets but requires 1 GiB
24
+ * of RAM and is unsuitable for mobile devices.
25
+ *
26
+ * The chosen preset is encoded into the output so a derived secret can be
27
+ * re-derived later without storing the parameters alongside.
28
+ */
29
+ export type Argon2idPreset = 'moderate' | 'sensitive'
30
+
31
+ export const ARGON2ID_SALT_BYTES = 16
32
+ export const MASTER_SECRET_BYTES = 32
33
+
34
+ interface PresetConfig {
35
+ opslimit: number // libsodium ops parameter
36
+ memlimit: number // libsodium memory parameter (bytes)
37
+ }
38
+
39
+ /** Resolve a preset name to (opslimit, memlimit) using libsodium constants. */
40
+ async function resolvePreset(preset: Argon2idPreset): Promise<PresetConfig> {
41
+ const sodium = await getSodium()
42
+ switch (preset) {
43
+ case 'moderate':
44
+ return {
45
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_MODERATE,
46
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_MODERATE,
47
+ }
48
+ case 'sensitive':
49
+ return {
50
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_SENSITIVE,
51
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_SENSITIVE,
52
+ }
53
+ default: {
54
+ const _exhaustive: never = preset
55
+ throw new Error(`unknown Argon2id preset: ${String(_exhaustive)}`)
56
+ }
57
+ }
58
+ }
59
+
60
+ export interface DeriveMasterSecretInput {
61
+ /** User passphrase. UTF-8 encoded internally. */
62
+ passphrase: string
63
+ /** Per-user salt. Must be ≥16 bytes. Generated if not provided. */
64
+ salt?: Uint8Array
65
+ /** Argon2id strength preset. Default: 'moderate'. */
66
+ preset?: Argon2idPreset
67
+ }
68
+
69
+ export interface DeriveMasterSecretOutput {
70
+ /** 32-byte master secret. Treat as the highest-value secret in the system. */
71
+ masterSecret: Uint8Array
72
+ /** Salt used (caller must persist this for re-derivation). */
73
+ salt: Uint8Array
74
+ /** Preset used. Encoded so a future re-derivation produces the same key. */
75
+ preset: Argon2idPreset
76
+ }
77
+
78
+ /**
79
+ * Derive a 32-byte master secret from a passphrase using Argon2id.
80
+ *
81
+ * The host application MUST persist `salt` and `preset` alongside the
82
+ * user's account so that future logins can reproduce the same master
83
+ * secret. The passphrase itself MUST NOT be stored.
84
+ */
85
+ export async function deriveMasterSecret(
86
+ input: DeriveMasterSecretInput,
87
+ ): Promise<DeriveMasterSecretOutput> {
88
+ const sodium = await getSodium()
89
+
90
+ if (typeof input.passphrase !== 'string' || input.passphrase.length === 0) {
91
+ throw new Error('deriveMasterSecret: passphrase must be a non-empty string')
92
+ }
93
+
94
+ const salt = input.salt ?? randomBytes(ARGON2ID_SALT_BYTES)
95
+ if (salt.length < ARGON2ID_SALT_BYTES) {
96
+ throw new RangeError(
97
+ `deriveMasterSecret: salt must be at least ${ARGON2ID_SALT_BYTES} bytes`,
98
+ )
99
+ }
100
+ // libsodium expects exactly SALTBYTES; if a longer salt is supplied,
101
+ // we domain-separate it through HKDF first to land on 16 bytes.
102
+ let usableSalt = salt
103
+ if (salt.length > ARGON2ID_SALT_BYTES) {
104
+ usableSalt = await hkdfSha256({
105
+ ikm: salt,
106
+ info: 'shieldfive/v1/argon2id/salt-compression',
107
+ length: ARGON2ID_SALT_BYTES,
108
+ })
109
+ }
110
+
111
+ const preset = input.preset ?? 'moderate'
112
+ const { opslimit, memlimit } = await resolvePreset(preset)
113
+
114
+ const passphraseBytes = new TextEncoder().encode(input.passphrase)
115
+
116
+ const derived = sodium.crypto_pwhash(
117
+ MASTER_SECRET_BYTES,
118
+ passphraseBytes,
119
+ usableSalt,
120
+ opslimit,
121
+ memlimit,
122
+ sodium.crypto_pwhash_ALG_ARGON2ID13,
123
+ )
124
+
125
+ return {
126
+ masterSecret: new Uint8Array(derived),
127
+ salt,
128
+ preset,
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Re-derive the same master secret given the previously stored salt and
134
+ * preset. Convenience wrapper; exactly equivalent to deriveMasterSecret
135
+ * called with the saved parameters.
136
+ */
137
+ export async function reDeriveMasterSecret(input: {
138
+ passphrase: string
139
+ salt: Uint8Array
140
+ preset: Argon2idPreset
141
+ }): Promise<Uint8Array> {
142
+ const result = await deriveMasterSecret(input)
143
+ return result.masterSecret
144
+ }
145
+
146
+ /**
147
+ * Verify a passphrase against a previously derived master secret without
148
+ * exposing whether the input was wrong before the constant-time compare.
149
+ * Returns true iff the rederived master secret matches.
150
+ */
151
+ export async function verifyPassphrase(input: {
152
+ passphrase: string
153
+ salt: Uint8Array
154
+ preset: Argon2idPreset
155
+ expectedMasterSecret: Uint8Array
156
+ }): Promise<boolean> {
157
+ const computed = await reDeriveMasterSecret(input)
158
+ if (computed.length !== input.expectedMasterSecret.length) return false
159
+ let diff = 0
160
+ for (let i = 0; i < computed.length; i += 1) {
161
+ diff |= computed[i]! ^ input.expectedMasterSecret[i]!
162
+ }
163
+ return diff === 0
164
+ }