@aithos/sdk 0.1.0-alpha.5 → 0.1.0-alpha.51

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 (67) hide show
  1. package/README.md +245 -7
  2. package/dist/src/apps.d.ts +224 -0
  3. package/dist/src/apps.js +432 -0
  4. package/dist/src/assets.d.ts +209 -0
  5. package/dist/src/assets.js +534 -0
  6. package/dist/src/auth-api.d.ts +219 -0
  7. package/dist/src/auth-api.js +248 -0
  8. package/dist/src/auth.d.ts +543 -0
  9. package/dist/src/auth.js +937 -31
  10. package/dist/src/compute.d.ts +464 -6
  11. package/dist/src/compute.js +746 -20
  12. package/dist/src/data-schema-contacts-v1.d.ts +14 -0
  13. package/dist/src/data-schema-contacts-v1.js +28 -0
  14. package/dist/src/data.d.ts +342 -0
  15. package/dist/src/data.js +1002 -0
  16. package/dist/src/endpoints.d.ts +25 -0
  17. package/dist/src/endpoints.js +7 -0
  18. package/dist/src/ethos.d.ts +85 -0
  19. package/dist/src/ethos.js +463 -7
  20. package/dist/src/index.d.ts +17 -6
  21. package/dist/src/index.js +25 -3
  22. package/dist/src/internal/delegate-bundle.js +7 -2
  23. package/dist/src/internal/envelope.d.ts +93 -0
  24. package/dist/src/internal/envelope.js +59 -0
  25. package/dist/src/mandates.d.ts +111 -2
  26. package/dist/src/mandates.js +150 -7
  27. package/dist/src/react/AithosAsset.d.ts +66 -0
  28. package/dist/src/react/AithosAsset.js +67 -0
  29. package/dist/src/react/context.d.ts +29 -0
  30. package/dist/src/react/context.js +31 -0
  31. package/dist/src/react/index.d.ts +29 -0
  32. package/dist/src/react/index.js +31 -0
  33. package/dist/src/react/use-aithos-asset.d.ts +39 -0
  34. package/dist/src/react/use-aithos-asset.js +118 -0
  35. package/dist/src/react/use-transcribe-pending.d.ts +21 -0
  36. package/dist/src/react/use-transcribe-pending.js +47 -0
  37. package/dist/src/sdk.d.ts +10 -0
  38. package/dist/src/sdk.js +22 -0
  39. package/dist/src/transcribe-resilience.d.ts +57 -0
  40. package/dist/src/transcribe-resilience.js +203 -0
  41. package/dist/src/web.d.ts +279 -0
  42. package/dist/src/web.js +186 -0
  43. package/dist/test/auth-j3.test.js +32 -1
  44. package/dist/test/canonical-conformance.test.d.ts +2 -0
  45. package/dist/test/canonical-conformance.test.js +86 -0
  46. package/dist/test/compute-delegate-path.test.d.ts +2 -0
  47. package/dist/test/compute-delegate-path.test.js +183 -0
  48. package/dist/test/compute.test.js +4 -0
  49. package/dist/test/endpoints.test.js +30 -1
  50. package/dist/test/envelope-core-conformance.test.d.ts +2 -0
  51. package/dist/test/envelope-core-conformance.test.js +75 -0
  52. package/dist/test/envelope.test.d.ts +2 -0
  53. package/dist/test/envelope.test.js +318 -0
  54. package/dist/test/ethos-first-edition.test.d.ts +2 -0
  55. package/dist/test/ethos-first-edition.test.js +371 -0
  56. package/dist/test/mandates-compute.test.d.ts +2 -0
  57. package/dist/test/mandates-compute.test.js +256 -0
  58. package/dist/test/sdk.test.js +11 -2
  59. package/dist/test/signup-bootstrap.test.d.ts +2 -0
  60. package/dist/test/signup-bootstrap.test.js +311 -0
  61. package/dist/test/transcribe-invoke.test.d.ts +2 -0
  62. package/dist/test/transcribe-invoke.test.js +204 -0
  63. package/dist/test/transcribe.test.d.ts +2 -0
  64. package/dist/test/transcribe.test.js +186 -0
  65. package/dist/test/web.test.d.ts +2 -0
  66. package/dist/test/web.test.js +270 -0
  67. package/package.json +20 -3
