@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,60 @@
1
+ /**
2
+ * v1 header builder and parser.
3
+ *
4
+ * The header is constructed without the MAC, then the MAC is computed
5
+ * with the content key, then the MAC is appended. On decode, the parser
6
+ * reads everything up to (but not including) the MAC, then the caller
7
+ * verifies the MAC before trusting any field.
8
+ */
9
+ import { type ParsedHeader, type SuiteId } from '../internal/types.js';
10
+ export interface HeaderInputs {
11
+ suite: SuiteId;
12
+ fileId: Uint8Array;
13
+ chunkSize: number;
14
+ totalChunks: number;
15
+ plaintextSize: number;
16
+ suitePayload: Uint8Array;
17
+ }
18
+ /**
19
+ * Build the unauthenticated header bytes (everything before the MAC).
20
+ * The caller appends the MAC after deriving header_mac_key.
21
+ */
22
+ export declare function buildHeaderUnauthenticated(input: HeaderInputs): Uint8Array;
23
+ /**
24
+ * Derive the per-file header MAC key from the content key + file_id.
25
+ */
26
+ export declare function deriveHeaderMacKey(contentKey: Uint8Array, fileId: Uint8Array): Promise<Uint8Array>;
27
+ /**
28
+ * Build a complete authenticated header. `contentKey` is the suite-specific
29
+ * key used to authenticate the header. For the PQ-hybrid suite this is the
30
+ * combined key K (post-HKDF); for AES-GCM and XChaCha suites this is the
31
+ * raw 32-byte content key.
32
+ */
33
+ export declare function buildAuthenticatedHeader(input: HeaderInputs, contentKey: Uint8Array): Promise<Uint8Array>;
34
+ /**
35
+ * Parse a header from a byte slice. Returns the parsed fields and the
36
+ * total bytes consumed. Does NOT verify the MAC — callers must call
37
+ * `verifyHeaderMac` separately, after deriving the key.
38
+ *
39
+ * Two-phase parse-then-verify keeps the parser usable for tooling that
40
+ * inspects encrypted files without holding the key.
41
+ */
42
+ export declare function parseHeader(input: Uint8Array): ParsedHeader & {
43
+ unauthenticatedBytes: Uint8Array;
44
+ mac: Uint8Array;
45
+ };
46
+ /**
47
+ * Verify the parsed header's MAC under the supplied content key.
48
+ * Throws on failure; returns the parsed header on success.
49
+ */
50
+ export declare function verifyHeaderMac(parsed: ReturnType<typeof parseHeader>, contentKey: Uint8Array): Promise<void>;
51
+ /**
52
+ * Build the AAD bound into every chunk's AEAD: domain || index || total || is_final.
53
+ */
54
+ export declare function buildChunkAad(chunkIndex: number, totalChunks: number, isFinal: boolean): Uint8Array;
55
+ /** Recognizable error class so callers can catch parse failures specifically */
56
+ export declare class HeaderError extends Error {
57
+ readonly code: string;
58
+ constructor(code: string);
59
+ }
60
+ //# sourceMappingURL=header.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header.d.ts","sourceRoot":"","sources":["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 * v1 header builder and parser.
3
+ *
4
+ * The header is constructed without the MAC, then the MAC is computed
5
+ * with the content key, then the MAC is appended. On decode, the parser
6
+ * reads everything up to (but not including) the MAC, then the caller
7
+ * verifies the MAC before trusting any field.
8
+ */
9
+ import { CHUNK_AAD_DOMAIN, CHUNK_AAD_LENGTH, FORMAT_MAGIC, FORMAT_MAGIC_LENGTH, HEADER_FIXED_PREFIX_LENGTH, HEADER_SIZES, HKDF_INFO, MAX_CHUNK_SIZE, MAX_TOTAL_CHUNKS, SUITE, } from '../internal/types.js';
10
+ import { concatBytes, readUint16BE, readUint32BE, readUint64BE, uint16BE, uint32BE, uint64BE, } from '../internal/encoding.js';
11
+ import { hkdfSha256 } from '../internal/hkdf.js';
12
+ import { hmacSha256, hmacSha256Verify } from '../internal/hmac.js';
13
+ const TEXT_ENCODER = new TextEncoder();
14
+ const CHUNK_AAD_DOMAIN_BYTES = TEXT_ENCODER.encode(CHUNK_AAD_DOMAIN);
15
+ const VALID_SUITES = new Set(Object.values(SUITE));
16
+ /**
17
+ * Build the unauthenticated header bytes (everything before the MAC).
18
+ * The caller appends the MAC after deriving header_mac_key.
19
+ */
20
+ export function buildHeaderUnauthenticated(input) {
21
+ validateHeaderInputs(input);
22
+ return concatBytes([
23
+ FORMAT_MAGIC,
24
+ new Uint8Array([input.suite]),
25
+ new Uint8Array([0x00]), // flags reserved
26
+ input.fileId,
27
+ uint32BE(input.chunkSize),
28
+ uint64BE(input.totalChunks),
29
+ uint64BE(input.plaintextSize),
30
+ uint16BE(input.suitePayload.length),
31
+ input.suitePayload,
32
+ ]);
33
+ }
34
+ /**
35
+ * Derive the per-file header MAC key from the content key + file_id.
36
+ */
37
+ export async function deriveHeaderMacKey(contentKey, fileId) {
38
+ return hkdfSha256({
39
+ ikm: contentKey,
40
+ salt: fileId,
41
+ info: HKDF_INFO.HEADER_MAC,
42
+ length: 32,
43
+ });
44
+ }
45
+ /**
46
+ * Build a complete authenticated header. `contentKey` is the suite-specific
47
+ * key used to authenticate the header. For the PQ-hybrid suite this is the
48
+ * combined key K (post-HKDF); for AES-GCM and XChaCha suites this is the
49
+ * raw 32-byte content key.
50
+ */
51
+ export async function buildAuthenticatedHeader(input, contentKey) {
52
+ const unauthenticated = buildHeaderUnauthenticated(input);
53
+ const macKey = await deriveHeaderMacKey(contentKey, input.fileId);
54
+ const mac = await hmacSha256(macKey, unauthenticated);
55
+ return concatBytes([unauthenticated, mac]);
56
+ }
57
+ /**
58
+ * Parse a header from a byte slice. Returns the parsed fields and the
59
+ * total bytes consumed. Does NOT verify the MAC — callers must call
60
+ * `verifyHeaderMac` separately, after deriving the key.
61
+ *
62
+ * Two-phase parse-then-verify keeps the parser usable for tooling that
63
+ * inspects encrypted files without holding the key.
64
+ */
65
+ export function parseHeader(input) {
66
+ if (input.length < HEADER_FIXED_PREFIX_LENGTH + HEADER_SIZES.HEADER_MAC) {
67
+ throw new HeaderError('header_too_short');
68
+ }
69
+ // Magic
70
+ for (let i = 0; i < FORMAT_MAGIC_LENGTH; i += 1) {
71
+ if (input[i] !== FORMAT_MAGIC[i]) {
72
+ throw new HeaderError('bad_magic');
73
+ }
74
+ }
75
+ let offset = FORMAT_MAGIC_LENGTH;
76
+ const suite = input[offset];
77
+ offset += HEADER_SIZES.SUITE;
78
+ if (!VALID_SUITES.has(suite)) {
79
+ throw new HeaderError('unknown_suite');
80
+ }
81
+ const flags = input[offset];
82
+ offset += HEADER_SIZES.FLAGS;
83
+ if (flags !== 0x00) {
84
+ throw new HeaderError('reserved_flags_set');
85
+ }
86
+ const fileId = input.slice(offset, offset + HEADER_SIZES.FILE_ID);
87
+ offset += HEADER_SIZES.FILE_ID;
88
+ const chunkSize = readUint32BE(input, offset);
89
+ offset += HEADER_SIZES.CHUNK_SIZE;
90
+ if (chunkSize === 0 || chunkSize > MAX_CHUNK_SIZE) {
91
+ throw new HeaderError('chunk_size_out_of_range');
92
+ }
93
+ const totalChunks = readUint64BE(input, offset);
94
+ offset += HEADER_SIZES.TOTAL_CHUNKS;
95
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
96
+ throw new HeaderError('total_chunks_out_of_range');
97
+ }
98
+ const plaintextSize = readUint64BE(input, offset);
99
+ offset += HEADER_SIZES.PLAINTEXT_SIZE;
100
+ // Cross-field consistency: total_chunks must match plaintextSize / chunkSize
101
+ if (totalChunks === 0 && plaintextSize !== 0) {
102
+ throw new HeaderError('total_chunks_zero_with_plaintext');
103
+ }
104
+ if (totalChunks > 0) {
105
+ const minPlaintext = (totalChunks - 1) * chunkSize + 1;
106
+ const maxPlaintext = totalChunks * chunkSize;
107
+ if (plaintextSize < minPlaintext || plaintextSize > maxPlaintext) {
108
+ throw new HeaderError('plaintext_size_inconsistent');
109
+ }
110
+ }
111
+ const suitePayloadLen = readUint16BE(input, offset);
112
+ offset += HEADER_SIZES.SUITE_PAYLOAD_LEN;
113
+ if (offset + suitePayloadLen + HEADER_SIZES.HEADER_MAC > input.length) {
114
+ throw new HeaderError('header_truncated');
115
+ }
116
+ const suitePayload = input.slice(offset, offset + suitePayloadLen);
117
+ offset += suitePayloadLen;
118
+ const macStart = offset;
119
+ const mac = input.slice(macStart, macStart + HEADER_SIZES.HEADER_MAC);
120
+ offset += HEADER_SIZES.HEADER_MAC;
121
+ const unauthenticatedBytes = input.slice(0, macStart);
122
+ return {
123
+ suite: suite,
124
+ flags,
125
+ fileId,
126
+ chunkSize,
127
+ totalChunks,
128
+ plaintextSize,
129
+ suitePayload,
130
+ headerLength: offset,
131
+ unauthenticatedBytes,
132
+ mac,
133
+ };
134
+ }
135
+ /**
136
+ * Verify the parsed header's MAC under the supplied content key.
137
+ * Throws on failure; returns the parsed header on success.
138
+ */
139
+ export async function verifyHeaderMac(parsed, contentKey) {
140
+ const macKey = await deriveHeaderMacKey(contentKey, parsed.fileId);
141
+ const ok = await hmacSha256Verify(macKey, parsed.unauthenticatedBytes, parsed.mac);
142
+ if (!ok) {
143
+ throw new HeaderError('header_mac_mismatch');
144
+ }
145
+ }
146
+ /**
147
+ * Build the AAD bound into every chunk's AEAD: domain || index || total || is_final.
148
+ */
149
+ export function buildChunkAad(chunkIndex, totalChunks, isFinal) {
150
+ if (!Number.isSafeInteger(chunkIndex) || chunkIndex < 0) {
151
+ throw new RangeError('buildChunkAad: chunkIndex out of range');
152
+ }
153
+ if (!Number.isSafeInteger(totalChunks) || totalChunks < 0) {
154
+ throw new RangeError('buildChunkAad: totalChunks out of range');
155
+ }
156
+ const out = new Uint8Array(CHUNK_AAD_LENGTH);
157
+ out.set(CHUNK_AAD_DOMAIN_BYTES, 0);
158
+ out.set(uint64BE(chunkIndex), CHUNK_AAD_DOMAIN_BYTES.length);
159
+ out.set(uint64BE(totalChunks), CHUNK_AAD_DOMAIN_BYTES.length + 8);
160
+ out[CHUNK_AAD_DOMAIN_BYTES.length + 16] = isFinal ? 0x01 : 0x00;
161
+ return out;
162
+ }
163
+ function validateHeaderInputs(input) {
164
+ if (!VALID_SUITES.has(input.suite)) {
165
+ throw new HeaderError('unknown_suite');
166
+ }
167
+ if (!(input.fileId instanceof Uint8Array)) {
168
+ throw new TypeError('fileId must be a Uint8Array');
169
+ }
170
+ if (input.fileId.length !== HEADER_SIZES.FILE_ID) {
171
+ throw new HeaderError('file_id_wrong_length');
172
+ }
173
+ if (!Number.isSafeInteger(input.chunkSize) ||
174
+ input.chunkSize <= 0 ||
175
+ input.chunkSize > MAX_CHUNK_SIZE) {
176
+ throw new HeaderError('chunk_size_out_of_range');
177
+ }
178
+ if (!Number.isSafeInteger(input.totalChunks) ||
179
+ input.totalChunks < 0 ||
180
+ input.totalChunks > MAX_TOTAL_CHUNKS) {
181
+ throw new HeaderError('total_chunks_out_of_range');
182
+ }
183
+ if (!Number.isSafeInteger(input.plaintextSize) ||
184
+ input.plaintextSize < 0) {
185
+ throw new HeaderError('plaintext_size_out_of_range');
186
+ }
187
+ if (!(input.suitePayload instanceof Uint8Array)) {
188
+ throw new TypeError('suitePayload must be a Uint8Array');
189
+ }
190
+ if (input.suitePayload.length > 0xffff) {
191
+ throw new HeaderError('suite_payload_too_large');
192
+ }
193
+ }
194
+ /** Recognizable error class so callers can catch parse failures specifically */
195
+ export class HeaderError extends Error {
196
+ code;
197
+ constructor(code) {
198
+ super(`shieldfive-crypto: header error: ${code}`);
199
+ this.name = 'HeaderError';
200
+ this.code = code;
201
+ }
202
+ }
203
+ //# sourceMappingURL=header.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header.js","sourceRoot":"","sources":["../../src/format/header.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,mBAAmB,EACnB,0BAA0B,EAC1B,YAAY,EACZ,SAAS,EACT,cAAc,EACd,gBAAgB,EAEhB,KAAK,GAEN,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EACL,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,QAAQ,EACR,QAAQ,EACR,QAAQ,GACT,MAAM,yBAAyB,CAAA;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAChD,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAA;AAElE,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAA;AACtC,MAAM,sBAAsB,GAAG,YAAY,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAA;AAEpE,MAAM,YAAY,GAAG,IAAI,GAAG,CAAS,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;AAW1D;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CAAC,KAAmB;IAC5D,oBAAoB,CAAC,KAAK,CAAC,CAAA;IAC3B,OAAO,WAAW,CAAC;QACjB,YAAY;QACZ,IAAI,UAAU,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC7B,IAAI,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,iBAAiB;QACzC,KAAK,CAAC,MAAM;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AAS,CAAC,mCAAmC,CAAC,CAAA;IAC1D,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC;QACvC,MAAM,IAAI,WAAW,CAAC,yBAAyB,CAAC,CAAA;IAClD,CAAC;AACH,CAAC;AAED,gFAAgF;AAChF,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC3B,IAAI,CAAQ;IACrB,YAAY,IAAY;QACtB,KAAK,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAA;QACjD,IAAI,CAAC,IAAI,GAAG,aAAa,CAAA;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF"}
@@ -0,0 +1,117 @@
1
+ /**
2
+ * User identity & public-key directory helpers.
3
+ *
4
+ * In a multi-user system, the PQ-hybrid suite needs the recipient's public
5
+ * key to encrypt to. This module provides:
6
+ *
7
+ * - A canonical wire format for publishing a user's public-key bundle
8
+ * (ML-KEM-1024 public key + a self-signed-by-application identity tag).
9
+ * - Helpers for creating, parsing, and verifying public-key bundles.
10
+ * - Helpers for re-encrypting a file's content key to additional
11
+ * recipients (sharing) without re-uploading the file.
12
+ *
13
+ * Cryptographic identity beyond the application's own auth layer is
14
+ * deliberately NOT in scope. The bundle format does not sign the public
15
+ * key with any user-controlled key — the trust anchor is the application's
16
+ * authenticated channel for publishing keys (TLS + auth token). If callers
17
+ * want stronger identity (e.g. SAS verification, gossiped signatures),
18
+ * they wrap this module rather than modify it.
19
+ */
20
+ export interface PublicIdentityBundle {
21
+ /** ML-KEM-1024 public key (1568 bytes) */
22
+ mlKemPublicKey: Uint8Array;
23
+ /** Application-assigned user ID (UTF-8 string, ≤255 bytes) */
24
+ userId: string;
25
+ /** Optional metadata blob (≤4 KiB), e.g. a profile JSON */
26
+ metadata?: Uint8Array;
27
+ /** Issuance timestamp (UNIX seconds, uint32) */
28
+ issuedAt: number;
29
+ }
30
+ /**
31
+ * Wire format for an identity bundle:
32
+ *
33
+ * magic 5 bytes "SF5I" + version
34
+ * issued_at 4 bytes uint32 BE (UNIX seconds)
35
+ * user_id_len 1 byte
36
+ * user_id variable UTF-8
37
+ * ml_kem_pk 1568 bytes
38
+ * metadata_len 2 bytes uint16 BE
39
+ * metadata variable opaque
40
+ *
41
+ * Unsigned. Trust comes from the channel that publishes it.
42
+ */
43
+ export declare function encodeIdentityBundle(bundle: PublicIdentityBundle): Uint8Array;
44
+ export declare function decodeIdentityBundle(bytes: Uint8Array): PublicIdentityBundle;
45
+ /**
46
+ * Serialize a bundle as a base64 string suitable for storing in a database
47
+ * column or transmitting over a JSON API.
48
+ */
49
+ export declare function bundleToBase64(bundle: PublicIdentityBundle): string;
50
+ export declare function bundleFromBase64(b64: string): PublicIdentityBundle;
51
+ export interface CreateIdentityOptions {
52
+ userId: string;
53
+ metadata?: Uint8Array;
54
+ /**
55
+ * If provided, the ML-KEM keypair is derived deterministically from
56
+ * this master secret. Otherwise a fresh keypair is generated. Most
57
+ * applications should pass the user's master secret here so that
58
+ * loss of an ML-KEM secret key does not lock the user out.
59
+ */
60
+ masterSecret?: Uint8Array;
61
+ /** Defaults to current time. */
62
+ issuedAt?: number;
63
+ }
64
+ export interface IdentityKeypair {
65
+ publicBundle: PublicIdentityBundle;
66
+ /** Encoded form of the public bundle for direct publishing. */
67
+ publicBundleBytes: Uint8Array;
68
+ /** ML-KEM-1024 secret key. Treat as highly sensitive. */
69
+ mlKemSecretKey: Uint8Array;
70
+ }
71
+ export declare function createIdentity(options: CreateIdentityOptions): Promise<IdentityKeypair>;
72
+ /**
73
+ * The PQ-hybrid suite encrypts each file's combined key for exactly one
74
+ * recipient (whoever owns the ML-KEM public key the encryptor used).
75
+ * Sharing a file with N additional recipients means: recover the
76
+ * original combined key (only the owner can do this), then produce N new
77
+ * suite_payloads — one per recipient — that decrypt to the SAME combined
78
+ * key. The chunks themselves are not re-encrypted.
79
+ *
80
+ * Each per-recipient suite_payload is stored alongside the file's chunks
81
+ * in the application's database (one row per recipient). The on-disk
82
+ * blob remains unchanged.
83
+ */
84
+ export interface ShareFileInput {
85
+ /** The file's combined key, recovered by the owner. */
86
+ combinedKey: Uint8Array;
87
+ /** The file's 16-byte file_id. */
88
+ fileId: Uint8Array;
89
+ /** The recipient's identity bundle (provides their ML-KEM public key). */
90
+ recipient: PublicIdentityBundle;
91
+ /** Classical envelope key the recipient holds. */
92
+ recipientEnvelopeKey: Uint8Array;
93
+ }
94
+ /**
95
+ * Build a new suite_payload that decrypts to `combinedKey` for the given
96
+ * recipient. Stored alongside the file as a per-recipient share record.
97
+ *
98
+ * NOTE: the standard `encapsulateForRecipient` produces a NEW combined
99
+ * key. To make sharing work, we use a different construction: we wrap
100
+ * the existing combined key under (recipient PQ KEM ⊕ recipient
101
+ * envelope) and emit only the wrapped form.
102
+ */
103
+ export declare function buildShareForRecipient(input: ShareFileInput): Promise<{
104
+ shareBundle: Uint8Array;
105
+ }>;
106
+ /**
107
+ * Recipient side: open a share bundle to recover the file's combined key.
108
+ * The recipient then uses that combined key with the standard PQ-hybrid
109
+ * decrypt path (via the original on-disk file).
110
+ */
111
+ export declare function openShareAsRecipient(input: {
112
+ shareBundle: Uint8Array;
113
+ fileId: Uint8Array;
114
+ recipientSecretKey: Uint8Array;
115
+ recipientEnvelopeKey: Uint8Array;
116
+ }): Promise<Uint8Array>;
117
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/identity/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AA2BH,MAAM,WAAW,oBAAoB;IACnC,0CAA0C;IAC1C,cAAc,EAAE,UAAU,CAAA;IAC1B,8DAA8D;IAC9D,MAAM,EAAE,MAAM,CAAA;IACd,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,UAAU,CAAA;IACrB,gDAAgD;IAChD,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED;;;;;;;;;;;;GAYG;AAEH,wBAAgB,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AA;IAC9B,oBAAoB,EAAE,UAAU,CAAA;CACjC,GAAG,OAAO,CAAC,UAAU,CAAC,CAgDtB"}
@@ -0,0 +1,217 @@
1
+ /**
2
+ * User identity & public-key directory helpers.
3
+ *
4
+ * In a multi-user system, the PQ-hybrid suite needs the recipient's public
5
+ * key to encrypt to. This module provides:
6
+ *
7
+ * - A canonical wire format for publishing a user's public-key bundle
8
+ * (ML-KEM-1024 public key + a self-signed-by-application identity tag).
9
+ * - Helpers for creating, parsing, and verifying public-key bundles.
10
+ * - Helpers for re-encrypting a file's content key to additional
11
+ * recipients (sharing) without re-uploading the file.
12
+ *
13
+ * Cryptographic identity beyond the application's own auth layer is
14
+ * deliberately NOT in scope. The bundle format does not sign the public
15
+ * key with any user-controlled key — the trust anchor is the application's
16
+ * authenticated channel for publishing keys (TLS + auth token). If callers
17
+ * want stronger identity (e.g. SAS verification, gossiped signatures),
18
+ * they wrap this module rather than modify it.
19
+ */
20
+ import { ML_KEM_1024_PUBLIC_KEY_BYTES, ML_KEM_1024_SECRET_KEY_BYTES, deriveMlKemKeypair, generateMlKemKeypair, encapsulateForRecipient, decapsulateFromHeader, parsePqHybridV1SuitePayload, buildPqHybridV1SuitePayload, } from '../suites/pq-hybrid-v1/index.js';
21
+ import { bytesToBase64, base64ToBytes, concatBytes, uint16BE, uint32BE, readUint16BE, readUint32BE, } from '../internal/encoding.js';
22
+ import { randomBytes } from '../internal/runtime.js';
23
+ import { getSodium } from '../internal/sodium.js';
24
+ const IDENTITY_BUNDLE_MAGIC = new Uint8Array([0x53, 0x46, 0x35, 0x49, 0x01]); // "SF5I" + version
25
+ const IDENTITY_BUNDLE_VERSION = 0x01;
26
+ /**
27
+ * Wire format for an identity bundle:
28
+ *
29
+ * magic 5 bytes "SF5I" + version
30
+ * issued_at 4 bytes uint32 BE (UNIX seconds)
31
+ * user_id_len 1 byte
32
+ * user_id variable UTF-8
33
+ * ml_kem_pk 1568 bytes
34
+ * metadata_len 2 bytes uint16 BE
35
+ * metadata variable opaque
36
+ *
37
+ * Unsigned. Trust comes from the channel that publishes it.
38
+ */
39
+ export function encodeIdentityBundle(bundle) {
40
+ if (bundle.mlKemPublicKey.length !== ML_KEM_1024_PUBLIC_KEY_BYTES) {
41
+ throw new RangeError(`encodeIdentityBundle: mlKemPublicKey must be ${ML_KEM_1024_PUBLIC_KEY_BYTES} bytes`);
42
+ }
43
+ const userIdBytes = new TextEncoder().encode(bundle.userId);
44
+ if (userIdBytes.length === 0 || userIdBytes.length > 255) {
45
+ throw new RangeError('encodeIdentityBundle: userId must be 1..255 UTF-8 bytes');
46
+ }
47
+ if (!Number.isSafeInteger(bundle.issuedAt) ||
48
+ bundle.issuedAt < 0 ||
49
+ bundle.issuedAt > 0xffff_ffff) {
50
+ throw new RangeError('encodeIdentityBundle: issuedAt must fit in uint32');
51
+ }
52
+ const metadata = bundle.metadata ?? new Uint8Array(0);
53
+ if (metadata.length > 4096) {
54
+ throw new RangeError('encodeIdentityBundle: metadata must be at most 4096 bytes');
55
+ }
56
+ return concatBytes([
57
+ IDENTITY_BUNDLE_MAGIC,
58
+ uint32BE(bundle.issuedAt),
59
+ new Uint8Array([userIdBytes.length]),
60
+ userIdBytes,
61
+ bundle.mlKemPublicKey,
62
+ uint16BE(metadata.length),
63
+ metadata,
64
+ ]);
65
+ }
66
+ export function decodeIdentityBundle(bytes) {
67
+ if (bytes.length < IDENTITY_BUNDLE_MAGIC.length + 4 + 1) {
68
+ throw new RangeError('decodeIdentityBundle: input too short');
69
+ }
70
+ for (let i = 0; i < IDENTITY_BUNDLE_MAGIC.length; i += 1) {
71
+ if (bytes[i] !== IDENTITY_BUNDLE_MAGIC[i]) {
72
+ throw new Error('decodeIdentityBundle: bad magic / unknown bundle version');
73
+ }
74
+ }
75
+ let offset = IDENTITY_BUNDLE_MAGIC.length;
76
+ const issuedAt = readUint32BE(bytes, offset);
77
+ offset += 4;
78
+ const userIdLen = bytes[offset];
79
+ offset += 1;
80
+ if (userIdLen === 0) {
81
+ throw new Error('decodeIdentityBundle: empty user_id');
82
+ }
83
+ if (offset + userIdLen + ML_KEM_1024_PUBLIC_KEY_BYTES + 2 > bytes.length) {
84
+ throw new Error('decodeIdentityBundle: truncated');
85
+ }
86
+ const userId = new TextDecoder('utf-8', { fatal: true }).decode(bytes.slice(offset, offset + userIdLen));
87
+ offset += userIdLen;
88
+ const mlKemPublicKey = bytes.slice(offset, offset + ML_KEM_1024_PUBLIC_KEY_BYTES);
89
+ offset += ML_KEM_1024_PUBLIC_KEY_BYTES;
90
+ const metadataLen = readUint16BE(bytes, offset);
91
+ offset += 2;
92
+ if (offset + metadataLen !== bytes.length) {
93
+ throw new Error('decodeIdentityBundle: trailing bytes or wrong metadata_len');
94
+ }
95
+ const metadata = bytes.slice(offset, offset + metadataLen);
96
+ const result = {
97
+ mlKemPublicKey,
98
+ userId,
99
+ issuedAt,
100
+ };
101
+ if (metadata.length > 0)
102
+ result.metadata = metadata;
103
+ return result;
104
+ }
105
+ /**
106
+ * Serialize a bundle as a base64 string suitable for storing in a database
107
+ * column or transmitting over a JSON API.
108
+ */
109
+ export function bundleToBase64(bundle) {
110
+ return bytesToBase64(encodeIdentityBundle(bundle));
111
+ }
112
+ export function bundleFromBase64(b64) {
113
+ return decodeIdentityBundle(base64ToBytes(b64));
114
+ }
115
+ export async function createIdentity(options) {
116
+ const keypair = options.masterSecret
117
+ ? await deriveMlKemKeypair(options.masterSecret)
118
+ : generateMlKemKeypair();
119
+ const bundle = {
120
+ mlKemPublicKey: keypair.publicKey,
121
+ userId: options.userId,
122
+ issuedAt: options.issuedAt ?? Math.floor(Date.now() / 1000),
123
+ };
124
+ if (options.metadata)
125
+ bundle.metadata = options.metadata;
126
+ if (keypair.secretKey.length !== ML_KEM_1024_SECRET_KEY_BYTES) {
127
+ throw new Error(`createIdentity: unexpected secret key length ${keypair.secretKey.length}`);
128
+ }
129
+ return {
130
+ publicBundle: bundle,
131
+ publicBundleBytes: encodeIdentityBundle(bundle),
132
+ mlKemSecretKey: keypair.secretKey,
133
+ };
134
+ }
135
+ /**
136
+ * Build a new suite_payload that decrypts to `combinedKey` for the given
137
+ * recipient. Stored alongside the file as a per-recipient share record.
138
+ *
139
+ * NOTE: the standard `encapsulateForRecipient` produces a NEW combined
140
+ * key. To make sharing work, we use a different construction: we wrap
141
+ * the existing combined key under (recipient PQ KEM ⊕ recipient
142
+ * envelope) and emit only the wrapped form.
143
+ */
144
+ export async function buildShareForRecipient(input) {
145
+ const sodium = await getSodium();
146
+ // Generate a fresh transport key for this share.
147
+ // ML-KEM encapsulation gives us the PQ-half of the transport secret.
148
+ const { suitePayload: pqPayload, combinedKey: transportKey } = await encapsulateForRecipient({
149
+ recipientPublicKey: input.recipient.mlKemPublicKey,
150
+ envelopeKey: input.recipientEnvelopeKey,
151
+ fileId: input.fileId,
152
+ });
153
+ // Now wrap the original combined key under the transport key using
154
+ // XSalsa20-Poly1305 secretbox.
155
+ if (transportKey.length !== 32) {
156
+ throw new Error('buildShareForRecipient: transport key length wrong');
157
+ }
158
+ const wrapNonce = randomBytes(24);
159
+ const wrappedCombinedKey = sodium.crypto_secretbox_easy(input.combinedKey, wrapNonce, transportKey);
160
+ if (wrappedCombinedKey.length !== 32 + 16) {
161
+ throw new Error('buildShareForRecipient: secretbox produced unexpected length');
162
+ }
163
+ // Share record format:
164
+ // [4 bytes BE length of pqPayload][pqPayload][24-byte wrap nonce][48-byte wrapped combined key]
165
+ return {
166
+ shareBundle: concatBytes([
167
+ uint32BE(pqPayload.length),
168
+ pqPayload,
169
+ wrapNonce,
170
+ wrappedCombinedKey,
171
+ ]),
172
+ };
173
+ }
174
+ /**
175
+ * Recipient side: open a share bundle to recover the file's combined key.
176
+ * The recipient then uses that combined key with the standard PQ-hybrid
177
+ * decrypt path (via the original on-disk file).
178
+ */
179
+ export async function openShareAsRecipient(input) {
180
+ const sodium = await getSodium();
181
+ if (input.shareBundle.length < 4) {
182
+ throw new Error('openShareAsRecipient: share too short');
183
+ }
184
+ let offset = 0;
185
+ const pqLen = readUint32BE(input.shareBundle, offset);
186
+ offset += 4;
187
+ if (offset + pqLen + 24 + 48 !== input.shareBundle.length) {
188
+ throw new Error('openShareAsRecipient: malformed share');
189
+ }
190
+ const pqPayload = input.shareBundle.slice(offset, offset + pqLen);
191
+ offset += pqLen;
192
+ const wrapNonce = input.shareBundle.slice(offset, offset + 24);
193
+ offset += 24;
194
+ const wrappedCombinedKey = input.shareBundle.slice(offset, offset + 48);
195
+ // Sanity-check the suite payload structure (this throws if malformed).
196
+ parsePqHybridV1SuitePayload(pqPayload);
197
+ // Round-trip through builder to ensure we got back the same bytes.
198
+ const checkBytes = buildPqHybridV1SuitePayload(parsePqHybridV1SuitePayload(pqPayload));
199
+ if (checkBytes.length !== pqPayload.length) {
200
+ throw new Error('openShareAsRecipient: pq payload self-check failed');
201
+ }
202
+ const { combinedKey: transportKey } = await decapsulateFromHeader({
203
+ suitePayload: pqPayload,
204
+ recipientSecretKey: input.recipientSecretKey,
205
+ envelopeKey: input.recipientEnvelopeKey,
206
+ fileId: input.fileId,
207
+ });
208
+ const unwrapped = sodium.crypto_secretbox_open_easy(wrappedCombinedKey, wrapNonce, transportKey);
209
+ if (!unwrapped) {
210
+ throw new Error('openShareAsRecipient: secretbox unwrap failed — wrong recipient or tampered share');
211
+ }
212
+ if (unwrapped.length !== 32) {
213
+ throw new Error('openShareAsRecipient: bad combined key length');
214
+ }
215
+ return new Uint8Array(unwrapped);
216
+ }
217
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/identity/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EACL,4BAA4B,EAC5B,4BAA4B,EAC5B,kBAAkB,EAClB,oBAAoB,EACpB,uBAAuB,EACvB,qBAAqB,EACrB,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,iCAAiC,CAAA;AACxC,OAAO,EACL,aAAa,EACb,aAAa,EACb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