@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.
- package/README.md +211 -7
- package/dist/src/apps.d.ts +155 -0
- package/dist/src/apps.js +288 -0
- package/dist/src/assets.d.ts +207 -0
- package/dist/src/assets.js +533 -0
- package/dist/src/auth-api.d.ts +138 -0
- package/dist/src/auth-api.js +168 -0
- package/dist/src/auth.d.ts +536 -119
- package/dist/src/auth.js +1207 -152
- package/dist/src/compute.d.ts +251 -9
- package/dist/src/compute.js +293 -16
- package/dist/src/data-schema-contacts-v1.d.ts +14 -0
- package/dist/src/data-schema-contacts-v1.js +28 -0
- package/dist/src/data.d.ts +153 -0
- package/dist/src/data.js +670 -0
- package/dist/src/endpoints.d.ts +9 -0
- package/dist/src/endpoints.js +5 -0
- package/dist/src/ethos.d.ts +202 -1
- package/dist/src/ethos.js +821 -16
- package/dist/src/index.d.ts +18 -6
- package/dist/src/index.js +39 -6
- package/dist/src/internal/delegate-bundle.d.ts +18 -0
- package/dist/src/internal/delegate-bundle.js +94 -0
- package/dist/src/internal/delegate-state.d.ts +45 -0
- package/dist/src/internal/delegate-state.js +120 -0
- package/dist/src/internal/envelope.d.ts +77 -0
- package/dist/src/internal/envelope.js +154 -0
- package/dist/src/internal/owner-signers.d.ts +78 -0
- package/dist/src/internal/owner-signers.js +179 -0
- package/dist/src/internal/protocol-client-bridge.d.ts +8 -0
- package/dist/src/internal/protocol-client-bridge.js +20 -0
- package/dist/src/internal/recovery-file.d.ts +29 -0
- package/dist/src/internal/recovery-file.js +98 -0
- package/dist/src/internal/signer.d.ts +59 -0
- package/dist/src/internal/signer.js +86 -0
- package/dist/src/key-store.d.ts +128 -0
- package/dist/src/key-store.js +244 -0
- package/dist/src/mandates.d.ts +163 -1
- package/dist/src/mandates.js +286 -8
- package/dist/src/react/AithosAsset.d.ts +66 -0
- package/dist/src/react/AithosAsset.js +67 -0
- package/dist/src/react/context.d.ts +29 -0
- package/dist/src/react/context.js +31 -0
- package/dist/src/react/index.d.ts +28 -0
- package/dist/src/react/index.js +30 -0
- package/dist/src/react/use-aithos-asset.d.ts +39 -0
- package/dist/src/react/use-aithos-asset.js +118 -0
- package/dist/src/sdk.d.ts +46 -3
- package/dist/src/sdk.js +49 -23
- package/dist/src/wallet.d.ts +4 -6
- package/dist/src/wallet.js +18 -8
- package/dist/src/web.d.ts +279 -0
- package/dist/src/web.js +186 -0
- package/dist/test/auth-j3.test.d.ts +2 -0
- package/dist/test/auth-j3.test.js +391 -0
- package/dist/test/compute-delegate-path.test.d.ts +2 -0
- package/dist/test/compute-delegate-path.test.js +183 -0
- package/dist/test/compute.test.js +26 -11
- package/dist/test/endpoints.test.js +20 -1
- package/dist/test/envelope.test.d.ts +2 -0
- package/dist/test/envelope.test.js +318 -0
- package/dist/test/ethos-first-edition.test.d.ts +2 -0
- package/dist/test/ethos-first-edition.test.js +248 -0
- package/dist/test/ethos.test.d.ts +2 -0
- package/dist/test/ethos.test.js +219 -0
- package/dist/test/key-store.test.d.ts +2 -0
- package/dist/test/key-store.test.js +161 -0
- package/dist/test/mandates-compute.test.d.ts +2 -0
- package/dist/test/mandates-compute.test.js +256 -0
- package/dist/test/mandates.test.d.ts +2 -0
- package/dist/test/mandates.test.js +93 -0
- package/dist/test/sdk.test.js +70 -30
- package/dist/test/signer.test.d.ts +2 -0
- package/dist/test/signer.test.js +117 -0
- package/dist/test/signup-bootstrap.test.d.ts +2 -0
- package/dist/test/signup-bootstrap.test.js +311 -0
- package/dist/test/wallet.test.js +20 -9
- package/dist/test/web.test.d.ts +2 -0
- package/dist/test/web.test.js +270 -0
- package/package.json +18 -3
package/README.md
CHANGED
|
@@ -55,15 +55,219 @@ const reply = await sdk.compute.invokeBedrock({
|
|
|
55
55
|
console.log(reply.content);
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
+
## Delegating compute to an agent — opt-in token spending
|
|
59
|
+
|
|
60
|
+
To let an agent (or another user, or a third-party app) invoke Bedrock
|
|
61
|
+
**in your name**, with **your credits**, you mint a mandate. Token
|
|
62
|
+
spending is its own opt-in capability — passing it is a separate,
|
|
63
|
+
named, validated input that a consent UI can review. It is NEVER an
|
|
64
|
+
implicit side-effect of an ethos read/write scope.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// Mint a mandate that lets agent Bob read your public ethos AND
|
|
68
|
+
// spend up to 5 000 microcredits/day on Haiku, capped at 100 000
|
|
69
|
+
// microcredits over the whole mandate lifetime.
|
|
70
|
+
const mandate = await sdk.mandates.create({
|
|
71
|
+
granteeId: "urn:agent:bob",
|
|
72
|
+
scopes: ["ethos.read.public"],
|
|
73
|
+
ttlSeconds: 86_400,
|
|
74
|
+
compute: {
|
|
75
|
+
dailyCapMicrocredits: 5_000,
|
|
76
|
+
totalCapMicrocredits: 100_000,
|
|
77
|
+
maxCreditsPerCall: 500,
|
|
78
|
+
allowedModels: ["claude-haiku-4-5"],
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Hand `mandate.bundle` (a `.aithos-delegate.json` Blob) to Bob.
|
|
83
|
+
// He imports it, then signs his own envelopes and calls
|
|
84
|
+
// sdk.compute.invokeBedrock({ mandateId: mandate.mandateId, … })
|
|
85
|
+
// — every invocation debits *your* wallet, capped per the budget
|
|
86
|
+
// you set.
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Three invariants the SDK enforces synchronously, before reaching the
|
|
90
|
+
network — they fail fast with a precise `AithosSDKError`:
|
|
91
|
+
|
|
92
|
+
- **No smuggling.** Adding `"compute.invoke"` directly to `scopes[]`
|
|
93
|
+
throws `mandates_invalid_scopes`. The `compute` namespace is the
|
|
94
|
+
only path, so a UI reviewing `compute` can never be bypassed.
|
|
95
|
+
- **No bearer compute.** A `compute` namespace without at least one
|
|
96
|
+
of `dailyCapMicrocredits` or `totalCapMicrocredits` throws
|
|
97
|
+
`mandates_invalid_compute`. Unbounded compute mandates are forbidden
|
|
98
|
+
by construction.
|
|
99
|
+
- **Compute-only is fine.** `scopes: []` is allowed when `compute` is
|
|
100
|
+
set — useful for agents that only consume tokens (e.g. creative
|
|
101
|
+
assistants) without seeing any of your data.
|
|
102
|
+
|
|
103
|
+
## Custodial auth — onboarding users without a recovery file
|
|
104
|
+
|
|
105
|
+
Three new methods on `AithosAuth` let an app create and authenticate
|
|
106
|
+
its end-users via a server-managed custody flow — the user only needs
|
|
107
|
+
an email address and a password sent by mail. No recovery file, no
|
|
108
|
+
Google account, no client-side cryptography to handle.
|
|
109
|
+
|
|
110
|
+
The model is honest custody: Aithos KMS-wraps the user's Ed25519
|
|
111
|
+
identity seeds, and unwraps them on every sign-in after password
|
|
112
|
+
verification. Equivalent to how Coinbase or any hosted SaaS keeps your
|
|
113
|
+
private key. Annunciated to the user in the welcome email.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { AithosSDK } from "@aithos/sdk";
|
|
117
|
+
|
|
118
|
+
// ─── Server-side: sign-up ───────────────────────────────────────────
|
|
119
|
+
// MUST run on your backend. The API key is a server secret —
|
|
120
|
+
// provisioned by Aithos via the operator runbook.
|
|
121
|
+
const sdk = new AithosSDK({ identity });
|
|
122
|
+
const result = await sdk.auth.signUpCustodial({
|
|
123
|
+
apiKey: process.env.AITHOS_API_KEY!,
|
|
124
|
+
email: "alice@example.com",
|
|
125
|
+
displayName: "Alice",
|
|
126
|
+
});
|
|
127
|
+
// → { userId, did, handle, email, mailSent }
|
|
128
|
+
// The user receives an email with their password and a sign-in link.
|
|
129
|
+
|
|
130
|
+
// ─── Browser-side: sign-in ──────────────────────────────────────────
|
|
131
|
+
// User pastes the password from their mail into your sign-in form,
|
|
132
|
+
// then your frontend calls this. No API key needed — the password
|
|
133
|
+
// is the credential.
|
|
134
|
+
const { session, passwordMustChange } = await sdk.auth.signInCustodial({
|
|
135
|
+
email: "alice@example.com",
|
|
136
|
+
password: "MyTempPass32chars",
|
|
137
|
+
});
|
|
138
|
+
// Local KeyStore is now hydrated with the 4 Ed25519 sphere seeds —
|
|
139
|
+
// the user can publish ethos editions, mint mandates, invoke compute,
|
|
140
|
+
// exactly as if they had signed in via a recovery file or Google SSO.
|
|
141
|
+
if (passwordMustChange) {
|
|
142
|
+
// Optional: nudge the user to set their own password via the
|
|
143
|
+
// standard reset flow.
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ─── Browser-side: request password reset ───────────────────────────
|
|
147
|
+
// The backend always returns silently (anti-enumeration). If the email
|
|
148
|
+
// is registered AND in custodial mode AND not in cooldown AND under the
|
|
149
|
+
// daily cap, a magic-link email is sent to the address.
|
|
150
|
+
await sdk.auth.requestPasswordReset({ email: "alice@example.com" });
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The reset finalization (collecting the new password from the user) is
|
|
154
|
+
done on a small web page hosted by Aithos at `https://app.aithos.be/reset`
|
|
155
|
+
(or your app's own `reset_base_url` if you've registered one — see the
|
|
156
|
+
operator runbook). The page POSTs to `/auth/custodial/reset/finalize`
|
|
157
|
+
and returns the user to your sign-in page on success.
|
|
158
|
+
|
|
159
|
+
### Getting an API key
|
|
160
|
+
|
|
161
|
+
API keys are provisioned out-of-band by Aithos. Contact the maintainer
|
|
162
|
+
(or use the self-service console at `aithos.be/console` when it ships
|
|
163
|
+
in V2). The pattern is `aithos_<env>_<32 chars b58>`. Keep it in your
|
|
164
|
+
backend's secrets manager — never in browser code.
|
|
165
|
+
|
|
166
|
+
### Trade-offs vs. the zk and Google SSO flows
|
|
167
|
+
|
|
168
|
+
| | zk (recovery file) | Google SSO (KMS) | **Custodial** |
|
|
169
|
+
|----------------|----------------------------|----------------------|---------------|
|
|
170
|
+
| User burden | downloads `recovery.json` | Google consent | email only |
|
|
171
|
+
| Password reset | requires recovery file | re-auth via Google | magic-link mail |
|
|
172
|
+
| Trust model | zero-knowledge (you only) | Aithos + Google | Aithos only |
|
|
173
|
+
| Multi-device | re-import recovery | re-Google | email + password |
|
|
174
|
+
| SDK signing capability | full | full | full |
|
|
175
|
+
|
|
176
|
+
Custodial is the right default for SDK-integrated apps that want
|
|
177
|
+
SaaS-grade UX. zk is the right default for power users who want
|
|
178
|
+
sovereign custody. SSO is the right default for users already invested
|
|
179
|
+
in the Google ecosystem.
|
|
180
|
+
|
|
181
|
+
## Extracting webpages without an LLM
|
|
182
|
+
|
|
183
|
+
`sdk.web` is a token-priced primitive that lets your agent read a
|
|
184
|
+
public webpage and get back cleaned HTML, purged CSS and a
|
|
185
|
+
deterministic visual signature — all computed server-side without an
|
|
186
|
+
LLM in the loop. Pricing is a flat **1 microcredit** per successful
|
|
187
|
+
extraction (refunded on failure), versus ~30 mc for a comparable
|
|
188
|
+
LLM-based extraction.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
import { AithosSDK } from "@aithos/sdk";
|
|
192
|
+
|
|
193
|
+
const sdk = new AithosSDK({ auth, appDid });
|
|
194
|
+
|
|
195
|
+
const { data, creditsCharged } = await sdk.web.extract({
|
|
196
|
+
url: "https://example.com",
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
console.log(data.meta.title); // "Example Domain"
|
|
200
|
+
console.log(data.visual_signature.colors.primary); // "#0078d4"
|
|
201
|
+
console.log(data.styles.css.length); // purged + minified CSS
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Owners can mint a mandate for delegate-only extraction:
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
import { WEB_EXTRACT_SCOPE } from "@aithos/sdk";
|
|
208
|
+
|
|
209
|
+
await sdk.mandates.create({
|
|
210
|
+
appDid: "did:aithos:app:my-agent",
|
|
211
|
+
scopes: [WEB_EXTRACT_SCOPE],
|
|
212
|
+
// ...
|
|
213
|
+
});
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## Calling a third-party Aithos-aware backend
|
|
217
|
+
|
|
218
|
+
If your app talks to its own backend (a service you built that verifies
|
|
219
|
+
Aithos envelopes per spec §11.2 using
|
|
220
|
+
`@aithos/protocol-core/envelope`), use `sdk.auth.signEnvelope` to sign
|
|
221
|
+
the request with the same primitive that SDK namespaces use internally
|
|
222
|
+
for `api.aithos.be`. No JWT, no shadow session — the user's DID in the
|
|
223
|
+
envelope's `iss` field is the identity.
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
import { AithosSDK, type SignedEnvelope } from "@aithos/sdk";
|
|
227
|
+
|
|
228
|
+
// Sign a request to your own backend with the active owner's
|
|
229
|
+
// public-sphere key. Default TTL is 60 s.
|
|
230
|
+
const envelope: SignedEnvelope = await sdk.auth.signEnvelope({
|
|
231
|
+
aud: "https://api.example.com/v1/widgets",
|
|
232
|
+
method: "myapp.widgets.create",
|
|
233
|
+
params: { name: "Widget #1" },
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
await fetch("https://api.example.com/v1/widgets", {
|
|
237
|
+
method: "POST",
|
|
238
|
+
headers: { "content-type": "application/json" },
|
|
239
|
+
body: JSON.stringify({
|
|
240
|
+
jsonrpc: "2.0",
|
|
241
|
+
id: crypto.randomUUID(),
|
|
242
|
+
method: "myapp.widgets.create",
|
|
243
|
+
params: { name: "Widget #1", _envelope: envelope },
|
|
244
|
+
}),
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
The envelope binds the signature to `(iss, aud, method, params_hash,
|
|
249
|
+
nonce, iat, exp)`, so a single envelope cannot be replayed against a
|
|
250
|
+
different endpoint, method, or payload. Throws
|
|
251
|
+
`AithosSDKError("auth_not_signed_in")` if no owner is loaded; throws
|
|
252
|
+
`AithosSDKError("auth_invalid_sphere")` if you pass a sphere outside
|
|
253
|
+
`"root" | "public" | "circle" | "self"` (default is `"public"`).
|
|
254
|
+
|
|
255
|
+
Server-side, your backend verifies the envelope with
|
|
256
|
+
`@aithos/protocol-core`'s `verifyEnvelope` (the 9-step check from spec
|
|
257
|
+
§11.4) — same algorithm that `api.aithos.be` uses, no re-implementation
|
|
258
|
+
needed.
|
|
259
|
+
|
|
58
260
|
## What lives where
|
|
59
261
|
|
|
60
|
-
| Namespace
|
|
61
|
-
|
|
|
62
|
-
| `sdk.
|
|
63
|
-
| `sdk.
|
|
64
|
-
| `sdk.
|
|
65
|
-
| `sdk.
|
|
66
|
-
| `sdk.
|
|
262
|
+
| Namespace | Purpose |
|
|
263
|
+
| -------------------------- | ------------------------------------------------------------------------------------------ |
|
|
264
|
+
| `sdk.auth` | Sign-in, sign-up, key custody — and `signEnvelope` for calls to your own Aithos-aware backend. |
|
|
265
|
+
| `sdk.compute` | Bedrock invocation through the Aithos compute proxy (signed envelope, wallet enforcement). |
|
|
266
|
+
| `sdk.web` | Webpage extraction without an LLM through the web extractor proxy (1 mc / call). |
|
|
267
|
+
| `sdk.wallet` | Stripe Checkout sessions for credit-pack top-ups, balance helpers. |
|
|
268
|
+
| `sdk.ethos` | Ethos-zone composition / parsing — re-exported from `@aithos/protocol-client`. |
|
|
269
|
+
| `sdk.onboarding` | First-run identity / DID flows — re-exported. |
|
|
270
|
+
| `sdk.mandates` | Mint / verify mandates — re-exported. |
|
|
67
271
|
|
|
68
272
|
## License
|
|
69
273
|
|
|
@@ -0,0 +1,155 @@
|
|
|
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
|
+
//# sourceMappingURL=apps.d.ts.map
|
package/dist/src/apps.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
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, sign } from "@aithos/protocol-client";
|
|
29
|
+
import { 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
|
+
#requireOwner() {
|
|
195
|
+
const owner = this.#deps.auth._getOwnerSigners();
|
|
196
|
+
if (!owner || owner.destroyed) {
|
|
197
|
+
throw new AithosSDKError("sdk_no_owner", "no owner signed in; sign in first");
|
|
198
|
+
}
|
|
199
|
+
return owner;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/* -------------------------------------------------------------------------- */
|
|
203
|
+
/* Validation */
|
|
204
|
+
/* -------------------------------------------------------------------------- */
|
|
205
|
+
function validateBudget(b) {
|
|
206
|
+
if (!Number.isInteger(b.perUserCap) || b.perUserCap < 0) {
|
|
207
|
+
throw new AithosSDKError("invalid_input", "budget.perUserCap must be a non-negative integer");
|
|
208
|
+
}
|
|
209
|
+
if (!Number.isInteger(b.perDayTotalCap) || b.perDayTotalCap < 0) {
|
|
210
|
+
throw new AithosSDKError("invalid_input", "budget.perDayTotalCap must be a non-negative integer");
|
|
211
|
+
}
|
|
212
|
+
if (b.perUserWindowSeconds !== undefined &&
|
|
213
|
+
b.perUserWindowSeconds !== null) {
|
|
214
|
+
if (!Number.isInteger(b.perUserWindowSeconds) ||
|
|
215
|
+
b.perUserWindowSeconds <= 0) {
|
|
216
|
+
throw new AithosSDKError("invalid_input", "budget.perUserWindowSeconds must be null or a positive integer");
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (b.poolCapTotal !== undefined && b.poolCapTotal !== null) {
|
|
220
|
+
if (!Number.isInteger(b.poolCapTotal) || b.poolCapTotal < 0) {
|
|
221
|
+
throw new AithosSDKError("invalid_input", "budget.poolCapTotal must be null or a non-negative integer");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function validateAudience(a) {
|
|
226
|
+
if (!a.appDid || typeof a.appDid !== "string") {
|
|
227
|
+
throw new AithosSDKError("invalid_input", "audience.appDid must be a DID string");
|
|
228
|
+
}
|
|
229
|
+
if (a.audienceSet === "open") {
|
|
230
|
+
if (a.consumers !== undefined) {
|
|
231
|
+
throw new AithosSDKError("invalid_input", "audience.consumers MUST be absent when audienceSet is 'open'");
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
else if (a.audienceSet === "list") {
|
|
235
|
+
if (!Array.isArray(a.consumers) || a.consumers.length === 0) {
|
|
236
|
+
throw new AithosSDKError("invalid_input", "audience.consumers MUST be a non-empty array when audienceSet is 'list'");
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
throw new AithosSDKError("invalid_input", `audience.audienceSet must be 'open' or 'list' (got: ${String(a.audienceSet)})`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/* -------------------------------------------------------------------------- */
|
|
244
|
+
/* ULID + JCS — local copies to avoid a runtime dep */
|
|
245
|
+
/* -------------------------------------------------------------------------- */
|
|
246
|
+
const ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
247
|
+
function ulid(now = Date.now()) {
|
|
248
|
+
// 10 chars timestamp + 16 chars random = 26 chars
|
|
249
|
+
let timePart = "";
|
|
250
|
+
let t = now;
|
|
251
|
+
for (let i = 0; i < 10; i++) {
|
|
252
|
+
const mod = t % 32;
|
|
253
|
+
timePart = ULID_ALPHABET[mod] + timePart;
|
|
254
|
+
t = (t - mod) / 32;
|
|
255
|
+
}
|
|
256
|
+
let randPart = "";
|
|
257
|
+
for (let i = 0; i < 16; i++) {
|
|
258
|
+
randPart += ULID_ALPHABET[Math.floor(Math.random() * 32)];
|
|
259
|
+
}
|
|
260
|
+
return timePart + randPart;
|
|
261
|
+
}
|
|
262
|
+
function randomBytes(n) {
|
|
263
|
+
const out = new Uint8Array(n);
|
|
264
|
+
crypto.getRandomValues(out);
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Minimal RFC-8785 (JCS) canonicalization. Sorts object keys
|
|
269
|
+
* lexicographically by code point, no whitespace, JSON.stringify for
|
|
270
|
+
* primitives. Matches the protocol-core canonicalize used to compute
|
|
271
|
+
* the hash the signature commits to.
|
|
272
|
+
*/
|
|
273
|
+
function jcsCanonicalize(value) {
|
|
274
|
+
if (value === null || typeof value !== "object") {
|
|
275
|
+
return JSON.stringify(value);
|
|
276
|
+
}
|
|
277
|
+
if (Array.isArray(value)) {
|
|
278
|
+
return "[" + value.map(jcsCanonicalize).join(",") + "]";
|
|
279
|
+
}
|
|
280
|
+
const obj = value;
|
|
281
|
+
const keys = Object.keys(obj).sort();
|
|
282
|
+
return ("{" +
|
|
283
|
+
keys
|
|
284
|
+
.map((k) => JSON.stringify(k) + ":" + jcsCanonicalize(obj[k]))
|
|
285
|
+
.join(",") +
|
|
286
|
+
"}");
|
|
287
|
+
}
|
|
288
|
+
//# sourceMappingURL=apps.js.map
|