@aithos/sdk 0.1.0-alpha.3 → 0.1.0-alpha.31

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