@@ -0,0 +1,1002 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Mathieu Colla
3
+ /**
4
+ * `sdk.data` — high-level API for the Aithos data sub-protocol PDS.
5
+ *
6
+ * The Aithos data sub-protocol stores operational records (contacts,
7
+ * messages, ...) under a subject's identity, encrypted client-side,
8
+ * accessible to authorized apps via signed mandates. This module is the
9
+ * ergonomic façade developers consume:
10
+ *
11
+ * const client = createDataClient({ pdsUrl, did, sphereSeed });
12
+ * const contacts = client.collection("contacts");
13
+ * const id = await contacts.insert({ name: "Jean", phone: "+33..." });
14
+ * const list = await contacts.list({ filter: { status: "lead" } });
15
+ *
16
+ * Under the hood the module handles: envelope signing per spec §11,
17
+ * CMK / DEK lifecycle (generate, wrap, unwrap), per-record AEAD
18
+ * encryption, split between indexable metadata (server-visible) and
19
+ * encrypted payload (server-blind), JSON-RPC dispatch.
20
+ *
21
+ * It does not (yet) handle: mandate-delegate authentication on the
22
+ * caller side (the SDK only signs as owner in v0.1), full schema
23
+ * publication (no `registerSchema` RPC yet — that lands with A2b, cf.
24
+ * aithos-protocol/PLAN-A2b-schema-self-registration.md), forward-secrecy
25
+ * CMK rotation primitives. Those land in later Sub-jalons.
26
+ *
27
+ * Apps that need to use a vendor schema (`aithos.x.<vendor>.<name>.v<N>`,
28
+ * or any non-`aithos.*` namespace) pass their schema definitions to
29
+ * `createDataClient({ schemas: [...] })`. The PDS accepts these at face
30
+ * value (no server-side metadata validation pending A2b); the SDK uses
31
+ * the supplied schema definitions to split records into indexable
32
+ * metadata and encrypted payload.
33
+ *
34
+ * Spec ref: spec/data/01..10 of the aithos-protocol repo.
35
+ */
36
+ import { x25519 } from "@noble/curves/ed25519.js";
37
+ import { hkdf } from "@noble/hashes/hkdf.js";
38
+ import { sha256, sha512 } from "@noble/hashes/sha2.js";
39
+ import { XChaCha20Poly1305 } from "@stablelib/xchacha20poly1305";
40
+ import * as ed from "@noble/ed25519";
41
+ import { multibaseToEd25519PublicKey, edPubToX25519Pub, } from "@aithos/protocol-client";
42
+ import { canonicalize } from "@aithos/protocol-core/canonical";
43
+ import { contactsV1 } from "./data-schema-contacts-v1.js";
44
+ import { DEFAULT_SDK_ENDPOINTS } from "./endpoints.js";
45
+ import { signOwnerEnvelope } from "./internal/envelope.js";
46
+ // noble/ed25519 v2 needs sha512 wired in for sync sign/verify
47
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
+ ed.etc.sha512Sync = (...m) =>
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
+ sha512(ed.etc.concatBytes(...m));
51
+ /* -------------------------------------------------------------------------- */
52
+ /* Schema registry (local) */
53
+ /* -------------------------------------------------------------------------- */
54
+ const SCHEMAS = new Map([
55
+ [contactsV1.schema, contactsV1],
56
+ ]);
57
+ /* -------------------------------------------------------------------------- */
58
+ /* Public factory */
59
+ /* -------------------------------------------------------------------------- */
60
+ export function createDataClient(args) {
61
+ return new DataClientImpl(args);
62
+ }
63
+ /**
64
+ * Build a read-only data client that reads a subject's collections under
65
+ * a mandate (delegate path). The returned {@link ReadonlyDataClient}
66
+ * signs every request as the delegate (bare-multibase verificationMethod
67
+ * + the mandate attached to the envelope), and decrypts records using the
68
+ * CMK the owner re-wrapped for this delegate via
69
+ * {@link DataClient.authorizeDelegate}.
70
+ *
71
+ * Writes are not available on the returned type and throw `-32042` if
72
+ * forced.
73
+ */
74
+ export function createDelegateDataClient(args) {
75
+ const granteePubMb = args.granteePubkeyMultibase ??
76
+ args.mandate.grantee?.pubkey;
77
+ if (!granteePubMb) {
78
+ throw new Error("createDelegateDataClient: mandate.grantee.pubkey is missing; pass granteePubkeyMultibase explicitly");
79
+ }
80
+ return new DataClientImpl({
81
+ pdsUrl: args.pdsUrl,
82
+ did: args.subjectDid,
83
+ // In delegate mode the seed is used only to derive the X25519 key that
84
+ // unwraps the re-wrapped CMK; envelope signing goes through the
85
+ // delegate path (buildSignedEnvelope), never signOwnerEnvelope.
86
+ sphereSeed: args.delegateSeed,
87
+ verificationMethod: granteePubMb,
88
+ ...(args.schemas ? { schemas: args.schemas } : {}),
89
+ ...(args.fetch ? { fetch: args.fetch } : {}),
90
+ delegate: {
91
+ delegateSeed: args.delegateSeed,
92
+ granteePubkeyMultibase: granteePubMb,
93
+ mandate: args.mandate,
94
+ },
95
+ });
96
+ }
97
+ /**
98
+ * Build an **append-only** data client from a `data.<collection>.append`
99
+ * mandate. The returned {@link AppendOnlyDataClient} can ONLY `insert`: it
100
+ * seals each record's DEK to the owner's public key (never the CMK), so it
101
+ * holds no read capability — it cannot decrypt anything in the collection,
102
+ * not even its own deposit. The PDS additionally enforces the append scope
103
+ * (insert allowed; get/list/update/delete refused).
104
+ */
105
+ export function createAppendDataClient(args) {
106
+ const granteePubMb = args.granteePubkeyMultibase ??
107
+ args.mandate.grantee?.pubkey;
108
+ if (!granteePubMb) {
109
+ throw new Error("createAppendDataClient: mandate.grantee.pubkey is missing; pass granteePubkeyMultibase explicitly");
110
+ }
111
+ const ownerKexPublicKey = edPubToX25519Pub(multibaseToEd25519PublicKey(args.ownerDataPubkeyMultibase));
112
+ const impl = new DataClientImpl({
113
+ pdsUrl: args.pdsUrl,
114
+ did: args.subjectDid,
115
+ // In deposit mode the seed signs envelopes; it is NEVER used to unwrap a
116
+ // CMK (the deposit client has none).
117
+ sphereSeed: args.delegateSeed,
118
+ verificationMethod: granteePubMb,
119
+ schemas: [args.schema, ...(args.schemas ?? [])],
120
+ ...(args.fetch ? { fetch: args.fetch } : {}),
121
+ deposit: {
122
+ delegateSeed: args.delegateSeed,
123
+ granteePubkeyMultibase: granteePubMb,
124
+ mandate: args.mandate,
125
+ ownerKexPublicKey,
126
+ ownerKexDidUrl: `${args.subjectDid}#data-kex`,
127
+ },
128
+ });
129
+ const defaultSchema = args.schema;
130
+ return {
131
+ collection(name) {
132
+ const state = impl._depositCollectionState(name, defaultSchema);
133
+ return {
134
+ name,
135
+ insert: (record) => impl._insertDeposit(state, record),
136
+ };
137
+ },
138
+ reset: () => impl.reset(),
139
+ };
140
+ }
141
+ class DataClientImpl {
142
+ #pdsUrl;
143
+ #did;
144
+ #seed;
145
+ #vm;
146
+ #fetch;
147
+ /** Delegate session, or undefined for the owner path. */
148
+ #delegate;
149
+ /** Deposit (append-only) session, or undefined. Mutually exclusive with
150
+ * {@link DataClientImpl.#delegate}. */
151
+ #deposit;
152
+ /**
153
+ * Per-client schema overrides, populated from `args.schemas` at
154
+ * construction. Looked up BEFORE the bundled SCHEMAS map (so an app
155
+ * can override a core schema locally if it really wants to, though
156
+ * the immutability rule of spec §3.5 strongly discourages this).
157
+ */
158
+ #localSchemas;
159
+ // Per-collection CMK cache: cleared on reset()
160
+ #cmkCache = new Map();
161
+ #colCache = new Map();
162
+ constructor(args) {
163
+ this.#pdsUrl = (args.pdsUrl ?? DEFAULT_SDK_ENDPOINTS.pds).replace(/\/$/, "");
164
+ this.#did = args.did;
165
+ this.#seed = args.sphereSeed;
166
+ this.#vm = args.verificationMethod;
167
+ this.#fetch = args.fetch ?? globalThis.fetch.bind(globalThis);
168
+ if (args.delegate)
169
+ this.#delegate = args.delegate;
170
+ if (args.deposit)
171
+ this.#deposit = args.deposit;
172
+ this.#localSchemas = new Map((args.schemas ?? []).map((s) => [s.schema, s]));
173
+ }
174
+ /** Throw a read-only error when a mutating verb is called on a delegate
175
+ * client. The PDS rejects these server-side too; this is the fast,
176
+ * local guard with a precise message. */
177
+ #assertOwner(op) {
178
+ if (this.#delegate) {
179
+ const e = new Error(`sdk.data: "${op}" is not permitted for a delegate client (read-only mandate). ` +
180
+ `A data.<collection>.read mandate grants get/list only; writes require the owner ` +
181
+ `or a data.<collection>.write mandate (not yet supported on the delegate path).`);
182
+ e.code = -32042;
183
+ throw e;
184
+ }
185
+ }
186
+ /**
187
+ * Resolve a schema id to its lite definition. App-supplied schemas
188
+ * (via `createDataClient({ schemas })`) take precedence over the
189
+ * SDK-bundled core registry.
190
+ */
191
+ #resolveSchema(schemaId) {
192
+ return this.#localSchemas.get(schemaId) ?? SCHEMAS.get(schemaId) ?? null;
193
+ }
194
+ collection(name) {
195
+ return new DataCollectionImpl(this, name);
196
+ }
197
+ async authorizeDelegate(args) {
198
+ this.#assertOwner("authorizeDelegate");
199
+ const granteePubMb = args.mandate.grantee?.pubkey;
200
+ if (!granteePubMb) {
201
+ throw new Error("sdk.data.authorizeDelegate: mandate.grantee.pubkey is required (data read mandates bind to a grantee key).");
202
+ }
203
+ // Ensure we hold the collection's CMK (owner unwrap path).
204
+ const state = await this._ensureCollection(args.collectionName);
205
+ const cmk = this.#cmkCache.get(args.collectionName);
206
+ if (!cmk) {
207
+ throw new Error(`sdk.data.authorizeDelegate: CMK for "${args.collectionName}" not loaded`);
208
+ }
209
+ // Derive the grantee's X25519 wrap-recipient key from its Ed25519
210
+ // public key (the same birational map the owner uses for its own key).
211
+ const granteeEdPub = multibaseToEd25519PublicKey(granteePubMb);
212
+ const granteeX25519Pub = edPubToX25519Pub(granteeEdPub);
213
+ const recipientDidUrl = delegateRecipientDidUrl(granteePubMb);
214
+ const wrap = this.#wrapCmkForRecipient({
215
+ cmk,
216
+ recipientPublicKey: granteeX25519Pub,
217
+ recipientDidUrl,
218
+ collectionUrn: state.urn,
219
+ });
220
+ await this.#call("/mcp/primitives/write", "aithos.data.authorize_app", {
221
+ collection_urn: state.urn,
222
+ mandate: args.mandate,
223
+ wrap,
224
+ });
225
+ }
226
+ async revokeDelegate(args) {
227
+ this.#assertOwner("revokeDelegate");
228
+ await this.#call("/mcp/primitives/write", "aithos.data.revoke_app", {
229
+ collection_urn: this.#collectionUrn(args.collectionName),
230
+ mandate_id: args.mandateId,
231
+ ...(args.reason ? { revocation: { reason: args.reason } } : {}),
232
+ });
233
+ }
234
+ async createCollection(args) {
235
+ this.#assertOwner("createCollection");
236
+ const cmk = randomBytes32();
237
+ const recipientDidUrl = `${this.#did}#data-kex`;
238
+ const collectionUrn = this.#collectionUrn(args.name);
239
+ const recipientPublic = ed25519SeedToX25519PublicKey(this.#seed);
240
+ const wrap = this.#wrapCmkForRecipient({
241
+ cmk,
242
+ recipientPublicKey: recipientPublic,
243
+ recipientDidUrl,
244
+ collectionUrn,
245
+ });
246
+ try {
247
+ await this.#call("/mcp/primitives/write", "aithos.data.create_collection", {
248
+ subject_did: this.#did,
249
+ collection_name: args.name,
250
+ schema: args.schema,
251
+ ...(args.forwardSecrecy ? { forward_secrecy: args.forwardSecrecy } : {}),
252
+ cmk_envelope: {
253
+ alg: "xchacha20poly1305-ietf",
254
+ wraps: [wrap],
255
+ },
256
+ });
257
+ // Cache CMK in memory for subsequent ops on this collection.
258
+ this.#cmkCache.set(args.name, cmk);
259
+ }
260
+ finally {
261
+ // CMK is retained in cache, only zero the local var if we didn't cache.
262
+ }
263
+ }
264
+ async ensureCollection(args) {
265
+ this.#assertOwner("ensureCollection");
266
+ try {
267
+ await this.createCollection(args);
268
+ }
269
+ catch (e) {
270
+ // -32073 AITHOS_DATA_COLLECTION_EXISTS → already created (possibly by a
271
+ // concurrent caller). That's the success case for get-or-create. Any
272
+ // other error propagates.
273
+ if (e.code === -32073)
274
+ return;
275
+ throw e;
276
+ }
277
+ }
278
+ async listCollections() {
279
+ const r = await this.#call("/mcp/primitives/read", "aithos.data.list_collections", {
280
+ subject_did: this.#did,
281
+ });
282
+ const items = r.items ?? [];
283
+ return items.map((c) => ({
284
+ name: c.name,
285
+ schema: c.schema,
286
+ record_count: c.record_count,
287
+ }));
288
+ }
289
+ async listGammaEntries(opts = {}) {
290
+ const params = { subject_did: this.#did };
291
+ if (opts.limit !== undefined)
292
+ params.limit = opts.limit;
293
+ if (opts.opPrefix)
294
+ params.op_prefix = opts.opPrefix;
295
+ if (opts.verify)
296
+ params.verify = true;
297
+ return this.#call("/mcp/primitives/read", "aithos.data.list_gamma_entries", params);
298
+ }
299
+ async registerSchema(schemaDoc) {
300
+ this.#assertOwner("registerSchema");
301
+ if (schemaDoc === null || typeof schemaDoc !== "object" || Array.isArray(schemaDoc)) {
302
+ throw new Error("sdk.data.registerSchema: schemaDoc must be a JSON object");
303
+ }
304
+ const r = (await this.#call("/mcp/primitives/write", "aithos.data.register_schema", {
305
+ subject_did: this.#did,
306
+ schema_doc: schemaDoc,
307
+ }));
308
+ return {
309
+ schemaId: r.schema_id,
310
+ docHash: r.doc_hash,
311
+ created: r.created,
312
+ ...(r.created_at ? { createdAt: r.created_at } : {}),
313
+ };
314
+ }
315
+ async getSchema(schemaId, opts = {}) {
316
+ const params = { schema: schemaId };
317
+ // Vendor schemas always need a subject_did to address the right
318
+ // registry ; for core schemas the PDS ignores it but we still send
319
+ // ours so the auth check (envelope iss === subject_did) lines up.
320
+ params.subject_did = opts.subjectDid ?? this.#did;
321
+ try {
322
+ const r = (await this.#call("/mcp/primitives/read", "aithos.data.get_schema", params));
323
+ return r.schema;
324
+ }
325
+ catch (e) {
326
+ if (e.code === -32070)
327
+ return null;
328
+ throw e;
329
+ }
330
+ }
331
+ reset() {
332
+ for (const k of this.#cmkCache.values())
333
+ k.fill(0);
334
+ this.#cmkCache.clear();
335
+ this.#colCache.clear();
336
+ }
337
+ /* -- Internals used by DataCollection -- */
338
+ async _ensureCollection(name) {
339
+ const cached = this.#colCache.get(name);
340
+ if (cached)
341
+ return cached;
342
+ // Fetch metadata from PDS
343
+ const meta = (await this.#call("/mcp/primitives/read", "aithos.data.get_collection", {
344
+ subject_did: this.#did,
345
+ collection_name: name,
346
+ }));
347
+ // Defensive structural validation — some PDS responses have been
348
+ // observed (alpha.27 era) returning a meta object that lacks
349
+ // `cmk_envelope` for missing collections, instead of the documented
350
+ // -32020 JSON-RPC error. Without this check, the next line crashes
351
+ // with "Cannot read properties of undefined (reading 'wraps')" which
352
+ // bypasses the upper-layer's missing-collection handling. We re-emit
353
+ // a clean -32020 here so callers can detect "collection not found"
354
+ // uniformly.
355
+ if (!meta ||
356
+ !meta.cmk_envelope ||
357
+ !Array.isArray(meta.cmk_envelope.wraps) ||
358
+ !meta.urn ||
359
+ !meta.schema) {
360
+ const err = new Error(`sdk.data: collection "${name}" not found or malformed ` +
361
+ `(meta missing required field). PDS returned: ${JSON.stringify(meta).slice(0, 200)}`);
362
+ err.code = -32020;
363
+ throw err;
364
+ }
365
+ // Look up our wrap and unwrap the CMK. Owner: the wrap addressed to
366
+ // `${did}#data-kex`, unwrapped with the owner sphere seed. Delegate:
367
+ // the wrap the owner re-wrapped for this grantee
368
+ // (`did:key:${granteePubkeyMultibase}#data-kex`), unwrapped with the
369
+ // delegate's own X25519 key (derived from its grantee seed).
370
+ const ourRecipient = this.#delegate
371
+ ? delegateRecipientDidUrl(this.#delegate.granteePubkeyMultibase)
372
+ : `${this.#did}#data-kex`;
373
+ const wrap = meta.cmk_envelope.wraps.find((w) => w.recipient === ourRecipient);
374
+ if (!wrap) {
375
+ throw new Error(this.#delegate
376
+ ? `sdk.data: no CMK wrap for ${ourRecipient} in collection "${name}". ` +
377
+ `The owner has not authorized this delegate on the collection yet — ` +
378
+ `ask them to call sdk.data...authorizeDelegate({ collectionName, mandate }).`
379
+ : `sdk.data: no CMK wrap for ${ourRecipient} in collection ${name}. The collection was either created with a different recipient, or this client is not the owner.`);
380
+ }
381
+ const unwrapSeed = this.#delegate ? this.#delegate.delegateSeed : this.#seed;
382
+ const cmk = this.#unwrapCmk({
383
+ wrap,
384
+ collectionUrn: meta.urn,
385
+ privateKey: ed25519SeedToX25519PrivateKey(unwrapSeed),
386
+ });
387
+ this.#cmkCache.set(name, cmk);
388
+ const schema = this.#resolveSchema(meta.schema);
389
+ if (!schema) {
390
+ throw new Error(`sdk.data: schema "${meta.schema}" not known to the SDK. ` +
391
+ `Pass it via createDataClient({ schemas: [...] }) if it's an ` +
392
+ `app-defined (vendor) schema, or upgrade the SDK if it's a core ` +
393
+ `schema added in a later release.`);
394
+ }
395
+ const state = { name, urn: meta.urn, schema };
396
+ this.#colCache.set(name, state);
397
+ return state;
398
+ }
399
+ async _insert(state, record) {
400
+ this.#assertOwner("insert");
401
+ const cmk = this.#cmkCache.get(state.name);
402
+ if (!cmk)
403
+ throw new Error("CMK not loaded");
404
+ const { metadata, payload } = splitRecord(record, state.schema);
405
+ const recordId = `record_${makeUlid()}`;
406
+ const encrypted = this.#encryptPayload({
407
+ collectionName: state.name,
408
+ recordId,
409
+ payload,
410
+ cmk,
411
+ });
412
+ const r = (await this.#call("/mcp/primitives/write", "aithos.data.insert_record", {
413
+ collection_urn: state.urn,
414
+ record_id: recordId,
415
+ metadata,
416
+ payload: encrypted,
417
+ }));
418
+ return r.record_id;
419
+ }
420
+ async _get(state, recordId) {
421
+ let raw;
422
+ try {
423
+ raw = await this.#call("/mcp/primitives/read", "aithos.data.get_record", {
424
+ collection_urn: state.urn,
425
+ record_id: recordId,
426
+ });
427
+ }
428
+ catch (e) {
429
+ if (e.code === -32020)
430
+ return null;
431
+ throw e;
432
+ }
433
+ return this.#decryptRecord(state, raw);
434
+ }
435
+ async _list(state, opts = {}) {
436
+ const params = {
437
+ collection_urn: state.urn,
438
+ };
439
+ if (opts.filter)
440
+ params.filter = opts.filter;
441
+ if (opts.order)
442
+ params.order = opts.order;
443
+ if (opts.limit !== undefined)
444
+ params.limit = opts.limit;
445
+ if (opts.cursor)
446
+ params.cursor = opts.cursor;
447
+ const r = (await this.#call("/mcp/primitives/read", "aithos.data.list_records", params));
448
+ // A read/write delegate (CMK-holder) cannot decrypt append-only deposits
449
+ // (sealed to the owner key). Skip them rather than crash the whole list —
450
+ // the owner reading the same collection decrypts everything. -32044 is the
451
+ // client-side "deposit unreadable by this session" marker.
452
+ const items = [];
453
+ for (const it of r.items) {
454
+ try {
455
+ items.push(this.#decryptRecord(state, it));
456
+ }
457
+ catch (e) {
458
+ if (e.code === -32044)
459
+ continue;
460
+ throw e;
461
+ }
462
+ }
463
+ return {
464
+ items,
465
+ ...(r.next_cursor ? { nextCursor: r.next_cursor } : {}),
466
+ };
467
+ }
468
+ async _update(state, recordId, record) {
469
+ this.#assertOwner("update");
470
+ const cmk = this.#cmkCache.get(state.name);
471
+ if (!cmk)
472
+ throw new Error("CMK not loaded");
473
+ const { metadata, payload } = splitRecord(record, state.schema);
474
+ const encrypted = this.#encryptPayload({
475
+ collectionName: state.name,
476
+ recordId,
477
+ payload,
478
+ cmk,
479
+ });
480
+ await this.#call("/mcp/primitives/write", "aithos.data.update_record", {
481
+ collection_urn: state.urn,
482
+ record_id: recordId,
483
+ metadata,
484
+ payload: encrypted,
485
+ });
486
+ }
487
+ async _delete(state, recordId) {
488
+ this.#assertOwner("delete");
489
+ await this.#call("/mcp/primitives/write", "aithos.data.delete_record", {
490
+ collection_urn: state.urn,
491
+ record_id: recordId,
492
+ });
493
+ }
494
+ /* -- JSON-RPC dispatch -- */
495
+ async #call(path, method, params) {
496
+ const aud = `${this.#pdsUrl}${path}`;
497
+ // Both paths use the SAME §11.2 envelope scheme (the data PDS verifies
498
+ // with @aithos/protocol-core, which canonicalizes the full envelope
499
+ // INCLUDING `proof` with proofValue=""). Delegate path: sign with the
500
+ // grantee key, bare-multibase verificationMethod, and attach the mandate
501
+ // so the PDS resolves the delegation and enforces its scopes.
502
+ // A mandate-bearing session (read-delegate OR append-deposit) signs as
503
+ // the grantee with the bare-multibase verificationMethod and attaches the
504
+ // mandate so the PDS resolves the delegation and enforces its scopes.
505
+ const mandateSession = this.#delegate ?? this.#deposit;
506
+ const envelope = mandateSession
507
+ ? await signOwnerEnvelope({
508
+ iss: this.#did, // the SUBJECT DID (mandate issuer), not the delegate
509
+ aud,
510
+ method,
511
+ params,
512
+ verificationMethod: mandateSession.granteePubkeyMultibase,
513
+ signer: {
514
+ sign: async (msg) => ed.sign(msg, mandateSession.delegateSeed),
515
+ },
516
+ mandate: mandateSession.mandate,
517
+ })
518
+ : await signOwnerEnvelope({
519
+ iss: this.#did,
520
+ aud,
521
+ method,
522
+ params,
523
+ verificationMethod: this.#vm,
524
+ signer: { sign: async (msg) => ed.sign(msg, this.#seed) },
525
+ });
526
+ const body = {
527
+ jsonrpc: "2.0",
528
+ id: makeUlid(),
529
+ method,
530
+ params: { ...params, _envelope: envelope },
531
+ };
532
+ const r = await this.#fetch(aud, {
533
+ method: "POST",
534
+ headers: { "content-type": "application/json" },
535
+ body: JSON.stringify(body),
536
+ });
537
+ const json = (await r.json());
538
+ if (json.error) {
539
+ const err = new Error(json.error.message);
540
+ err.code = json.error.code;
541
+ err.data = json.error.data;
542
+ throw err;
543
+ }
544
+ return json.result ?? {};
545
+ }
546
+ /* -- Crypto helpers -- */
547
+ #collectionUrn(name) {
548
+ return `urn:aithos:collection:${this.#did}:${name}`;
549
+ }
550
+ #wrapCmkForRecipient(args) {
551
+ const ephSk = x25519.utils.randomSecretKey();
552
+ const ephPk = x25519.getPublicKey(ephSk);
553
+ const shared = x25519.getSharedSecret(ephSk, args.recipientPublicKey);
554
+ const wrapKey = hkdf(sha256, shared, utf8("aithos-data-cmk-wrap-v1"), utf8(args.recipientDidUrl), 32);
555
+ const wrapNonce = randomBytes24();
556
+ const aad = aadCmkWrap(args.collectionUrn, args.recipientDidUrl);
557
+ const aead = new XChaCha20Poly1305(wrapKey);
558
+ const wrapped = aead.seal(wrapNonce, args.cmk, aad);
559
+ wrapKey.fill(0);
560
+ shared.fill(0);
561
+ return {
562
+ recipient: args.recipientDidUrl,
563
+ alg: "x25519-hkdf-sha256-aead",
564
+ ephemeral_public: base64Std(ephPk),
565
+ wrap_nonce: base64Std(wrapNonce),
566
+ wrapped_key: base64Std(wrapped),
567
+ };
568
+ }
569
+ #unwrapCmk(args) {
570
+ const ephPk = fromBase64(args.wrap.ephemeral_public);
571
+ const wrapNonce = fromBase64(args.wrap.wrap_nonce);
572
+ const wrappedKey = fromBase64(args.wrap.wrapped_key);
573
+ const shared = x25519.getSharedSecret(args.privateKey, ephPk);
574
+ const wrapKey = hkdf(sha256, shared, utf8("aithos-data-cmk-wrap-v1"), utf8(args.wrap.recipient), 32);
575
+ const aad = aadCmkWrap(args.collectionUrn, args.wrap.recipient);
576
+ const aead = new XChaCha20Poly1305(wrapKey);
577
+ const cmk = aead.open(wrapNonce, wrappedKey, aad);
578
+ wrapKey.fill(0);
579
+ shared.fill(0);
580
+ if (!cmk)
581
+ throw new Error("sdk.data: CMK unwrap failed (wrong key or AAD mismatch)");
582
+ return cmk;
583
+ }
584
+ #encryptPayload(args) {
585
+ const dek = randomBytes32();
586
+ try {
587
+ const plaintext = new TextEncoder().encode(jcsCanonicalize(args.payload));
588
+ const nonce = randomBytes24();
589
+ const aad = aadRecord(this.#did, args.collectionName, args.recordId);
590
+ const aead = new XChaCha20Poly1305(dek);
591
+ const ciphertext = aead.seal(nonce, plaintext, aad);
592
+ const dekWrapNonce = randomBytes24();
593
+ const dekAad = aadDekWrap(this.#did, args.collectionName, args.recordId);
594
+ const dekAead = new XChaCha20Poly1305(args.cmk);
595
+ const wrapped = dekAead.seal(dekWrapNonce, dek, dekAad);
596
+ const dekWrap = new Uint8Array(dekWrapNonce.length + wrapped.length);
597
+ dekWrap.set(dekWrapNonce, 0);
598
+ dekWrap.set(wrapped, dekWrapNonce.length);
599
+ return {
600
+ alg: "xchacha20poly1305-ietf",
601
+ nonce: base64Std(nonce),
602
+ ciphertext: base64Std(ciphertext),
603
+ dek_wrapped_for_cmk: base64Std(dekWrap),
604
+ };
605
+ }
606
+ finally {
607
+ dek.fill(0);
608
+ }
609
+ }
610
+ /**
611
+ * Seal a record's payload for the append-only deposit path: encrypt under a
612
+ * fresh DEK, then seal that DEK to the OWNER's X25519 public key (never the
613
+ * CMK). Mirrors `@aithos/data-crypto` `wrapDEKForRecipient` byte-for-byte so
614
+ * the owner (SDK or CLI) can unwrap it. The depositor keeps no key material.
615
+ */
616
+ #encryptPayloadForOwner(args) {
617
+ const dek = randomBytes32();
618
+ try {
619
+ const plaintext = new TextEncoder().encode(jcsCanonicalize(args.payload));
620
+ const nonce = randomBytes24();
621
+ const aad = aadRecord(this.#did, args.collectionName, args.recordId);
622
+ const ciphertext = new XChaCha20Poly1305(dek).seal(nonce, plaintext, aad);
623
+ // Seal the DEK to the owner's X25519 key (ECIES, fresh ephemeral).
624
+ const ephSk = x25519.utils.randomSecretKey();
625
+ const ephPk = x25519.getPublicKey(ephSk);
626
+ const shared = x25519.getSharedSecret(ephSk, args.ownerKexPublicKey);
627
+ const wrapKey = hkdf(sha256, shared, DEPOSIT_WRAP_SALT, utf8(args.ownerKexDidUrl), 32);
628
+ const wrapNonce = randomBytes24();
629
+ const wrapAad = aadDepositWrap(this.#did, args.collectionName, args.recordId, args.ownerKexDidUrl);
630
+ const wrappedKey = new XChaCha20Poly1305(wrapKey).seal(wrapNonce, dek, wrapAad);
631
+ wrapKey.fill(0);
632
+ shared.fill(0);
633
+ return {
634
+ alg: "xchacha20poly1305-ietf",
635
+ nonce: base64Std(nonce),
636
+ ciphertext: base64Std(ciphertext),
637
+ dek_wrapped_for_owner: {
638
+ recipient: args.ownerKexDidUrl,
639
+ alg: "x25519-hkdf-sha256-aead",
640
+ ephemeral_public: base64Std(ephPk),
641
+ wrap_nonce: base64Std(wrapNonce),
642
+ wrapped_key: base64Std(wrappedKey),
643
+ },
644
+ };
645
+ }
646
+ finally {
647
+ dek.fill(0);
648
+ }
649
+ }
650
+ #decryptRecord(state, raw) {
651
+ if (raw.deleted) {
652
+ // Soft-deleted record — payload was cleared.
653
+ return { ...raw.metadata, _deleted: true };
654
+ }
655
+ let dek;
656
+ if (raw.payload.dek_wrapped_for_owner) {
657
+ // Append-only deposit: the DEK is sealed to the OWNER's #data-kex key.
658
+ // Only the owner (no delegate/deposit session) can open it. A read
659
+ // delegate holds the CMK, not the owner key, so it must skip deposits.
660
+ if (this.#delegate || this.#deposit) {
661
+ const e = new Error("sdk.data: record is an append-only deposit — only the collection owner can decrypt it (this client holds a delegate/deposit mandate, not the owner key).");
662
+ e.code = -32044; // AITHOS_DATA_DEPOSIT_UNREADABLE (client-side)
663
+ throw e;
664
+ }
665
+ const w = raw.payload.dek_wrapped_for_owner;
666
+ const ownerKexSk = ed25519SeedToX25519PrivateKey(this.#seed);
667
+ try {
668
+ const ephPk = fromBase64(w.ephemeral_public);
669
+ const shared = x25519.getSharedSecret(ownerKexSk, ephPk);
670
+ const wrapKey = hkdf(sha256, shared, DEPOSIT_WRAP_SALT, utf8(w.recipient), 32);
671
+ const wrapAad = aadDepositWrap(this.#did, state.name, raw.record_id, w.recipient);
672
+ dek = new XChaCha20Poly1305(wrapKey).open(fromBase64(w.wrap_nonce), fromBase64(w.wrapped_key), wrapAad);
673
+ wrapKey.fill(0);
674
+ shared.fill(0);
675
+ }
676
+ finally {
677
+ ownerKexSk.fill(0);
678
+ }
679
+ if (!dek)
680
+ throw new Error("sdk.data: deposit DEK unwrap failed (wrong owner key or AAD mismatch)");
681
+ }
682
+ else {
683
+ // CMK path (owner / read-write delegate).
684
+ const cmk = this.#cmkCache.get(state.name);
685
+ if (!cmk) {
686
+ throw new Error("sdk.data: CMK not loaded — call ensureCollection first");
687
+ }
688
+ if (raw.payload.dek_wrapped_for_cmk === undefined) {
689
+ throw new Error("sdk.data: record payload has neither dek_wrapped_for_cmk nor dek_wrapped_for_owner");
690
+ }
691
+ const wrapBuf = fromBase64(raw.payload.dek_wrapped_for_cmk);
692
+ const wrapNonce = wrapBuf.slice(0, 24);
693
+ const wrapped = wrapBuf.slice(24);
694
+ const dekAad = aadDekWrap(this.#did, state.name, raw.record_id);
695
+ dek = new XChaCha20Poly1305(cmk).open(wrapNonce, wrapped, dekAad);
696
+ if (!dek)
697
+ throw new Error("sdk.data: DEK unwrap failed");
698
+ }
699
+ try {
700
+ const nonce = fromBase64(raw.payload.nonce);
701
+ const ciphertext = fromBase64(raw.payload.ciphertext);
702
+ const aad = aadRecord(this.#did, state.name, raw.record_id);
703
+ const aead = new XChaCha20Poly1305(dek);
704
+ const plaintext = aead.open(nonce, ciphertext, aad);
705
+ if (!plaintext)
706
+ throw new Error("sdk.data: payload decrypt failed");
707
+ const payload = JSON.parse(new TextDecoder().decode(plaintext));
708
+ return { record_id: raw.record_id, ...raw.metadata, ...payload };
709
+ }
710
+ finally {
711
+ dek.fill(0);
712
+ }
713
+ }
714
+ /**
715
+ * Append-only deposit insert. Used by the {@link createAppendDataClient}
716
+ * path: builds the record locally (no CMK, no server schema fetch — the
717
+ * caller supplies the schema), seals the DEK to the owner key, and POSTs
718
+ * `insert_record`. The PDS enforces the `data.<col>.append` scope.
719
+ */
720
+ async _insertDeposit(state, record) {
721
+ if (!this.#deposit) {
722
+ throw new Error("sdk.data: _insertDeposit called without a deposit session");
723
+ }
724
+ const { metadata, payload } = splitRecord(record, state.schema);
725
+ const recordId = `record_${makeUlid()}`;
726
+ const encrypted = this.#encryptPayloadForOwner({
727
+ collectionName: state.name,
728
+ recordId,
729
+ payload,
730
+ ownerKexPublicKey: this.#deposit.ownerKexPublicKey,
731
+ ownerKexDidUrl: this.#deposit.ownerKexDidUrl,
732
+ });
733
+ const r = (await this.#call("/mcp/primitives/write", "aithos.data.insert_record", {
734
+ collection_urn: state.urn,
735
+ record_id: recordId,
736
+ metadata,
737
+ payload: encrypted,
738
+ }));
739
+ return r.record_id;
740
+ }
741
+ /** Build a local collection state for the deposit path (no server fetch:
742
+ * append clients are not authorized to read collection metadata). */
743
+ _depositCollectionState(name, schema) {
744
+ return { name, urn: this.#collectionUrn(name), schema };
745
+ }
746
+ }
747
+ class DataCollectionImpl {
748
+ client;
749
+ name;
750
+ constructor(client, name) {
751
+ this.client = client;
752
+ this.name = name;
753
+ }
754
+ async insert(record) {
755
+ const state = await this.client._ensureCollection(this.name);
756
+ return this.client._insert(state, record);
757
+ }
758
+ async get(recordId) {
759
+ const state = await this.client._ensureCollection(this.name);
760
+ return this.client._get(state, recordId);
761
+ }
762
+ async list(opts) {
763
+ const state = await this.client._ensureCollection(this.name);
764
+ return this.client._list(state, opts);
765
+ }
766
+ async update(recordId, record) {
767
+ const state = await this.client._ensureCollection(this.name);
768
+ return this.client._update(state, recordId, record);
769
+ }
770
+ async delete(recordId) {
771
+ const state = await this.client._ensureCollection(this.name);
772
+ return this.client._delete(state, recordId);
773
+ }
774
+ }
775
+ /* -------------------------------------------------------------------------- */
776
+ /* Record split (metadata vs payload) */
777
+ /* -------------------------------------------------------------------------- */
778
+ function splitRecord(record, schema) {
779
+ const metadata = {};
780
+ const payload = {};
781
+ for (const [k, v] of Object.entries(record)) {
782
+ if (schema.auto.has(k))
783
+ continue; // server-set
784
+ if (schema.indexable.has(k)) {
785
+ metadata[k] = v;
786
+ }
787
+ else if (schema.encrypted.has(k)) {
788
+ payload[k] = v;
789
+ }
790
+ else {
791
+ // Unknown field — drop. Server will reject in any case (additionalProperties: false).
792
+ }
793
+ }
794
+ return { metadata, payload };
795
+ }
796
+ /* -------------------------------------------------------------------------- */
797
+ /* Crypto helpers */
798
+ /* -------------------------------------------------------------------------- */
799
+ function randomBytes32() {
800
+ return cryptoRandom(32);
801
+ }
802
+ function randomBytes24() {
803
+ return cryptoRandom(24);
804
+ }
805
+ /** Cross-platform CSPRNG: Web Crypto in browser, Node WebCrypto in Node 19+. */
806
+ function cryptoRandom(n) {
807
+ const buf = new Uint8Array(n);
808
+ // globalThis.crypto exists in browsers and in Node 19+
809
+ globalThis.crypto?.getRandomValues(buf);
810
+ return buf;
811
+ }
812
+ function utf8(s) {
813
+ return new TextEncoder().encode(s);
814
+ }
815
+ /**
816
+ * Recipient DID URL used for a delegate's CMK wrap. Built from the
817
+ * grantee's Ed25519 public-key multibase so that (a) the owner side
818
+ * (`authorizeDelegate`) and the delegate side (`_ensureCollection`)
819
+ * derive the EXACT same string — it's bound into the wrap AAD and the
820
+ * HKDF info, so any mismatch fails the unwrap — and (b) the string
821
+ * contains `mandate.grantee.pubkey`, which the PDS `authorize_app`
822
+ * handler requires (`wrap.recipient.includes(grantee.pubkey)`).
823
+ */
824
+ function delegateRecipientDidUrl(granteePubkeyMultibase) {
825
+ return `did:key:${granteePubkeyMultibase}#data-kex`;
826
+ }
827
+ function aadCmkWrap(collectionUrn, recipient) {
828
+ const p = utf8("aithos-data-cmk-v1\0");
829
+ const c = utf8(collectionUrn);
830
+ const sep = new Uint8Array([0]);
831
+ const r = utf8(recipient);
832
+ const out = new Uint8Array(p.length + c.length + sep.length + r.length);
833
+ let off = 0;
834
+ out.set(p, off);
835
+ off += p.length;
836
+ out.set(c, off);
837
+ off += c.length;
838
+ out.set(sep, off);
839
+ off += sep.length;
840
+ out.set(r, off);
841
+ return out;
842
+ }
843
+ function aadDekWrap(subjectDid, collectionName, recordId) {
844
+ const p = utf8("aithos-data-dek-v1\0");
845
+ return concat3WithSeps(p, subjectDid, collectionName, recordId);
846
+ }
847
+ function aadRecord(subjectDid, collectionName, recordId) {
848
+ const p = utf8("aithos-data-record-v1\0");
849
+ return concat3WithSeps(p, subjectDid, collectionName, recordId);
850
+ }
851
+ /**
852
+ * HKDF salt for the append-only deposit DEK wrap. Distinct from the CMK wrap
853
+ * salt so the two key-derivation domains never collide. MUST match
854
+ * `@aithos/data-crypto` `DEPOSIT_WRAP_SALT`.
855
+ */
856
+ const DEPOSIT_WRAP_SALT = utf8("aithos-data-dek-deposit-wrap-v1");
857
+ /**
858
+ * AAD for the deposit DEK wrap:
859
+ * "aithos-data-dek-deposit-v1\0" ‖ subject ‖ \0 ‖ collection ‖ \0 ‖
860
+ * record ‖ \0 ‖ recipient_did_url
861
+ * MUST match `@aithos/data-crypto` `aadForDepositWrap`.
862
+ */
863
+ function aadDepositWrap(subjectDid, collectionName, recordId, recipientDidUrl) {
864
+ const prefix = utf8("aithos-data-dek-deposit-v1\0");
865
+ const parts = [subjectDid, collectionName, recordId, recipientDidUrl].map(utf8);
866
+ const sep = new Uint8Array([0]);
867
+ let total = prefix.length;
868
+ for (let i = 0; i < parts.length; i++) {
869
+ total += parts[i].length + (i < parts.length - 1 ? sep.length : 0);
870
+ }
871
+ const out = new Uint8Array(total);
872
+ let off = 0;
873
+ out.set(prefix, off);
874
+ off += prefix.length;
875
+ for (let i = 0; i < parts.length; i++) {
876
+ out.set(parts[i], off);
877
+ off += parts[i].length;
878
+ if (i < parts.length - 1) {
879
+ out.set(sep, off);
880
+ off += sep.length;
881
+ }
882
+ }
883
+ return out;
884
+ }
885
+ function concat3WithSeps(prefix, a, b, c) {
886
+ const aa = utf8(a);
887
+ const bb = utf8(b);
888
+ const cc = utf8(c);
889
+ const sep = new Uint8Array([0]);
890
+ const total = prefix.length + aa.length + sep.length + bb.length + sep.length + cc.length;
891
+ const out = new Uint8Array(total);
892
+ let off = 0;
893
+ out.set(prefix, off);
894
+ off += prefix.length;
895
+ out.set(aa, off);
896
+ off += aa.length;
897
+ out.set(sep, off);
898
+ off += sep.length;
899
+ out.set(bb, off);
900
+ off += bb.length;
901
+ out.set(sep, off);
902
+ off += sep.length;
903
+ out.set(cc, off);
904
+ return out;
905
+ }
906
+ /**
907
+ * Derive a 32-byte X25519 private key from an Ed25519 seed via SHA-512
908
+ * truncation + clamping. Mirrors libsodium's
909
+ * crypto_sign_ed25519_sk_to_curve25519 for the secret-key side. Used so
910
+ * a single Ed25519 sphere seed can both sign envelopes and key-agree
911
+ * with mandate recipients.
912
+ */
913
+ function ed25519SeedToX25519PrivateKey(seed) {
914
+ if (seed.length !== 32)
915
+ throw new Error("Ed25519 seed must be 32 bytes");
916
+ const h = sha512(seed);
917
+ const sk = new Uint8Array(h.slice(0, 32));
918
+ // Clamp per X25519 spec
919
+ sk[0] = sk[0] & 248;
920
+ sk[31] = sk[31] & 127;
921
+ sk[31] = sk[31] | 64;
922
+ return sk;
923
+ }
924
+ function ed25519SeedToX25519PublicKey(seed) {
925
+ const sk = ed25519SeedToX25519PrivateKey(seed);
926
+ try {
927
+ return x25519.getPublicKey(sk);
928
+ }
929
+ finally {
930
+ sk.fill(0);
931
+ }
932
+ }
933
+ function makeUlid() {
934
+ // Lightweight ULID — millisecond timestamp + 80 bits of randomness.
935
+ // Crockford base32. For tests this is sufficient; production uses
936
+ // the canonical ulid package.
937
+ const tsBuf = new Uint8Array(6);
938
+ let ts = Date.now();
939
+ for (let i = 5; i >= 0; i--) {
940
+ tsBuf[i] = ts & 0xff;
941
+ ts = Math.floor(ts / 256);
942
+ }
943
+ const rndBuf = cryptoRandom(10);
944
+ const all = new Uint8Array(16);
945
+ all.set(tsBuf, 0);
946
+ all.set(rndBuf, 6);
947
+ const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
948
+ let bits = 0;
949
+ let value = 0;
950
+ let out = "";
951
+ for (const b of all) {
952
+ value = (value << 8) | b;
953
+ bits += 8;
954
+ while (bits >= 5) {
955
+ out += alphabet[(value >> (bits - 5)) & 0x1f];
956
+ bits -= 5;
957
+ }
958
+ }
959
+ if (bits > 0)
960
+ out += alphabet[(value << (5 - bits)) & 0x1f];
961
+ return out.slice(0, 26);
962
+ }
963
+ /** Standard base64 (with `=` padding). Browser + Node compatible. */
964
+ function base64Std(bytes) {
965
+ let bin = "";
966
+ for (let i = 0; i < bytes.length; i++)
967
+ bin += String.fromCharCode(bytes[i]);
968
+ return btoa(bin);
969
+ }
970
+ /** base64url (URL-safe, no padding). */
971
+ function base64url(bytes) {
972
+ return base64Std(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
973
+ }
974
+ function fromBase64(s) {
975
+ // Accept either standard base64 or base64url
976
+ const std = s.replace(/-/g, "+").replace(/_/g, "/");
977
+ const padded = std + "=".repeat((4 - (std.length % 4)) % 4);
978
+ const bin = atob(padded);
979
+ const out = new Uint8Array(bin.length);
980
+ for (let i = 0; i < bin.length; i++)
981
+ out[i] = bin.charCodeAt(i);
982
+ return out;
983
+ }
984
+ function sha256Hex(s) {
985
+ const d = sha256(new TextEncoder().encode(s));
986
+ let hex = "";
987
+ for (const b of d)
988
+ hex += b.toString(16).padStart(2, "0");
989
+ return hex;
990
+ }
991
+ /* -------------------------------------------------------------------------- */
992
+ /* JCS-style canonicalization (RFC 8785 subset) */
993
+ /* -------------------------------------------------------------------------- */
994
+ // Single canonicalization source of truth: @aithos/protocol-core. Kept as a
995
+ // local alias so the encryption-AAD call sites read naturally; the byte output
996
+ // is proven identical to the former hand-rolled JCS by
997
+ // test/canonical-conformance.test.ts (critical: this feeds pre-encryption
998
+ // canonicalization, so any drift would corrupt data).
999
+ function jcsCanonicalize(value) {
1000
+ return canonicalize(value);
1001
+ }
1002
+ //# sourceMappingURL=data.js.map