@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
package/src/index.ts ADDED
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @shieldfive/crypto — open-source, post-quantum-hybrid client-side
3
+ * encryption for cloud storage.
4
+ *
5
+ * Public entry point. Most callers should import from a specific suite
6
+ * subpath instead of the bare module name:
7
+ *
8
+ * import { encryptBlob, decryptBlob } from '@shieldfive/crypto/pq-hybrid-v1'
9
+ * import { encryptBlob, decryptBlob } from '@shieldfive/crypto/aes-gcm-v2'
10
+ * import { decryptBlob } from '@shieldfive/crypto/aes-gcm-v1' // decrypt-only
11
+ * import { encryptBlob, decryptBlob } from '@shieldfive/crypto/xchacha-v1'
12
+ * import { decryptV0 } from '@shieldfive/crypto/legacy-v0'
13
+ *
14
+ * The umbrella `import { ... } from '@shieldfive/crypto'` exposes shared
15
+ * format primitives, type definitions, and an auto-routing decryptor that
16
+ * dispatches by suite ID.
17
+ */
18
+
19
+ // ──────────────────────────────────────────────────────────────────────
20
+ // Format primitives
21
+ // ──────────────────────────────────────────────────────────────────────
22
+ export {
23
+ buildAuthenticatedHeader,
24
+ buildChunkAad,
25
+ buildHeaderUnauthenticated,
26
+ deriveHeaderMacKey,
27
+ HeaderError,
28
+ parseHeader,
29
+ verifyHeaderMac,
30
+ } from './format/header.js'
31
+
32
+ // ──────────────────────────────────────────────────────────────────────
33
+ // Type definitions and constants
34
+ // ──────────────────────────────────────────────────────────────────────
35
+ export {
36
+ CHUNK_AAD_DOMAIN,
37
+ CHUNK_AAD_LENGTH,
38
+ DEFAULT_CHUNK_SIZE,
39
+ FORMAT_MAGIC,
40
+ FORMAT_MAGIC_LENGTH,
41
+ HEADER_FIXED_PREFIX_LENGTH,
42
+ HEADER_SIZES,
43
+ HKDF_INFO,
44
+ MAX_CHUNK_SIZE,
45
+ MAX_TOTAL_CHUNKS,
46
+ SUITE,
47
+ SUITE_NAMES,
48
+ } from './internal/types.js'
49
+ export type {
50
+ EncryptedFile,
51
+ ParsedHeader,
52
+ ProgressCallback,
53
+ SuiteId,
54
+ SuiteName,
55
+ } from './internal/types.js'
56
+
57
+ // ──────────────────────────────────────────────────────────────────────
58
+ // Encoding utilities (base64, hex, uint codecs)
59
+ // ──────────────────────────────────────────────────────────────────────
60
+ export {
61
+ base64ToBytes,
62
+ bytesToBase64,
63
+ bytesToHex,
64
+ hexToBytes,
65
+ concatBytes,
66
+ } from './internal/encoding.js'
67
+
68
+ // ──────────────────────────────────────────────────────────────────────
69
+ // Runtime helpers
70
+ // ──────────────────────────────────────────────────────────────────────
71
+ export {
72
+ constantTimeEqual,
73
+ randomBytes,
74
+ zeroize,
75
+ } from './internal/runtime.js'
76
+
77
+ // ──────────────────────────────────────────────────────────────────────
78
+ // Re-export suite namespaces for direct consumption.
79
+ // The aes-gcm encrypt path on the umbrella is v2 (0x04). v1 (0x01) is
80
+ // exposed decrypt-only here because new files should never be written
81
+ // with the narrow 4-byte nonce prefix. Callers that genuinely need to
82
+ // re-encrypt as v1 (e.g. migration tooling) can still import from the
83
+ // @shieldfive/crypto/aes-gcm-v1 subpath.
84
+ // ──────────────────────────────────────────────────────────────────────
85
+ import {
86
+ decryptBlob as aesGcmV1DecryptBlob,
87
+ decryptToBytes as aesGcmV1DecryptToBytes,
88
+ } from './suites/aes-gcm-v1/api.js'
89
+ export const aesGcmV1 = {
90
+ decryptBlob: aesGcmV1DecryptBlob,
91
+ decryptToBytes: aesGcmV1DecryptToBytes,
92
+ }
93
+ export * as aesGcmV2 from './suites/aes-gcm-v2/api.js'
94
+ export * as xchachaV1 from './suites/xchacha-v1/api.js'
95
+ export * as pqHybridV1 from './suites/pq-hybrid-v1/api.js'
96
+ export * as legacyV0 from './suites/aes-gcm-v0/api.js'
97
+ export * as streamsAesGcmV1 from './streams/aes-gcm-v1.js'
98
+ export * as kdfArgon2id from './kdf/argon2id.js'
99
+ export * as identity from './identity/index.js'
100
+ export * as migrationV0 from './migration/v0-bridge.js'
101
+
102
+ // ──────────────────────────────────────────────────────────────────────
103
+ // Auto-routing decryptor
104
+ // ──────────────────────────────────────────────────────────────────────
105
+ import { parseHeader, HeaderError } from './format/header.js'
106
+ import { SUITE, type SuiteId } from './internal/types.js'
107
+ import * as aes from './suites/aes-gcm-v1/api.js'
108
+ import * as aesV2 from './suites/aes-gcm-v2/api.js'
109
+ import * as xchacha from './suites/xchacha-v1/api.js'
110
+ import * as pqHybrid from './suites/pq-hybrid-v1/api.js'
111
+
112
+ export interface AutoDecryptOptions {
113
+ blob: Blob
114
+ /** Used for AES-GCM-v1/v2 and XChaCha-v1 (32-byte raw content key) */
115
+ contentKey?: Uint8Array
116
+ /** Required for PQ-hybrid: ML-KEM-1024 secret key (3168 bytes) */
117
+ recipientSecretKey?: Uint8Array
118
+ /** Required for PQ-hybrid: classical 32-byte envelope key */
119
+ envelopeKey?: Uint8Array
120
+ /** Optional progress callback (0..1) */
121
+ onProgress?: (progress: number) => void
122
+ }
123
+
124
+ /**
125
+ * Decrypt a v1-format blob, automatically dispatching to the correct suite
126
+ * based on the header's suite byte. Throws if the suite requires inputs the
127
+ * caller didn't provide. For v0 (legacy) files, use `legacyV0.decryptV0`
128
+ * directly — v0 has no header, so the dispatcher cannot route to it.
129
+ */
130
+ export async function autoDecryptBlob(
131
+ options: AutoDecryptOptions,
132
+ ): Promise<Blob> {
133
+ const { blob } = options
134
+ if (!(blob instanceof Blob)) {
135
+ throw new TypeError('autoDecryptBlob: blob must be a Blob or File')
136
+ }
137
+
138
+ const headerProbe = new Uint8Array(
139
+ await blob.slice(0, Math.min(blob.size, 4096)).arrayBuffer(),
140
+ )
141
+
142
+ let suite: SuiteId
143
+ try {
144
+ const parsed = parseHeader(headerProbe)
145
+ suite = parsed.suite
146
+ } catch (err) {
147
+ // If parse fails because of a too-short probe, escalate. Suites with
148
+ // larger suite_payloads (notably PQ hybrid at 1664 bytes) need more.
149
+ if (err instanceof HeaderError && err.code === 'header_too_short') {
150
+ const bigger = new Uint8Array(
151
+ await blob
152
+ .slice(0, Math.min(blob.size, 4 + 0xffff + 64))
153
+ .arrayBuffer(),
154
+ )
155
+ const parsed = parseHeader(bigger)
156
+ suite = parsed.suite
157
+ } else {
158
+ throw err
159
+ }
160
+ }
161
+
162
+ switch (suite) {
163
+ case SUITE.AES_256_GCM_V1: {
164
+ if (!options.contentKey) {
165
+ throw new Error(
166
+ 'autoDecryptBlob: contentKey required for aes-256-gcm-v1',
167
+ )
168
+ }
169
+ return aes.decryptBlob({
170
+ blob,
171
+ contentKey: options.contentKey,
172
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
173
+ })
174
+ }
175
+ case SUITE.AES_256_GCM_V2: {
176
+ if (!options.contentKey) {
177
+ throw new Error(
178
+ 'autoDecryptBlob: contentKey required for aes-256-gcm-v2',
179
+ )
180
+ }
181
+ return aesV2.decryptBlob({
182
+ blob,
183
+ contentKey: options.contentKey,
184
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
185
+ })
186
+ }
187
+ case SUITE.XCHACHA20_POLY1305_V1: {
188
+ if (!options.contentKey) {
189
+ throw new Error(
190
+ 'autoDecryptBlob: contentKey required for xchacha20-poly1305-v1',
191
+ )
192
+ }
193
+ return xchacha.decryptBlob({
194
+ blob,
195
+ contentKey: options.contentKey,
196
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
197
+ })
198
+ }
199
+ case SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1: {
200
+ if (!options.recipientSecretKey || !options.envelopeKey) {
201
+ throw new Error(
202
+ 'autoDecryptBlob: recipientSecretKey and envelopeKey required for pq-hybrid-v1',
203
+ )
204
+ }
205
+ return pqHybrid.decryptBlob({
206
+ blob,
207
+ recipientSecretKey: options.recipientSecretKey,
208
+ envelopeKey: options.envelopeKey,
209
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
210
+ })
211
+ }
212
+ default: {
213
+ throw new HeaderError(
214
+ `autoDecryptBlob: unknown suite 0x${(suite as number).toString(16)}`,
215
+ )
216
+ }
217
+ }
218
+ }
219
+
220
+ /** Library version, also written into format documentation. */
221
+ export const SHIELDFIVE_CRYPTO_VERSION = '1.0.0-alpha.11'
222
+
223
+ /** Default cipher suite for new files when not specified by the caller. */
224
+ export const DEFAULT_SUITE = SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1
@@ -0,0 +1,152 @@
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
+ return Buffer.from(bytes).toString('base64')
30
+ }
31
+
32
+ export function base64ToBytes(value: string): Uint8Array {
33
+ if (typeof value !== 'string') {
34
+ throw new TypeError('base64ToBytes: input must be a string')
35
+ }
36
+ if (typeof atob === 'function') {
37
+ const binary = atob(value)
38
+ const out = new Uint8Array(binary.length)
39
+ for (let i = 0; i < binary.length; i += 1) {
40
+ out[i] = binary.charCodeAt(i)
41
+ }
42
+ return out
43
+ }
44
+ return new Uint8Array(Buffer.from(value, 'base64'))
45
+ }
46
+
47
+ export function bytesToHex(bytes: Uint8Array): string {
48
+ let out = ''
49
+ for (let i = 0; i < bytes.length; i += 1) {
50
+ out += bytes[i]!.toString(16).padStart(2, '0')
51
+ }
52
+ return out
53
+ }
54
+
55
+ const HEX_RE = /^[0-9a-f]*$/i
56
+
57
+ export function hexToBytes(hex: string): Uint8Array {
58
+ if (typeof hex !== 'string') {
59
+ throw new TypeError('hexToBytes: input must be a string')
60
+ }
61
+ if (hex.length % 2 !== 0 || !HEX_RE.test(hex)) {
62
+ throw new TypeError('hexToBytes: input must be even-length hexadecimal')
63
+ }
64
+ const out = new Uint8Array(hex.length / 2)
65
+ for (let i = 0; i < out.length; i += 1) {
66
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
67
+ }
68
+ return out
69
+ }
70
+
71
+ export function concatBytes(parts: ReadonlyArray<Uint8Array>): Uint8Array {
72
+ let total = 0
73
+ for (const part of parts) total += part.length
74
+ const out = new Uint8Array(total)
75
+ let offset = 0
76
+ for (const part of parts) {
77
+ out.set(part, offset)
78
+ offset += part.length
79
+ }
80
+ return out
81
+ }
82
+
83
+ export function uint32BE(value: number): Uint8Array {
84
+ if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff_ffff) {
85
+ throw new RangeError('uint32BE: value out of range')
86
+ }
87
+ const out = new Uint8Array(4)
88
+ new DataView(out.buffer).setUint32(0, value, false)
89
+ return out
90
+ }
91
+
92
+ export function readUint32BE(bytes: Uint8Array, offset = 0): number {
93
+ if (offset + 4 > bytes.length) {
94
+ throw new RangeError('readUint32BE: insufficient bytes')
95
+ }
96
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(
97
+ 0,
98
+ false,
99
+ )
100
+ }
101
+
102
+ export function uint16BE(value: number): Uint8Array {
103
+ if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff) {
104
+ throw new RangeError('uint16BE: value out of range')
105
+ }
106
+ const out = new Uint8Array(2)
107
+ new DataView(out.buffer).setUint16(0, value, false)
108
+ return out
109
+ }
110
+
111
+ export function readUint16BE(bytes: Uint8Array, offset = 0): number {
112
+ if (offset + 2 > bytes.length) {
113
+ throw new RangeError('readUint16BE: insufficient bytes')
114
+ }
115
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, 2).getUint16(
116
+ 0,
117
+ false,
118
+ )
119
+ }
120
+
121
+ /**
122
+ * Encode a non-negative integer as 8 big-endian bytes. The library never
123
+ * emits values exceeding Number.MAX_SAFE_INTEGER (2^53 - 1) because the
124
+ * format spec caps total_chunks at 1e9 and plaintext_size is bounded by
125
+ * what JavaScript can sensibly handle.
126
+ */
127
+ export function uint64BE(value: number): Uint8Array {
128
+ if (!Number.isSafeInteger(value) || value < 0) {
129
+ throw new RangeError('uint64BE: value must be a non-negative safe integer')
130
+ }
131
+ const out = new Uint8Array(8)
132
+ // Top 4 bytes: high uint32 (value / 2^32, truncated)
133
+ const high = Math.floor(value / 0x1_0000_0000)
134
+ const low = value >>> 0
135
+ new DataView(out.buffer).setUint32(0, high, false)
136
+ new DataView(out.buffer).setUint32(4, low, false)
137
+ return out
138
+ }
139
+
140
+ export function readUint64BE(bytes: Uint8Array, offset = 0): number {
141
+ if (offset + 8 > bytes.length) {
142
+ throw new RangeError('readUint64BE: insufficient bytes')
143
+ }
144
+ const view = new DataView(bytes.buffer, bytes.byteOffset + offset, 8)
145
+ const high = view.getUint32(0, false)
146
+ const low = view.getUint32(4, false)
147
+ // Reject values that don't fit in a safe JS integer (> 2^53 - 1).
148
+ if (high > 0x1f_ffff) {
149
+ throw new RangeError('readUint64BE: value exceeds Number.MAX_SAFE_INTEGER')
150
+ }
151
+ return high * 0x1_0000_0000 + low
152
+ }
@@ -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
+ }