@aithos/sdk 0.1.0-alpha.40 → 0.1.0-alpha.42

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 (40) hide show
  1. package/dist/src/apps.d.ts +224 -0
  2. package/dist/src/apps.js +443 -0
  3. package/dist/src/compute.d.ts +30 -0
  4. package/dist/src/index.d.ts +3 -1
  5. package/dist/src/index.js +7 -1
  6. package/dist/src/sdk.d.ts +7 -0
  7. package/dist/src/sdk.js +13 -0
  8. package/dist/test/auth-j3.test.d.ts +2 -0
  9. package/dist/test/auth-j3.test.js +391 -0
  10. package/dist/test/auth.test.d.ts +2 -0
  11. package/dist/test/auth.test.js +175 -0
  12. package/dist/test/compute-delegate-path.test.d.ts +2 -0
  13. package/dist/test/compute-delegate-path.test.js +183 -0
  14. package/dist/test/compute.test.d.ts +2 -0
  15. package/dist/test/compute.test.js +194 -0
  16. package/dist/test/endpoints.test.d.ts +2 -0
  17. package/dist/test/endpoints.test.js +62 -0
  18. package/dist/test/envelope.test.d.ts +2 -0
  19. package/dist/test/envelope.test.js +318 -0
  20. package/dist/test/ethos-first-edition.test.d.ts +2 -0
  21. package/dist/test/ethos-first-edition.test.js +248 -0
  22. package/dist/test/ethos.test.d.ts +2 -0
  23. package/dist/test/ethos.test.js +219 -0
  24. package/dist/test/key-store.test.d.ts +2 -0
  25. package/dist/test/key-store.test.js +161 -0
  26. package/dist/test/mandates-compute.test.d.ts +2 -0
  27. package/dist/test/mandates-compute.test.js +256 -0
  28. package/dist/test/mandates.test.d.ts +2 -0
  29. package/dist/test/mandates.test.js +93 -0
  30. package/dist/test/sdk.test.d.ts +2 -0
  31. package/dist/test/sdk.test.js +126 -0
  32. package/dist/test/signer.test.d.ts +2 -0
  33. package/dist/test/signer.test.js +117 -0
  34. package/dist/test/signup-bootstrap.test.d.ts +2 -0
  35. package/dist/test/signup-bootstrap.test.js +311 -0
  36. package/dist/test/wallet.test.d.ts +2 -0
  37. package/dist/test/wallet.test.js +121 -0
  38. package/dist/test/web.test.d.ts +2 -0
  39. package/dist/test/web.test.js +270 -0
  40. package/package.json +10 -11
