@calimero-network/mero-js 33.2.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,7 +14,8 @@ 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';
@@ -351,6 +352,14 @@ export declare class CalimeroClient {
351
352
  finishAccountRecovery(passkey: PasskeyProvider, accountId?: string): Promise<CalimeroSession>;
352
353
  /** One of `app`'s blobs, by id (base58 or hex). */
353
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>;
354
363
  /**
355
364
  * Download a component app's blob with a grant one of its runs handed out
356
365
  * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
@@ -409,8 +418,34 @@ export declare class CalimeroClient {
409
418
  * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request
410
419
  * once `navigate` returns (or `confirm` declines): with a popup
411
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.
412
423
  */
413
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>;
414
449
  /**
415
450
  * Poll `client.consent.pageResult` until the request is decided, every
416
451
  * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)
@@ -11,13 +11,14 @@
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, UnavailableError, 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';
22
23
  /** The largest file sent as one request, and the part size a session is asked for. */
23
24
  export const FILE_PART_BYTES = 16 * 1024 * 1024;
@@ -333,6 +334,18 @@ export class CalimeroClient {
333
334
  async downloadBlob(app, id) {
334
335
  return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());
335
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
+ }
336
349
  /**
337
350
  * Download a component app's blob with a grant one of its runs handed out
338
351
  * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
@@ -496,6 +509,8 @@ export class CalimeroClient {
496
509
  * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request
497
510
  * once `navigate` returns (or `confirm` declines): with a popup
498
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.
499
514
  */
500
515
  async openConsentPage(request, navigateOrOptions = {}) {
501
516
  const options = typeof navigateOrOptions === 'function' ? { navigate: navigateOrOptions } : navigateOrOptions;
@@ -506,6 +521,8 @@ export class CalimeroClient {
506
521
  throw new Error('no window to open the consent page in; pass `navigate`');
507
522
  w.location.assign(url);
508
523
  });
524
+ // The organization kinds (core#5014) are typed by hand in approvals.ts
525
+ // until the vendored OpenAPI document names them.
509
526
  const started = await this.consent.pageCreate({ body: request });
510
527
  if (started.code !== undefined) {
511
528
  const expected = await confirmationCode(started.requestId);
@@ -519,9 +536,93 @@ export class CalimeroClient {
519
536
  }
520
537
  if (options.confirm && !(await options.confirm(started)))
521
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
+ }
522
545
  navigate(started.url);
523
546
  return started;
524
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
+ }
525
626
  /**
526
627
  * Poll `client.consent.pageResult` until the request is decided, every
527
628
  * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)
@@ -530,7 +631,7 @@ export class CalimeroClient {
530
631
  async waitForConsent(requestId, options = {}) {
531
632
  const interval = options.intervalMs ?? 2000;
532
633
  for (;;) {
533
- const result = await this.consent.pageResult({ request: requestId });
634
+ const result = (await this.consent.pageResult({ request: requestId }));
534
635
  if (result.status !== 'pending')
535
636
  return result;
536
637
  if (options.signal?.aborted)
@@ -541,3 +642,23 @@ export class CalimeroClient {
541
642
  }
542
643
  }
543
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>;
@@ -0,0 +1,128 @@
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 { concat, fromHex, fromHexUnsized, hex } from '../crypto/internal.js';
7
+ import { ExportError, SEGMENT_BYTES, SegmentReader, fileId, unwrapExport } from '../sealed/file.js';
8
+ import { x25519KeyPair } from '../sealed/noise.js';
9
+ import { routePath } from '../runtime/transport.js';
10
+ export { ExportError } from '../sealed/file.js';
11
+ function hexField(value, label, bytes) {
12
+ if (typeof value !== 'string')
13
+ throw new ExportError('BAD_ANSWER', `the node answered a bad ${label}`);
14
+ try {
15
+ return bytes === undefined ? fromHexUnsized(value, label) : fromHex(value, label, bytes);
16
+ }
17
+ catch {
18
+ throw new ExportError('BAD_ANSWER', `the node answered a bad ${label}`);
19
+ }
20
+ }
21
+ /** The answer's fields, checked for shape; whether they name the requested file is checked after. */
22
+ function checked(answer) {
23
+ const a = answer;
24
+ if (typeof a !== 'object' || a === null)
25
+ throw new ExportError('BAD_ANSWER', 'the node answered a bad export');
26
+ if (typeof a.app !== 'string')
27
+ throw new ExportError('BAD_ANSWER', 'the node answered a bad app');
28
+ if (typeof a.size !== 'number' || !Number.isSafeInteger(a.size) || a.size < 0) {
29
+ throw new ExportError('BAD_ANSWER', 'the node answered a bad size');
30
+ }
31
+ if (!Array.isArray(a.segments))
32
+ throw new ExportError('BAD_ANSWER', 'the node answered a bad segment list');
33
+ return {
34
+ app: a.app,
35
+ size: a.size,
36
+ named: hexField(a.id, 'file id', 32),
37
+ segments: a.segments.map((h) => hexField(h, 'segment hash', 32)),
38
+ sha256: hex(hexField(a.sha256, 'sha256', 32)),
39
+ ephemeral: hexField(a.ephemeral, 'ephemeral key', 32),
40
+ wrapped: hexField(a.wrapped, 'wrapped key'),
41
+ };
42
+ }
43
+ const aborted = () => new ExportError('ABORTED', 'the export was aborted');
44
+ /** A segment's bytes, refusing one longer than a whole segment before buffering it, and stopping on `signal`. */
45
+ async function readSegment(response, signal) {
46
+ const declared = Number(response.headers.get('content-length'));
47
+ if (Number.isFinite(declared) && declared > SEGMENT_BYTES) {
48
+ await response.body?.cancel();
49
+ throw new ExportError('TOO_LARGE', 'a segment is longer than a whole segment');
50
+ }
51
+ if (!response.body)
52
+ return new Uint8Array();
53
+ const reader = response.body.getReader();
54
+ const stop = () => void reader.cancel();
55
+ signal?.addEventListener('abort', stop);
56
+ const parts = [];
57
+ let total = 0;
58
+ try {
59
+ for (;;) {
60
+ const { done, value } = await reader.read();
61
+ if (done)
62
+ break;
63
+ total += value.length;
64
+ if (total > SEGMENT_BYTES) {
65
+ await reader.cancel();
66
+ throw new ExportError('TOO_LARGE', 'a segment is longer than a whole segment');
67
+ }
68
+ parts.push(value);
69
+ }
70
+ }
71
+ finally {
72
+ signal?.removeEventListener('abort', stop);
73
+ }
74
+ if (signal?.aborted)
75
+ throw aborted();
76
+ return concat(...parts);
77
+ }
78
+ /**
79
+ * Write the plaintext of sealed file `id` (64 hex) of app `app` to `sink`, one
80
+ * segment at a time. Each segment is checked against its hash before it is
81
+ * opened, and the segment list, size and plaintext hash against the file's id
82
+ * and mark at the end. On rejection, discard what `sink` received: it is
83
+ * authentic but may be a prefix of the file. A failed check is an
84
+ * {@link ExportError}; a refusal by the node is the transport's own error.
85
+ * `recipientSecret` pins the export key, for the published vectors only.
86
+ */
87
+ export async function exportFileTo(transport, app, id, sink, signal, recipientSecret) {
88
+ try {
89
+ return await exportChecked(transport, app, id, sink, signal, recipientSecret);
90
+ }
91
+ catch (error) {
92
+ if (signal?.aborted && !(error instanceof ExportError))
93
+ throw aborted();
94
+ throw error;
95
+ }
96
+ }
97
+ async function exportChecked(transport, app, id, sink, signal, recipientSecret) {
98
+ const recipient = await x25519KeyPair(recipientSecret);
99
+ // shortcut: not in the generated routes until the next openapi sync; they move there then.
100
+ const answer = checked(await transport.json('POST', routePath('apps/{app}/files/{id}/export', { app, id }), {
101
+ body: { recipient: hex(recipient.publicKey) },
102
+ signal,
103
+ }));
104
+ const { segments, named } = answer;
105
+ if (segments.length === 0 || hex(await fileId(segments)) !== hex(named) || hex(named) !== id) {
106
+ throw new ExportError('NOT_THE_FILE', `the node answered segments that are not the file ${id}`);
107
+ }
108
+ const dataKey = await unwrapExport(recipient, answer.ephemeral, { appId: answer.app, fileId: id }, answer.wrapped);
109
+ const reader = await SegmentReader.create(dataKey, segments);
110
+ for (let k = 0; k < segments.length; k += 1) {
111
+ if (signal?.aborted)
112
+ throw aborted();
113
+ const response = await transport.request('GET', routePath('apps/{app}/files/{id}/segments/{k}', { app, id, k }), {
114
+ signal,
115
+ });
116
+ await reader.push(await readSegment(response, signal), (chunk) => sink.write(chunk));
117
+ }
118
+ const last = await reader.finishExpecting(answer.size, answer.sha256);
119
+ if (last.length > 0)
120
+ await sink.write(last);
121
+ return { size: answer.size, sha256: answer.sha256 };
122
+ }
123
+ /** The plaintext of sealed file `id` of app `app`, in memory. Prefer {@link exportFileTo} for a large file. */
124
+ export async function exportFile(transport, app, id, signal) {
125
+ const chunks = [];
126
+ await exportFileTo(transport, app, id, { write: (chunk) => void chunks.push(chunk) }, signal);
127
+ return concat(...chunks);
128
+ }
@@ -1,4 +1,6 @@
1
1
  export { CalimeroClient, FILE_PART_BYTES, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
2
+ export { ExportError } from './files.js';
3
+ export type { ExportErrorCode, ExportedFile, FileSink } from './files.js';
2
4
  export { DEFAULT_DIRECTORY, DirectoryError } from '../runtime/directory.js';
3
5
  export type { DirectoryFailure } from '../runtime/directory.js';
4
6
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ClusterNotUpgraded, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, NotServing, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
@@ -9,7 +11,7 @@ export type { AttestationDoc, NodePolicy, NodeReleasePolicy } from '../runtime/a
9
11
  export { browserPasskey, b64url, fromB64url, passkeyConfirm } from '../runtime/passkey.js';
10
12
  export { MAX_RECOVERY_NONCE_BYTES, RECOVERY_DOMAIN, newRecoverySeed, parseRecoverySeed, recoveryMessage, recoveryPublicKey, recoverySeedText, signRecovery, } from './recovery-key.js';
11
13
  export type { ConfirmCallback, ConfirmChallenge, PasskeyConfirmOptions, AssertionJSON, PasskeyCreateOptions, PasskeyGetOptions, PasskeyProvider, PasskeyUserVerification, RegistrationJSON, } from '../runtime/passkey.js';
12
- export { MAX_REPORT_PAGE, RELEASE_VERIFIER, compareVersions, confirmationCode, consentReturn, pageQuery, pendingApprovalsFrom, publisherBindingBytes, publisherBindingMessage, releaseConsent, releaseNotesUrl, stalledBy, upgradeConsent, verifyReleaseUrl, withdrawConsent, } from './approvals.js';
13
- export type { ActorKind, AppsReport, Authority, ConsentRequest, ConsentResult, ConsentScope, ConsentStarted, OpenConsentOptions, Governance, LatestBlocked, PageOptions, PendingApprovals, PendingRelease, PendingUpgrade, ReleaseDeadline, ReleaseRules, ReportScope, ReportedApp, ReportedBundle, RuntimeShortNode, } from './approvals.js';
14
+ export { CONSENT_STORAGE_KEY, MAX_REPORT_PAGE, RELEASE_VERIFIER, acceptInviteConsent, compareVersions, confirmationCode, consentReturn, createInviteConsent, createOrgConsent, pageQuery, pendingApprovalsFrom, publisherBindingBytes, publisherBindingMessage, releaseConsent, releaseNotesUrl, stalledBy, upgradeConsent, verifyReleaseUrl, withdrawConsent, withoutConsentReturn, } from './approvals.js';
15
+ export type { ActorKind, AppsReport, Authority, ConsentKind, ConsentOutcomes, ConsentRequest, ConsentResult, ConsentResultOf, ConsentScope, ConsentStarted, InviteConsentSubject, InviteRole, OpenConsentOptions, ResumeConsentOptions, Governance, LatestBlocked, PageOptions, PendingApprovals, PendingRelease, PendingUpgrade, ReleaseDeadline, ReleaseRules, ReportScope, ReportedApp, ReportedBundle, RuntimeShortNode, } from './approvals.js';
14
16
  export { DEFAULT_ORG_CAPABILITIES, ORG_CAPABILITIES, orgCapabilities } from './capabilities.js';
15
17
  export type { OrgCapability } from './capabilities.js';
@@ -8,10 +8,11 @@
8
8
  // the runtime's errors, passkeys and directory, which callers of the client
9
9
  // use. src/routes/index.ts describes the layering.
10
10
  export { CalimeroClient, FILE_PART_BYTES, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
11
+ export { ExportError } from './files.js';
11
12
  export { DEFAULT_DIRECTORY, DirectoryError } from '../runtime/directory.js';
12
13
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ClusterNotUpgraded, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, NotServing, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
13
14
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from '../runtime/attestation.js';
14
15
  export { browserPasskey, b64url, fromB64url, passkeyConfirm } from '../runtime/passkey.js';
15
16
  export { MAX_RECOVERY_NONCE_BYTES, RECOVERY_DOMAIN, newRecoverySeed, parseRecoverySeed, recoveryMessage, recoveryPublicKey, recoverySeedText, signRecovery, } from './recovery-key.js';
16
- export { MAX_REPORT_PAGE, RELEASE_VERIFIER, compareVersions, confirmationCode, consentReturn, pageQuery, pendingApprovalsFrom, publisherBindingBytes, publisherBindingMessage, releaseConsent, releaseNotesUrl, stalledBy, upgradeConsent, verifyReleaseUrl, withdrawConsent, } from './approvals.js';
17
+ export { CONSENT_STORAGE_KEY, MAX_REPORT_PAGE, RELEASE_VERIFIER, acceptInviteConsent, compareVersions, confirmationCode, consentReturn, createInviteConsent, createOrgConsent, pageQuery, pendingApprovalsFrom, publisherBindingBytes, publisherBindingMessage, releaseConsent, releaseNotesUrl, stalledBy, upgradeConsent, verifyReleaseUrl, withdrawConsent, withoutConsentReturn, } from './approvals.js';
17
18
  export { DEFAULT_ORG_CAPABILITIES, ORG_CAPABILITIES, orgCapabilities } from './capabilities.js';