@aithos/sdk 0.1.0-alpha.1 → 0.1.0-alpha.10

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 (55) hide show
  1. package/README.md +45 -0
  2. package/dist/src/auth-api.d.ts +41 -0
  3. package/dist/src/auth-api.js +82 -0
  4. package/dist/src/auth.d.ts +166 -0
  5. package/dist/src/auth.js +730 -0
  6. package/dist/src/compute.d.ts +27 -6
  7. package/dist/src/compute.js +67 -10
  8. package/dist/src/ethos.d.ts +117 -1
  9. package/dist/src/ethos.js +646 -16
  10. package/dist/src/index.d.ts +11 -4
  11. package/dist/src/index.js +31 -5
  12. package/dist/src/internal/delegate-bundle.d.ts +18 -0
  13. package/dist/src/internal/delegate-bundle.js +94 -0
  14. package/dist/src/internal/delegate-state.d.ts +45 -0
  15. package/dist/src/internal/delegate-state.js +120 -0
  16. package/dist/src/internal/owner-signers.d.ts +78 -0
  17. package/dist/src/internal/owner-signers.js +179 -0
  18. package/dist/src/internal/protocol-client-bridge.d.ts +8 -0
  19. package/dist/src/internal/protocol-client-bridge.js +20 -0
  20. package/dist/src/internal/recovery-file.d.ts +29 -0
  21. package/dist/src/internal/recovery-file.js +98 -0
  22. package/dist/src/internal/signer.d.ts +59 -0
  23. package/dist/src/internal/signer.js +86 -0
  24. package/dist/src/key-store.d.ts +128 -0
  25. package/dist/src/key-store.js +244 -0
  26. package/dist/src/mandates.d.ts +163 -1
  27. package/dist/src/mandates.js +286 -8
  28. package/dist/src/sdk.d.ts +36 -3
  29. package/dist/src/sdk.js +28 -22
  30. package/dist/src/session-store.d.ts +58 -0
  31. package/dist/src/session-store.js +158 -0
  32. package/dist/src/wallet.d.ts +42 -2
  33. package/dist/src/wallet.js +89 -14
  34. package/dist/test/auth-j3.test.d.ts +2 -0
  35. package/dist/test/auth-j3.test.js +391 -0
  36. package/dist/test/auth.test.d.ts +2 -0
  37. package/dist/test/auth.test.js +175 -0
  38. package/dist/test/compute-delegate-path.test.d.ts +2 -0
  39. package/dist/test/compute-delegate-path.test.js +183 -0
  40. package/dist/test/compute.test.js +22 -11
  41. package/dist/test/ethos-first-edition.test.d.ts +2 -0
  42. package/dist/test/ethos-first-edition.test.js +248 -0
  43. package/dist/test/ethos.test.d.ts +2 -0
  44. package/dist/test/ethos.test.js +219 -0
  45. package/dist/test/key-store.test.d.ts +2 -0
  46. package/dist/test/key-store.test.js +161 -0
  47. package/dist/test/mandates-compute.test.d.ts +2 -0
  48. package/dist/test/mandates-compute.test.js +256 -0
  49. package/dist/test/mandates.test.d.ts +2 -0
  50. package/dist/test/mandates.test.js +93 -0
  51. package/dist/test/sdk.test.js +70 -30
  52. package/dist/test/signer.test.d.ts +2 -0
  53. package/dist/test/signer.test.js +117 -0
  54. package/dist/test/wallet.test.js +20 -9
  55. package/package.json +4 -3
package/README.md CHANGED
@@ -55,6 +55,51 @@ 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
+
58
103
  ## What lives where
59
104
 
60
105
  | Namespace | Purpose |
