@aithos/sdk 0.1.0-alpha.45 → 0.1.0-alpha.47

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.
@@ -132,6 +132,87 @@ export type CustodialVerifyEmailApiResponse = {
132
132
  * or past its TTL.
133
133
  */
134
134
  export declare function custodialVerifyEmail(http: HttpClient, input: CustodialVerifyEmailApiInput): Promise<CustodialVerifyEmailApiResponse>;
135
+ /**
136
+ * Input for {@link custodialInvite}. The app authenticates via `apiKey`
137
+ * (server-only secret) or `publicKey` (browser-safe, Origin-gated). The
138
+ * `invitePayload` is an OPAQUE app string delivered verbatim to the invitee
139
+ * on {@link custodialAccept}. For Aithos invitations it's a delegate bundle
140
+ * (mandate + seed) serialized as JSON — but the auth backend never parses it;
141
+ * it stores it bound to a single-use token and returns it at accept time.
142
+ */
143
+ export interface CustodialInviteApiInput {
144
+ readonly apiKey?: string;
145
+ readonly publicKey?: string;
146
+ readonly email: string;
147
+ /** Opaque payload delivered to the invitee on accept (e.g. a mandate bundle JSON). */
148
+ readonly invitePayload: string;
149
+ /** Token TTL in seconds. Backend clamps to its own min/max. Default backend-side. */
150
+ readonly ttlSeconds?: number;
151
+ /** Optional display name pre-filled on the pending account. */
152
+ readonly displayName?: string;
153
+ }
154
+ export interface CustodialInviteApiResponse {
155
+ readonly status: "invited";
156
+ readonly email: string;
157
+ readonly mailSent: boolean;
158
+ readonly mailMessageId?: string;
159
+ }
160
+ /**
161
+ * Send an invitation magic link carrying an opaque payload. The backend
162
+ * mints a single-use token, stores `{ token, email, invite_payload, ttl }`,
163
+ * and emails the magic link (same SES path as the verification mail). The
164
+ * payload (e.g. a mandate bundle) stays server-side — it never rides the
165
+ * email URL. The invitee redeems it via {@link custodialAccept}.
166
+ *
167
+ * No password here: this is an invitation, not an account creation. The
168
+ * invitee chooses their password when they accept.
169
+ */
170
+ export declare function custodialInvite(http: HttpClient, input: CustodialInviteApiInput): Promise<CustodialInviteApiResponse>;
171
+ export interface CustodialAcceptApiInput {
172
+ readonly email: string;
173
+ readonly token: string;
174
+ /**
175
+ * Password. For a brand-new account the invitee SETS it here; for an
176
+ * existing account they AUTHENTICATE with it. Required unless the backend
177
+ * accepts a session-bound redemption (not in v1).
178
+ */
179
+ readonly password?: string;
180
+ }
181
+ /**
182
+ * Result of redeeming an invitation. Always `signed_in` on success — the
183
+ * token is consumed, the account is created (or the existing one is
184
+ * authenticated), and a full session payload is returned alongside the
185
+ * `invitePayload` the inviter attached. `accountCreated` distinguishes the
186
+ * two cases for UX.
187
+ */
188
+ export interface CustodialAcceptApiResponse {
189
+ readonly status: "signed_in";
190
+ readonly session: string;
191
+ readonly exp: number;
192
+ readonly did: string;
193
+ readonly handle: string;
194
+ readonly displayName: string;
195
+ readonly seed: Uint8Array;
196
+ readonly encKey: Uint8Array;
197
+ readonly blob: Uint8Array;
198
+ readonly blobNonce: Uint8Array;
199
+ readonly blobVersion: number;
200
+ /** The opaque payload the inviter attached (e.g. a mandate bundle JSON). */
201
+ readonly invitePayload: string;
202
+ /** True when a new account was provisioned; false when an existing one signed in. */
203
+ readonly accountCreated: boolean;
204
+ }
205
+ /**
206
+ * Redeem an invitation token from the magic link. Consumes the token
207
+ * (single-use), creates the account with the supplied password (or
208
+ * authenticates an existing account), and returns a session + the inviter's
209
+ * `invitePayload`.
210
+ *
211
+ * Throws `auth_token_invalid_or_expired` (bad/consumed/expired token) or an
212
+ * auth error if an existing account's password is wrong / a new password is
213
+ * too weak.
214
+ */
215
+ export declare function custodialAccept(http: HttpClient, input: CustodialAcceptApiInput): Promise<CustodialAcceptApiResponse>;
135
216
  /** Re-send the verification mail for a pending account. The backend
136
217
  * is anti-enum (always 200) and rate-limited 1/h/account, so this is
137
218
  * safe to call even when the user state is unknown. Accepts the same
@@ -183,6 +183,86 @@ export async function custodialVerifyEmail(http, input) {
183
183
  blobVersion: wire.blob_version,
184
184
  };
185
185
  }
186
+ /**
187
+ * Send an invitation magic link carrying an opaque payload. The backend
188
+ * mints a single-use token, stores `{ token, email, invite_payload, ttl }`,
189
+ * and emails the magic link (same SES path as the verification mail). The
190
+ * payload (e.g. a mandate bundle) stays server-side — it never rides the
191
+ * email URL. The invitee redeems it via {@link custodialAccept}.
192
+ *
193
+ * No password here: this is an invitation, not an account creation. The
194
+ * invitee chooses their password when they accept.
195
+ */
196
+ export async function custodialInvite(http, input) {
197
+ if (!input.apiKey && !input.publicKey) {
198
+ throw new AithosSDKError("auth_missing_api_key", "inviteCustodial requires either apiKey or publicKey");
199
+ }
200
+ if (input.apiKey && input.publicKey) {
201
+ throw new AithosSDKError("auth_invalid_input", "inviteCustodial: pass exactly one of apiKey or publicKey, not both");
202
+ }
203
+ const bearer = (input.apiKey ?? input.publicKey);
204
+ const res = await http.fetchImpl(`${http.authBaseUrl}/auth/custodial/invite`, {
205
+ method: "POST",
206
+ headers: {
207
+ "content-type": "application/json",
208
+ authorization: `Bearer ${bearer}`,
209
+ },
210
+ body: JSON.stringify({
211
+ email: input.email,
212
+ invite_payload: input.invitePayload,
213
+ ...(input.ttlSeconds !== undefined ? { ttl_seconds: input.ttlSeconds } : {}),
214
+ ...(input.displayName ? { display_name: input.displayName } : {}),
215
+ }),
216
+ });
217
+ if (!res.ok)
218
+ throw await readError(res, "custodial_invite_failed");
219
+ const wire = (await res.json());
220
+ return {
221
+ status: "invited",
222
+ email: wire.email,
223
+ mailSent: wire.mail_sent,
224
+ ...(wire.mail_message_id !== undefined ? { mailMessageId: wire.mail_message_id } : {}),
225
+ };
226
+ }
227
+ /**
228
+ * Redeem an invitation token from the magic link. Consumes the token
229
+ * (single-use), creates the account with the supplied password (or
230
+ * authenticates an existing account), and returns a session + the inviter's
231
+ * `invitePayload`.
232
+ *
233
+ * Throws `auth_token_invalid_or_expired` (bad/consumed/expired token) or an
234
+ * auth error if an existing account's password is wrong / a new password is
235
+ * too weak.
236
+ */
237
+ export async function custodialAccept(http, input) {
238
+ const res = await http.fetchImpl(`${http.authBaseUrl}/auth/custodial/accept`, {
239
+ method: "POST",
240
+ headers: { "content-type": "application/json" },
241
+ body: JSON.stringify({
242
+ email: input.email,
243
+ token: input.token,
244
+ ...(input.password ? { password: input.password } : {}),
245
+ }),
246
+ });
247
+ if (!res.ok)
248
+ throw await readError(res, "custodial_accept_failed");
249
+ const wire = (await res.json());
250
+ return {
251
+ status: "signed_in",
252
+ session: wire.session,
253
+ exp: wire.exp,
254
+ did: wire.did,
255
+ handle: wire.handle,
256
+ displayName: wire.display_name,
257
+ seed: b64ToBytes(wire.seed_b64),
258
+ encKey: b64ToBytes(wire.enc_key_b64),
259
+ blob: wire.blob_b64 ? b64ToBytes(wire.blob_b64) : new Uint8Array(0),
260
+ blobNonce: wire.blob_nonce_b64 ? b64ToBytes(wire.blob_nonce_b64) : new Uint8Array(0),
261
+ blobVersion: wire.blob_version,
262
+ invitePayload: wire.invite_payload,
263
+ accountCreated: wire.account_created,
264
+ };
265
+ }
186
266
  /* ---- POST /auth/custodial/verify/resend -------------------------------- */
187
267
  /** Re-send the verification mail for a pending account. The backend
188
268
  * is anti-enum (always 200) and rate-limited 1/h/account, so this is
@@ -152,6 +152,64 @@ export interface ImportMandateInput {
152
152
  /** Delegate bundle as a Blob or already-decoded JSON string. */
153
153
  readonly bundle: Blob | string;
154
154
  }
