@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.
@@ -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,15 +1,17 @@
1
- export { CalimeroClient, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
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';
5
7
  export type { Committed, SignUpRefusal } from '../runtime/errors.js';
6
- export type { AppInfo, AppTeam, AppTeams, BlobInfo, DeadLetter, Deployer, FrontendManifest, PackageOrigin, SignInOptions, AccountRecovery, SignUpOptions, SignUpPolicy, CallResult, CalimeroClientOptions, CalimeroConnectOptions, NodeEvent, CalimeroSession, PackageInfo, RetryOptions, OrgInfo, OrgInvite, OrgMode, RecoveryTimes, PresenceEntry, ScopeAppsResult, ScopedAppTeam, TeamInfo, UpgradeRun, ViewResult, } from './calimero-client.js';
8
+ export type { AppInfo, AppTeam, AppTeams, BlobInfo, FileData, FileInfo, DeadLetter, Deployer, FrontendManifest, PackageOrigin, SignInOptions, AccountRecovery, SignUpOptions, SignUpPolicy, CallResult, CalimeroClientOptions, CalimeroConnectOptions, NodeEvent, CalimeroSession, PackageInfo, RetryOptions, OrgInfo, OrgInvite, OrgMode, RecoveryTimes, PresenceEntry, ScopeAppsResult, ScopedAppTeam, TeamInfo, UpgradeRun, ViewResult, } from './calimero-client.js';
7
9
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from '../runtime/attestation.js';
8
10
  export type { AttestationDoc, NodePolicy, NodeReleasePolicy } from '../runtime/attestation.js';
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';
@@ -7,11 +7,12 @@
7
7
  // (`recovery-key.ts`) and capability bits (`capabilities.ts`). It re-exports
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
- export { CalimeroClient, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
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';