@aithos/sdk 0.1.0-alpha.4 → 0.1.0-alpha.41

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 (80) hide show
  1. package/README.md +211 -7
  2. package/dist/src/apps.d.ts +155 -0
  3. package/dist/src/apps.js +288 -0
  4. package/dist/src/assets.d.ts +207 -0
  5. package/dist/src/assets.js +533 -0
  6. package/dist/src/auth-api.d.ts +138 -0
  7. package/dist/src/auth-api.js +168 -0
  8. package/dist/src/auth.d.ts +536 -119
  9. package/dist/src/auth.js +1207 -152
  10. package/dist/src/compute.d.ts +251 -9
  11. package/dist/src/compute.js +293 -16
  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 +153 -0
  15. package/dist/src/data.js +670 -0
  16. package/dist/src/endpoints.d.ts +9 -0
  17. package/dist/src/endpoints.js +5 -0
  18. package/dist/src/ethos.d.ts +202 -1
  19. package/dist/src/ethos.js +821 -16
  20. package/dist/src/index.d.ts +18 -6
  21. package/dist/src/index.js +39 -6
  22. package/dist/src/internal/delegate-bundle.d.ts +18 -0
  23. package/dist/src/internal/delegate-bundle.js +94 -0
  24. package/dist/src/internal/delegate-state.d.ts +45 -0
  25. package/dist/src/internal/delegate-state.js +120 -0
  26. package/dist/src/internal/envelope.d.ts +77 -0
  27. package/dist/src/internal/envelope.js +154 -0
  28. package/dist/src/internal/owner-signers.d.ts +78 -0
  29. package/dist/src/internal/owner-signers.js +179 -0
  30. package/dist/src/internal/protocol-client-bridge.d.ts +8 -0
  31. package/dist/src/internal/protocol-client-bridge.js +20 -0
  32. package/dist/src/internal/recovery-file.d.ts +29 -0
  33. package/dist/src/internal/recovery-file.js +98 -0
  34. package/dist/src/internal/signer.d.ts +59 -0
  35. package/dist/src/internal/signer.js +86 -0
  36. package/dist/src/key-store.d.ts +128 -0
  37. package/dist/src/key-store.js +244 -0
  38. package/dist/src/mandates.d.ts +163 -1
  39. package/dist/src/mandates.js +286 -8
  40. package/dist/src/react/AithosAsset.d.ts +66 -0
  41. package/dist/src/react/AithosAsset.js +67 -0
  42. package/dist/src/react/context.d.ts +29 -0
  43. package/dist/src/react/context.js +31 -0
  44. package/dist/src/react/index.d.ts +28 -0
  45. package/dist/src/react/index.js +30 -0
  46. package/dist/src/react/use-aithos-asset.d.ts +39 -0
  47. package/dist/src/react/use-aithos-asset.js +118 -0
  48. package/dist/src/sdk.d.ts +46 -3
  49. package/dist/src/sdk.js +49 -23
  50. package/dist/src/wallet.d.ts +4 -6
  51. package/dist/src/wallet.js +18 -8
  52. package/dist/src/web.d.ts +279 -0
  53. package/dist/src/web.js +186 -0
  54. package/dist/test/auth-j3.test.d.ts +2 -0
  55. package/dist/test/auth-j3.test.js +391 -0
  56. package/dist/test/compute-delegate-path.test.d.ts +2 -0
  57. package/dist/test/compute-delegate-path.test.js +183 -0
  58. package/dist/test/compute.test.js +26 -11
  59. package/dist/test/endpoints.test.js +20 -1
  60. package/dist/test/envelope.test.d.ts +2 -0
  61. package/dist/test/envelope.test.js +318 -0
  62. package/dist/test/ethos-first-edition.test.d.ts +2 -0
  63. package/dist/test/ethos-first-edition.test.js +248 -0
  64. package/dist/test/ethos.test.d.ts +2 -0
  65. package/dist/test/ethos.test.js +219 -0
  66. package/dist/test/key-store.test.d.ts +2 -0
  67. package/dist/test/key-store.test.js +161 -0
  68. package/dist/test/mandates-compute.test.d.ts +2 -0
  69. package/dist/test/mandates-compute.test.js +256 -0
  70. package/dist/test/mandates.test.d.ts +2 -0
  71. package/dist/test/mandates.test.js +93 -0
  72. package/dist/test/sdk.test.js +70 -30
  73. package/dist/test/signer.test.d.ts +2 -0
  74. package/dist/test/signer.test.js +117 -0
  75. package/dist/test/signup-bootstrap.test.d.ts +2 -0
  76. package/dist/test/signup-bootstrap.test.js +311 -0
  77. package/dist/test/wallet.test.js +20 -9
  78. package/dist/test/web.test.d.ts +2 -0
  79. package/dist/test/web.test.js +270 -0
  80. package/package.json +18 -3