@@ -0,0 +1,41 @@
1
+ import { type KdfParams } from "@aithos/protocol-client";
2
+ interface HttpClient {
3
+ readonly fetchImpl: typeof fetch;
4
+ readonly authBaseUrl: string;
5
+ }
6
+ export interface RegisterApiInput {
7
+ readonly email: string;
8
+ readonly handle: string;
9
+ readonly displayName: string;
10
+ readonly did: string;
11
+ readonly authKey: Uint8Array;
12
+ readonly authSalt: Uint8Array;
13
+ readonly encSalt: Uint8Array;
14
+ readonly kdf: KdfParams;
15
+ readonly blob: Uint8Array;
16
+ readonly blobNonce: Uint8Array;
17
+ readonly blobVersion: number;
18
+ }
19
+ export interface RegisterApiResponse {
20
+ readonly session: string;
21
+ readonly exp: number;
22
+ }
23
+ export declare function registerAccount(http: HttpClient, input: RegisterApiInput): Promise<RegisterApiResponse>;
24
+ export interface LoginChallengeResponse {
25
+ readonly authSalt: Uint8Array;
26
+ readonly encSalt: Uint8Array;
27
+ readonly kdf: KdfParams;
28
+ }
29
+ export declare function loginChallenge(http: HttpClient, email: string): Promise<LoginChallengeResponse>;
30
+ export interface LoginVerifyResponse {
31
+ readonly session: string;
32
+ readonly exp: number;
33
+ readonly did: string;
34
+ readonly handle: string;
35
+ readonly blob: Uint8Array;
36
+ readonly blobNonce: Uint8Array;
37
+ readonly blobVersion: number;
38
+ }
39
+ export declare function loginVerify(http: HttpClient, email: string, authKey: Uint8Array): Promise<LoginVerifyResponse>;
40
+ export {};
41
+ //# sourceMappingURL=auth-api.d.ts.map
@@ -0,0 +1,82 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Mathieu Colla
3
+ // Thin HTTP client over the Aithos auth Lambda.
4
+ //
5
+ // Internal — not exported from the package's public surface. The
6
+ // {@link AithosAuth} class composes these calls with the crypto
7
+ // primitives in `@aithos/protocol-client` and the session store in
8
+ // {@link ./session-store.ts} to expose a high-level
9
+ // signIn / signUp / signInWithGoogle API.
10
+ //
11
+ // Wire format mirrors `aithos/auth/API.md` exactly. All `*_b64` fields
12
+ // are standard-base64 (not URL-safe), padding stripped — see
13
+ // `bytesToB64` / `b64ToBytes` in `@aithos/protocol-client`.
14
+ import { bytesToB64, b64ToBytes, } from "@aithos/protocol-client";
15
+ import { AithosSDKError } from "./types.js";
16
+ async function readError(res, defaultCode) {
17
+ let body = null;
18
+ try {
19
+ body = (await res.json());
20
+ }
21
+ catch {
22
+ /* body not JSON */
23
+ }
24
+ const code = typeof body?.code === "string" ? `auth_${body.code}` : `auth_${defaultCode}`;
25
+ const message = body?.error ?? `${res.status} ${res.statusText || "request failed"}`;
26
+ return new AithosSDKError(code, message, {
27
+ status: res.status,
28
+ ...(body !== null ? { data: body } : {}),
29
+ });
30
+ }
31
+ async function postJson(http, path, body, jwt) {
32
+ const res = await http.fetchImpl(`${http.authBaseUrl}${path}`, {
33
+ method: "POST",
34
+ headers: {
35
+ "content-type": "application/json",
36
+ ...(jwt ? { authorization: `Bearer ${jwt}` } : {}),
37
+ },
38
+ body: JSON.stringify(body),
39
+ });
40
+ if (!res.ok)
41
+ throw await readError(res, "request_failed");
42
+ return (await res.json());
43
+ }
44
+ export async function registerAccount(http, input) {
45
+ return postJson(http, "/auth/register", {
46
+ email: input.email,
47
+ handle: input.handle,
48
+ display_name: input.displayName,
49
+ did: input.did,
50
+ auth_key_b64: bytesToB64(input.authKey),
51
+ auth_salt_b64: bytesToB64(input.authSalt),
52
+ enc_salt_b64: bytesToB64(input.encSalt),
53
+ kdf: input.kdf,
54
+ blob_b64: bytesToB64(input.blob),
55
+ blob_nonce_b64: bytesToB64(input.blobNonce),
56
+ blob_version: input.blobVersion,
57
+ });
58
+ }
59
+ export async function loginChallenge(http, email) {
60
+ const wire = await postJson(http, "/auth/login/challenge", { email });
61
+ return {
62
+ authSalt: b64ToBytes(wire.auth_salt_b64),
63
+ encSalt: b64ToBytes(wire.enc_salt_b64),
64
+ kdf: wire.kdf,
65
+ };
66
+ }
67
+ export async function loginVerify(http, email, authKey) {
68
+ const wire = await postJson(http, "/auth/login/verify", {
69
+ email,
70
+ auth_key_b64: bytesToB64(authKey),
71
+ });
72
+ return {
73
+ session: wire.session,
74
+ exp: wire.exp,
75
+ did: wire.did,
76
+ handle: wire.handle,
77
+ blob: b64ToBytes(wire.blob_b64),
78
+ blobNonce: b64ToBytes(wire.blob_nonce_b64),
79
+ blobVersion: wire.blob_version,
80
+ };
81
+ }
82
+ //# sourceMappingURL=auth-api.js.map
@@ -0,0 +1,166 @@
1
+ import { type AithosSessionStore } from "./session-store.js";
2
+ import { type AithosKeyStore } from "./key-store.js";
3
+ import { DelegateActor } from "./internal/delegate-state.js";
4
+ import { OwnerSigners } from "./internal/owner-signers.js";
5
+ /** Default URL of the Aithos auth backend. */
6
+ export declare const DEFAULT_AUTH_BASE_URL = "https://auth.aithos.be";
7
+ /** Default URL of the Aithos primitives API (publish_identity, publish_ethos_edition, etc.). */
8
+ export declare const DEFAULT_API_BASE_URL = "https://api.aithos.be";
9
+ export interface AithosAuthConfig {
10
+ readonly authBaseUrl?: string;
11
+ /**
12
+ * Base URL of the Aithos primitives API (`api.aithos.be`). Used by
13
+ * {@link AithosAuth.signUp} to bootstrap the user's Ethos via
14
+ * `aithos.publish_identity` after the auth account is created. Override
15
+ * for staging or self-hosted deployments. Defaults to
16
+ * {@link DEFAULT_API_BASE_URL}.
17
+ */
18
+ readonly apiBaseUrl?: string;
19
+ readonly fetch?: typeof fetch;
20
+ readonly window?: Pick<Window, "location" | "history">;
21
+ /** Pluggable JWT-session storage. Defaults to {@link defaultSessionStore}. */
22
+ readonly sessionStore?: AithosSessionStore;
23
+ /** Pluggable key persistence. Defaults to {@link defaultKeyStore}. */
24
+ readonly keyStore?: AithosKeyStore;
25
+ }
26
+ /**
27
+ * Active Aithos session. Returned by JWT-backed entry points
28
+ * (`signIn`, `signUp`, `handleCallback`). Recovery-file and mandate
29
+ * sign-ins do NOT return an `AithosSession` — they yield the lighter
30
+ * {@link OwnerInfo} / {@link DelegateInfo}.
31
+ */
32
+ export interface AithosSession {
33
+ readonly session: string;
34
+ readonly exp: number;
35
+ readonly did: string;
36
+ readonly handle: string;
37
+ readonly blob_b64: string;
38
+ readonly blob_nonce_b64: string;
39
+ readonly blob_version: number;
40
+ readonly enc_key_b64: string;
41
+ readonly is_first_login: boolean;
42
+ }
43
+ /**
44
+ * Public information about the loaded owner identity. Available after
45
+ * any owner-side sign-in (password, Google, recovery), regardless of
46
+ * whether a JWT is also present.
47
+ */
48
+ export interface OwnerInfo {
49
+ readonly did: string;
50
+ readonly handle: string;
51
+ readonly displayName: string;
52
+ }
53
+ /**
54
+ * Public information about a delegate session held by the SDK. Returned
55
+ * by `importMandate` and `getDelegates`.
56
+ */
57
+ export interface DelegateInfo {
58
+ readonly mandateId: string;
59
+ readonly subjectDid: string;
60
+ readonly granteeId: string;
61
+ readonly scopes: readonly string[];
62
+ /** ISO-8601, or null when the mandate has no `not_after`. */
63
+ readonly expiresAt: string | null;
64
+ readonly label?: string;
65
+ }
66
+ export interface SignInWithGoogleOptions {
67
+ readonly appState?: string;
68
+ }
69
+ export interface SignInInput {
70
+ readonly email: string;
71
+ readonly password: string;
72
+ }
73
+ export interface SignUpInput {
74
+ readonly email: string;
75
+ readonly password: string;
76
+ readonly handle: string;
77
+ readonly displayName?: string;
78
+ }
79
+ export interface SignUpResult {
80
+ readonly session: AithosSession;
81
+ readonly recoveryFile: Blob;
82
+ readonly recoveryFilename: string;
83
+ }
84
+ export interface SignInWithRecoveryInput {
85
+ /** Recovery file as a Blob (browser File input) or already-decoded JSON string. */
86
+ readonly file: Blob | string;
87
+ }
88
+ export interface ImportMandateInput {
89
+ /** Delegate bundle as a Blob or already-decoded JSON string. */
90
+ readonly bundle: Blob | string;
91
+ }
92
+ export declare class AithosAuth {
93
+ #private;
94
+ readonly authBaseUrl: string;
95
+ readonly apiBaseUrl: string;
96
+ constructor(config?: AithosAuthConfig);
97
+ /**
98
+ * Reload signing material and JWT session from the configured stores.
99
+ * Must be called once at app boot before relying on
100
+ * {@link getCurrentSession} / {@link getOwnerInfo} / {@link canSignAsOwner}
101
+ * — until then they reflect only what's been done in-memory in the
102
+ * current tab.
103
+ *
104
+ * Strict consistency: if the JWT and the stored owner disagree about
105
+ * who's signed in, both are wiped and the user re-auths. JWT-less
106
+ * owner state (loaded from keyStore but no JWT) is a valid resumed
107
+ * state — the user signed in via recovery or imported a mandate at
108
+ * some earlier moment and never went through the JWT flow.
109
+ */
110
+ resume(): Promise<void>;
111
+ /** JWT-backed session. Null when signed in via recovery / mandate / not at all. */
112
+ getCurrentSession(): AithosSession | null;
113
+ /** Loaded owner identity. Independent of JWT presence. */
114
+ getOwnerInfo(): OwnerInfo | null;
115
+ getDelegates(): readonly DelegateInfo[];
116
+ canSignAsOwner(): boolean;
117
+ canSignAsDelegateFor(did: string): boolean;
118
+ /**
119
+ * Internal accessor used by sibling SDK namespaces (compute, wallet,
120
+ * ethos) when they need to sign on behalf of the owner. Returns null
121
+ * if no owner is loaded.
122
+ *
123
+ * @internal
124
+ */
125
+ _getOwnerSigners(): OwnerSigners | null;
126
+ /**
127
+ * Internal accessor — looks up an active delegate by mandate id.
128
+ * @internal
129
+ */
130
+ _getDelegateActor(mandateId: string): DelegateActor | undefined;
131
+ /**
132
+ * Internal accessor — finds the first active delegate whose subject
133
+ * matches `did`. Used by `sdk.ethos.of(did)` when the user holds a
134
+ * mandate for that subject.
135
+ * @internal
136
+ */
137
+ _findDelegateForSubject(did: string): DelegateActor | undefined;
138
+ signIn(input: SignInInput): Promise<AithosSession>;
139
+ signUp(input: SignUpInput): Promise<SignUpResult>;
140
+ /**
141
+ * Sign in by uploading a recovery file. Hydrates the owner signers
142
+ * locally — no JWT is obtained on this path because the recovery
143
+ * file alone doesn't authenticate against the auth backend (no
144
+ * password, no Google session). Apps that need compute/wallet
145
+ * access should follow up with an email+password sign-in or with
146
+ * Google SSO.
147
+ *
148
+ * The recovery file is ALWAYS the file produced by `signUp` (or the
149
+ * equivalent one emitted by `protocol-client`'s `runOnboarding`).
150
+ * Both shapes are accepted.
151
+ */
152
+ signInWithRecovery(input: SignInWithRecoveryInput): Promise<OwnerInfo>;
153
+ /**
154
+ * Import a delegate bundle (`.aithos-delegate.json`). Works in any
155
+ * state: with no owner loaded (delegate-only session), or alongside
156
+ * an existing owner (the user holds mandates for other people's
157
+ * ethoses while also being an owner themselves).
158
+ */
159
+ importMandate(input: ImportMandateInput): Promise<DelegateInfo>;
160
+ removeMandate(mandateId: string): Promise<void>;
161
+ signInWithGoogle(opts?: SignInWithGoogleOptions): never;
162
+ handleCallback(): Promise<AithosSession | null>;
163
+ exchange(aithosCode: string): Promise<AithosSession>;
164
+ signOut(): Promise<void>;
165
+ }
166
+ //# sourceMappingURL=auth.d.ts.map