155
+ /**
156
+ * Input to {@link AithosAuth.inviteCustodial}. Sends an invitation magic link
157
+ * that carries an opaque payload (typically a delegate bundle) to deliver to
158
+ * the invitee on accept. Mandate-agnostic: `mandateBundle` may be ANY mandate
159
+ * (read/write/append/ethos/compute…) — the auth backend stores it verbatim,
160
+ * bound to a single-use token, and never parses it.
161
+ *
162
+ * The app authenticates via `apiKey` (server-only secret) or `publicKey`
163
+ * (browser-safe, Origin-gated), or the constructor's default `publicKey`.
164
+ * No user password here — the invitee chooses it when they accept.
165
+ */
166
+ export interface InviteCustodialInput {
167
+ readonly apiKey?: string;
168
+ readonly publicKey?: string;
169
+ /** Invitee email — receives the magic link. */
170
+ readonly email: string;
171
+ /**
172
+ * The mandate to deliver. Accept the SDK's `MintedMandate.bundle` (Blob),
173
+ * a JSON string, or a plain bundle object — all normalized to a JSON string.
174
+ */
175
+ readonly mandateBundle: Blob | string | Record<string, unknown>;
176
+ /** Token TTL in seconds (backend clamps to its policy). */
177
+ readonly ttlSeconds?: number;
178
+ /** Optional display name pre-filled on the pending account. */
179
+ readonly displayName?: string;
180
+ }
181
+ /** Result of {@link AithosAuth.inviteCustodial}. */
182
+ export interface InviteCustodialResult {
183
+ readonly status: "invited";
184
+ readonly email: string;
185
+ readonly mailSent: boolean;
186
+ readonly mailMessageId?: string;
187
+ }
188
+ /**
189
+ * Input to {@link AithosAuth.acceptInvite}. `email` and `token` come from the
190
+ * `?email=&token=` query string of the invitation link. `password` is set by
191
+ * the invitee for a NEW account, or used to authenticate an EXISTING one — so
192
+ * it's required whenever the user isn't already signed in.
193
+ */
194
+ export interface AcceptInviteInput {
195
+ readonly email: string;
196
+ readonly token: string;
197
+ readonly password?: string;
198
+ }
199
+ /**
200
+ * Result of {@link AithosAuth.acceptInvite}. The token is consumed, the
201
+ * session is hydrated (account created or existing one signed in), and the
202
+ * invited mandate has been imported into the keystore — `delegate` describes
203
+ * it. Read `delegate.subjectDid` to identify the issuer (e.g. resolve their
204
+ * public Ethos via `sdk.ethos.of(delegate.subjectDid)`).
205
+ */
206
+ export interface AcceptInviteResult {
207
+ readonly status: "signed_in";
208
+ readonly session: AithosSession;
209
+ readonly delegate: DelegateInfo;
210
+ /** True when a new account was provisioned; false when an existing one signed in. */
211
+ readonly accountCreated: boolean;
212
+ }
155
213
  /**
156
214
  * Input to {@link AithosAuth.signUpCustodial}.
157
215
  *
@@ -544,6 +602,32 @@ export declare class AithosAuth {
544
602
  * past its 1h TTL — surface a "request a fresh link" CTA in that case.
545
603
  */
546
604
  verifyEmail(input: VerifyEmailInput): Promise<VerifyEmailResult>;
