@calimero-network/mero-js 33.1.0 → 33.3.0

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 CHANGED
@@ -110,7 +110,7 @@ flows and streams a single route cannot be:
110
110
  - **Organization recovery**: `startRecovery(org, seed)` (the seed signs here and never leaves the process); `newRecoverySeed`, `recoveryPublicKey`.
111
111
  - **Blobs**: `downloadBlob(app, id)`, `downloadBlobGranted(app, id, grant)` (bytes; `client.apps.blobDownload` answers a `Blob` with its type).
112
112
  - **Streams**: `events(app, from?, signal?)`, `presenceStream(app, signal?)`.
113
- - **Approvals from an app**: `pendingApprovals(org?)`, `appsReportAll(org)`, then `openConsentPage(request, …)` to send the user to the node's consent page, and `waitForConsent(requestId)`. Show the answer's `code` to the user before sending them to `url` (`openConsentPage`'s `confirm` hook); they should see the same code on the page (`confirmationCode(requestId)` checks it). See [Ask your users to approve node images and app upgrades](https://calimero-network.github.io/mero-js/guides/user-approvals/).
113
+ - **Approvals from an app**: `pendingApprovals(org?)`, `appsReportAll(org)`, then `openConsentPage(request, …)` to send the user to the node's consent page, and `waitForConsent(requestId)`; back on `returnTo`, `resumeConsent()` reads the decision on the request this page started from the node (never from the URL) and refuses a return for another request, one still pending, or one a newer request replaced (`CONSENT_REPLACED`: an account has one undecided request per node). Besides releases, upgrades and outbound hosts, `createOrgConsent`, `createInviteConsent` and `acceptInviteConsent` ask for a new organization, an invite or joining with one; the result's `outcome` (`{ orgId }`, `{ token }`, `{ org }`) is typed by `kind`. Show the answer's `code` to the user before sending them to `url` (`openConsentPage`'s `confirm` hook); they should see the same code on the page (`confirmationCode(requestId)` checks it). See [Ask your users to approve node images and app upgrades](https://calimero-network.github.io/mero-js/guides/user-approvals/).
114
114
 
115
115
  Refusals are typed (`LoginRequired`, `PasskeyUnknownHere`, `WrongNode`, `NotFound`, `ConfirmRequired`, `ConfirmCancelled`, `ConfirmPromptBlocked`,
116
116
  `ArgsTooLarge`, `IdempotencyMismatch`, `ReleaseDeadlineError`, `RuntimeTooOld`, `ConsentStale`, `AppError`, `TrapError`,
@@ -142,7 +142,43 @@ export type ConsentRequest = {
142
142
  prefixes?: string[];
143
143
  };
144
144
  returnTo: string;
145
+ } | {
146
+ /** A new organization, owned by whoever approves. Outcome: `{ orgId }`. */
147
+ kind: 'createOrg';
148
+ subject: {
149
+ name: string;
150
+ };
151
+ returnTo: string;
152
+ } | {
153
+ /** A new invite to `subject.org`. Outcome: `{ token }`. */
154
+ kind: 'createInvite';
155
+ subject: InviteConsentSubject;
156
+ returnTo: string;
157
+ } | {
158
+ /** Joining an organization with an invite's `token`. Outcome: `{ org }`. */
159
+ kind: 'acceptInvite';
160
+ subject: {
161
+ token: string;
162
+ };
163
+ returnTo: string;
145
164
  };
165
+ /** A consent request's kind. */
166
+ export type ConsentKind = ConsentRequest['kind'];
167
+ /** A role an invite gives (core's `Role`). */
168
+ export type InviteRole = 'guest' | 'member' | 'admin';
169
+ /** What a `createInvite` consent request asks for. */
170
+ export interface InviteConsentSubject {
171
+ org: string;
172
+ role: InviteRole;
173
+ /** Teams the invite joins its user to. */
174
+ teams?: string[];
175
+ /** How long the invite lasts, in seconds. */
176
+ ttlSecs?: number;
177
+ /** How many times it may be used. */
178
+ uses?: number;
179
+ /** Whether it gives every app of the organization. */
180
+ allApps?: boolean;
181
+ }
146
182
  /** The node's answer to a consent request: send the person to `url`. */
147
183
  export type ConsentStarted = ApiAnswer<'consent_page_create'>;
148
184
  /** How {@link CalimeroClient.openConsentPage} sends the person to the page. */
@@ -164,8 +200,46 @@ export interface OpenConsentOptions {
164
200
  * {@link ConsentStarted.code} to check the node's answer.
165
201
  */
166
202
  export declare function confirmationCode(requestId: string): Promise<string>;
167
- /** `GET /consent/{id}/result`. */
168
- export type ConsentResult = ApiAnswer<'consent_page_result'>;
203
+ /**
204
+ * What an approval made, by kind (`outcome` on {@link ConsentResult}, once
205
+ * approved): `release`, `upgrade` and `outbound` make nothing. An invite's
206
+ * `token` is a credential: keep it out of logs.
207
+ */
208
+ export interface ConsentOutcomes {
209
+ release: never;
210
+ upgrade: never;
211
+ outbound: never;
212
+ createOrg: {
213
+ orgId: string;
214
+ };
215
+ createInvite: {
216
+ token: string;
217
+ };
218
+ acceptInvite: {
219
+ org: string;
220
+ };
221
+ }
222
+ /** `GET /consent/{id}/result` for a request of kind `K`. */
223
+ export interface ConsentResultOf<K extends ConsentKind> {
224
+ requestId: string;
225
+ kind: K;
226
+ status: 'pending' | 'approved' | 'declined';
227
+ /** Unix seconds; `null` while pending. */
228
+ decidedAt: number | null;
229
+ /** What the approval made, once approved, for the kinds that make something. */
230
+ outcome?: ConsentOutcomes[K];
231
+ }
232
+ /**
233
+ * `GET /consent/{id}/result`, narrowed by `kind`:
234
+ * `if (r.kind === 'createOrg') r.outcome?.orgId`. Read `outcome` only from
235
+ * this sealed answer, never from the page's redirect, which carries none.
236
+ *
237
+ * Typed here by hand: the vendored OpenAPI document does not name the
238
+ * organization kinds (core#5014) yet; the next openapi-sync brings them.
239
+ */
240
+ export type ConsentResult = {
241
+ [K in ConsentKind]: ConsentResultOf<K>;
242
+ }[ConsentKind];
169
243
  /**
170
244
  * What the consent page put on `returnTo` when it sent the person back, or
171
245
  * `null` when `href` carries none. A hint only (anyone can type a URL): confirm
@@ -175,6 +249,20 @@ export declare function consentReturn(href: string | URL): {
175
249
  requestId: string;
176
250
  result: 'approved' | 'declined';
177
251
  } | null;
252
+ /** `href` without the consent page's `request_id` and `result`. */
253
+ export declare function withoutConsentReturn(href: string | URL): string;
254
+ /** The `sessionStorage` key {@link CalimeroClient.openConsentPage} keeps its request id under, for {@link CalimeroClient.resumeConsent}. */
255
+ export declare const CONSENT_STORAGE_KEY = "calimero.consent";
256
+ /** How {@link CalimeroClient.resumeConsent} reads the page's return. */
257
+ export interface ResumeConsentOptions {
258
+ /**
259
+ * The request this page started; by default the one
260
+ * {@link CalimeroClient.openConsentPage} stored in this tab.
261
+ */
262
+ requestId?: string;
263
+ /** The URL the page sent the person back to; by default `location.href`, whose parameters are then removed. */
264
+ href?: string;
265
+ }
178
266
  /** The public verifier for mero-tee releases (`attestation-verifier`). */
179
267
  export declare const RELEASE_VERIFIER = "https://mero-tee.vercel.app";
180
268
  /** A mero-tee release's notes on GitHub. */
@@ -248,3 +336,15 @@ export declare function releaseConsent(scope: ReportScope, version: string, retu
248
336
  export declare function withdrawConsent(scope: ReportScope, version: string, returnTo: string): ConsentRequest;
249
337
  /** The consent request that upgrades `app` to `toVersion`. */
250
338
  export declare function upgradeConsent(app: string, toVersion: string, returnTo: string): ConsentRequest;
339
+ /** The consent request that creates an organization named `name`; its outcome names the new `orgId`. */
340
+ export declare function createOrgConsent(name: string, returnTo: string): ConsentRequest & {
341
+ kind: 'createOrg';
342
+ };
343
+ /** The consent request that creates an invite to `subject.org`; its outcome carries the invite's `token`. */
344
+ export declare function createInviteConsent(subject: InviteConsentSubject, returnTo: string): ConsentRequest & {
345
+ kind: 'createInvite';
346
+ };
347
+ /** The consent request that joins the organization `token` invites to; its outcome names the `org`. */
348
+ export declare function acceptInviteConsent(token: string, returnTo: string): ConsentRequest & {
349
+ kind: 'acceptInvite';
350
+ };
@@ -106,6 +106,15 @@ export function consentReturn(href) {
106
106
  return null;
107
107
  return { requestId, result };
108
108
  }
109
+ /** `href` without the consent page's `request_id` and `result`. */
110
+ export function withoutConsentReturn(href) {
111
+ const url = new URL(String(href));
112
+ url.searchParams.delete('request_id');
113
+ url.searchParams.delete('result');
114
+ return url.toString();
115
+ }
116
+ /** The `sessionStorage` key {@link CalimeroClient.openConsentPage} keeps its request id under, for {@link CalimeroClient.resumeConsent}. */
117
+ export const CONSENT_STORAGE_KEY = 'calimero.consent';
109
118
  // ---------------------------------------------------------------- pending
110
119
  /** The public verifier for mero-tee releases (`attestation-verifier`). */
111
120
  export const RELEASE_VERIFIER = 'https://mero-tee.vercel.app';
@@ -191,3 +200,15 @@ export function withdrawConsent(scope, version, returnTo) {
191
200
  export function upgradeConsent(app, toVersion, returnTo) {
192
201
  return { kind: 'upgrade', subject: { app, toVersion }, returnTo };
193
202
  }
203
+ /** The consent request that creates an organization named `name`; its outcome names the new `orgId`. */
204
+ export function createOrgConsent(name, returnTo) {
205
+ return { kind: 'createOrg', subject: { name }, returnTo };
206
+ }
207
+ /** The consent request that creates an invite to `subject.org`; its outcome carries the invite's `token`. */
208
+ export function createInviteConsent(subject, returnTo) {
209
+ return { kind: 'createInvite', subject, returnTo };
210
+ }
211
+ /** The consent request that joins the organization `token` invites to; its outcome names the `org`. */
212
+ export function acceptInviteConsent(token, returnTo) {
213
+ return { kind: 'acceptInvite', subject: { token }, returnTo };
214
+ }
@@ -14,11 +14,14 @@ import { type NodePolicy } from '../runtime/attestation.js';
14
14
  import { type PasskeyProvider } from '../runtime/passkey.js';
15
15
  import { type RouteClientOptions } from '../routes/route-client.js';
16
16
  import { type Routes } from '../generated/methods.js';
17
- import { type AppsReport, type ConsentRequest, type ConsentResult, type ConsentStarted, type OpenConsentOptions, type PendingApprovals } from './approvals.js';
17
+ import { type ExportedFile, type FileSink } from './files.js';
18
+ import { type AppsReport, type ConsentRequest, type ConsentResult, type ConsentStarted, type OpenConsentOptions, type ResumeConsentOptions, type PendingApprovals } from './approvals.js';
18
19
  import type { ApiAnswer, ApiSchema } from '../routes/types.js';
19
20
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
20
21
  export type { Committed, SignUpRefusal } from '../runtime/errors.js';
21
22
  export type { CalimeroSession, NodeEvent };
23
+ /** The largest file sent as one request, and the part size a session is asked for. */
24
+ export declare const FILE_PART_BYTES: number;
22
25
  export type CallResult = ApiAnswer<'intents'>;
23
26
  export type ViewResult = ApiAnswer<'views'>;
24
27
  /** An installed package and its releases. */
@@ -32,6 +35,10 @@ export type AppInfo = ApiSchema<'AppEntry'>;
32
35
  export type UpgradeRun = ApiSchema<'UpgradeRun'>;
33
36
  /** One of an app's blobs: `blobId` base58 (what apps print), `id` hex. */
34
37
  export type BlobInfo = ApiAnswer<'blob_info'>;
38
+ /** A sealed file: `id` and `sha256` hex, `blobId` base58 (what apps print), `index` the log index that recorded it. */
39
+ export type FileInfo = ApiAnswer<'file_info'>;
40
+ /** What {@link CalimeroClient.uploadFile} takes; a `Blob` is read part by part, never whole. */
41
+ export type FileData = Blob | Uint8Array | ArrayBuffer;
35
42
  /** One device present in an app (`publishPresence`); `state` hex, `null` once retracted. */
36
43
  export type PresenceEntry = ApiAnswer<'presence_get'>['present'][number];
37
44
  /**
@@ -345,12 +352,37 @@ export declare class CalimeroClient {
345
352
  finishAccountRecovery(passkey: PasskeyProvider, accountId?: string): Promise<CalimeroSession>;
346
353
  /** One of `app`'s blobs, by id (base58 or hex). */
347
354
  downloadBlob(app: string, id: string): Promise<Uint8Array>;
355
+ /**
356
+ * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,
357
+ * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of
358
+ * the file. A failed check is an `ExportError`; `signal` aborts the download.
359
+ */
360
+ exportFileTo(app: string, id: string, sink: FileSink, signal?: AbortSignal): Promise<ExportedFile>;
361
+ /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */
362
+ exportFile(app: string, id: string, signal?: AbortSignal): Promise<Uint8Array>;
348
363
  /**
349
364
  * Download a component app's blob with a grant one of its runs handed out
350
365
  * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
351
366
  * permission. A bad or expired grant answers `NotFound`, as a missing blob.
352
367
  */
353
368
  downloadBlobGranted(app: string, id: string, grant: string): Promise<Uint8Array>;
369
+ /**
370
+ * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
371
+ * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
372
+ * file for each, so one that may have reached it is never repeated); a larger file
373
+ * is a session of parts, each sent again after a dropped connection or a `503`.
374
+ * A session the node lost is begun again once; any other failure aborts it.
375
+ * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
376
+ */
377
+ uploadFile(app: string, data: FileData): Promise<FileInfo>;
378
+ /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
379
+ private uploadSession;
380
+ /** Send every part, in order, from wherever the node says the session is. */
381
+ private sendParts;
382
+ /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
383
+ private untilAvailable;
384
+ /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
385
+ private isTransient;
354
386
  /** Committed events from index `from`, then live, until `signal` aborts. */
355
387
  events(app: string, from?: number, signal?: AbortSignal): AsyncGenerator<NodeEvent>;
356
388
  /**
@@ -386,8 +418,34 @@ export declare class CalimeroClient {
386
418
  * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request
387
419
  * once `navigate` returns (or `confirm` declines): with a popup
388
420
  * (`url => window.open(url)`), poll it with {@link waitForConsent}.
421
+ * Before navigating it keeps `requestId` in `sessionStorage` (where there
422
+ * is one), for {@link resumeConsent} when the page sends the person back.
389
423
  */
390
424
  openConsentPage(request: ConsentRequest, navigateOrOptions?: ((url: string) => void) | OpenConsentOptions): Promise<ConsentStarted>;
425
+ /**
426
+ * On the page the consent page sent the person back to
427
+ * (`returnTo?request_id=…&result=…`): the decision on the request this page
428
+ * started, read from the node (`GET /consent/{id}/result`), never from the
429
+ * URL. `null` when the URL carries no `request_id`. The request is
430
+ * `options.requestId`, or the one {@link openConsentPage} stored in this
431
+ * tab; with the default `href` (`location.href`) the parameters are then
432
+ * removed with `history.replaceState`, and the stored id once decided.
433
+ *
434
+ * Throws `CalimeroError`:
435
+ * - `CONSENT_NOT_STARTED`: the URL names a request, and this page started none;
436
+ * - `CONSENT_REQUEST_MISMATCH`: the URL names another request than this page's;
437
+ * - `CONSENT_NOT_DECIDED`: this page's request is still pending although the
438
+ * page sent the person back, a sign that another request was approved on a
439
+ * page that was not the node's. Do not act on it;
440
+ * - `CONSENT_REPLACED`: the node no longer knows this page's request (`404`):
441
+ * an account has one undecided request per node, and a newer one replaced
442
+ * it, possibly on a page that was not the node's. Do not act on it either.
443
+ *
444
+ * The URL's `result` is never trusted: the answer's `status` is the node's.
445
+ * An approval's `outcome` (`orgId`, an invite's `token`, the `org` joined) is
446
+ * in the answer, typed by `kind`.
447
+ */
448
+ resumeConsent(options?: ResumeConsentOptions): Promise<ConsentResult | null>;
391
449
  /**
392
450
  * Poll `client.consent.pageResult` until the request is decided, every
393
451
  * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)
@@ -11,14 +11,21 @@
11
11
  */
12
12
  import { DEFAULT_RETRY, NodeTransport, directoryTransport, refusal, retryDelayMs, routePath, } from '../runtime/transport.js';
13
13
  import { DEFAULT_DIRECTORY } from '../runtime/directory.js';
14
- import { CalimeroError, LoginRequired, OriginNotRegistered, WrongRecoveryCode } from '../runtime/errors.js';
14
+ import { CalimeroError, LoginRequired, NotFound, OriginNotRegistered, UnavailableError, WrongRecoveryCode } from '../runtime/errors.js';
15
15
  import { b64url, fromB64url } from '../runtime/passkey.js';
16
16
  import { createRouteClient } from '../routes/route-client.js';
17
17
  import { createRoutes } from '../generated/methods.js';
18
18
  import { passkeyConfirm } from '../runtime/passkey.js';
19
+ import { exportFile, exportFileTo } from './files.js';
19
20
  import { signRecovery } from './recovery-key.js';
20
- import { confirmationCode, pageQuery, pendingApprovalsFrom, } from './approvals.js';
21
+ import { CONSENT_STORAGE_KEY, confirmationCode, pageQuery, pendingApprovalsFrom, withoutConsentReturn, } from './approvals.js';
21
22
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
23
+ /** The largest file sent as one request, and the part size a session is asked for. */
24
+ export const FILE_PART_BYTES = 16 * 1024 * 1024;
25
+ const PART_RESENDS = 1; // times a part is sent again before the node is asked where the session is
26
+ const MAX_FAILURES = 8; // failed sends in a row, with no part accepted between them, before giving up
27
+ const MAX_JUMPS = 16; // PART_OUT_OF_ORDER answers followed in one session before giving up
28
+ const CALL_RETRIES = 8; // times beginning and completing a session are sent again while the node is unavailable
22
29
  /** A deployer's key, as `GET /deployers` lists it and `DELETE /deployers/{key}` takes it. */
23
30
  export function deployerKey(deployer) {
24
31
  return 'account' in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
@@ -75,6 +82,19 @@ export function presenceState(state) {
75
82
  return state === null ? null : toHex(state);
76
83
  }
77
84
  export { DEFAULT_RETRY, retryDelayMs };
85
+ /** Bytes `start` to `end` of `data`, as a view or a slice: a `Blob` is never read whole. */
86
+ async function readSlice(data, start, end) {
87
+ if (data instanceof Blob)
88
+ return new Uint8Array(await data.slice(start, end).arrayBuffer());
89
+ return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);
90
+ }
91
+ /** The `next` an answer names, which cannot be past the last part. */
92
+ function nextPart(answer, parts) {
93
+ const next = answer?.next;
94
+ if (typeof next === 'number' && Number.isInteger(next) && next >= 0 && next <= parts)
95
+ return next;
96
+ throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);
97
+ }
78
98
  export class CalimeroClient {
79
99
  /**
80
100
  * A client for the Calimero Cloud cluster named `cluster`: its node list read
@@ -314,6 +334,18 @@ export class CalimeroClient {
314
334
  async downloadBlob(app, id) {
315
335
  return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());
316
336
  }
337
+ /**
338
+ * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,
339
+ * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of
340
+ * the file. A failed check is an `ExportError`; `signal` aborts the download.
341
+ */
342
+ exportFileTo(app, id, sink, signal) {
343
+ return exportFileTo(this.transport, app, id, sink, signal);
344
+ }
345
+ /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */
346
+ exportFile(app, id, signal) {
347
+ return exportFile(this.transport, app, id, signal);
348
+ }
317
349
  /**
318
350
  * Download a component app's blob with a grant one of its runs handed out
319
351
  * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
@@ -322,6 +354,97 @@ export class CalimeroClient {
322
354
  async downloadBlobGranted(app, id, grant) {
323
355
  return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());
324
356
  }
357
+ /**
358
+ * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
359
+ * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
360
+ * file for each, so one that may have reached it is never repeated); a larger file
361
+ * is a session of parts, each sent again after a dropped connection or a `503`.
362
+ * A session the node lost is begun again once; any other failure aborts it.
363
+ * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
364
+ */
365
+ async uploadFile(app, data) {
366
+ const size = data instanceof Blob ? data.size : data.byteLength;
367
+ if (size <= FILE_PART_BYTES)
368
+ return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });
369
+ try {
370
+ return await this.uploadSession(app, data, size);
371
+ }
372
+ catch (error) {
373
+ if (!(error instanceof CalimeroError) || error.code !== 'UPLOAD_UNKNOWN')
374
+ throw error;
375
+ return this.uploadSession(app, data, size);
376
+ }
377
+ }
378
+ /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
379
+ async uploadSession(app, data, size) {
380
+ const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));
381
+ const { uploadId: upload, partBytes, parts } = begin;
382
+ if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {
383
+ throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);
384
+ }
385
+ try {
386
+ await this.sendParts(app, upload, data, size, partBytes, parts);
387
+ return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));
388
+ }
389
+ catch (error) {
390
+ if (!(error instanceof CalimeroError && error.code === 'UPLOAD_UNKNOWN'))
391
+ await this.apps.uploadAbort({ app, upload }).catch(() => undefined);
392
+ throw error;
393
+ }
394
+ }
395
+ /** Send every part, in order, from wherever the node says the session is. */
396
+ async sendParts(app, upload, data, size, partBytes, parts) {
397
+ let [next, failures, jumps] = [0, 0, 0];
398
+ while (next < parts) {
399
+ try {
400
+ const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));
401
+ next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);
402
+ failures = 0;
403
+ continue;
404
+ }
405
+ catch (error) {
406
+ if (error instanceof CalimeroError && error.code === 'PART_OUT_OF_ORDER') {
407
+ jumps += 1;
408
+ if (jumps > MAX_JUMPS)
409
+ throw error;
410
+ next = nextPart(error.details, parts);
411
+ continue;
412
+ }
413
+ if (!this.isTransient(error) || ++failures > MAX_FAILURES)
414
+ throw error;
415
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));
416
+ if (failures > PART_RESENDS) {
417
+ try {
418
+ const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);
419
+ if (at > next)
420
+ failures = 0;
421
+ next = at;
422
+ }
423
+ catch (asked) {
424
+ if (!this.isTransient(asked))
425
+ throw asked;
426
+ }
427
+ }
428
+ }
429
+ }
430
+ }
431
+ /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
432
+ async untilAvailable(send) {
433
+ for (let retry = 0;; retry++) {
434
+ try {
435
+ return await send();
436
+ }
437
+ catch (error) {
438
+ if (!this.isTransient(error) || retry >= CALL_RETRIES)
439
+ throw error;
440
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));
441
+ }
442
+ }
443
+ }
444
+ /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
445
+ isTransient(error) {
446
+ return error instanceof UnavailableError || this.transport.isNetworkFailure(error);
447
+ }
325
448
  // ---------------------------------------------------------------- packages
