@myfield/sdk 0.9.2 → 0.9.3

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.
@@ -1,58 +0,0 @@
1
- // AES-GCM envelope, wire compatible with the established myfield bucket sync
2
- // envelope shape. The worker only validates envelope shape (zero-knowledge
3
- // storage); it never decrypts payloads. AAD binds bucketId and the blinded
4
- // wire object id.
5
-
6
- import { b64urlToBytes, bytesToB64url, utf8Decode, utf8Encode } from "../internal/encoding.ts";
7
- import type { BucketKeys } from "./keys.ts";
8
-
9
- export type EncryptedEnvelopeFields = {
10
- ciphertext: string;
11
- cipherMeta: { alg: "AES-GCM"; iv: string; keyId: string; bucketId: string; aad: string };
12
- wrappedDEK: string;
13
- wrappedDEKMeta: { alg: "direct-bucket-key"; keyId: string; bucketId: string };
14
- };
15
-
16
- export async function encryptEnvelopeFields(keys: BucketKeys, wireObjectId: string, plaintext: Uint8Array): Promise<EncryptedEnvelopeFields> {
17
- const iv = crypto.getRandomValues(new Uint8Array(12));
18
- const aad = buildAad(keys.bucketId, wireObjectId);
19
- const plaintextBuffer = plaintext.buffer.slice(plaintext.byteOffset, plaintext.byteOffset + plaintext.byteLength) as ArrayBuffer;
20
- const ciphertext = new Uint8Array(
21
- await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: utf8Encode(aad) }, keys.payloadKey, plaintextBuffer)
22
- );
23
- return {
24
- ciphertext: bytesToB64url(ciphertext),
25
- cipherMeta: { alg: "AES-GCM", iv: bytesToB64url(iv), keyId: keys.keyId, bucketId: keys.bucketId, aad },
26
- wrappedDEK: keys.keyId,
27
- wrappedDEKMeta: { alg: "direct-bucket-key", keyId: keys.keyId, bucketId: keys.bucketId },
28
- };
29
- }
30
-
31
- export async function decryptEnvelope(keys: BucketKeys, wireObjectId: string, envelope: Uint8Array): Promise<Uint8Array> {
32
- const parsed = JSON.parse(utf8Decode(envelope)) as {
33
- cipherMeta?: { alg?: unknown; iv?: unknown; keyId?: unknown; bucketId?: unknown; aad?: unknown };
34
- ciphertext?: unknown;
35
- };
36
- if (
37
- typeof parsed.ciphertext !== "string" ||
38
- parsed.cipherMeta?.alg !== "AES-GCM" ||
39
- parsed.cipherMeta.keyId !== keys.keyId ||
40
- parsed.cipherMeta.bucketId !== keys.bucketId ||
41
- typeof parsed.cipherMeta.iv !== "string" ||
42
- typeof parsed.cipherMeta.aad !== "string"
43
- ) {
44
- throw new Error("corrupted sync envelope");
45
- }
46
- if (parsed.cipherMeta.aad !== buildAad(keys.bucketId, wireObjectId)) throw new Error("sync envelope aad mismatch");
47
- return new Uint8Array(
48
- await crypto.subtle.decrypt(
49
- { name: "AES-GCM", iv: b64urlToBytes(parsed.cipherMeta.iv) as BufferSource, additionalData: utf8Encode(parsed.cipherMeta.aad) },
50
- keys.payloadKey,
51
- b64urlToBytes(parsed.ciphertext) as BufferSource
52
- )
53
- );
54
- }
55
-
56
- function buildAad(bucketId: string, wireObjectId: string): string {
57
- return `myfield.bucket.sync.v1|${bucketId}|${wireObjectId}`;
58
- }
@@ -1,324 +0,0 @@
1
- // LWW-Map payload format. Everything in this file describes plaintext that
2
- // only exists inside the encrypted payload; the worker never sees it.
3
- //
4
- // Wire layout:
5
- // [1-byte format version][4-byte big-endian header length][utf8 JSON header][binary parts...]
6
- // Document body:
7
- // { t: "lww-map", fields: { name: { v, ts, actor } }, tombstones: { name: { ts, actor } } }
8
- // or { t: "opaque", data: <arbitrary JSON> } for custom merge strategies.
9
- // Unknown top-level and entry keys are kept (BUCKET-SPEC merge steps 4-5).
10
- // Binary typed field values are represented in the JSON header as part references
11
- // and carried as raw bytes in the binary parts section.
12
-
13
- import { utf8Decode, utf8Encode } from "../internal/encoding.ts";
14
- import {
15
- cloneStoredBinaryValue,
16
- fieldValueToCanonicalJson,
17
- hydrateFieldValue,
18
- isStoredBinaryValue,
19
- type StoredBinaryValue,
20
- } from "./binary.ts";
21
-
22
- export const PAYLOAD_FORMAT_VERSION = 1;
23
- const HEADER_LENGTH_BYTES = 4;
24
- const PART_LENGTH_BYTES = 4;
25
- const BINARY_PART_MARKER = "binary-part-v1";
26
-
27
- export type LwwFieldEntry = { v: unknown; ts: number; actor: string; [extra: string]: unknown };
28
- export type LwwTombstone = { ts: number; actor: string; [extra: string]: unknown };
29
-
30
- export type LwwMapDoc = {
31
- t: "lww-map";
32
- fields: Record<string, LwwFieldEntry>;
33
- tombstones: Record<string, LwwTombstone>;
34
- ext?: Record<string, unknown>;
35
- };
36
-
37
- const LWW_MAP_KEYS = new Set(["t", "fields", "tombstones"]);
38
-
39
- export type OpaqueDoc = { t: "opaque"; data: unknown };
40
-
41
- export type PayloadDoc = LwwMapDoc | OpaqueDoc;
42
-
43
- export function emptyLwwMapDoc(): LwwMapDoc {
44
- return { t: "lww-map", fields: {}, tombstones: {} };
45
- }
46
-
47
- export function encodePayloadDoc(doc: PayloadDoc): Uint8Array {
48
- const parts: Uint8Array[] = [];
49
- const body = doc.t === "lww-map" ? { ...(doc.ext || {}), t: doc.t, fields: doc.fields, tombstones: doc.tombstones } : doc;
50
- const header = utf8Encode(JSON.stringify(encodeHeaderValue(body, parts)));
51
- let totalLength = 1 + HEADER_LENGTH_BYTES + header.byteLength;
52
- for (const part of parts) totalLength += PART_LENGTH_BYTES + part.byteLength;
53
- const out = new Uint8Array(totalLength);
54
- out[0] = PAYLOAD_FORMAT_VERSION;
55
- writeU32(out, 1, header.byteLength);
56
- out.set(header, 1 + HEADER_LENGTH_BYTES);
57
- let offset = 1 + HEADER_LENGTH_BYTES + header.byteLength;
58
- for (const part of parts) {
59
- writeU32(out, offset, part.byteLength);
60
- offset += PART_LENGTH_BYTES;
61
- out.set(part, offset);
62
- offset += part.byteLength;
63
- }
64
- return out;
65
- }
66
-
67
- export function decodePayloadDoc(bytes: Uint8Array): PayloadDoc {
68
- if (bytes.length < 2) throw new Error("payload too short");
69
- const version = bytes[0];
70
- if (version !== PAYLOAD_FORMAT_VERSION) throw new Error(`unsupported payload format version: ${version}`);
71
- if (bytes.length < 1 + HEADER_LENGTH_BYTES) throw new Error("payload header too short");
72
- const headerLength = readU32(bytes, 1);
73
- const headerStart = 1 + HEADER_LENGTH_BYTES;
74
- const headerEnd = headerStart + headerLength;
75
- if (headerEnd > bytes.length) throw new Error("payload header length out of range");
76
- const parsed = JSON.parse(utf8Decode(bytes.subarray(headerStart, headerEnd)));
77
- const parts: Uint8Array[] = [];
78
- let offset = headerEnd;
79
- while (offset < bytes.length) {
80
- if (offset + PART_LENGTH_BYTES > bytes.length) throw new Error("payload part length out of range");
81
- const partLength = readU32(bytes, offset);
82
- offset += PART_LENGTH_BYTES;
83
- if (offset + partLength > bytes.length) throw new Error("payload part out of range");
84
- parts.push(bytes.slice(offset, offset + partLength));
85
- offset += partLength;
86
- }
87
- return parsePayloadDoc(decodeHeaderValue(parsed, parts));
88
- }
89
-
90
- function parsePayloadDoc(parsed: unknown): PayloadDoc {
91
- const docRoot = parsed as Partial<PayloadDoc> | null;
92
- if (docRoot?.t === "lww-map") {
93
- const doc = docRoot as Partial<LwwMapDoc>;
94
- if (!isRecord(doc.fields) || !isRecord(doc.tombstones)) throw new Error("invalid lww-map payload");
95
- for (const entry of Object.values(doc.fields)) {
96
- if (!isLwwFieldEntry(entry)) throw new Error("invalid lww-map field entry");
97
- }
98
- for (const entry of Object.values(doc.tombstones)) {
99
- if (!isLwwTombstone(entry)) throw new Error("invalid lww-map tombstone");
100
- }
101
- const ext = Object.fromEntries(Object.entries(doc).filter(([key]) => !LWW_MAP_KEYS.has(key)));
102
- return {
103
- t: "lww-map",
104
- fields: doc.fields as Record<string, LwwFieldEntry>,
105
- tombstones: doc.tombstones as Record<string, LwwTombstone>,
106
- ...(Object.keys(ext).length ? { ext } : {}),
107
- };
108
- }
109
- if (docRoot?.t === "opaque") return { t: "opaque", data: (docRoot as OpaqueDoc).data };
110
- throw new Error("unknown payload doc type");
111
- }
112
-
113
- // (ts, actor) total order: higher timestamp wins; equal timestamps fall back
114
- // to actor id lexicographic order so every replica picks the same winner.
115
- function wins(aTs: number, aActor: string, bTs: number, bActor: string): boolean {
116
- if (aTs !== bTs) return aTs > bTs;
117
- return aActor > bActor;
118
- }
119
-
120
- // Full (ts, actor) ties (malformed input, or an older SDK that dropped extra
121
- // keys) fall back to the value, then the whole entry, to stay deterministic.
122
- function fieldEntryWins(a: LwwFieldEntry, b: LwwFieldEntry): boolean {
123
- if (a.ts !== b.ts) return a.ts > b.ts;
124
- if (a.actor !== b.actor) return a.actor > b.actor;
125
- const aValue = JSON.stringify(fieldValueToCanonicalJson(a.v));
126
- const bValue = JSON.stringify(fieldValueToCanonicalJson(b.v));
127
- if (aValue !== bValue) return aValue > bValue;
128
- return canonicalJson(a) > canonicalJson(b);
129
- }
130
-
131
- function tombstoneWins(a: LwwTombstone, b: LwwTombstone): boolean {
132
- if (a.ts !== b.ts || a.actor !== b.actor) return wins(a.ts, a.actor, b.ts, b.actor);
133
- return canonicalJson(a) > canonicalJson(b);
134
- }
135
-
136
- // State-based LWW-Map merge: commutative, associative, idempotent. A field
137
- // survives only if its entry beats every tombstone recorded for the same
138
- // name; on an exact (ts, actor) tie between a value and a tombstone the
139
- // tombstone wins so deletes are stable under replay.
140
- export function mergeLwwMapDocs(a: LwwMapDoc, b: LwwMapDoc): LwwMapDoc {
141
- const tombstones: Record<string, LwwTombstone> = {};
142
- for (const source of [a.tombstones, b.tombstones]) {
143
- for (const [name, stone] of Object.entries(source)) {
144
- const existing = tombstones[name];
145
- if (!existing || tombstoneWins(stone, existing)) tombstones[name] = { ...stone };
146
- }
147
- }
148
- const fields: Record<string, LwwFieldEntry> = {};
149
- for (const source of [a.fields, b.fields]) {
150
- for (const [name, entry] of Object.entries(source)) {
151
- const existing = fields[name];
152
- if (!existing || fieldEntryWins(entry, existing)) fields[name] = { ...entry };
153
- }
154
- }
155
- for (const [name, stone] of Object.entries(tombstones)) {
156
- const entry = fields[name];
157
- if (entry && !wins(entry.ts, entry.actor, stone.ts, stone.actor)) delete fields[name];
158
- }
159
- const ext = mergeExt(a.ext, b.ext);
160
- return { t: "lww-map", fields, tombstones, ...(ext ? { ext } : {}) };
161
- }
162
-
163
- function mergeExt(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
164
- if (!a && !b) return undefined;
165
- const merged: Record<string, unknown> = { ...(a || {}) };
166
- for (const [key, value] of Object.entries(b || {})) {
167
- if (!(key in merged) || canonicalJson(value) > canonicalJson(merged[key])) merged[key] = value;
168
- }
169
- return Object.keys(merged).length ? merged : undefined;
170
- }
171
-
172
- function canonicalJson(value: unknown): string {
173
- return stableStringify(fieldValueToCanonicalJson(value));
174
- }
175
-
176
- function stableStringify(value: unknown): string {
177
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
178
- if (value && typeof value === "object") {
179
- const entries = Object.entries(value as Record<string, unknown>)
180
- .filter(([, item]) => item !== undefined)
181
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
182
- return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
183
- }
184
- return JSON.stringify(value) ?? "null";
185
- }
186
-
187
- export function lwwMapDocsEqual(a: LwwMapDoc, b: LwwMapDoc): boolean {
188
- return canonicalJson(canonicalLwwMapDoc(a)) === canonicalJson(canonicalLwwMapDoc(b));
189
- }
190
-
191
- function canonicalLwwMapDoc(doc: LwwMapDoc): unknown {
192
- return {
193
- fields: Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, { ...entry, v: fieldValueToCanonicalJson(entry.v) }])),
194
- tombstones: doc.tombstones,
195
- ext: doc.ext || {},
196
- };
197
- }
198
-
199
- export function lwwMapLatestTs(doc: LwwMapDoc): number | null {
200
- let latest: number | null = null;
201
- for (const entry of [...Object.values(doc.fields), ...Object.values(doc.tombstones)]) {
202
- if (latest === null || entry.ts > latest) latest = entry.ts;
203
- }
204
- return latest;
205
- }
206
-
207
- // Plain field view with tombstones and metadata hidden.
208
- export function lwwMapValues(doc: LwwMapDoc): Record<string, unknown> {
209
- return Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, hydrateFieldValue(entry.v)]));
210
- }
211
-
212
- // Hybrid clock: strictly monotonic per client and never behind any observed
213
- // remote timestamp, so a device with a slow clock cannot silently lose wins.
214
- export class LwwClock {
215
- private maxSeen = 0;
216
-
217
- observeDoc(doc: LwwMapDoc): void {
218
- for (const entry of Object.values(doc.fields)) this.observe(entry.ts);
219
- for (const stone of Object.values(doc.tombstones)) this.observe(stone.ts);
220
- }
221
-
222
- observe(ts: number): void {
223
- if (!Number.isFinite(ts)) return;
224
- if (ts > this.maxSeen) this.maxSeen = ts;
225
- }
226
-
227
- next(): number {
228
- const ts = Math.max(Date.now() + 1, this.maxSeen + 1);
229
- this.maxSeen = ts;
230
- return ts;
231
- }
232
- }
233
-
234
- // Applies local writes. `undefined` values delete the field (tombstone).
235
- export function applyLwwMapUpdates(doc: LwwMapDoc, updates: Record<string, unknown>, clock: LwwClock, actor: string): LwwMapDoc {
236
- const next: LwwMapDoc = {
237
- t: "lww-map",
238
- fields: { ...doc.fields },
239
- tombstones: { ...doc.tombstones },
240
- ...(doc.ext ? { ext: { ...doc.ext } } : {}),
241
- };
242
- for (const [name, value] of Object.entries(updates)) {
243
- const ts = clock.next();
244
- if (value === undefined) {
245
- delete next.fields[name];
246
- next.tombstones[name] = { ts, actor };
247
- } else {
248
- next.fields[name] = { v: value, ts, actor };
249
- delete next.tombstones[name];
250
- }
251
- }
252
- return next;
253
- }
254
-
255
- function isRecord(value: unknown): value is Record<string, unknown> {
256
- return !!value && typeof value === "object" && !Array.isArray(value);
257
- }
258
-
259
- function encodeHeaderValue(value: unknown, parts: Uint8Array[]): unknown {
260
- if (isStoredBinaryValue(value)) {
261
- const index = parts.length;
262
- parts.push(value.bytes);
263
- return {
264
- __myfieldSdkType: BINARY_PART_MARKER,
265
- part: index,
266
- size: value.size,
267
- ...(value.mimeType ? { mimeType: value.mimeType } : {}),
268
- ...(value.name ? { name: value.name } : {}),
269
- ...(typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}),
270
- };
271
- }
272
- if (Array.isArray(value)) return value.map((item) => encodeHeaderValue(item, parts));
273
- if (value && typeof value === "object") {
274
- return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, encodeHeaderValue(item, parts)]));
275
- }
276
- return value;
277
- }
278
-
279
- function decodeHeaderValue(value: unknown, parts: Uint8Array[]): unknown {
280
- const maybePart = value as { __myfieldSdkType?: unknown; part?: unknown; size?: unknown; mimeType?: unknown; name?: unknown; lastModified?: unknown } | null;
281
- if (maybePart?.__myfieldSdkType === BINARY_PART_MARKER) {
282
- const partIndex = maybePart.part;
283
- if (typeof partIndex !== "number" || !Number.isSafeInteger(partIndex) || partIndex < 0 || partIndex >= parts.length) throw new Error("invalid binary part reference");
284
- const bytes = parts[partIndex];
285
- if (!bytes) throw new Error("missing binary part");
286
- if (typeof maybePart.size !== "number" || maybePart.size !== bytes.byteLength) throw new Error("binary part size mismatch");
287
- const stored: StoredBinaryValue = {
288
- __myfieldSdkType: "binary-v1",
289
- size: bytes.byteLength,
290
- bytes,
291
- ...(typeof maybePart.mimeType === "string" && maybePart.mimeType ? { mimeType: maybePart.mimeType } : {}),
292
- ...(typeof maybePart.name === "string" && maybePart.name ? { name: maybePart.name } : {}),
293
- ...(typeof maybePart.lastModified === "number" && Number.isFinite(maybePart.lastModified) ? { lastModified: maybePart.lastModified } : {}),
294
- };
295
- return cloneStoredBinaryValue(stored);
296
- }
297
- if (Array.isArray(value)) return value.map((item) => decodeHeaderValue(item, parts));
298
- if (value && typeof value === "object") {
299
- return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, decodeHeaderValue(item, parts)]));
300
- }
301
- return value;
302
- }
303
-
304
- function writeU32(bytes: Uint8Array, offset: number, value: number): void {
305
- if (!Number.isSafeInteger(value) || value < 0 || value > 0xffffffff) throw new Error("uint32 out of range");
306
- bytes[offset] = (value >>> 24) & 255;
307
- bytes[offset + 1] = (value >>> 16) & 255;
308
- bytes[offset + 2] = (value >>> 8) & 255;
309
- bytes[offset + 3] = value & 255;
310
- }
311
-
312
- function readU32(bytes: Uint8Array, offset: number): number {
313
- return ((bytes[offset] ?? 0) * 0x1000000) + (((bytes[offset + 1] ?? 0) << 16) | ((bytes[offset + 2] ?? 0) << 8) | (bytes[offset + 3] ?? 0));
314
- }
315
-
316
- function isLwwFieldEntry(value: unknown): value is LwwFieldEntry {
317
- const row = value as Partial<LwwFieldEntry> | null;
318
- return !!row && typeof row.ts === "number" && Number.isFinite(row.ts) && typeof row.actor === "string" && "v" in row;
319
- }
320
-
321
- function isLwwTombstone(value: unknown): value is LwwTombstone {
322
- const row = value as Partial<LwwTombstone> | null;
323
- return !!row && typeof row.ts === "number" && Number.isFinite(row.ts) && typeof row.actor === "string";
324
- }
@@ -1,40 +0,0 @@
1
- export {
2
- PAYLOAD_FORMAT_VERSION,
3
- emptyLwwMapDoc,
4
- encodePayloadDoc,
5
- decodePayloadDoc,
6
- mergeLwwMapDocs,
7
- lwwMapValues,
8
- lwwMapDocsEqual,
9
- applyLwwMapUpdates,
10
- LwwClock,
11
- type LwwMapDoc,
12
- type LwwFieldEntry,
13
- type LwwTombstone,
14
- type OpaqueDoc,
15
- type PayloadDoc,
16
- } from "./format.ts";
17
- export {
18
- deriveBucketKeysFromRaw,
19
- unwrapBucketKeys,
20
- ID_BLINDING_SALT,
21
- ID_BLINDING_INFO_PREFIX,
22
- WIRE_ID_PREFIX,
23
- WIRE_ID_HEX_LENGTH,
24
- type BucketKeys,
25
- type BucketKeyGrantEnvelope,
26
- } from "./keys.ts";
27
- export { encryptEnvelopeFields, decryptEnvelope, type EncryptedEnvelopeFields } from "./crypto.ts";
28
- export {
29
- BucketTransport,
30
- BucketTransportError,
31
- type BucketTransportOptions,
32
- type SessionCredential,
33
- type SessionProvider,
34
- type TransportHeadResult,
35
- type TransportPayloadResult,
36
- type TransportPullResult,
37
- type TransportPushResult,
38
- } from "./transport.ts";
39
- export { createMemoryStorageAdapter, createIndexedDbStorageAdapter, type StorageAdapter } from "./store.ts";
40
- export { BucketClient, type BucketClientOptions, type BucketTransportLike, type MergeStrategy } from "./client.ts";
@@ -1,104 +0,0 @@
1
- // Bucket key material. The callback-provided bucket access grant wraps a raw
2
- // 256-bit bucket key to the instance wrapping key (ECDH + HKDF + AES-GCM).
3
- // The SDK unwraps the raw bytes once, derives two independent subkeys, and
4
- // discards the raw bytes:
5
- // - payload key: AES-GCM-256 for object payload envelopes (wire compatible
6
- // with the established bucket sync envelope format).
7
- // - object-id key: HMAC-SHA-256 for deterministic object-id blinding.
8
- //
9
- // Id derivation is part of the SDK bucket format contract: every SDK
10
- // version/language must derive identical wire ids for the same bucket.
11
- // idKey = HKDF-SHA-256(ikm = raw bucket key, salt = "myfield.sdk.v1",
12
- // info = "object-id|" + bucketId)
13
- // wireId = "ob_" + hex(HMAC-SHA-256(idKey, utf8(appObjectId)))[0..32)
14
-
15
- import { b64urlToBytes, bytesToHex, utf8Encode } from "../internal/encoding.ts";
16
-
17
- export const ID_BLINDING_SALT = "myfield.sdk.v1";
18
- export const ID_BLINDING_INFO_PREFIX = "object-id|";
19
- export const WIRE_ID_PREFIX = "ob_";
20
- export const WIRE_ID_HEX_LENGTH = 32;
21
-
22
- export type BucketKeys = {
23
- bucketId: string;
24
- keyId: string;
25
- payloadKey: CryptoKey;
26
- wireObjectId: (appObjectId: string) => Promise<string>;
27
- };
28
-
29
- export type BucketKeyGrantEnvelope = {
30
- kind: "bucket-key";
31
- bucketId: string;
32
- keyId: string;
33
- targetInstanceId: string;
34
- targetWrappingPublicJwk: JsonWebKey;
35
- ephemeralPublicJwk: JsonWebKey;
36
- wrapAlg: "ECDH-HKDF-SHA-256/AES-GCM-256";
37
- salt: string;
38
- iv: string;
39
- aad: string;
40
- ciphertext: string;
41
- };
42
-
43
- export async function deriveBucketKeysFromRaw(bucketId: string, keyId: string, rawKey: Uint8Array): Promise<BucketKeys> {
44
- if (rawKey.length !== 32) throw new Error("bucket key must be 256-bit");
45
- const rawBuffer = rawKey.buffer.slice(rawKey.byteOffset, rawKey.byteOffset + rawKey.byteLength) as ArrayBuffer;
46
- const payloadKey = await crypto.subtle.importKey("raw", rawBuffer, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
47
- const hkdfMaterial = await crypto.subtle.importKey("raw", rawBuffer, "HKDF", false, ["deriveKey"]);
48
- const idKey = await crypto.subtle.deriveKey(
49
- {
50
- name: "HKDF",
51
- hash: "SHA-256",
52
- salt: utf8Encode(ID_BLINDING_SALT),
53
- info: utf8Encode(`${ID_BLINDING_INFO_PREFIX}${bucketId}`),
54
- },
55
- hkdfMaterial,
56
- { name: "HMAC", hash: "SHA-256" },
57
- false,
58
- ["sign"]
59
- );
60
- const wireIdCache = new Map<string, string>();
61
- return {
62
- bucketId,
63
- keyId,
64
- payloadKey,
65
- async wireObjectId(appObjectId: string): Promise<string> {
66
- const safe = String(appObjectId || "");
67
- if (!safe) throw new Error("objectId required");
68
- const cached = wireIdCache.get(safe);
69
- if (cached) return cached;
70
- const mac = new Uint8Array(await crypto.subtle.sign("HMAC", idKey, utf8Encode(safe)));
71
- const wireId = `${WIRE_ID_PREFIX}${bytesToHex(mac).slice(0, WIRE_ID_HEX_LENGTH)}`;
72
- wireIdCache.set(safe, wireId);
73
- return wireId;
74
- },
75
- };
76
- }
77
-
78
- // Unwraps the raw bucket key from a grant envelope, derives the subkeys, and
79
- // lets the raw bytes go out of scope. Uses decrypt (not unwrapKey) because the
80
- // raw bytes are needed as HKDF input for the id key.
81
- export async function unwrapBucketKeys(envelope: BucketKeyGrantEnvelope, instanceWrappingPrivateKey: CryptoKey): Promise<BucketKeys> {
82
- const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
83
- const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, instanceWrappingPrivateKey, 256);
84
- const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
85
- const wrappingKey = await crypto.subtle.deriveKey(
86
- { name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt) as BufferSource, info: utf8Encode(envelope.aad) },
87
- material,
88
- { name: "AES-GCM", length: 256 },
89
- false,
90
- ["decrypt"]
91
- );
92
- const raw = new Uint8Array(
93
- await crypto.subtle.decrypt(
94
- { name: "AES-GCM", iv: b64urlToBytes(envelope.iv) as BufferSource, additionalData: utf8Encode(envelope.aad) },
95
- wrappingKey,
96
- b64urlToBytes(envelope.ciphertext) as BufferSource
97
- )
98
- );
99
- try {
100
- return await deriveBucketKeysFromRaw(envelope.bucketId, envelope.keyId, raw);
101
- } finally {
102
- raw.fill(0);
103
- }
104
- }