605
+ /**
606
+ * Send an invitation magic link carrying a mandate. The issuer (owner)
607
+ * mints any mandate via {@link AithosSDK.mandates} (read/write/append/…),
608
+ * then calls this with the bundle: the auth backend stores it bound to a
609
+ * single-use token and emails the magic link. The mandate (and its delegate
610
+ * seed) never ride the email URL. The invitee redeems it via
611
+ * {@link acceptInvite}.
612
+ *
613
+ * Generic — knows nothing about the mandate's scope. Authenticate with
614
+ * `apiKey` (server) or `publicKey` (browser, Origin-gated).
615
+ */
616
+ inviteCustodial(input: InviteCustodialInput): Promise<InviteCustodialResult>;
617
+ /**
618
+ * Redeem an invitation from the magic link: consume the token, sign in
619
+ * (create the account with `password`, or authenticate an existing one),
620
+ * and AUTO-IMPORT the mandate the inviter attached. Returns the session and
621
+ * the imported {@link DelegateInfo}.
622
+ *
623
+ * Mount this on the page declared as the invitation's verify/redirect URL;
624
+ * read `email` + `token` from `window.location.search`, collect the
625
+ * `password`, call this.
626
+ *
627
+ * Throws `auth_token_invalid_or_expired` (bad/consumed/expired token) or an
628
+ * auth error if an existing account's password is wrong / a new one is weak.
629
+ */
630
+ acceptInvite(input: AcceptInviteInput): Promise<AcceptInviteResult>;
547
631
  /**
548
632
  * Re-send the verification mail for a pending account. Use when the
549
633
  * user reports never having received the welcome mail, or when their
package/dist/src/auth.js CHANGED
@@ -21,7 +21,7 @@
21
21
  // keyStore is the source of truth for "is the user signed in", the
22
22
  // JWT is auxiliary for compute/wallet.
23
23
  import { browserIdentityFromStored, buildBlobPlaintext, buildSignedEnvelope, createBrowserIdentity, decryptBlob, DEFAULT_KDF, deriveAuthAndEncKeys, encryptBlob, parseBlob, randomNonce, randomSalt, serializeBlob, signedDidDocument, zeroize, } from "@aithos/protocol-client";
24
- import { custodialResendVerify, custodialResetFinalize, custodialResetRequest, custodialSignIn, custodialSignUp, custodialVerifyEmail, loginChallenge, loginVerify, putBlob, registerAccount, } from "./auth-api.js";
24
+ import { custodialAccept, custodialInvite, custodialResendVerify, custodialResetFinalize, custodialResetRequest, custodialSignIn, custodialSignUp, custodialVerifyEmail, loginChallenge, loginVerify, putBlob, registerAccount, } from "./auth-api.js";
25
25
  import { defaultSessionStore, } from "./session-store.js";
26
26
  import { defaultKeyStore, } from "./key-store.js";
27
27
  import { parseDelegateBundle, readDelegateBundleText, } from "./internal/delegate-bundle.js";
@@ -1029,6 +1029,138 @@ export class AithosAuth {
1029
1029
  this.#sessionStore.set(session);
1030
1030
  return { status: "signed_in", session, passwordMustChange: false };
1031
1031
  }
1032
+ /**
1033
+ * Send an invitation magic link carrying a mandate. The issuer (owner)
1034
+ * mints any mandate via {@link AithosSDK.mandates} (read/write/append/…),
1035
+ * then calls this with the bundle: the auth backend stores it bound to a
1036
+ * single-use token and emails the magic link. The mandate (and its delegate
1037
+ * seed) never ride the email URL. The invitee redeems it via
1038
+ * {@link acceptInvite}.
1039
+ *
1040
+ * Generic — knows nothing about the mandate's scope. Authenticate with
1041
+ * `apiKey` (server) or `publicKey` (browser, Origin-gated).
1042
+ */
1043
+ async inviteCustodial(input) {
1044
+ if (!input.email) {
1045
+ throw new AithosSDKError("auth_invalid_input", "inviteCustodial: email is required");
1046
+ }
1047
+ if (input.mandateBundle === undefined || input.mandateBundle === null) {
1048
+ throw new AithosSDKError("auth_invalid_input", "inviteCustodial: mandateBundle is required");
1049
+ }
1050
+ const apiKey = input.apiKey;
1051
+ const publicKey = input.publicKey ?? this.#publicKey;
1052
+ if (!apiKey && !publicKey) {
1053
+ throw new AithosSDKError("auth_missing_api_key", "inviteCustodial: pass apiKey, or publicKey, or set publicKey on the AithosAuth constructor");
1054
+ }
1055
+ // Normalize the bundle to a JSON string (the opaque invite payload).
1056
+ let invitePayload;
1057
+ if (typeof input.mandateBundle === "string") {
1058
+ invitePayload = input.mandateBundle;
1059
+ }
1060
+ else if (input.mandateBundle instanceof Blob) {
1061
+ invitePayload = await input.mandateBundle.text();
1062
+ }
1063
+ else {
1064
+ invitePayload = JSON.stringify(input.mandateBundle);
1065
+ }
1066
+ const result = await custodialInvite({ fetchImpl: this.#fetchImpl, authBaseUrl: this.authBaseUrl }, {
1067
+ email: input.email,
1068
+ invitePayload,
1069
+ ...(apiKey ? { apiKey } : publicKey ? { publicKey } : {}),
1070
+ ...(input.ttlSeconds !== undefined ? { ttlSeconds: input.ttlSeconds } : {}),
1071
+ ...(input.displayName ? { displayName: input.displayName } : {}),
1072
+ });
1073
+ return {
1074
+ status: "invited",
1075
+ email: result.email,
1076
+ mailSent: result.mailSent,
1077
+ ...(result.mailMessageId !== undefined ? { mailMessageId: result.mailMessageId } : {}),
1078
+ };
1079
+ }
1080
+ /**
1081
+ * Redeem an invitation from the magic link: consume the token, sign in
1082
+ * (create the account with `password`, or authenticate an existing one),
1083
+ * and AUTO-IMPORT the mandate the inviter attached. Returns the session and
1084
+ * the imported {@link DelegateInfo}.
1085
+ *
1086
+ * Mount this on the page declared as the invitation's verify/redirect URL;
1087
+ * read `email` + `token` from `window.location.search`, collect the
1088
+ * `password`, call this.
1089
+ *
1090
+ * Throws `auth_token_invalid_or_expired` (bad/consumed/expired token) or an
1091
+ * auth error if an existing account's password is wrong / a new one is weak.
1092
+ */
1093
+ async acceptInvite(input) {
1094
+ if (!input.email || !input.token) {
1095
+ throw new AithosSDKError("auth_invalid_input", "acceptInvite: email and token are required");
1096
+ }
1097
+ const resp = await custodialAccept({ fetchImpl: this.#fetchImpl, authBaseUrl: this.authBaseUrl }, {
1098
+ email: input.email,
1099
+ token: input.token,
1100
+ ...(input.password ? { password: input.password } : {}),
1101
+ });
1102
+ // Materialise the 4 sphere seeds + session — same shape as the verifyEmail
1103
+ // magic-link path. Kept inline (additive; verifyEmail is left untouched).
1104
+ if (resp.seed.byteLength !== 128) {
1105
+ zeroize(resp.seed);
1106
+ zeroize(resp.encKey);
1107
+ throw new AithosSDKError("auth_custodial_seed_format", `acceptInvite: expected 128-byte seed bundle, got ${resp.seed.byteLength}`);
1108
+ }
1109
+ const seedRoot = resp.seed.slice(0, 32);
1110
+ const seedPublic = resp.seed.slice(32, 64);
1111
+ const seedCircle = resp.seed.slice(64, 96);
1112
+ const seedSelf = resp.seed.slice(96, 128);
1113
+ const stored = {
1114
+ version: "0.1.0-hex",
1115
+ did: resp.did,
1116
+ handle: resp.handle,
1117
+ displayName: resp.displayName,
1118
+ seedsHex: {
1119
+ root: bytesToHex(seedRoot),
1120
+ public: bytesToHex(seedPublic),
1121
+ circle: bytesToHex(seedCircle),
1122
+ self: bytesToHex(seedSelf),
1123
+ },
1124
+ savedAt: new Date().toISOString(),
1125
+ };
1126
+ zeroize(resp.seed);
1127
+ zeroize(seedRoot);
1128
+ zeroize(seedPublic);
1129
+ zeroize(seedCircle);
1130
+ zeroize(seedSelf);
1131
+ zeroize(resp.encKey);
1132
+ const identity = browserIdentityFromStored({
1133
+ handle: stored.handle,
1134
+ displayName: stored.displayName,
1135
+ did: stored.did,
1136
+ seeds: stored.seedsHex,
1137
+ });
1138
+ await this.#publishIdentity(identity);
1139
+ if (this.#ownerSigners)
1140
+ this.#ownerSigners.destroy();
1141
+ this.#ownerSigners = OwnerSigners.fromStoredOwnerKeys(stored);
1142
+ await this.#keyStore.saveOwner(stored);
1143
+ const session = {
1144
+ session: resp.session,
1145
+ exp: resp.exp,
1146
+ did: resp.did,
1147
+ handle: resp.handle,
1148
+ blob_b64: bytesToB64Public(resp.blob),
1149
+ blob_nonce_b64: bytesToB64Public(resp.blobNonce),
1150
+ blob_version: resp.blobVersion,
1151
+ enc_key_b64: "",
1152
+ is_first_login: false,
1153
+ };
1154
+ this.#sessionStore.set(session);
1155
+ // Import the invited mandate into the keystore (generic — any scope).
1156
+ const delegate = await this.importMandate({ bundle: resp.invitePayload });
1157
+ return {
1158
+ status: "signed_in",
1159
+ session,
1160
+ delegate,
1161
+ accountCreated: resp.accountCreated,
1162
+ };
1163
+ }
1032
1164
  /**
1033
1165
  * Re-send the verification mail for a pending account. Use when the
1034
1166
  * user reports never having received the welcome mail, or when their
@@ -277,4 +277,60 @@ export interface CreateDelegateDataClientArgs {
277
277
  * forced.
278
278
  */
279
279
  export declare function createDelegateDataClient(args: CreateDelegateDataClientArgs): ReadonlyDataClient;
280
+ /** An append-only handle on one collection: `insert` and nothing else. */
281
+ export interface AppendOnlyDataCollection {
282
+ readonly name: string;
283
+ /**
284
+ * Deposit a record. The DEK is sealed to the owner's public key, so the
285
+ * depositor cannot read this (or any) record back. Returns the record id.
286
+ */
287
+ insert(record: Record<string, unknown>): Promise<string>;
288
+ }
289
+ /** A client holding a `data.<collection>.append` mandate. Insert-only. */
290
+ export interface AppendOnlyDataClient {
291
+ /** Get an append-only handle on a collection (schema supplied at
292
+ * construction — append clients cannot read collection metadata). */
293
+ collection(name: string): AppendOnlyDataCollection;
294
+ /** Drop in-memory cache. */
295
+ reset(): void;
296
+ }
297
+ export interface CreateAppendDataClientArgs {
298
+ /** PDS base URL (same endpoint the owner writes to). */
299
+ readonly pdsUrl: string;
300
+ /** DID of the SUBJECT who owns the target collection (the mandate issuer). */
301
+ readonly subjectDid: string;
302
+ /**
303
+ * The owner's `#data` Ed25519 public key (multibase z…). The depositor
304
+ * derives the owner's X25519 wrap target from it and seals each DEK to it.
305
+ * Source: the append mandate / invitation, or the owner's DID document.
306
+ */
307
+ readonly ownerDataPubkeyMultibase: string;
308
+ /** The signed mandate carrying `data.<collection>.append`. */
309
+ readonly mandate: SignedMandate;
310
+ /** The depositor's Ed25519 seed (32 bytes) — the grantee key the mandate is
311
+ * bound to. Signs each insert envelope. NEVER used to read. */
312
+ readonly delegateSeed: Uint8Array;
313
+ /** Defaults to `mandate.grantee.pubkey`. */
314
+ readonly granteePubkeyMultibase?: string;
315
+ /**
316
+ * Schema of the target collection(s). The append client builds records
317
+ * locally (it cannot fetch collection metadata), so the caller MUST supply
318
+ * the schema(s) used by the collection it deposits into. The first entry is
319
+ * used as the default; multiple may be passed for multi-collection clients.
320
+ */
321
+ readonly schema: AithosSchemaLite;
322
+ /** Additional schemas (looked up by id alongside `schema`). */
323
+ readonly schemas?: readonly AithosSchemaLite[];
324
+ /** `fetch` override (tests). */
325
+ readonly fetch?: typeof fetch;
326
+ }
327
+ /**
328
+ * Build an **append-only** data client from a `data.<collection>.append`
329
+ * mandate. The returned {@link AppendOnlyDataClient} can ONLY `insert`: it
330
+ * seals each record's DEK to the owner's public key (never the CMK), so it
331
+ * holds no read capability — it cannot decrypt anything in the collection,
332
+ * not even its own deposit. The PDS additionally enforces the append scope
333
+ * (insert allowed; get/list/update/delete refused).
334
+ */
335
+ export declare function createAppendDataClient(args: CreateAppendDataClientArgs): AppendOnlyDataClient;
280
336
  //# sourceMappingURL=data.d.ts.map
package/dist/src/data.js CHANGED
@@ -92,6 +92,50 @@ export function createDelegateDataClient(args) {
92
92
  },
93
93
  });