@@ -0,0 +1,670 @@
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 { contactsV1 } from "./data-schema-contacts-v1.js";
42
+ import { signOwnerEnvelope } from "./internal/envelope.js";
43
+ // noble/ed25519 v2 needs sha512 wired in for sync sign/verify
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ ed.etc.sha512Sync = (...m) =>
46
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
+ sha512(ed.etc.concatBytes(...m));
48
+ /* -------------------------------------------------------------------------- */
49
+ /* Schema registry (local) */
50
+ /* -------------------------------------------------------------------------- */
51
+ const SCHEMAS = new Map([
52
+ [contactsV1.schema, contactsV1],
53
+ ]);
54
+ /* -------------------------------------------------------------------------- */
55
+ /* Public factory */
56
+ /* -------------------------------------------------------------------------- */
57
+ export function createDataClient(args) {
58
+ return new DataClientImpl(args);
59
+ }
60
+ /* -------------------------------------------------------------------------- */
61
+ /* Implementation */
62
+ /* -------------------------------------------------------------------------- */
63
+ class DataClientImpl {
64
+ #pdsUrl;
65
+ #did;
66
+ #seed;
67
+ #vm;
68
+ #fetch;
69
+ /**
70
+ * Per-client schema overrides, populated from `args.schemas` at
71
+ * construction. Looked up BEFORE the bundled SCHEMAS map (so an app
72
+ * can override a core schema locally if it really wants to, though
73
+ * the immutability rule of spec §3.5 strongly discourages this).
74
+ */
75
+ #localSchemas;
76
+ // Per-collection CMK cache: cleared on reset()
77
+ #cmkCache = new Map();
78
+ #colCache = new Map();
79
+ constructor(args) {
80
+ this.#pdsUrl = args.pdsUrl.replace(/\/$/, "");
81
+ this.#did = args.did;
82
+ this.#seed = args.sphereSeed;
83
+ this.#vm = args.verificationMethod;
84
+ this.#fetch = args.fetch ?? globalThis.fetch.bind(globalThis);
85
+ this.#localSchemas = new Map((args.schemas ?? []).map((s) => [s.schema, s]));
86
+ }
87
+ /**
88
+ * Resolve a schema id to its lite definition. App-supplied schemas
89
+ * (via `createDataClient({ schemas })`) take precedence over the
90
+ * SDK-bundled core registry.
91
+ */
92
+ #resolveSchema(schemaId) {
93
+ return this.#localSchemas.get(schemaId) ?? SCHEMAS.get(schemaId) ?? null;
94
+ }
95
+ collection(name) {
96
+ return new DataCollectionImpl(this, name);
97
+ }
98
+ async createCollection(args) {
99
+ const cmk = randomBytes32();
100
+ const recipientDidUrl = `${this.#did}#data-kex`;
101
+ const collectionUrn = this.#collectionUrn(args.name);
102
+ const recipientPublic = ed25519SeedToX25519PublicKey(this.#seed);
103
+ const wrap = this.#wrapCmkForRecipient({
104
+ cmk,
105
+ recipientPublicKey: recipientPublic,
106
+ recipientDidUrl,
107
+ collectionUrn,
108
+ });
109
+ try {
110
+ await this.#call("/mcp/primitives/write", "aithos.data.create_collection", {
111
+ subject_did: this.#did,
112
+ collection_name: args.name,
113
+ schema: args.schema,
114
+ ...(args.forwardSecrecy ? { forward_secrecy: args.forwardSecrecy } : {}),
115
+ cmk_envelope: {
116
+ alg: "xchacha20poly1305-ietf",
117
+ wraps: [wrap],
118
+ },
119
+ });
120
+ // Cache CMK in memory for subsequent ops on this collection.
121
+ this.#cmkCache.set(args.name, cmk);
122
+ }
123
+ finally {
124
+ // CMK is retained in cache, only zero the local var if we didn't cache.
125
+ }
126
+ }
127
+ async listCollections() {
128
+ const r = await this.#call("/mcp/primitives/read", "aithos.data.list_collections", {
129
+ subject_did: this.#did,
130
+ });
131
+ const items = r.items ?? [];
132
+ return items.map((c) => ({
133
+ name: c.name,
134
+ schema: c.schema,
135
+ record_count: c.record_count,
136
+ }));
137
+ }
138
+ async listGammaEntries(opts = {}) {
139
+ const params = { subject_did: this.#did };
140
+ if (opts.limit !== undefined)
141
+ params.limit = opts.limit;
142
+ if (opts.opPrefix)
143
+ params.op_prefix = opts.opPrefix;
144
+ if (opts.verify)
145
+ params.verify = true;
146
+ return this.#call("/mcp/primitives/read", "aithos.data.list_gamma_entries", params);
147
+ }
148
+ async registerSchema(schemaDoc) {
149
+ if (schemaDoc === null || typeof schemaDoc !== "object" || Array.isArray(schemaDoc)) {
150
+ throw new Error("sdk.data.registerSchema: schemaDoc must be a JSON object");
151
+ }
152
+ const r = (await this.#call("/mcp/primitives/write", "aithos.data.register_schema", {
153
+ subject_did: this.#did,
154
+ schema_doc: schemaDoc,
155
+ }));
156
+ return {
157
+ schemaId: r.schema_id,
158
+ docHash: r.doc_hash,
159
+ created: r.created,
160
+ ...(r.created_at ? { createdAt: r.created_at } : {}),
161
+ };
162
+ }
163
+ async getSchema(schemaId, opts = {}) {
164
+ const params = { schema: schemaId };
165
+ // Vendor schemas always need a subject_did to address the right
166
+ // registry ; for core schemas the PDS ignores it but we still send
167
+ // ours so the auth check (envelope iss === subject_did) lines up.
168
+ params.subject_did = opts.subjectDid ?? this.#did;
169
+ try {
170
+ const r = (await this.#call("/mcp/primitives/read", "aithos.data.get_schema", params));
171
+ return r.schema;
172
+ }
173
+ catch (e) {
174
+ if (e.code === -32070)
175
+ return null;
176
+ throw e;
177
+ }
178
+ }
179
+ reset() {
180
+ for (const k of this.#cmkCache.values())
181
+ k.fill(0);
182
+ this.#cmkCache.clear();
183
+ this.#colCache.clear();
184
+ }
185
+ /* -- Internals used by DataCollection -- */
186
+ async _ensureCollection(name) {
187
+ const cached = this.#colCache.get(name);
188
+ if (cached)
189
+ return cached;
190
+ // Fetch metadata from PDS
191
+ const meta = (await this.#call("/mcp/primitives/read", "aithos.data.get_collection", {
192
+ subject_did: this.#did,
193
+ collection_name: name,
194
+ }));
195
+ // Defensive structural validation — some PDS responses have been
196
+ // observed (alpha.27 era) returning a meta object that lacks
197
+ // `cmk_envelope` for missing collections, instead of the documented
198
+ // -32020 JSON-RPC error. Without this check, the next line crashes
199
+ // with "Cannot read properties of undefined (reading 'wraps')" which
200
+ // bypasses the upper-layer's missing-collection handling. We re-emit
201
+ // a clean -32020 here so callers can detect "collection not found"
202
+ // uniformly.
203
+ if (!meta ||
204
+ !meta.cmk_envelope ||
205
+ !Array.isArray(meta.cmk_envelope.wraps) ||
206
+ !meta.urn ||
207
+ !meta.schema) {
208
+ const err = new Error(`sdk.data: collection "${name}" not found or malformed ` +
209
+ `(meta missing required field). PDS returned: ${JSON.stringify(meta).slice(0, 200)}`);
210
+ err.code = -32020;
211
+ throw err;
212
+ }
213
+ // Look up our wrap and unwrap the CMK
214
+ const ourRecipient = `${this.#did}#data-kex`;
215
+ const wrap = meta.cmk_envelope.wraps.find((w) => w.recipient === ourRecipient);
216
+ if (!wrap) {
217
+ throw new Error(`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.`);
218
+ }
219
+ const cmk = this.#unwrapCmk({
220
+ wrap,
221
+ collectionUrn: meta.urn,
222
+ privateKey: ed25519SeedToX25519PrivateKey(this.#seed),
223
+ });
224
+ this.#cmkCache.set(name, cmk);
225
+ const schema = this.#resolveSchema(meta.schema);
226
+ if (!schema) {
227
+ throw new Error(`sdk.data: schema "${meta.schema}" not known to the SDK. ` +
228
+ `Pass it via createDataClient({ schemas: [...] }) if it's an ` +
229
+ `app-defined (vendor) schema, or upgrade the SDK if it's a core ` +
230
+ `schema added in a later release.`);
231
+ }
232
+ const state = { name, urn: meta.urn, schema };
233
+ this.#colCache.set(name, state);
234
+ return state;
235
+ }
236
+ async _insert(state, record) {
237
+ const cmk = this.#cmkCache.get(state.name);
238
+ if (!cmk)
239
+ throw new Error("CMK not loaded");
240
+ const { metadata, payload } = splitRecord(record, state.schema);
241
+ const recordId = `record_${makeUlid()}`;
242
+ const encrypted = this.#encryptPayload({
243
+ collectionName: state.name,
244
+ recordId,
245
+ payload,
246
+ cmk,
247
+ });
248
+ const r = (await this.#call("/mcp/primitives/write", "aithos.data.insert_record", {
249
+ collection_urn: state.urn,
250
+ record_id: recordId,
251
+ metadata,
252
+ payload: encrypted,
253
+ }));
254
+ return r.record_id;
255
+ }
256
+ async _get(state, recordId) {
257
+ let raw;
258
+ try {
259
+ raw = await this.#call("/mcp/primitives/read", "aithos.data.get_record", {
260
+ collection_urn: state.urn,
261
+ record_id: recordId,
262
+ });
263
+ }
264
+ catch (e) {
265
+ if (e.code === -32020)
266
+ return null;
267
+ throw e;
268
+ }
269
+ return this.#decryptRecord(state, raw);
270
+ }
271
+ async _list(state, opts = {}) {
272
+ const params = {
273
+ collection_urn: state.urn,
274
+ };
275
+ if (opts.filter)
276
+ params.filter = opts.filter;
277
+ if (opts.order)
278
+ params.order = opts.order;
279
+ if (opts.limit !== undefined)
280
+ params.limit = opts.limit;
281
+ if (opts.cursor)
282
+ params.cursor = opts.cursor;
283
+ const r = (await this.#call("/mcp/primitives/read", "aithos.data.list_records", params));
284
+ const items = r.items.map((it) => this.#decryptRecord(state, it));
285
+ return {
286
+ items,
287
+ ...(r.next_cursor ? { nextCursor: r.next_cursor } : {}),
288
+ };
289
+ }
290
+ async _update(state, recordId, record) {
291
+ const cmk = this.#cmkCache.get(state.name);
292
+ if (!cmk)
293
+ throw new Error("CMK not loaded");
294
+ const { metadata, payload } = splitRecord(record, state.schema);
295
+ const encrypted = this.#encryptPayload({
296
+ collectionName: state.name,
297
+ recordId,
298
+ payload,
299
+ cmk,
300
+ });
301
+ await this.#call("/mcp/primitives/write", "aithos.data.update_record", {
302
+ collection_urn: state.urn,
303
+ record_id: recordId,
304
+ metadata,
305
+ payload: encrypted,
306
+ });
307
+ }
308
+ async _delete(state, recordId) {
309
+ await this.#call("/mcp/primitives/write", "aithos.data.delete_record", {
310
+ collection_urn: state.urn,
311
+ record_id: recordId,
312
+ });
313
+ }
314
+ /* -- JSON-RPC dispatch -- */
315
+ async #call(path, method, params) {
316
+ const aud = `${this.#pdsUrl}${path}`;
317
+ const envelope = await signOwnerEnvelope({
318
+ iss: this.#did,
319
+ aud,
320
+ method,
321
+ params,
322
+ verificationMethod: this.#vm,
323
+ signer: { sign: async (msg) => ed.sign(msg, this.#seed) },
324
+ });
325
+ const body = {
326
+ jsonrpc: "2.0",
327
+ id: makeUlid(),
328
+ method,
329
+ params: { ...params, _envelope: envelope },
330
+ };
331
+ const r = await this.#fetch(aud, {
332
+ method: "POST",
333
+ headers: { "content-type": "application/json" },
334
+ body: JSON.stringify(body),
335
+ });
336
+ const json = (await r.json());
337
+ if (json.error) {
338
+ const err = new Error(json.error.message);
339
+ err.code = json.error.code;
340
+ err.data = json.error.data;
341
+ throw err;
342
+ }
343
+ return json.result ?? {};
344
+ }
345
+ /* -- Crypto helpers -- */
346
+ #collectionUrn(name) {
347
+ return `urn:aithos:collection:${this.#did}:${name}`;
348
+ }
349
+ #wrapCmkForRecipient(args) {
350
+ const ephSk = x25519.utils.randomSecretKey();
351
+ const ephPk = x25519.getPublicKey(ephSk);
352
+ const shared = x25519.getSharedSecret(ephSk, args.recipientPublicKey);
353
+ const wrapKey = hkdf(sha256, shared, utf8("aithos-data-cmk-wrap-v1"), utf8(args.recipientDidUrl), 32);
354
+ const wrapNonce = randomBytes24();
355
+ const aad = aadCmkWrap(args.collectionUrn, args.recipientDidUrl);
356
+ const aead = new XChaCha20Poly1305(wrapKey);
357
+ const wrapped = aead.seal(wrapNonce, args.cmk, aad);
358
+ wrapKey.fill(0);
359
+ shared.fill(0);
360
+ return {
361
+ recipient: args.recipientDidUrl,
362
+ alg: "x25519-hkdf-sha256-aead",
363
+ ephemeral_public: base64Std(ephPk),
364
+ wrap_nonce: base64Std(wrapNonce),
365
+ wrapped_key: base64Std(wrapped),
366
+ };
367
+ }
368
+ #unwrapCmk(args) {
369
+ const ephPk = fromBase64(args.wrap.ephemeral_public);
370
+ const wrapNonce = fromBase64(args.wrap.wrap_nonce);
371
+ const wrappedKey = fromBase64(args.wrap.wrapped_key);
372
+ const shared = x25519.getSharedSecret(args.privateKey, ephPk);
373
+ const wrapKey = hkdf(sha256, shared, utf8("aithos-data-cmk-wrap-v1"), utf8(args.wrap.recipient), 32);
374
+ const aad = aadCmkWrap(args.collectionUrn, args.wrap.recipient);
375
+ const aead = new XChaCha20Poly1305(wrapKey);
376
+ const cmk = aead.open(wrapNonce, wrappedKey, aad);
377
+ wrapKey.fill(0);
378
+ shared.fill(0);
379
+ if (!cmk)
380
+ throw new Error("sdk.data: CMK unwrap failed (wrong key or AAD mismatch)");
381
+ return cmk;
382
+ }
383
+ #encryptPayload(args) {
384
+ const dek = randomBytes32();
385
+ try {
386
+ const plaintext = new TextEncoder().encode(jcsCanonicalize(args.payload));
387
+ const nonce = randomBytes24();
388
+ const aad = aadRecord(this.#did, args.collectionName, args.recordId);
389
+ const aead = new XChaCha20Poly1305(dek);
390
+ const ciphertext = aead.seal(nonce, plaintext, aad);
391
+ const dekWrapNonce = randomBytes24();
392
+ const dekAad = aadDekWrap(this.#did, args.collectionName, args.recordId);
393
+ const dekAead = new XChaCha20Poly1305(args.cmk);
394
+ const wrapped = dekAead.seal(dekWrapNonce, dek, dekAad);
395
+ const dekWrap = new Uint8Array(dekWrapNonce.length + wrapped.length);
396
+ dekWrap.set(dekWrapNonce, 0);
397
+ dekWrap.set(wrapped, dekWrapNonce.length);
398
+ return {
399
+ alg: "xchacha20poly1305-ietf",
400
+ nonce: base64Std(nonce),
401
+ ciphertext: base64Std(ciphertext),
402
+ dek_wrapped_for_cmk: base64Std(dekWrap),
403
+ };
404
+ }
405
+ finally {
406
+ dek.fill(0);
407
+ }
408
+ }
409
+ #decryptRecord(state, raw) {
410
+ if (raw.deleted) {
411
+ // Soft-deleted record — payload was cleared.
412
+ return { ...raw.metadata, _deleted: true };
413
+ }
414
+ const cmk = this.#cmkCache.get(state.name);
415
+ if (!cmk) {
416
+ throw new Error("sdk.data: CMK not loaded — call ensureCollection first");
417
+ }
418
+ // Unwrap DEK
419
+ const wrapBuf = fromBase64(raw.payload.dek_wrapped_for_cmk);
420
+ const wrapNonce = wrapBuf.slice(0, 24);
421
+ const wrapped = wrapBuf.slice(24);
422
+ const dekAad = aadDekWrap(this.#did, state.name, raw.record_id);
423
+ const dekAead = new XChaCha20Poly1305(cmk);
424
+ const dek = dekAead.open(wrapNonce, wrapped, dekAad);
425
+ if (!dek)
426
+ throw new Error("sdk.data: DEK unwrap failed");
427
+ try {
428
+ const nonce = fromBase64(raw.payload.nonce);
429
+ const ciphertext = fromBase64(raw.payload.ciphertext);
430
+ const aad = aadRecord(this.#did, state.name, raw.record_id);
431
+ const aead = new XChaCha20Poly1305(dek);
432
+ const plaintext = aead.open(nonce, ciphertext, aad);
433
+ if (!plaintext)
434
+ throw new Error("sdk.data: payload decrypt failed");
435
+ const payload = JSON.parse(new TextDecoder().decode(plaintext));
436
+ return { record_id: raw.record_id, ...raw.metadata, ...payload };
437
+ }
438
+ finally {
439
+ dek.fill(0);
440
+ }
441
+ }
442
+ }
443
+ class DataCollectionImpl {
444
+ client;
445
+ name;
446
+ constructor(client, name) {
447
+ this.client = client;
448
+ this.name = name;
449
+ }
450
+ async insert(record) {
451
+ const state = await this.client._ensureCollection(this.name);
452
+ return this.client._insert(state, record);
453
+ }
454
+ async get(recordId) {
455
+ const state = await this.client._ensureCollection(this.name);
456
+ return this.client._get(state, recordId);
457
+ }
458
+ async list(opts) {
459
+ const state = await this.client._ensureCollection(this.name);
460
+ return this.client._list(state, opts);
461
+ }
462
+ async update(recordId, record) {
463
+ const state = await this.client._ensureCollection(this.name);
464
+ return this.client._update(state, recordId, record);
465
+ }
466
+ async delete(recordId) {
467
+ const state = await this.client._ensureCollection(this.name);
468
+ return this.client._delete(state, recordId);
469
+ }
470
+ }
471
+ /* -------------------------------------------------------------------------- */
472
+ /* Record split (metadata vs payload) */
473
+ /* -------------------------------------------------------------------------- */
474
+ function splitRecord(record, schema) {
475
+ const metadata = {};
476
+ const payload = {};
477
+ for (const [k, v] of Object.entries(record)) {
478
+ if (schema.auto.has(k))
479
+ continue; // server-set
480
+ if (schema.indexable.has(k)) {
481
+ metadata[k] = v;
482
+ }
483
+ else if (schema.encrypted.has(k)) {
484
+ payload[k] = v;
485
+ }
486
+ else {
487
+ // Unknown field — drop. Server will reject in any case (additionalProperties: false).
488
+ }
489
+ }
490
+ return { metadata, payload };
491
+ }
492
+ /* -------------------------------------------------------------------------- */
493
+ /* Crypto helpers */
494
+ /* -------------------------------------------------------------------------- */
495
+ function randomBytes32() {
496
+ return cryptoRandom(32);
497
+ }
498
+ function randomBytes24() {
499
+ return cryptoRandom(24);
500
+ }
501
+ /** Cross-platform CSPRNG: Web Crypto in browser, Node WebCrypto in Node 19+. */
502
+ function cryptoRandom(n) {
503
+ const buf = new Uint8Array(n);
504
+ // globalThis.crypto exists in browsers and in Node 19+
505
+ globalThis.crypto?.getRandomValues(buf);
506
+ return buf;
507
+ }
508
+ function utf8(s) {
509
+ return new TextEncoder().encode(s);
510
+ }
511
+ function aadCmkWrap(collectionUrn, recipient) {
512
+ const p = utf8("aithos-data-cmk-v1\0");
513
+ const c = utf8(collectionUrn);
514
+ const sep = new Uint8Array([0]);
515
+ const r = utf8(recipient);
516
+ const out = new Uint8Array(p.length + c.length + sep.length + r.length);
517
+ let off = 0;
518
+ out.set(p, off);
519
+ off += p.length;
520
+ out.set(c, off);
521
+ off += c.length;
522
+ out.set(sep, off);
523
+ off += sep.length;
524
+ out.set(r, off);
525
+ return out;
526
+ }
527
+ function aadDekWrap(subjectDid, collectionName, recordId) {
528
+ const p = utf8("aithos-data-dek-v1\0");
529
+ return concat3WithSeps(p, subjectDid, collectionName, recordId);
530
+ }
531
+ function aadRecord(subjectDid, collectionName, recordId) {
532
+ const p = utf8("aithos-data-record-v1\0");
533
+ return concat3WithSeps(p, subjectDid, collectionName, recordId);
534
+ }
535
+ function concat3WithSeps(prefix, a, b, c) {
536
+ const aa = utf8(a);
537
+ const bb = utf8(b);
538
+ const cc = utf8(c);
539
+ const sep = new Uint8Array([0]);
540
+ const total = prefix.length + aa.length + sep.length + bb.length + sep.length + cc.length;
541
+ const out = new Uint8Array(total);
542
+ let off = 0;
543
+ out.set(prefix, off);
544
+ off += prefix.length;
545
+ out.set(aa, off);
546
+ off += aa.length;
547
+ out.set(sep, off);
548
+ off += sep.length;
549
+ out.set(bb, off);
550
+ off += bb.length;
551
+ out.set(sep, off);
552
+ off += sep.length;
553
+ out.set(cc, off);
554
+ return out;
555
+ }
556
+ /**
557
+ * Derive a 32-byte X25519 private key from an Ed25519 seed via SHA-512
558
+ * truncation + clamping. Mirrors libsodium's
559
+ * crypto_sign_ed25519_sk_to_curve25519 for the secret-key side. Used so
560
+ * a single Ed25519 sphere seed can both sign envelopes and key-agree
561
+ * with mandate recipients.
562
+ */
563
+ function ed25519SeedToX25519PrivateKey(seed) {
564
+ if (seed.length !== 32)
565
+ throw new Error("Ed25519 seed must be 32 bytes");
566
+ const h = sha512(seed);
567
+ const sk = new Uint8Array(h.slice(0, 32));
568
+ // Clamp per X25519 spec
569
+ sk[0] = sk[0] & 248;
570
+ sk[31] = sk[31] & 127;
571
+ sk[31] = sk[31] | 64;
572
+ return sk;
573
+ }
574
+ function ed25519SeedToX25519PublicKey(seed) {
575
+ const sk = ed25519SeedToX25519PrivateKey(seed);
576
+ try {
577
+ return x25519.getPublicKey(sk);
578
+ }
579
+ finally {
580
+ sk.fill(0);
581
+ }
582
+ }
583
+ function makeUlid() {
584
+ // Lightweight ULID — millisecond timestamp + 80 bits of randomness.
585
+ // Crockford base32. For tests this is sufficient; production uses
586
+ // the canonical ulid package.
587
+ const tsBuf = new Uint8Array(6);
588
+ let ts = Date.now();
589
+ for (let i = 5; i >= 0; i--) {
590
+ tsBuf[i] = ts & 0xff;
591
+ ts = Math.floor(ts / 256);
592
+ }
593
+ const rndBuf = cryptoRandom(10);
594
+ const all = new Uint8Array(16);
595
+ all.set(tsBuf, 0);
596
+ all.set(rndBuf, 6);
597
+ const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
598
+ let bits = 0;
599
+ let value = 0;
600
+ let out = "";
601
+ for (const b of all) {
602
+ value = (value << 8) | b;
603
+ bits += 8;
604
+ while (bits >= 5) {
605
+ out += alphabet[(value >> (bits - 5)) & 0x1f];
606
+ bits -= 5;
607
+ }
608
+ }
609
+ if (bits > 0)
610
+ out += alphabet[(value << (5 - bits)) & 0x1f];
611
+ return out.slice(0, 26);
612
+ }
613
+ /** Standard base64 (with `=` padding). Browser + Node compatible. */
614
+ function base64Std(bytes) {
615
+ let bin = "";
616
+ for (let i = 0; i < bytes.length; i++)
617
+ bin += String.fromCharCode(bytes[i]);
618
+ return btoa(bin);
619
+ }
620
+ /** base64url (URL-safe, no padding). */
621
+ function base64url(bytes) {
622
+ return base64Std(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
623
+ }
624
+ function fromBase64(s) {
625
+ // Accept either standard base64 or base64url
626
+ const std = s.replace(/-/g, "+").replace(/_/g, "/");
627
+ const padded = std + "=".repeat((4 - (std.length % 4)) % 4);
628
+ const bin = atob(padded);
629
+ const out = new Uint8Array(bin.length);
630
+ for (let i = 0; i < bin.length; i++)
631
+ out[i] = bin.charCodeAt(i);
632
+ return out;
633
+ }
634
+ function sha256Hex(s) {
635
+ const d = sha256(new TextEncoder().encode(s));
636
+ let hex = "";
637
+ for (const b of d)
638
+ hex += b.toString(16).padStart(2, "0");
639
+ return hex;
640
+ }
641
+ /* -------------------------------------------------------------------------- */
642
+ /* JCS-style canonicalization (RFC 8785 subset) */
643
+ /* -------------------------------------------------------------------------- */
644
+ function jcsCanonicalize(value) {
645
+ if (value === null)
646
+ return "null";
647
+ if (value === undefined)
648
+ throw new Error("Cannot canonicalize undefined");
649
+ if (typeof value === "boolean")
650
+ return value ? "true" : "false";
651
+ if (typeof value === "number") {
652
+ if (!Number.isFinite(value))
653
+ throw new Error("non-finite number");
654
+ return value.toString();
655
+ }
656
+ if (typeof value === "string")
657
+ return JSON.stringify(value);
658
+ if (Array.isArray(value)) {
659
+ return "[" + value.map(jcsCanonicalize).join(",") + "]";
660
+ }
661
+ if (typeof value === "object") {
662
+ const obj = value;
663
+ const keys = Object.keys(obj).sort();
664
+ return ("{" +
665
+ keys.map((k) => JSON.stringify(k) + ":" + jcsCanonicalize(obj[k])).join(",") +
666
+ "}");
667
+ }
668
+ throw new Error(`Cannot canonicalize ${typeof value}`);
669
+ }
670
+ //# sourceMappingURL=data.js.map
@@ -10,11 +10,20 @@ export interface AithosSdkEndpoints {
10
10
  * suffixes a fixed path to it.
11
11
  */
12
12
  readonly wallet: string;
13
+ /**
14
+ * Web extractor proxy base URL — `aithos.web_extract`. Default
15
+ * `https://extract.aithos.be`. Same JSON-RPC + signed-envelope shape
16
+ * as the compute proxy, distinct audience so a mandate can hold one
17
+ * scope without the other.
18
+ */
19
+ readonly web: string;
13
20
  }
14
21
  /** Production defaults. */
15
22
  export declare const DEFAULT_SDK_ENDPOINTS: AithosSdkEndpoints;
16
23
  /** Compose the full compute-invoke URL: `${compute}/v1/invoke`. */
17
24
  export declare function computeInvokeUrl(endpoints: AithosSdkEndpoints): string;
25
+ /** Compose the full web-extract URL: `${web}/v1/invoke`. */
26
+ export declare function webInvokeUrl(endpoints: AithosSdkEndpoints): string;
18
27
  /** Compose the full top-up-checkout URL: `${wallet}/v1/wallet/topup/checkout`. */
19
28
  export declare function walletTopupCheckoutUrl(endpoints: AithosSdkEndpoints): string;
20
29
  /**