@@ -0,0 +1,224 @@
1
+ import type { AithosAuth } from "./auth.js";
2
+ import type { AithosSdkEndpoints } from "./endpoints.js";
3
+ /**
4
+ * The audience set scopes which consumers are eligible. `"open"` lets
5
+ * any DID invoke the app; `"list"` restricts to an explicit allowlist.
6
+ */
7
+ export type AudienceSet = "open" | "list";
8
+ export interface SponsorshipBudgetInput {
9
+ /**
10
+ * Authority-interpreted unit of account. Default `"aithos.mc"` (the
11
+ * platform microcredit, ≈ €0.001 of AWS pass-through cost). Authorities
12
+ * MAY accept other units — see draft §13.3.4.
13
+ */
14
+ readonly unit?: string;
15
+ /** Lifetime cap per consumer, in `unit`. */
16
+ readonly perUserCap: number;
17
+ /** If set, the per-user cap applies over a sliding window. */
18
+ readonly perUserWindowSeconds?: number | null;
19
+ /** UTC-day cap on total sponsored consumption across all consumers. */
20
+ readonly perDayTotalCap: number;
21
+ /** Lifetime pool cap across all consumers. `null` ≡ no cap. */
22
+ readonly poolCapTotal?: number | null;
23
+ }
24
+ export interface SponsorshipAudienceInput {
25
+ /** App DID the sponsorship covers (typically `sdk.appDid`). */
26
+ readonly appDid: string;
27
+ readonly audienceSet: AudienceSet;
28
+ /** Required iff `audienceSet === "list"`. */
29
+ readonly consumers?: readonly string[];
30
+ }
31
+ export interface SponsorshipAccountingAuthorityInput {
32
+ readonly did: string;
33
+ readonly endpoint: string;
34
+ }
35
+ export interface CreateSponsorshipMandateArgs {
36
+ readonly audience: SponsorshipAudienceInput;
37
+ readonly scopes: readonly string[];
38
+ readonly allowedMethods: readonly string[];
39
+ readonly allowedModels?: readonly string[];
40
+ readonly budget: SponsorshipBudgetInput;
41
+ readonly accountingAuthority: SponsorshipAccountingAuthorityInput;
42
+ /** Defaults to now. */
43
+ readonly notBefore?: Date;
44
+ /** Defaults to 365 days. */
45
+ readonly ttlSeconds?: number;
46
+ }
47
+ /**
48
+ * Signed sponsorship mandate, ready to seed into the authority's
49
+ * `aithos-app-sponsorships` table. Same shape as
50
+ * `@aithos/protocol-core`'s `SponsorshipMandate`.
51
+ */
52
+ export interface SignedSponsorshipMandate {
53
+ readonly "aithos-sponsorship-mandate": "0.1.0";
54
+ readonly id: string;
55
+ readonly issuer: string;
56
+ readonly issued_by_key: string;
57
+ readonly audience: {
58
+ readonly app_did: string;
59
+ readonly audience_set: AudienceSet;
60
+ readonly consumers?: readonly string[];
61
+ };
62
+ readonly scopes: readonly string[];
63
+ readonly allowed_methods: readonly string[];
64
+ readonly allowed_models?: readonly string[];
65
+ readonly budget: {
66
+ readonly unit: string;
67
+ readonly per_user_cap: number;
68
+ readonly per_user_window_seconds: number | null;
69
+ readonly per_day_total_cap: number;
70
+ readonly pool_cap_total: number | null;
71
+ };
72
+ readonly accounting_authority: {
73
+ readonly did: string;
74
+ readonly endpoint: string;
75
+ };
76
+ readonly not_before: string;
77
+ readonly not_after: string;
78
+ readonly issued_at: string;
79
+ readonly nonce: string;
80
+ readonly signature: {
81
+ readonly alg: "ed25519";
82
+ readonly key: string;
83
+ readonly value: string;
84
+ };
85
+ }
86
+ export interface SignedSponsorshipRevocation {
87
+ readonly "aithos-revocation": "0.1.0";
88
+ readonly mandate_id: string;
89
+ readonly mandate_kind: "sponsorship-mandate";
90
+ readonly issuer: string;
91
+ readonly issued_by_key: string;
92
+ readonly revoked_at: string;
93
+ readonly reason: string;
94
+ readonly signature: {
95
+ readonly alg: "ed25519";
96
+ readonly key: string;
97
+ readonly value: string;
98
+ };
99
+ }
100
+ export type AppCreditPackId = "app-credits-10k" | "app-credits-50k" | "app-credits-200k";
101
+ export interface CreateAppTopupSessionArgs {
102
+ /** Which app-credits pack to purchase. */
103
+ readonly packId: AppCreditPackId;
104
+ /** Where Stripe redirects after a successful payment. */
105
+ readonly successUrl: string;
106
+ /** Where Stripe redirects if the user cancels. */
107
+ readonly cancelUrl: string;
108
+ /** Abort signal to cancel the request. */
109
+ readonly signal?: AbortSignal;
110
+ }
111
+ export interface CreateAppTopupSessionResult {
112
+ readonly checkoutUrl: string;
113
+ readonly sessionId: string;
114
+ }
115
+ export interface AppsNamespaceDeps {
116
+ readonly auth: AithosAuth;
117
+ readonly appDid: string;
118
+ readonly endpoints: AithosSdkEndpoints;
119
+ readonly fetch: typeof fetch;
120
+ }
121
+ export declare class AppsNamespace {
122
+ #private;
123
+ constructor(deps: AppsNamespaceDeps);
124
+ /**
125
+ * Build and sign a `SponsorshipMandate` as the calling owner. The
126
+ * returned JSON is signed by the owner's `#public` sphere key, ready
127
+ * to be seeded into the authority's `aithos-app-sponsorships` table.
128
+ *
129
+ * V0.1 has no server endpoint — get the row into DDB via:
130
+ * 1. `aws dynamodb put-item --table-name aithos-app-sponsorships
131
+ * --item file://mandate.json` (raw), or
132
+ * 2. The ops bootstrap script in
133
+ * `innoesate/aithos/platform/scripts/seed-sponsorship.mjs`
134
+ * (planned for V0.2).
135
+ *
136
+ * Hash with `sponsorshipMandateHash()` from `@aithos/protocol-core`
137
+ * if you need to embed it in an envelope's `sponsorship.hash` field.
138
+ */
139
+ createSponsorshipMandate(args: CreateSponsorshipMandateArgs): Promise<SignedSponsorshipMandate>;
140
+ /**
141
+ * Build and sign a §4.6 revocation document targeting a sponsorship
142
+ * mandate. Same upload caveat as `createSponsorshipMandate`.
143
+ */
144
+ revokeSponsorshipMandate(mandate: SignedSponsorshipMandate, reason: string): Promise<SignedSponsorshipRevocation>;
145
+ /**
146
+ * Stripe Checkout session for an `app-credits-*` pack. The session is
147
+ * bound to the calling owner's DID (which is treated as the app's
148
+ * funding DID — Option A unified wallet, see plan §3.4).
149
+ *
150
+ * Same endpoint and auth pattern as `sdk.wallet.createTopupSession`,
151
+ * just with the app-credits pack id family.
152
+ */
153
+ createAppTopupSession(args: CreateAppTopupSessionArgs): Promise<CreateAppTopupSessionResult>;
154
+ /**
155
+ * Build, sign, and PUBLISH a SponsorshipMandate to the authority's
156
+ * `aithos-app-sponsorships` table via `aithos.sponsorship_create`.
157
+ *
158
+ * Combines local signing (see {@link createSponsorshipMandate}) with the
159
+ * server upload step. After this resolves, the sponsorship is active —
160
+ * the next `sdk.compute.invokeBedrock` call targeting `args.audience.appDid`
161
+ * may be sponsored (subject to caps).
162
+ *
163
+ * Requires that the calling owner is the registered `owner_did` of
164
+ * `args.audience.appDid` in `aithos-auth-apps`; otherwise the server
165
+ * rejects with `-32042` "not the owner".
166
+ */
167
+ publishSponsorship(args: CreateSponsorshipMandateArgs): Promise<{
168
+ mandate: SignedSponsorshipMandate;
169
+ sponsorshipId: string;
170
+ mandateHash: string;
171
+ status: "active";
172
+ createdAt: number;
173
+ }>;
174
+ /**
175
+ * Read the active sponsorship for an app. Open endpoint (no envelope
176
+ * required): the mandate is publicly signed and resolvable anyway.
177
+ *
178
+ * Returns `{ exists: false }` when no row exists for the app.
179
+ */
180
+ getSponsorship(args: {
181
+ appDid: string;
182
+ signal?: AbortSignal;
183
+ }): Promise<{
184
+ exists: false;
185
+ } | {
186
+ exists: true;
187
+ sponsorshipId: string;
188
+ mandate: SignedSponsorshipMandate;
189
+ mandateHash: string;
190
+ status: "active" | "paused" | "depleted" | "expired" | "revoked";
191
+ poolConsumedLifetime: number;
192
+ createdAt: number;
193
+ lastUpdatedAt: number;
194
+ }>;
195
+ /**
196
+ * Revoke a published sponsorship by `app_did` + `sponsorship_id`. The
197
+ * row is marked `status: "revoked"` server-side; the routing cache is
198
+ * invalidated so the next compute call falls back to the user wallet.
199
+ */
200
+ revokeSponsorship(args: {
201
+ appDid: string;
202
+ sponsorshipId: string;
203
+ reason: string;
204
+ signal?: AbortSignal;
205
+ }): Promise<{
206
+ status: "revoked";
207
+ }>;
208
+ /**
209
+ * Read the app's wallet balance (= the sponsor pool). Requires owner
210
+ * signature.
211
+ */
212
+ getAppWalletBalance(args: {
213
+ appDid: string;
214
+ signal?: AbortSignal;
215
+ }): Promise<{
216
+ appDid: string;
217
+ exists: boolean;
218
+ balance: number;
219
+ balancePurchase: number;
220
+ balanceGrant: number;
221
+ dailySpent: number;
222
+ }>;
223
+ }
224
+ //# sourceMappingURL=apps.d.ts.map
@@ -0,0 +1,443 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Mathieu Colla
3
+ // `sdk.apps` namespace — sponsorship lifecycle for app developers.
4
+ //
5
+ // V0.1 surface (2026-05-27) — minimal but sufficient to bootstrap a free
6
+ // trial flow on Linkedone and similar apps:
7
+ //
8
+ // createSponsorshipMandate(args)
9
+ // Build + sign a SponsorshipMandate as the calling owner. Returns
10
+ // the signed JSON. The caller is responsible for getting the row
11
+ // into the authority's `aithos-app-sponsorships` table — V0.1 has
12
+ // no server endpoint for it (manual `aws dynamodb put-item` or a
13
+ // Terraform-managed seed). V0.2 will add a server endpoint.
14
+ //
15
+ // revokeSponsorshipMandate(mandate, reason)
16
+ // Build + sign a §4.6 revocation document targeting the mandate.
17
+ // Same upload caveat as create — V0.1 has no server endpoint.
18
+ //
19
+ // createAppTopupSession(args)
20
+ // Stripe Checkout session for an `app-credits-*` pack. Reuses the
21
+ // existing wallet-topup endpoint; the difference is the pack id
22
+ // and the DID being credited (the app's, not the user's).
23
+ //
24
+ // Why no `getSponsorshipStatus*` in V0.1: the read side requires either
25
+ // a CloudFront-fronted read endpoint or direct DDB access. We'll add it
26
+ // in V0.2 once the sponsorship-api Lambda exists; for now, devs check
27
+ // their sponsorship via the AWS Console.
28
+ import { base64url, buildSignedEnvelope, sign } from "@aithos/protocol-client";
29
+ import { computeInvokeUrl, walletTopupCheckoutUrl } from "./endpoints.js";
30
+ import { ownerKeyPair } from "./internal/protocol-client-bridge.js";
31
+ import { AithosSDKError } from "./types.js";
32
+ /* -------------------------------------------------------------------------- */
33
+ /* Class */
34
+ /* -------------------------------------------------------------------------- */
35
+ export class AppsNamespace {
36
+ #deps;
37
+ constructor(deps) {
38
+ this.#deps = deps;
39
+ }
40
+ /**
41
+ * Build and sign a `SponsorshipMandate` as the calling owner. The
42
+ * returned JSON is signed by the owner's `#public` sphere key, ready
43
+ * to be seeded into the authority's `aithos-app-sponsorships` table.
44
+ *
45
+ * V0.1 has no server endpoint — get the row into DDB via:
46
+ * 1. `aws dynamodb put-item --table-name aithos-app-sponsorships
47
+ * --item file://mandate.json` (raw), or
48
+ * 2. The ops bootstrap script in
49
+ * `innoesate/aithos/platform/scripts/seed-sponsorship.mjs`
50
+ * (planned for V0.2).
51
+ *
52
+ * Hash with `sponsorshipMandateHash()` from `@aithos/protocol-core`
53
+ * if you need to embed it in an envelope's `sponsorship.hash` field.
54
+ */
55
+ async createSponsorshipMandate(args) {
56
+ const owner = this.#requireOwner();
57
+ validateBudget(args.budget);
58
+ validateAudience(args.audience);
59
+ if (args.scopes.length === 0) {
60
+ throw new AithosSDKError("invalid_input", "scopes must be non-empty");
61
+ }
62
+ if (args.allowedMethods.length === 0) {
63
+ throw new AithosSDKError("invalid_input", "allowedMethods must be non-empty");
64
+ }
65
+ const nb = args.notBefore ?? new Date();
66
+ const ttl = args.ttlSeconds ?? 365 * 24 * 3600;
67
+ const na = new Date(nb.getTime() + ttl * 1000);
68
+ if (na <= nb) {
69
+ throw new AithosSDKError("invalid_input", "ttlSeconds must produce not_after > not_before");
70
+ }
71
+ const nonce = base64url(randomBytes(9));
72
+ const unsigned = {
73
+ "aithos-sponsorship-mandate": "0.1.0",
74
+ id: `spons_${ulid()}`,
75
+ issuer: owner.did,
76
+ issued_by_key: `${owner.did}#public`,
77
+ audience: {
78
+ app_did: args.audience.appDid,
79
+ audience_set: args.audience.audienceSet,
80
+ ...(args.audience.consumers !== undefined
81
+ ? { consumers: [...args.audience.consumers] }
82
+ : {}),
83
+ },
84
+ scopes: [...args.scopes],
85
+ allowed_methods: [...args.allowedMethods],
86
+ ...(args.allowedModels ? { allowed_models: [...args.allowedModels] } : {}),
87
+ budget: {
88
+ unit: args.budget.unit ?? "aithos.mc",
89
+ per_user_cap: args.budget.perUserCap,
90
+ per_user_window_seconds: args.budget.perUserWindowSeconds === undefined
91
+ ? null
92
+ : args.budget.perUserWindowSeconds,
93
+ per_day_total_cap: args.budget.perDayTotalCap,
94
+ pool_cap_total: args.budget.poolCapTotal === undefined
95
+ ? null
96
+ : args.budget.poolCapTotal,
97
+ },
98
+ accounting_authority: { ...args.accountingAuthority },
99
+ not_before: nb.toISOString(),
100
+ not_after: na.toISOString(),
101
+ issued_at: new Date().toISOString(),
102
+ nonce,
103
+ signature: { alg: "ed25519", key: `${owner.did}#public`, value: "" },
104
+ };
105
+ const bytes = new TextEncoder().encode(jcsCanonicalize(unsigned));
106
+ const ownerPub = ownerKeyPair(owner, "public");
107
+ const sigBytes = sign(bytes, ownerPub.seed);
108
+ return {
109
+ ...unsigned,
110
+ signature: { ...unsigned.signature, value: base64url(sigBytes) },
111
+ };
112
+ }
113
+ /**
114
+ * Build and sign a §4.6 revocation document targeting a sponsorship
115
+ * mandate. Same upload caveat as `createSponsorshipMandate`.
116
+ */
117
+ async revokeSponsorshipMandate(mandate, reason) {
118
+ const owner = this.#requireOwner();
119
+ if (mandate.issuer !== owner.did) {
120
+ throw new AithosSDKError("invalid_input", `mandate.issuer (${mandate.issuer}) does not match signed-in owner (${owner.did}) — only the sponsor can revoke`);
121
+ }
122
+ const unsigned = {
123
+ "aithos-revocation": "0.1.0",
124
+ mandate_id: mandate.id,
125
+ mandate_kind: "sponsorship-mandate",
126
+ issuer: owner.did,
127
+ issued_by_key: `${owner.did}#public`,
128
+ revoked_at: new Date().toISOString(),
129
+ reason,
130
+ signature: { alg: "ed25519", key: `${owner.did}#public`, value: "" },
131
+ };
132
+ const bytes = new TextEncoder().encode(jcsCanonicalize(unsigned));
133
+ const ownerPub = ownerKeyPair(owner, "public");
134
+ const sigBytes = sign(bytes, ownerPub.seed);
135
+ return {
136
+ ...unsigned,
137
+ signature: { ...unsigned.signature, value: base64url(sigBytes) },
138
+ };
139
+ }
140
+ /**
141
+ * Stripe Checkout session for an `app-credits-*` pack. The session is
142
+ * bound to the calling owner's DID (which is treated as the app's
143
+ * funding DID — Option A unified wallet, see plan §3.4).
144
+ *
145
+ * Same endpoint and auth pattern as `sdk.wallet.createTopupSession`,
146
+ * just with the app-credits pack id family.
147
+ */
148
+ async createAppTopupSession(args) {
149
+ const { auth, endpoints, fetch: fetchImpl } = this.#deps;
150
+ const owner = auth._getOwnerSigners();
151
+ if (!owner || owner.destroyed) {
152
+ throw new AithosSDKError("sdk_no_owner", "no owner signed in; sign in first");
153
+ }
154
+ const url = walletTopupCheckoutUrl(endpoints);
155
+ let res;
156
+ try {
157
+ res = await fetchImpl(url, {
158
+ method: "POST",
159
+ headers: { "content-type": "application/json" },
160
+ body: JSON.stringify({
161
+ // Same endpoint as user-pack top-ups. The Lambda's pack-table
162
+ // distinguishes `app-credits-*` from `credits-*` and routes
163
+ // the credit to the same `aithos-wallet-user` row keyed on
164
+ // `user_did`, which for an app is its DID (= sdk.appDid).
165
+ user_did: this.#deps.appDid,
166
+ pack_id: args.packId,
167
+ success_url: args.successUrl,
168
+ cancel_url: args.cancelUrl,
169
+ }),
170
+ ...(args.signal ? { signal: args.signal } : {}),
171
+ });
172
+ }
173
+ catch (e) {
174
+ throw new AithosSDKError("network", e.message);
175
+ }
176
+ let body;
177
+ try {
178
+ body = await res.json();
179
+ }
180
+ catch {
181
+ throw new AithosSDKError("http", `HTTP ${res.status} ${res.statusText} — non-JSON response`, { status: res.status });
182
+ }
183
+ if (!res.ok) {
184
+ const err = body;
185
+ throw new AithosSDKError(err.error ?? "http", err.detail ?? `HTTP ${res.status} ${res.statusText}`, { status: res.status });
186
+ }
187
+ const ok = body;
188
+ if (typeof ok.checkout_url !== "string" ||
189
+ typeof ok.session_id !== "string") {
190
+ throw new AithosSDKError("empty", "wallet response missing checkout_url or session_id");
191
+ }
192
+ return { checkoutUrl: ok.checkout_url, sessionId: ok.session_id };
193
+ }
194
+ /**
195
+ * Build, sign, and PUBLISH a SponsorshipMandate to the authority's
196
+ * `aithos-app-sponsorships` table via `aithos.sponsorship_create`.
197
+ *
198
+ * Combines local signing (see {@link createSponsorshipMandate}) with the
199
+ * server upload step. After this resolves, the sponsorship is active —
200
+ * the next `sdk.compute.invokeBedrock` call targeting `args.audience.appDid`
201
+ * may be sponsored (subject to caps).
202
+ *
203
+ * Requires that the calling owner is the registered `owner_did` of
204
+ * `args.audience.appDid` in `aithos-auth-apps`; otherwise the server
205
+ * rejects with `-32042` "not the owner".
206
+ */
207
+ async publishSponsorship(args) {
208
+ const mandate = await this.createSponsorshipMandate(args);
209
+ const result = await this.#signedRpc({
210
+ method: "aithos.sponsorship_create",
211
+ params: { mandate },
212
+ });
213
+ return {
214
+ mandate,
215
+ sponsorshipId: result.sponsorship_id,
216
+ mandateHash: result.mandate_hash,
217
+ status: result.status,
218
+ createdAt: result.created_at,
219
+ };
220
+ }
221
+ /**
222
+ * Read the active sponsorship for an app. Open endpoint (no envelope
223
+ * required): the mandate is publicly signed and resolvable anyway.
224
+ *
225
+ * Returns `{ exists: false }` when no row exists for the app.
226
+ */
227
+ async getSponsorship(args) {
228
+ const { endpoints, fetch: fetchImpl } = this.#deps;
229
+ const url = computeInvokeUrl(endpoints);
230
+ let res;
231
+ try {
232
+ res = await fetchImpl(url, {
233
+ method: "POST",
234
+ headers: { "content-type": "application/json" },
235
+ body: JSON.stringify({
236
+ jsonrpc: "2.0",
237
+ id: "aithos.sponsorship_get",
238
+ method: "aithos.sponsorship_get",
239
+ params: { app_did: args.appDid },
240
+ }),
241
+ ...(args.signal ? { signal: args.signal } : {}),
242
+ });
243
+ }
244
+ catch (e) {
245
+ throw new AithosSDKError("network", e.message);
246
+ }
247
+ const body = (await res.json());
248
+ if (body.error) {
249
+ throw new AithosSDKError(String(body.error.code), body.error.message);
250
+ }
251
+ const r = body.result ?? {};
252
+ if (r.exists === false || !r.exists) {
253
+ return { exists: false };
254
+ }
255
+ return {
256
+ exists: true,
257
+ sponsorshipId: r.sponsorship_id,
258
+ mandate: r.mandate,
259
+ mandateHash: r.mandate_hash,
260
+ status: r.status,
261
+ poolConsumedLifetime: r.pool_consumed_lifetime ?? 0,
262
+ createdAt: r.created_at ?? 0,
263
+ lastUpdatedAt: r.last_updated_at ?? 0,
264
+ };
265
+ }
266
+ /**
267
+ * Revoke a published sponsorship by `app_did` + `sponsorship_id`. The
268
+ * row is marked `status: "revoked"` server-side; the routing cache is
269
+ * invalidated so the next compute call falls back to the user wallet.
270
+ */
271
+ async revokeSponsorship(args) {
272
+ const result = await this.#signedRpc({
273
+ method: "aithos.sponsorship_revoke",
274
+ params: {
275
+ app_did: args.appDid,
276
+ sponsorship_id: args.sponsorshipId,
277
+ reason: args.reason,
278
+ },
279
+ ...(args.signal ? { signal: args.signal } : {}),
280
+ });
281
+ return result;
282
+ }
283
+ /**
284
+ * Read the app's wallet balance (= the sponsor pool). Requires owner
285
+ * signature.
286
+ */
287
+ async getAppWalletBalance(args) {
288
+ const result = await this.#signedRpc({
289
+ method: "aithos.app_wallet_get_balance",
290
+ params: { app_did: args.appDid },
291
+ ...(args.signal ? { signal: args.signal } : {}),
292
+ });
293
+ return {
294
+ appDid: result.app_did,
295
+ exists: result.exists,
296
+ balance: result.balance,
297
+ balancePurchase: result.balance_purchase,
298
+ balanceGrant: result.balance_grant,
299
+ dailySpent: result.daily_spent,
300
+ };
301
+ }
302
+ /**
303
+ * Internal: sign an envelope with the calling owner's `#public` sphere
304
+ * and POST a JSON-RPC request to the compute proxy. Used by the
305
+ * sponsorship CRUD methods above. Mirrors `ComputeNamespace.#signAndPost`.
306
+ */
307
+ async #signedRpc(opts) {
308
+ const { endpoints, fetch: fetchImpl } = this.#deps;
309
+ const owner = this.#requireOwner();
310
+ const publicKp = ownerKeyPair(owner, "public");
311
+ const url = computeInvokeUrl(endpoints);
312
+ const envelope = buildSignedEnvelope({
313
+ iss: owner.did,
314
+ aud: url,
315
+ method: opts.method,
316
+ verificationMethod: `${owner.did}#public`,
317
+ params: opts.params,
318
+ signer: publicKp,
319
+ });
320
+ let res;
321
+ try {
322
+ res = await fetchImpl(url, {
323
+ method: "POST",
324
+ headers: { "content-type": "application/json" },
325
+ body: JSON.stringify({
326
+ jsonrpc: "2.0",
327
+ id: opts.method,
328
+ method: opts.method,
329
+ params: { ...opts.params, _envelope: envelope },
330
+ }),
331
+ ...(opts.signal ? { signal: opts.signal } : {}),
332
+ });
333
+ }
334
+ catch (e) {
335
+ throw new AithosSDKError("network", e.message);
336
+ }
337
+ if (!res.ok) {
338
+ throw new AithosSDKError("http", `HTTP ${res.status} ${res.statusText}`, { status: res.status });
339
+ }
340
+ const body = (await res.json());
341
+ if (body.error) {
342
+ throw new AithosSDKError(String(body.error.code), body.error.message, body.error.data ? { data: body.error.data } : undefined);
343
+ }
344
+ if (body.result === undefined) {
345
+ throw new AithosSDKError("empty", `empty result for ${opts.method}`);
346
+ }
347
+ return body.result;
348
+ }
349
+ #requireOwner() {
350
+ const owner = this.#deps.auth._getOwnerSigners();
351
+ if (!owner || owner.destroyed) {
352
+ throw new AithosSDKError("sdk_no_owner", "no owner signed in; sign in first");
353
+ }
354
+ return owner;
355
+ }
356
+ }
357
+ /* -------------------------------------------------------------------------- */
358
+ /* Validation */
359
+ /* -------------------------------------------------------------------------- */
360
+ function validateBudget(b) {
361
+ if (!Number.isInteger(b.perUserCap) || b.perUserCap < 0) {
362
+ throw new AithosSDKError("invalid_input", "budget.perUserCap must be a non-negative integer");
363
+ }
364
+ if (!Number.isInteger(b.perDayTotalCap) || b.perDayTotalCap < 0) {
365
+ throw new AithosSDKError("invalid_input", "budget.perDayTotalCap must be a non-negative integer");
366
+ }
367
+ if (b.perUserWindowSeconds !== undefined &&
368
+ b.perUserWindowSeconds !== null) {
369
+ if (!Number.isInteger(b.perUserWindowSeconds) ||
370
+ b.perUserWindowSeconds <= 0) {
371
+ throw new AithosSDKError("invalid_input", "budget.perUserWindowSeconds must be null or a positive integer");
372
+ }
373
+ }
374
+ if (b.poolCapTotal !== undefined && b.poolCapTotal !== null) {
375
+ if (!Number.isInteger(b.poolCapTotal) || b.poolCapTotal < 0) {
376
+ throw new AithosSDKError("invalid_input", "budget.poolCapTotal must be null or a non-negative integer");
377
+ }
378
+ }
379
+ }
380
+ function validateAudience(a) {
381
+ if (!a.appDid || typeof a.appDid !== "string") {
382
+ throw new AithosSDKError("invalid_input", "audience.appDid must be a DID string");
383
+ }
384
+ if (a.audienceSet === "open") {
385
+ if (a.consumers !== undefined) {
386
+ throw new AithosSDKError("invalid_input", "audience.consumers MUST be absent when audienceSet is 'open'");
387
+ }
388
+ }
389
+ else if (a.audienceSet === "list") {
390
+ if (!Array.isArray(a.consumers) || a.consumers.length === 0) {
391
+ throw new AithosSDKError("invalid_input", "audience.consumers MUST be a non-empty array when audienceSet is 'list'");
392
+ }
393
+ }
394
+ else {
395
+ throw new AithosSDKError("invalid_input", `audience.audienceSet must be 'open' or 'list' (got: ${String(a.audienceSet)})`);
396
+ }
397
+ }
398
+ /* -------------------------------------------------------------------------- */
399
+ /* ULID + JCS — local copies to avoid a runtime dep */
400
+ /* -------------------------------------------------------------------------- */
401
+ const ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
402
+ function ulid(now = Date.now()) {
403
+ // 10 chars timestamp + 16 chars random = 26 chars
404
+ let timePart = "";
405
+ let t = now;
406
+ for (let i = 0; i < 10; i++) {
407
+ const mod = t % 32;
408
+ timePart = ULID_ALPHABET[mod] + timePart;
409
+ t = (t - mod) / 32;
410
+ }
411
+ let randPart = "";
412
+ for (let i = 0; i < 16; i++) {
413
+ randPart += ULID_ALPHABET[Math.floor(Math.random() * 32)];
414
+ }
415
+ return timePart + randPart;
416
+ }
417
+ function randomBytes(n) {
418
+ const out = new Uint8Array(n);
419
+ crypto.getRandomValues(out);
420
+ return out;
421
+ }
422
+ /**
423
+ * Minimal RFC-8785 (JCS) canonicalization. Sorts object keys
424
+ * lexicographically by code point, no whitespace, JSON.stringify for
425
+ * primitives. Matches the protocol-core canonicalize used to compute
426
+ * the hash the signature commits to.
427
+ */
428
+ function jcsCanonicalize(value) {
429
+ if (value === null || typeof value !== "object") {
430
+ return JSON.stringify(value);
431
+ }
432
+ if (Array.isArray(value)) {
433
+ return "[" + value.map(jcsCanonicalize).join(",") + "]";
434
+ }
435
+ const obj = value;
436
+ const keys = Object.keys(obj).sort();
437
+ return ("{" +
438
+ keys
439
+ .map((k) => JSON.stringify(k) + ":" + jcsCanonicalize(obj[k]))
440
+ .join(",") +
441
+ "}");
442
+ }
443
+ //# sourceMappingURL=apps.js.map