94
94
  }
95
+ /**
96
+ * Build an **append-only** data client from a `data.<collection>.append`
97
+ * mandate. The returned {@link AppendOnlyDataClient} can ONLY `insert`: it
98
+ * seals each record's DEK to the owner's public key (never the CMK), so it
99
+ * holds no read capability — it cannot decrypt anything in the collection,
100
+ * not even its own deposit. The PDS additionally enforces the append scope
101
+ * (insert allowed; get/list/update/delete refused).
102
+ */
103
+ export function createAppendDataClient(args) {
104
+ const granteePubMb = args.granteePubkeyMultibase ??
105
+ args.mandate.grantee?.pubkey;
106
+ if (!granteePubMb) {
107
+ throw new Error("createAppendDataClient: mandate.grantee.pubkey is missing; pass granteePubkeyMultibase explicitly");
108
+ }
109
+ const ownerKexPublicKey = edPubToX25519Pub(multibaseToEd25519PublicKey(args.ownerDataPubkeyMultibase));
110
+ const impl = new DataClientImpl({
111
+ pdsUrl: args.pdsUrl,
112
+ did: args.subjectDid,
113
+ // In deposit mode the seed signs envelopes; it is NEVER used to unwrap a
114
+ // CMK (the deposit client has none).
115
+ sphereSeed: args.delegateSeed,
116
+ verificationMethod: granteePubMb,
117
+ schemas: [args.schema, ...(args.schemas ?? [])],
118
+ ...(args.fetch ? { fetch: args.fetch } : {}),
119
+ deposit: {
120
+ delegateSeed: args.delegateSeed,
121
+ granteePubkeyMultibase: granteePubMb,
122
+ mandate: args.mandate,
123
+ ownerKexPublicKey,
124
+ ownerKexDidUrl: `${args.subjectDid}#data-kex`,
125
+ },
126
+ });
127
+ const defaultSchema = args.schema;
128
+ return {
129
+ collection(name) {
130
+ const state = impl._depositCollectionState(name, defaultSchema);
131
+ return {
132
+ name,
133
+ insert: (record) => impl._insertDeposit(state, record),
134
+ };
135
+ },
136
+ reset: () => impl.reset(),
137
+ };
138
+ }
95
139
  class DataClientImpl {
96
140
  #pdsUrl;
97
141
  #did;
@@ -100,6 +144,9 @@ class DataClientImpl {
100
144
  #fetch;
101
145
  /** Delegate session, or undefined for the owner path. */
102
146
  #delegate;
147
+ /** Deposit (append-only) session, or undefined. Mutually exclusive with
148
+ * {@link DataClientImpl.#delegate}. */
149
+ #deposit;
103
150
  /**
104
151
  * Per-client schema overrides, populated from `args.schemas` at
105
152
  * construction. Looked up BEFORE the bundled SCHEMAS map (so an app
@@ -118,6 +165,8 @@ class DataClientImpl {
118
165
  this.#fetch = args.fetch ?? globalThis.fetch.bind(globalThis);
119
166
  if (args.delegate)
120
167
  this.#delegate = args.delegate;
168
+ if (args.deposit)
169
+ this.#deposit = args.deposit;
121
170
  this.#localSchemas = new Map((args.schemas ?? []).map((s) => [s.schema, s]));
122
171
  }
123
172
  /** Throw a read-only error when a mutating verb is called on a delegate
@@ -394,7 +443,21 @@ class DataClientImpl {
394
443
  if (opts.cursor)
395
444
  params.cursor = opts.cursor;
396
445
  const r = (await this.#call("/mcp/primitives/read", "aithos.data.list_records", params));
397
- const items = r.items.map((it) => this.#decryptRecord(state, it));
446
+ // A read/write delegate (CMK-holder) cannot decrypt append-only deposits
447
+ // (sealed to the owner key). Skip them rather than crash the whole list —
448
+ // the owner reading the same collection decrypts everything. -32044 is the
449
+ // client-side "deposit unreadable by this session" marker.
450
+ const items = [];
451
+ for (const it of r.items) {
452
+ try {
453
+ items.push(this.#decryptRecord(state, it));
454
+ }
455
+ catch (e) {
456
+ if (e.code === -32044)
457
+ continue;
458
+ throw e;
459
+ }
460
+ }
398
461
  return {
399
462
  items,
400
463
  ...(r.next_cursor ? { nextCursor: r.next_cursor } : {}),
@@ -434,17 +497,21 @@ class DataClientImpl {
434
497
  // INCLUDING `proof` with proofValue=""). Delegate path: sign with the
435
498
  // grantee key, bare-multibase verificationMethod, and attach the mandate
436
499
  // so the PDS resolves the delegation and enforces its scopes.
437
- const envelope = this.#delegate
500
+ // A mandate-bearing session (read-delegate OR append-deposit) signs as
501
+ // the grantee with the bare-multibase verificationMethod and attaches the
502
+ // mandate so the PDS resolves the delegation and enforces its scopes.
503
+ const mandateSession = this.#delegate ?? this.#deposit;
504
+ const envelope = mandateSession
438
505
  ? await signOwnerEnvelope({
439
506
  iss: this.#did, // the SUBJECT DID (mandate issuer), not the delegate
440
507
  aud,
441
508
  method,
442
509
  params,
443
- verificationMethod: this.#delegate.granteePubkeyMultibase,
510
+ verificationMethod: mandateSession.granteePubkeyMultibase,
444
511
  signer: {
445
- sign: async (msg) => ed.sign(msg, this.#delegate.delegateSeed),
512
+ sign: async (msg) => ed.sign(msg, mandateSession.delegateSeed),
446
513
  },
447
- mandate: this.#delegate.mandate,
514
+ mandate: mandateSession.mandate,
448
515
  })
449
516
  : await signOwnerEnvelope({
450
517
  iss: this.#did,
@@ -538,24 +605,95 @@ class DataClientImpl {
538
605
  dek.fill(0);
539
606
  }
540
607
  }
608
+ /**
609
+ * Seal a record's payload for the append-only deposit path: encrypt under a
610
+ * fresh DEK, then seal that DEK to the OWNER's X25519 public key (never the
611
+ * CMK). Mirrors `@aithos/data-crypto` `wrapDEKForRecipient` byte-for-byte so
612
+ * the owner (SDK or CLI) can unwrap it. The depositor keeps no key material.
613
+ */
614
+ #encryptPayloadForOwner(args) {
615
+ const dek = randomBytes32();
616
+ try {
617
+ const plaintext = new TextEncoder().encode(jcsCanonicalize(args.payload));
618
+ const nonce = randomBytes24();
619
+ const aad = aadRecord(this.#did, args.collectionName, args.recordId);
620
+ const ciphertext = new XChaCha20Poly1305(dek).seal(nonce, plaintext, aad);
621
+ // Seal the DEK to the owner's X25519 key (ECIES, fresh ephemeral).
622
+ const ephSk = x25519.utils.randomSecretKey();
623
+ const ephPk = x25519.getPublicKey(ephSk);
624
+ const shared = x25519.getSharedSecret(ephSk, args.ownerKexPublicKey);
625
+ const wrapKey = hkdf(sha256, shared, DEPOSIT_WRAP_SALT, utf8(args.ownerKexDidUrl), 32);
626
+ const wrapNonce = randomBytes24();
627
+ const wrapAad = aadDepositWrap(this.#did, args.collectionName, args.recordId, args.ownerKexDidUrl);
628
+ const wrappedKey = new XChaCha20Poly1305(wrapKey).seal(wrapNonce, dek, wrapAad);
629
+ wrapKey.fill(0);
630
+ shared.fill(0);
631
+ return {
632
+ alg: "xchacha20poly1305-ietf",
633
+ nonce: base64Std(nonce),
634
+ ciphertext: base64Std(ciphertext),
635
+ dek_wrapped_for_owner: {
636
+ recipient: args.ownerKexDidUrl,
637
+ alg: "x25519-hkdf-sha256-aead",
638
+ ephemeral_public: base64Std(ephPk),
639
+ wrap_nonce: base64Std(wrapNonce),
640
+ wrapped_key: base64Std(wrappedKey),
641
+ },
642
+ };
643
+ }
644
+ finally {
645
+ dek.fill(0);
646
+ }
647
+ }
541
648
  #decryptRecord(state, raw) {
542
649
  if (raw.deleted) {
543
650
  // Soft-deleted record — payload was cleared.
544
651
  return { ...raw.metadata, _deleted: true };
545
652
  }
546
- const cmk = this.#cmkCache.get(state.name);
547
- if (!cmk) {
548
- throw new Error("sdk.data: CMK not loaded call ensureCollection first");
549
- }
550
- // Unwrap DEK
551
- const wrapBuf = fromBase64(raw.payload.dek_wrapped_for_cmk);
552
- const wrapNonce = wrapBuf.slice(0, 24);
553
- const wrapped = wrapBuf.slice(24);
554
- const dekAad = aadDekWrap(this.#did, state.name, raw.record_id);
555
- const dekAead = new XChaCha20Poly1305(cmk);
556
- const dek = dekAead.open(wrapNonce, wrapped, dekAad);
557
- if (!dek)
558
- throw new Error("sdk.data: DEK unwrap failed");
653
+ let dek;
654
+ if (raw.payload.dek_wrapped_for_owner) {
655
+ // Append-only deposit: the DEK is sealed to the OWNER's #data-kex key.
656
+ // Only the owner (no delegate/deposit session) can open it. A read
657
+ // delegate holds the CMK, not the owner key, so it must skip deposits.
658
+ if (this.#delegate || this.#deposit) {
659
+ const e = new Error("sdk.data: record is an append-only deposit — only the collection owner can decrypt it (this client holds a delegate/deposit mandate, not the owner key).");
660
+ e.code = -32044; // AITHOS_DATA_DEPOSIT_UNREADABLE (client-side)
661
+ throw e;
662
+ }
663
+ const w = raw.payload.dek_wrapped_for_owner;
664
+ const ownerKexSk = ed25519SeedToX25519PrivateKey(this.#seed);
665
+ try {
666
+ const ephPk = fromBase64(w.ephemeral_public);
667
+ const shared = x25519.getSharedSecret(ownerKexSk, ephPk);
668
+ const wrapKey = hkdf(sha256, shared, DEPOSIT_WRAP_SALT, utf8(w.recipient), 32);
669
+ const wrapAad = aadDepositWrap(this.#did, state.name, raw.record_id, w.recipient);
670
+ dek = new XChaCha20Poly1305(wrapKey).open(fromBase64(w.wrap_nonce), fromBase64(w.wrapped_key), wrapAad);
671
+ wrapKey.fill(0);
672
+ shared.fill(0);
673
+ }
674
+ finally {
675
+ ownerKexSk.fill(0);
676
+ }
677
+ if (!dek)
678
+ throw new Error("sdk.data: deposit DEK unwrap failed (wrong owner key or AAD mismatch)");
679
+ }
680
+ else {
681
+ // CMK path (owner / read-write delegate).
682
+ const cmk = this.#cmkCache.get(state.name);
683
+ if (!cmk) {
684
+ throw new Error("sdk.data: CMK not loaded — call ensureCollection first");
685
+ }
686
+ if (raw.payload.dek_wrapped_for_cmk === undefined) {
687
+ throw new Error("sdk.data: record payload has neither dek_wrapped_for_cmk nor dek_wrapped_for_owner");
688
+ }
689
+ const wrapBuf = fromBase64(raw.payload.dek_wrapped_for_cmk);
690
+ const wrapNonce = wrapBuf.slice(0, 24);
691
+ const wrapped = wrapBuf.slice(24);
692
+ const dekAad = aadDekWrap(this.#did, state.name, raw.record_id);
693
+ dek = new XChaCha20Poly1305(cmk).open(wrapNonce, wrapped, dekAad);
694
+ if (!dek)
695
+ throw new Error("sdk.data: DEK unwrap failed");
696
+ }
559
697
  try {
560
698
  const nonce = fromBase64(raw.payload.nonce);
561
699
  const ciphertext = fromBase64(raw.payload.ciphertext);
@@ -571,6 +709,38 @@ class DataClientImpl {
571
709
  dek.fill(0);
572
710
  }
573
711
  }
712
+ /**
713
+ * Append-only deposit insert. Used by the {@link createAppendDataClient}
714
+ * path: builds the record locally (no CMK, no server schema fetch — the
715
+ * caller supplies the schema), seals the DEK to the owner key, and POSTs
716
+ * `insert_record`. The PDS enforces the `data.<col>.append` scope.
717
+ */
718
+ async _insertDeposit(state, record) {
719
+ if (!this.#deposit) {
720
+ throw new Error("sdk.data: _insertDeposit called without a deposit session");
721
+ }
722
+ const { metadata, payload } = splitRecord(record, state.schema);
723
+ const recordId = `record_${makeUlid()}`;
724
+ const encrypted = this.#encryptPayloadForOwner({
725
+ collectionName: state.name,
726
+ recordId,
727
+ payload,
728
+ ownerKexPublicKey: this.#deposit.ownerKexPublicKey,
729
+ ownerKexDidUrl: this.#deposit.ownerKexDidUrl,
730
+ });
731
+ const r = (await this.#call("/mcp/primitives/write", "aithos.data.insert_record", {
732
+ collection_urn: state.urn,
733
+ record_id: recordId,
734
+ metadata,
735
+ payload: encrypted,
736
+ }));
737
+ return r.record_id;
738
+ }
739
+ /** Build a local collection state for the deposit path (no server fetch:
740
+ * append clients are not authorized to read collection metadata). */
741
+ _depositCollectionState(name, schema) {
742
+ return { name, urn: this.#collectionUrn(name), schema };
743
+ }
574
744
  }
575
745
  class DataCollectionImpl {
576
746
  client;
@@ -676,6 +846,40 @@ function aadRecord(subjectDid, collectionName, recordId) {
676
846
  const p = utf8("aithos-data-record-v1\0");
677
847
  return concat3WithSeps(p, subjectDid, collectionName, recordId);
678
848
  }
849
+ /**
850
+ * HKDF salt for the append-only deposit DEK wrap. Distinct from the CMK wrap
851
+ * salt so the two key-derivation domains never collide. MUST match
852
+ * `@aithos/data-crypto` `DEPOSIT_WRAP_SALT`.
853
+ */
854
+ const DEPOSIT_WRAP_SALT = utf8("aithos-data-dek-deposit-wrap-v1");
855
+ /**
856
+ * AAD for the deposit DEK wrap:
857
+ * "aithos-data-dek-deposit-v1\0" ‖ subject ‖ \0 ‖ collection ‖ \0 ‖
858
+ * record ‖ \0 ‖ recipient_did_url
859
+ * MUST match `@aithos/data-crypto` `aadForDepositWrap`.
860
+ */
861
+ function aadDepositWrap(subjectDid, collectionName, recordId, recipientDidUrl) {
862
+ const prefix = utf8("aithos-data-dek-deposit-v1\0");
863
+ const parts = [subjectDid, collectionName, recordId, recipientDidUrl].map(utf8);
864
+ const sep = new Uint8Array([0]);
865
+ let total = prefix.length;
866
+ for (let i = 0; i < parts.length; i++) {
867
+ total += parts[i].length + (i < parts.length - 1 ? sep.length : 0);
868
+ }
869
+ const out = new Uint8Array(total);
870
+ let off = 0;
871
+ out.set(prefix, off);
872
+ off += prefix.length;
873
+ for (let i = 0; i < parts.length; i++) {
874
+ out.set(parts[i], off);
875
+ off += parts[i].length;
876
+ if (i < parts.length - 1) {
877
+ out.set(sep, off);
878
+ off += sep.length;
879
+ }
880
+ }
881
+ return out;
882
+ }
679
883
  function concat3WithSeps(prefix, a, b, c) {
680
884
  const aa = utf8(a);
681
885
  const bb = utf8(b);
@@ -14,7 +14,7 @@ export { WalletNamespace } from "./wallet.js";
14
14
  export type { ComponentStyle, ExtractArgs, ExtractContent, ExtractData, ExtractForm, ExtractFormField, ExtractHeading, ExtractIconDeclaration, ExtractImage, ExtractLink, ExtractLogo, ExtractMeta, ExtractResult, ExtractSection, ExtractStructure, ExtractStyles, FetchAssetArgs, FetchAssetResult, PaletteEntry, VisualSignature, WebNamespaceDeps, } from "./web.js";
15
15
  export { WebNamespace, WEB_EXTRACT_SCOPE } from "./web.js";
16
16
  export { AithosAuth, DEFAULT_API_BASE_URL, DEFAULT_AUTH_BASE_URL, } from "./auth.js";
17
- export type { AithosAuthConfig, AithosSession, ApplyPasswordResetInput, ApplyPasswordResetResult, CompleteSsoFirstLoginInput, CompleteSsoFirstLoginResult, CustodialSignInInput, CustodialSignInResult, CustodialSignUpInput, CustodialSignUpResult, DelegateInfo, ImportMandateInput, OwnerInfo, RequestPasswordResetInput, ResendVerificationInput, SignInInput, SignInWithGoogleOptions, SignInWithRecoveryInput, SignUpInput, SignUpResult, VerifyEmailInput, VerifyEmailResult, } from "./auth.js";
17
+ export type { AcceptInviteInput, AcceptInviteResult, AithosAuthConfig, AithosSession, ApplyPasswordResetInput, ApplyPasswordResetResult, CompleteSsoFirstLoginInput, CompleteSsoFirstLoginResult, CustodialSignInInput, CustodialSignInResult, CustodialSignUpInput, CustodialSignUpResult, DelegateInfo, ImportMandateInput, InviteCustodialInput, InviteCustodialResult, OwnerInfo, RequestPasswordResetInput, ResendVerificationInput, SignInInput, SignInWithGoogleOptions, SignInWithRecoveryInput, SignUpInput, SignUpResult, VerifyEmailInput, VerifyEmailResult, } from "./auth.js";
18
18
  export type { SignedEnvelope } from "./internal/envelope.js";
19
19
  export { DEFAULT_SESSION_STORAGE_KEY, defaultSessionStore, localStorageStore, noopStore, sessionStorageStore, type AithosSessionStore, } from "./session-store.js";
20
20
  export { DEFAULT_KEYSTORE_DB_NAME, defaultKeyStore, indexedDbKeyStore, memoryKeyStore, type AithosKeyStore, type StoredDelegateKeys, type StoredOwnerKeys, } from "./key-store.js";
@@ -27,6 +27,6 @@ export type { AudienceSet, AppCreditPackId, CreateAppTopupSessionArgs, CreateApp
27
27
  export * as onboarding from "./onboarding.js";
28
28
  export { createBrowserIdentity, browserIdentityFromStored, type BrowserIdentity, } from "@aithos/protocol-client";
29
29
  export type { Section } from "@aithos/protocol-client";
30
- export { createDataClient, createDelegateDataClient, type CreateDataClientArgs, type CreateDelegateDataClientArgs, type DataClient, type DataCollection, type ReadonlyDataClient, type ReadonlyDataCollection, type ListOpts, type AithosSchemaLite, } from "./data.js";
30
+ export { createDataClient, createDelegateDataClient, createAppendDataClient, type CreateDataClientArgs, type CreateDelegateDataClientArgs, type CreateAppendDataClientArgs, type DataClient, type DataCollection, type ReadonlyDataClient, type ReadonlyDataCollection, type AppendOnlyDataClient, type AppendOnlyDataCollection, type ListOpts, type AithosSchemaLite, } from "./data.js";
31
31
  export { createAssetsClient, AssetsClient, type CreateAssetsClientArgs, type AttachedContext, type AssetUploadInput, type AssetUploadResult, type AssetFetchResult, type AssetBrief, type ListAssetsOpts, type ThumbnailUploadInput, type ThumbnailUploadResult, type RecipientResolver, type RecipientSet, } from "./assets.js";
32
32
  //# sourceMappingURL=index.d.ts.map
package/dist/src/index.js CHANGED
@@ -68,7 +68,7 @@ export { createBrowserIdentity, browserIdentityFromStored, } from "@aithos/proto
68
68
  // `sdk.data` namespace — Aithos data sub-protocol PDS client. Manages
69
69
  // the lifecycle of subject-owned, encrypted, schema-validated records.
70
70
  // See spec/data/ in the aithos-protocol repo.
71
- export { createDataClient, createDelegateDataClient, } from "./data.js";
71
+ export { createDataClient, createDelegateDataClient, createAppendDataClient, } from "./data.js";
72
72
  // `sdk.assets` — Aithos assets sub-protocol PDS client. Upload,
73
73
  // fetch, list, ref/unref binary content (images, PDFs, audio, video)
74
74
  // owned by a subject. AEAD-encrypted per-asset under AMKs wrapped for
@@ -14,6 +14,19 @@ export type Scope = "ethos.read.public" | "ethos.read.circle" | "ethos.read.self
14
14
  * `data.<collection>.<action>` (Aithos-protocol `spec/data/04-mandates.md`
15
15
  * §4.2) and the server-side check `requireScope` in data-backend. */
16
16
  export type DataAction = "read" | "write" | "admin";
17
+ /**
18
+ * A **lateral** data capability — deliberately OUTSIDE the
19
+ * `read ⊂ write ⊂ admin` hierarchy (the same way `gamma.write` sits beside
20
+ * the ethos scopes). Keeping it a separate type makes the security invariant
21
+ * structural rather than conventional: `append` can never be reached by
22
+ * widening a `write`/`admin` scope, so it cannot accidentally carry read.
23
+ *
24
+ * `append` authorizes `insert_record` ONLY (no read, update, or delete). The
25
+ * depositor seals each record's DEK to the owner's public key
26
+ * ({@link createAppendDataClient}) and holds no read capability — it cannot
27
+ * decrypt anything in the collection, not even its own deposit.
28
+ */
29
+ export type DataLateralAction = "append";
17
30
  /**
18
31
  * A data-access scope: `data.<collection>.<action>`, or the cross-collection
19
32
  * wildcard `data.*.<action>`. Examples: `data.contacts.read`,
@@ -29,7 +42,7 @@ export type DataAction = "read" | "write" | "admin";
29
42
  * Collection names MUST NOT contain `.` (the server splits the scope on
30
43
  * `.` and reads the first three segments).
31
44
  */
32
- export type DataScope = `data.${string}.${DataAction}`;
45
+ export type DataScope = `data.${string}.${DataAction}` | `data.${string}.${DataLateralAction}`;
33
46
  /**
34
47
  * The opt-in scope that authorizes a delegate to spend the subject's
35
48
  * compute credits via the Aithos compute proxy. Mirror of
@@ -250,9 +250,10 @@ function defaultSphereFromScopes(scopes) {
250
250
  return "self";
251
251
  }
252
252
  /** `true` iff `s` is a well-formed data scope `data.<collection>.<action>`
253
- * with no filter suffix and a non-empty, dot-free collection name. */
253
+ * with no filter suffix and a non-empty, dot-free collection name. The
254
+ * lateral `append` action is accepted alongside read/write/admin. */
254
255
  function isWellFormedDataScope(s) {
255
- return /^data\.[^.]+\.(read|write|admin)$/.test(s);
256
+ return /^data\.[^.]+\.(read|write|admin|append)$/.test(s);
256
257
  }
257
258
  /**
258
259
  * Validate the SDK-side `compute` namespace and project it onto the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aithos/sdk",
3
- "version": "0.1.0-alpha.45",
3
+ "version": "0.1.0-alpha.47",
4
4
  "description": "Aithos SDK — high-level TypeScript developer kit for building agentic apps on the Aithos protocol. Wraps @aithos/protocol-client and exposes the Aithos compute proxy and wallet (Stripe top-up) endpoints.",
5
5
  "keywords": [
6
6
  "aithos",