326
449
  // ---------------------------------------------------------------- app instances
327
450
  /** Committed events from index `from`, then live, until `signal` aborts. */
@@ -386,6 +509,8 @@ export class CalimeroClient {
386
509
  * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request
387
510
  * once `navigate` returns (or `confirm` declines): with a popup
388
511
  * (`url => window.open(url)`), poll it with {@link waitForConsent}.
512
+ * Before navigating it keeps `requestId` in `sessionStorage` (where there
513
+ * is one), for {@link resumeConsent} when the page sends the person back.
389
514
  */
390
515
  async openConsentPage(request, navigateOrOptions = {}) {
391
516
  const options = typeof navigateOrOptions === 'function' ? { navigate: navigateOrOptions } : navigateOrOptions;
@@ -396,6 +521,8 @@ export class CalimeroClient {
396
521
  throw new Error('no window to open the consent page in; pass `navigate`');
397
522
  w.location.assign(url);
398
523
  });
524
+ // The organization kinds (core#5014) are typed by hand in approvals.ts
525
+ // until the vendored OpenAPI document names them.
399
526
  const started = await this.consent.pageCreate({ body: request });
400
527
  if (started.code !== undefined) {
401
528
  const expected = await confirmationCode(started.requestId);
@@ -409,9 +536,93 @@ export class CalimeroClient {
409
536
  }
410
537
  if (options.confirm && !(await options.confirm(started)))
411
538
  return started;
539
+ try {
540
+ consentStorage()?.setItem(CONSENT_STORAGE_KEY, started.requestId);
541
+ }
542
+ catch {
543
+ // No storage here: pass `requestId` to `resumeConsent`.
544
+ }
412
545
  navigate(started.url);
413
546
  return started;
414
547
  }
548
+ /**
549
+ * On the page the consent page sent the person back to
550
+ * (`returnTo?request_id=…&result=…`): the decision on the request this page
551
+ * started, read from the node (`GET /consent/{id}/result`), never from the
552
+ * URL. `null` when the URL carries no `request_id`. The request is
553
+ * `options.requestId`, or the one {@link openConsentPage} stored in this
554
+ * tab; with the default `href` (`location.href`) the parameters are then
555
+ * removed with `history.replaceState`, and the stored id once decided.
556
+ *
557
+ * Throws `CalimeroError`:
558
+ * - `CONSENT_NOT_STARTED`: the URL names a request, and this page started none;
559
+ * - `CONSENT_REQUEST_MISMATCH`: the URL names another request than this page's;
560
+ * - `CONSENT_NOT_DECIDED`: this page's request is still pending although the
561
+ * page sent the person back, a sign that another request was approved on a
562
+ * page that was not the node's. Do not act on it;
563
+ * - `CONSENT_REPLACED`: the node no longer knows this page's request (`404`):
564
+ * an account has one undecided request per node, and a newer one replaced
565
+ * it, possibly on a page that was not the node's. Do not act on it either.
566
+ *
567
+ * The URL's `result` is never trusted: the answer's `status` is the node's.
568
+ * An approval's `outcome` (`orgId`, an invite's `token`, the `org` joined) is
569
+ * in the answer, typed by `kind`.
570
+ */
571
+ async resumeConsent(options = {}) {
572
+ const g = globalThis;
573
+ const href = options.href ?? g.location?.href;
574
+ if (href === undefined)
575
+ throw new Error('no page to read the consent return from; pass `href`');
576
+ const url = new URL(href);
577
+ const returned = url.searchParams.get('request_id');
578
+ if (!returned)
579
+ return null;
580
+ if (options.href === undefined && g.history)
581
+ g.history.replaceState(g.history.state, '', withoutConsentReturn(url));
582
+ let ownId = options.requestId;
583
+ if (ownId === undefined) {
584
+ try {
585
+ ownId = consentStorage()?.getItem(CONSENT_STORAGE_KEY) ?? undefined;
586
+ }
587
+ catch {
588
+ ownId = undefined;
589
+ }
590
+ }
591
+ if (!ownId) {
592
+ throw new CalimeroError(200, 'CONSENT_NOT_STARTED', 'this page started no consent request', { returned });
593
+ }
594
+ if (returned !== ownId) {
595
+ throw new CalimeroError(200, 'CONSENT_REQUEST_MISMATCH', 'the consent page returned another request than this page started', {
596
+ requestId: ownId,
597
+ returned,
598
+ });
599
+ }
600
+ let result;
601
+ try {
602
+ result = (await this.consent.pageResult({ request: ownId }));
603
+ }
604
+ catch (e) {
605
+ // One undecided request per account per node: a newer one replaced
606
+ // this page's, which then answers 404, perhaps swapped on a forged page.
607
+ if (e instanceof NotFound) {
608
+ forgetConsent(ownId);
609
+ throw new CalimeroError(404, 'CONSENT_REPLACED', "this page's consent request was replaced by a newer one", {
610
+ requestId: ownId,
611
+ });
612
+ }
613
+ throw e;
614
+ }
615
+ if (result.requestId !== ownId) {
616
+ throw new CalimeroError(200, 'CONSENT_REQUEST_MISMATCH', 'the node answered another request', { requestId: ownId, returned: result.requestId });
617
+ }
618
+ if (result.status === 'pending') {
619
+ throw new CalimeroError(200, 'CONSENT_NOT_DECIDED', 'the consent page returned, but this request is still pending', {
620
+ requestId: ownId,
621
+ });
622
+ }
623
+ forgetConsent(ownId);
624
+ return result;
625
+ }
415
626
  /**
416
627
  * Poll `client.consent.pageResult` until the request is decided, every
417
628
  * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)
@@ -420,7 +631,7 @@ export class CalimeroClient {
420
631
  async waitForConsent(requestId, options = {}) {
421
632
  const interval = options.intervalMs ?? 2000;
422
633
  for (;;) {
423
- const result = await this.consent.pageResult({ request: requestId });
634
+ const result = (await this.consent.pageResult({ request: requestId }));
424
635
  if (result.status !== 'pending')
425
636
  return result;
426
637
  if (options.signal?.aborted)
@@ -431,3 +642,23 @@ export class CalimeroClient {
431
642
  }
432
643
  }
433
644
  }
645
+ /** This page's `sessionStorage`, where there is one (a sandboxed frame or a turned-off store throws). */
646
+ function consentStorage() {
647
+ try {
648
+ return globalThis.sessionStorage;
649
+ }
650
+ catch {
651
+ return undefined;
652
+ }
653
+ }
654
+ /** Drop the stored consent request id, when it is `requestId`. */
655
+ function forgetConsent(requestId) {
656
+ try {
657
+ const store = consentStorage();
658
+ if (store?.getItem(CONSENT_STORAGE_KEY) === requestId)
659
+ store.removeItem(CONSENT_STORAGE_KEY);
660
+ }
661
+ catch {
662
+ // nothing to clear
663
+ }
664
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Downloading a sealed file, as core's `Client::export_file_to` does: the node
3
+ * answers only ciphertext and the file's data key wrapped to a key made here
4
+ * for this call, and nothing it says is believed until it checks out.
5
+ */
6
+ import { type Transport } from '../runtime/transport.js';
7
+ export { ExportError, type ExportErrorCode } from '../sealed/file.js';
8
+ /** Where an export writes the plaintext, in order. A `WritableStreamDefaultWriter` fits. */
9
+ export interface FileSink {
10
+ write(chunk: Uint8Array): Promise<void> | void;
11
+ }
12
+ /** What an export wrote, as proven against the file's mark. */
13
+ export interface ExportedFile {
14
+ size: number;
15
+ /** SHA-256 of the plaintext, hex. */
16
+ sha256: string;
17
+ }
18
+ type ExportTransport = Pick<Transport, 'json' | 'request'>;
19
+ /**
20
+ * Write the plaintext of sealed file `id` (64 hex) of app `app` to `sink`, one
21
+ * segment at a time. Each segment is checked against its hash before it is
22
+ * opened, and the segment list, size and plaintext hash against the file's id
23
+ * and mark at the end. On rejection, discard what `sink` received: it is
24
+ * authentic but may be a prefix of the file. A failed check is an
25
+ * {@link ExportError}; a refusal by the node is the transport's own error.
26
+ * `recipientSecret` pins the export key, for the published vectors only.
27
+ */
28
+ export declare function exportFileTo(transport: ExportTransport, app: string, id: string, sink: FileSink, signal?: AbortSignal, recipientSecret?: Uint8Array): Promise<ExportedFile>;
29
+ /** The plaintext of sealed file `id` of app `app`, in memory. Prefer {@link exportFileTo} for a large file. */
30
+ export declare function exportFile(transport: ExportTransport, app: string, id: string, signal?: AbortSignal): Promise<Uint8Array>;