@calimero-network/mero-js 29.16.0 → 30.0.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
@@ -29,7 +29,7 @@ quotes and is loaded on first use.
29
29
  ## Quick start
30
30
 
31
31
  ```ts
32
- import { CalimeroClient, browserPasskey } from '@calimero-network/mero-js';
32
+ import { CalimeroClient, browserPasskey, passkeyConfirm } from '@calimero-network/mero-js';
33
33
 
34
34
  // Reach a Calimero Cloud cluster by name.
35
35
  const client = await CalimeroClient.connect({
@@ -39,14 +39,14 @@ const client = await CalimeroClient.connect({
39
39
  });
40
40
 
41
41
  await client.signUp(browserPasskey(), 'alice'); // or signIn(browserPasskey())
42
- await client.installPackage('com.example.kv', '1.0.0'); // signed .mpk from the registry
43
- const app = await client.createApp('kv', { package: 'com.example.kv', version: '1.0.0' }, { confirmMethods: ['clear'] });
42
+ await client.packages.install({ package: 'com.example.kv', version: '1.0.0' }); // signed .mpk from the registry
43
+ const { appId: app } = await client.apps.create({ name: 'kv', package: 'com.example.kv', version: '1.0.0' });
44
44
 
45
- await client.call(app, 'set', { key: 'a', value: '1' });
46
- const { result } = await client.view(app, 'get', { key: 'a' });
47
- await client.callConfirmed(app, 'clear', {}, browserPasskey()); // passkey consent
45
+ await client.apps.call({ app, method: 'set', args: { key: 'a', value: '1' } });
46
+ const { result } = await client.apps.view({ app, method: 'get', args: { key: 'a' } });
47
+ await client.apps.call({ app, method: 'clear', args: {} }, { confirm: passkeyConfirm(browserPasskey()) }); // passkey consent
48
48
  for await (const event of client.events(app)) console.log(event);
49
- await client.upgradeApp(app, { version: '1.1.0' }, browserPasskey()); // the owner approves
49
+ await client.apps.upgrade({ app, version: '1.1.0' }, { confirm: passkeyConfirm(browserPasskey()) }); // the owner approves
50
50
  ```
51
51
 
52
52
  A development cluster (`merod local`, `merod run --dev`) sends mock quotes,
@@ -97,18 +97,18 @@ Pinned measurements go through `policy.verifyQuote` (`createQuoteVerifier`).
97
97
 
98
98
  ## The API
99
99
 
100
- - **Credentials**: `signUp` (with an `invite`, on a cluster that takes new accounts by invite; `signUpPolicy` reads which), `signIn`, `refresh`, `signOut`, `signOutEverywhere`, `listSessions`, `revokeSession`, `listActivity`, `useSession`, `useApiKey`, `me`, `usage`, `addPasskey`, `labelPasskey`, `removePasskey`, `createApiKey`, `listApiKeys`, `revokeApiKey`. Adding or removing a passkey and creating an API key are approved with a passkey the account already has.
101
- - **Account recovery** (core #4844): `createRecoveryCode`, `removeRecoveryCode` (passkey-approved; the code is shown once), then signed out `startAccountRecovery(code, passkey)` and, 72 hours later, `finishAccountRecovery(passkey, accountId?)`; a passkey the account still has cancels in between (`cancelAccountRecovery`; `me()` shows `recoveryCode` and `recoveryPending`).
102
- - **Package origins**: `packageOrigins.list`, `packageOrigins.add`, `packageOrigins.remove`. A package's managers register the web origins of a frontend they host themselves (approved with a passkey); `signUp` and `signIn` on such a page send its origin, sign for that origin's relying-party id, and open a session bound to the package (`me()` answers its `app` and `origin`). An unregistered origin is refused with `OriginNotRegistered`. `packageOrigins.add(pkg, origin, passkey, { served: true })` registers a custom domain: the cluster also serves the package's frontend there from its signed bundle (`https://host`, no port; the passkey's consent names `served: true`); `list` answers `served` on each origin, and the extra refusals are `NotServing` (the cluster serves no frontends), `ClusterNotUpgraded` (a node is on an older release), `QuotaExceeded` (4 served per package, 64 per cluster) and `OriginTaken` (held with the other `served`).
103
- - **Packages**: `installPackage`, `uploadPackage`, `packages`, `package`, `uninstallPackage`; `uploadBundle` (raw WASM, development clusters only).
104
- - **Apps**: `createApp`, `listApps`, `getApp`, `deleteApp`, `setAccess`, `setAppMetadata`, `appStorage`, `appAbi`, `upgradeApp`, `transferApp`, `moveApp`.
105
- - **Calls**: `call`, `callConfirmed`, `view`, `events`. A call always carries an idempotency key, and is sent again with it while the node answers `503`, then to the next node.
106
- - **Blobs and presence**: `uploadBlob`, `downloadBlob`, `listBlobs`, `blobInfo`, `deleteBlob`; `publishPresence`, `presence`, `presenceStream`.
107
- - **Organizations**: `createOrg`, `getOrg`, `orgMembersSecurity` (owners and admins: each member's passkey count to `3+`, recovery code set, last active day, live sessions), `deleteOrg`, `setOrgMetadata`, `setMember`, `removeMember`, `setMemberMetadata`, `setCapabilities` (`ORG_CAPABILITIES`), `setTeamDefaultCapabilities`, teams, app teams (`listAppTeams`, `scopeApps`), `invite` (`{ allApps: true }`: whoever redeems it gets every app added later), `setAllApps` (owner or admin: every app added later, for a member), `redeemInvite`, `listInvites`, `revokeInvite`, recovery (`setRecoveryKey`, `startRecovery`, `cancelRecovery`, `finishRecovery`; `newRecoverySeed`, `recoveryPublicKey`). Setting or removing a member or team member, capabilities, invites (minting and revoking) and scoping apps are approved with the caller's passkey; redeeming an invite is not.
108
- - **Owner decisions** (passkey approval, never from an app's frontend): `upgradeOrg`, `upgradeRun`, `retryUpgradeRun`, `approveRelease`, `approveOutbound`, `bindPublisher`, `upgradePublished`.
109
- - **Approvals from an app**: `appsReport`, `releaseRules`, `pendingApprovals`, then `requestConsent` / `openConsentPage` to send the user to the node's consent page, and `consentResult`. 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/).
110
- - **Operator** (ops token): `opsApps`, `opsOrgs`, `opsServedOrigins` (every custom domain the log holds, by package label), `setReleaseDeadline`, `liftReleaseDeadline`.
111
- - **Any route**: `get`, `post`, `put`, `delete`; `postConfirmed` and `deleteConfirmed` answer a `412 CONFIRM_REQUIRED` with a passkey.
100
+ Every route of the node is a generated method, in a group per area
101
+ (`client.apps`, `client.auth`, `client.orgs`, `client.packages`,
102
+ `client.deployments`, `client.consent`, `client.ops`, `client.public`); see
103
+ [below](#the-runtime-and-the-route-layer). The hand-written methods left are the
104
+ flows and streams a single route cannot be:
105
+
106
+ - **Credentials**: `signUp(passkey, name, { invite?, origin?, signal? })`, `signIn(passkey, { origin?, signal? })`, `refresh`, `signOut`, `signOutEverywhere`, `useSession`, `useApiKey`, `addPasskey(newPasskey, approver)`.
107
+ - **Account recovery** (core #4844): signed out, `startAccountRecovery(code, passkey)` and, 72 hours later, `finishAccountRecovery(passkey, accountId?)`. The code itself is `client.auth.recoveryCreate({}, { confirm })`.
108
+ - **Organization recovery**: `startRecovery(org, seed)` (the seed signs here and never leaves the process); `newRecoverySeed`, `recoveryPublicKey`.
109
+ - **Blobs**: `downloadBlob(app, id)`, `downloadBlobGranted(app, id, grant)` (bytes; `client.apps.blobDownload` answers a `Blob` with its type).
110
+ - **Streams**: `events(app, from?, signal?)`, `presenceStream(app, signal?)`.
111
+ - **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/).
112
112
 
113
113
  Refusals are typed (`LoginRequired`, `PasskeyUnknownHere`, `WrongNode`, `NotFound`, `ConfirmRequired`, `ConfirmCancelled`, `ConfirmPromptBlocked`,
114
114
  `ArgsTooLarge`, `IdempotencyMismatch`, `ReleaseDeadlineError`, `RuntimeTooOld`, `ConsentStale`, `AppError`, `TrapError`,
@@ -130,9 +130,66 @@ the client for mero-tee's private agent gate (`attestAgent`, `provisionAgent`,
130
130
  The client is two layers. The **runtime** (`@calimero-network/mero-js/runtime`,
131
131
  `src/runtime/`) is everything that is not a route: the node's attestation, the
132
132
  sealed channel, the credential and the session's refresh on a `401`, moving on
133
- `421 WRONG_NODE`, D70 retries and failover, the `412 CONFIRM_REQUIRED` passkey
134
- step-up, error mapping and server-sent events. Its whole surface toward routes is
135
- one interface:
133
+ `421 WRONG_NODE`, D70 retries and failover, error mapping and server-sent
134
+ events. The **route layer** is generated from core's OpenAPI document
135
+ (`openapi/core-openapi.json`, the node's `docs/public/openapi.json`) by
136
+ `pnpm gen:api`: `openapi-typescript` writes the types (`src/generated/api.ts`)
137
+ and `scripts/gen-methods.mjs` one method per operation
138
+ (`src/generated/methods.ts`), grouped by the operation's tag. `CalimeroClient`
139
+ exposes the groups, which share `client.transport`'s session:
140
+
141
+ ```ts
142
+ import { passkeyConfirm } from '@calimero-network/mero-js';
143
+
144
+ const org = await client.orgs.get({ org: orgId }); // the typed payload
145
+ const { result } = await client.apps.call({ app, method: 'set', args: { key: 'a' } });
146
+ const { token } = await client.orgs.inviteCreate( // a step-up (412)
147
+ { org: orgId, role: 'member' },
148
+ { confirm: passkeyConfirm(passkey) },
149
+ );
150
+ await client.apps.blobUpload({ app, body: bytes, contentType: 'image/png' });
151
+ ```
152
+
153
+ - **Groups**: `client.apps`, `client.auth`, `client.orgs`, `client.packages`,
154
+ `client.deployments`, `client.consent`, `client.ops`, `client.public`.
155
+ - **One argument object**: path parameters, query parameters and body fields
156
+ merged, all typed from the document. The body goes whole under `body` when it is
157
+ raw bytes (with an optional `contentType`) or when its field names would collide.
158
+ A route whose query parameter is named like a path parameter takes its query
159
+ under `query`.
160
+ - **The answer** is the route's typed success payload (a `Blob` for a download).
161
+ A refusal is thrown as the typed `CalimeroError` (`NotFound`, `ConfirmRequired`, ...).
162
+ - **Challenges**: the second argument `{ confirm?, operatorProof?, signal? }`
163
+ answers this call's `412 CONFIRM_REQUIRED` (`passkeyConfirm(passkey)`) or
164
+ `428 OPERATOR_SIGNATURE_REQUIRED` (the operator key's signature over the
165
+ statement). The client's own `new CalimeroClient(options, { confirm, operatorProof })`
166
+ answers every call that gives none.
167
+ - **Retries**: a route the document marks `x-calimero-retry-safe` (a call, a
168
+ view, a method by its path) is sent again on a `503` as D70 says; one whose
169
+ retries require an `idempotencyKey` gets one when it has none, which its retries
170
+ and its confirmed retry share. A `421 WRONG_NODE` moves to the next node.
171
+ - **Step-ups** ask the passkey for the route's own user verification
172
+ (`x-calimero-user-verification`: `preferred` for the sign-up's confirmation,
173
+ `required` elsewhere).
174
+ - **Streams** (`events`, `presenceStream`) stay hand-written on the runtime.
175
+ - `createRoutes(createApiClient(transport, { confirm, operatorProof }))` builds
176
+ the same groups on any `NodeTransport`.
177
+
178
+ `client.api` is the **low-level** escape hatch: the raw `openapi-fetch`
179
+ client the methods run on (`client.api.GET('/orgs/{org}', { params: { path: {
180
+ org } } })` answers `{ data, error, response }`). Its `fetch` is
181
+ `transportFetch(transport)`: the path, query and body go through the transport
182
+ (sealed, with the credential), and the two routes served in the clear
183
+ (`/attestation`, `/health`) go unsealed. `stepUp(...)` and
184
+ `operatorSignature(...)` are its middleware; `unwrap(result)` throws a refusal.
185
+ Apps should not write against it.
186
+
187
+ The single-route methods of 29.x (`createOrg`, `call`, ...) are gone; see
188
+ [Upgrading from 29.x](#upgrading-from-29x). The ceremonies (`signUp`, `signIn`, `addPasskey`,
189
+ account and organization recovery, `openConsentPage`, ...) stay as flows.
190
+
191
+ The runtime's own surface toward routes is still one interface, for a route
192
+ layer of your own:
136
193
 
137
194
  ```ts
138
195
  interface Transport {
@@ -144,21 +201,155 @@ interface Transport {
144
201
  // userVerification?, retry?: true | 'once' (D70), signal?, promptSignal? }
145
202
  ```
146
203
 
147
- A refusal is thrown as its typed `CalimeroError`. `NodeTransport` implements it;
148
- `routePath('apps/{app}/blobs/{id}', { app, id })` fills a path with encoded
149
- segments. The **route layer**, `CalimeroClient`, is the hand-written methods on
150
- top; `client.transport` is its runtime, so a route layer of your own (one
151
- generated from the node's OpenAPI document, say) shares the client's session:
152
-
153
- ```ts
154
- import { routePath } from '@calimero-network/mero-js/runtime';
155
-
156
- const app = await client.transport.json('GET', routePath('apps/{app}', { app: appId }));
157
- await client.transport.json('DELETE', routePath('orgs/{org}', { org }), { body: {}, passkey });
158
- ```
159
-
160
- The `/runtime` entry re-exports the package's own bundle, so its error classes are
161
- the ones `CalimeroClient` throws (`instanceof` holds across both imports).
204
+ `NodeTransport` implements it, and `exchange(method, path, options)` answers a
205
+ refusal as the node's response instead of throwing it (what the generated
206
+ client sends through). The `/runtime` entry re-exports the package's own bundle,
207
+ so its error classes are the ones `CalimeroClient` throws (`instanceof` holds
208
+ across both imports).
209
+
210
+ ### Refreshing the OpenAPI document
211
+
212
+ `openapi/core-openapi.json` is vendored from core at the commit `openapi/SOURCE`
213
+ names. `scripts/refresh-openapi.sh [<core ref>]` (`pnpm refresh:openapi`)
214
+ fetches it again, records the commit and regenerates `src/generated/`;
215
+ `pnpm check:api` fails when the generated types or methods are not those of the
216
+ vendored document.
217
+
218
+ `.github/workflows/openapi-sync.yml` does this on its own: core sends a
219
+ `repository_dispatch` (`core-openapi`, with the core commit) whenever its
220
+ document changes, and a weekly run catches a missed one (or run it by hand with a
221
+ `ref`). When the document or the generated code changed, it opens or refreshes a
222
+ pull request on `chore/core-openapi` that lists the generated methods added,
223
+ removed or changed (`scripts/openapi-sync-summary.mjs`); a removed or renamed
224
+ one needs a major release.
225
+
226
+ It opens that pull request with a GitHub App's token, so the pull request's CI
227
+ runs: the organization's shared `vars.ACTIONS_APP_ID` /
228
+ `secrets.ACTIONS_APP_PRIVATE_KEY`, which must be shared with this repository. The
229
+ app must be installed on this repository
230
+ with contents and pull-requests write.
231
+
232
+ ## Upgrading from 29.x
233
+
234
+ 30.0 removes the single-route methods 29.x deprecated, and the untyped `get`,
235
+ `post`, `put`, `delete`, `postConfirmed` and `deleteConfirmed`. Each is a
236
+ generated method now, which takes one argument object and answers the route's
237
+ payload (pick the field the old method answered: `(await client.orgs.create({
238
+ name })).orgId`). A step-up takes `{ confirm: passkeyConfirm(passkey) }` as the
239
+ second argument. `client.packages` and `client.deployments` are groups, no longer
240
+ callable (`(await client.packages.list()).packages`).
241
+
242
+ | 29.x | 30.0 |
243
+ | --- | --- |
244
+ | `signUpPolicy()` | `client.deployments.signUpPublic()` |
245
+ | `listSessions()` | `(await client.auth.sessionsList()).sessions` |
246
+ | `revokeSession(session)` | `client.auth.sessionRevoke({ session })` |
247
+ | `listActivity(after)` | `(await client.auth.activityList({ after })).activity` |
248
+ | `me()` | `client.auth.me()` |
249
+ | `removePasskey(credentialId, passkey)` | `client.auth.passkeyRemove({ cred: credentialId }, { confirm: passkeyConfirm(passkey) })` |
250
+ | `labelPasskey(credentialId, label)` | `client.auth.passkeyLabel({ cred: credentialId, label })` |
251
+ | `createRecoveryCode(passkey)` | `(await client.auth.recoveryCreate({}, { confirm: passkeyConfirm(passkey) })).code` |
252
+ | `removeRecoveryCode(passkey)` | `client.auth.recoveryRemove({}, { confirm: passkeyConfirm(passkey) })` |
253
+ | `cancelAccountRecovery(passkey)` | `client.auth.accountRecoveryCancel({}, { confirm: passkeyConfirm(passkey) })` |
254
+ | `usage()` | `client.auth.usage()` |
255
+ | `attestation()` | `client.public.attestation({ nonce: '00'.repeat(32) })` |
256
+ | `listApiKeys()` | `(await client.auth.apikeyList()).keys` |
257
+ | `revokeApiKey(keyId, passkey)` | `client.auth.apikeyRevoke({ key: keyId }, { confirm: passkeyConfirm(passkey) })` |
258
+ | `createApiKey(options, passkey)` | `client.auth.apikeyCreate({ ...options }, { confirm: passkeyConfirm(passkey) })` |
259
+ | `uploadBundle(wasm)` | `(await client.packages.bundlePut({ body: wasm, contentType: 'application/wasm' })).hash` |
260
+ | `uploadBlob(app, data, contentType)` | `client.apps.blobUpload({ app, body: data, contentType })` |
261
+ | `blobContent(app, id, options)` | `client.apps.blobDownload({ app, id, grant })` (a `Blob`: `arrayBuffer()` and `type`) |
262
+ | `listBlobs(app)` | `(await client.apps.blobList({ app })).blobs` |
263
+ | `blobInfo(app, id)` | `client.apps.blobInfo({ app, id })` |
264
+ | `deleteBlob(app, id)` | `client.apps.blobDelete({ app, id })` |
265
+ | `uploadPackage(mpk)` | `client.packages.upload({ body: mpk, contentType: 'application/octet-stream' })` |
266
+ | `installPackage(pkg, version)` | `client.packages.install({ package: pkg, version })` |
267
+ | `packages()` | `(await client.packages.list()).packages` |
268
+ | `package(pkg)` | `client.packages.get({ package: pkg })` |
269
+ | `uninstallPackage(pkg, version)` | `client.packages.uninstall({ package: pkg })` or `client.packages.versionUninstall({ package: pkg, version })` |
270
+ | `listApps(filter)` | `(await client.apps.list({ ...filter })).apps` |
271
+ | `getApp(app)` | `client.apps.get({ app })` |
272
+ | `deleteApp(app)` | `client.apps.delete({ app })` |
273
+ | `setAccess(app, access)` | `client.apps.access({ app, access })` |
274
+ | `setAppMetadata(app, metadata)` | `client.apps.metadata({ app, metadata })` |
275
+ | `appXcalls(app)` | `client.apps.xcalls({ app })` |
276
+ | `appStorage(app)` | `client.apps.storage({ app })` |
277
+ | `appAbi(app)` | `client.apps.abi({ app })` |
278
+ | `transferApp(app, to, passkey)` | `client.apps.transfer({ app, to }, { confirm: passkeyConfirm(passkey) })` |
279
+ | `moveApp(app, toOrg, options, passkey)` | `client.apps.move({ app, toOrg, ...options }, { confirm: passkeyConfirm(passkey) })` |
280
+ | `upgradeApp(app, target, passkey)` | `client.apps.upgrade({ app, ...target }, { confirm: passkeyConfirm(passkey) })` |
281
+ | `createApp(name, bundle, options)` | `(await client.apps.create({ name, bundle, ...options })).appId` |
282
+ | `call(app, method, args, idempotencyKey)` | `client.apps.call({ app, method, args, idempotencyKey })` |
283
+ | `callConfirmed(app, method, args, passkey, idempotencyKey)` | `client.apps.call({ app, method, args, idempotencyKey }, { confirm: passkeyConfirm(passkey) })` |
284
+ | `view(app, method, args, options)` | `client.apps.view({ app, method, args, consistency: options.stale ? 'stale' : undefined, minIndex: options.minIndex })` |
285
+ | `publishPresence(app, seq, state)` | `client.apps.presencePublish({ app, seq, state: presenceState(state) })` |
286
+ | `presence(app)` | `(await client.apps.presenceGet({ app })).present` |
287
+ | `setAlias(alias, app)` | `client.auth.aliasSet({ alias, app })` |
288
+ | `aliases()` | `(await client.auth.aliasList()).aliases` |
289
+ | `alias(alias)` | `(await client.auth.aliasGet({ alias })).appId` |
290
+ | `deleteAlias(alias)` | `client.auth.aliasDelete({ alias })` |
291
+ | `createOrg(name, options)` | `(await client.orgs.create({ name, ...options })).orgId` |
292
+ | `setRecoveryKey(org, publicKey, passkey)` | `client.orgs.recoverySet({ org, publicKey }, { confirm: passkeyConfirm(passkey) })` |
293
+ | `cancelRecovery(org, passkey)` | `client.orgs.recoveryCancel({ org }, { confirm: passkeyConfirm(passkey) })` |
294
+ | `finishRecovery(org, passkey)` | `client.orgs.recoveryFinish({ org }, { confirm: passkeyConfirm(passkey) })` |
295
+ | `getOrg(org)` | `client.orgs.get({ org })` |
296
+ | `orgMembersSecurity(org)` | `(await client.orgs.members({ org, detail: 'security' })).members` |
297
+ | `deleteOrg(org, passkey)` | `client.orgs.delete({ org }, { confirm: passkeyConfirm(passkey) })` |
298
+ | `setOrgMetadata(org, metadata)` | `client.orgs.metadata({ org, metadata })` |
299
+ | `setMemberMetadata(org, account, metadata)` | `client.orgs.memberMetadata({ org, account, metadata })` |
300
+ | `upgradeOrg(org, target, passkey)` | `client.orgs.upgrade({ org, ...target }, { confirm: passkeyConfirm(passkey) })` |
301
+ | `upgradeRun(org, run)` | `client.orgs.upgradeStatus({ org, run })` |
302
+ | `retryUpgradeRun(org, run, passkey)` | `client.orgs.upgradeRetry({ org, run }, { confirm: passkeyConfirm(passkey) })` |
303
+ | `approveRelease(org, version, passkey, approved)` | `client.auth.accountReleaseApproval({ version, approved }, { confirm: passkeyConfirm(passkey) })` or `client.orgs.releaseApproval({ org, version, approved }, { confirm: passkeyConfirm(passkey) })` |
304
+ | `approveOutbound(org, pkg, passkey, options)` | `client.auth.accountOutboundApproval({ package: pkg, ...options }, { confirm: passkeyConfirm(passkey) })` or `client.orgs.outboundApproval({ org, package: pkg, ...options }, { confirm: passkeyConfirm(passkey) })` |
305
+ | `appsReport(org, page)` | `client.auth.accountApps({ ...page })` or `client.orgs.apps({ org, ...page })` |
306
+ | `releaseRules()` | `client.public.releasesPublic()` |
307
+ | `requestConsent(request)` | `client.consent.pageCreate({ body: request })` |
308
+ | `consentResult(requestId)` | `client.consent.pageResult({ request: requestId })` |
309
+ | `publisherBinding(signerId)` | `client.public.publisherBinding({ signer: signerId })` |
310
+ | `bindPublisher(org, proof, passkey)` | `client.orgs.publisher({ org, ...proof }, { confirm: passkeyConfirm(passkey) })` |
311
+ | `upgradePublished(org, pkg, target, passkey)` | `client.orgs.publisherUpgrade({ org, package: pkg, ...target }, { confirm: passkeyConfirm(passkey) })` |
312
+ | `opsApps(page)` | `client.ops.apps({ ...page })` |
313
+ | `opsOrgs(page)` | `client.ops.orgs({ ...page })` |
314
+ | `opsServedOrigins()` | `client.ops.served()` |
315
+ | `setReleaseDeadline(version, after)` | `client.ops.releaseDeadline({ version, after }) (after as an RFC 3339 string)` |
316
+ | `liftReleaseDeadline(version)` | `client.ops.releaseDeadlineLift({ version })` |
317
+ | `setMember(org, account, role, passkey)` | `client.orgs.setMember({ org, account, role }, { confirm: passkeyConfirm(passkey) })` |
318
+ | `removeMember(org, account, passkey)` | `client.orgs.removeMember({ org, account }, { confirm: passkeyConfirm(passkey) })` |
319
+ | `setCapabilities(org, capabilities, passkey, at)` | `client.orgs.capabilities({ org, capabilities, ...at }, { confirm: passkeyConfirm(passkey) })` |
320
+ | `setAllApps(org, account, allApps, passkey)` | `client.orgs.allApps({ org, account, allApps }, { confirm: passkeyConfirm(passkey) })` |
321
+ | `setTeamDefaultCapabilities(org, team, capabilities, passkey)` | `client.orgs.capabilities({ org, team, capabilities }, { confirm: passkeyConfirm(passkey) })` |
322
+ | `createTeam(org, name, join, parent)` | `(await client.orgs.teamCreate({ org, name, join, parent })).teamId` |
323
+ | `getTeam(org, team)` | `client.orgs.teamGet({ org, team })` |
324
+ | `updateTeam(org, team, update)` | `client.orgs.teamUpdate({ org, team, ...update })` |
325
+ | `deleteTeam(org, team, passkey)` | `client.orgs.teamDelete({ org, team }, { confirm: passkeyConfirm(passkey) })` |
326
+ | `setTeamMember(org, team, account, passkey, row)` | `client.orgs.teamSetMember({ org, team, account, ...row }, { confirm: passkeyConfirm(passkey) })` |
327
+ | `removeTeamMember(org, team, account, passkey)` | `client.orgs.teamRemoveMember({ org, team, account }, { confirm: passkeyConfirm(passkey) })` |
328
+ | `invite(org, role, passkey, teams, options)` | `(await client.orgs.inviteCreate({ org, role, teams, ...options }, { confirm: passkeyConfirm(passkey) })).token` |
329
+ | `redeemInvite(token)` | `client.orgs.inviteRedeem({ token })` |
330
+ | `listInvites(org)` | `(await client.orgs.inviteList({ org })).invites` |
331
+ | `revokeInvite(org, inviteKey, passkey)` | `client.orgs.inviteRevoke({ org, key: inviteKey }, { confirm: passkeyConfirm(passkey) })` |
332
+ | `listAppTeams(org)` | `client.orgs.appTeamList({ org })` |
333
+ | `scopeApps(org, passkey, options)` | `client.orgs.appTeamsScope({ org, ...options }, { confirm: passkeyConfirm(passkey) })` |
334
+ | `packageOrigins.list(pkg)` | `(await client.packages.originsList({ package: pkg })).origins` |
335
+ | `packageOrigins.add(pkg, origin, passkey, options)` | `client.packages.originsAdd({ package: pkg, origin, ...options }, { confirm: passkeyConfirm(passkey) })` |
336
+ | `packageOrigins.remove(pkg, origin, passkey)` | `client.packages.originsRemove({ package: pkg, origin }, { confirm: passkeyConfirm(passkey) })` |
337
+ | `grantDeployer(deployer, passkey, options)` | `client.deployments.deployerGrant({ deployer, ...options }, { confirm: passkeyConfirm(passkey) }) (until as an RFC 3339 string)` |
338
+ | `deployers()` | `client.deployments.deployerList()` |
339
+ | `revokeDeployer(deployer, passkey)` | `client.deployments.deployerRevoke({ key: deployerKey(deployer) }, { confirm: passkeyConfirm(passkey) })` (or the key string itself) |
340
+ | `createDeployment(name, owner, passkey)` | `(await client.deployments.create({ name, owner }, { confirm: passkeyConfirm(passkey) })).id` |
341
+ | `deployments()` | `(await client.deployments.list()).deployments` |
342
+ | `deployment(id)` | `client.deployments.get({ id })` |
343
+ | `deleteDeployment(id, passkey)` | `client.deployments.delete({ id }, { confirm: passkeyConfirm(passkey) })` |
344
+ | `offerApp(id, offer, passkey)` | `client.deployments.offer({ id, ...offer }, { confirm: passkeyConfirm(passkey) })` |
345
+ | `withdrawApp(id, app, passkey)` | `client.deployments.withdraw({ id, app }, { confirm: passkeyConfirm(passkey) })` |
346
+ | `deploymentOrgs(id)` | `client.deployments.orgs({ id })` |
347
+ | `get(path)` | the route's generated method: `client.get('orgs/' + org)` → `client.orgs.get({ org })` |
348
+ | `post(path, body)` | the route's generated method: `client.post('orgs', { name })` → `client.orgs.create({ name })` |
349
+ | `put(path, body)` | the route's generated method: `client.put('auth/aliases/' + alias, { app })` → `client.auth.aliasSet({ alias, app })` |
350
+ | `delete(path, body)` | the route's generated method: `client.delete('apps/' + app)` → `client.apps.delete({ app })` |
351
+ | `postConfirmed(path, body, passkey)` | the route's generated method with `{ confirm: passkeyConfirm(passkey) }`: `client.postConfirmed('orgs/' + org + '/upgrade', body, passkey)` → `client.orgs.upgrade({ org, ...body }, { confirm: passkeyConfirm(passkey) })` |
352
+ | `deleteConfirmed(path, passkey, body)` | the route's generated method with `{ confirm: passkeyConfirm(passkey) }`: `client.deleteConfirmed('orgs/' + org, passkey)` → `client.orgs.delete({ org }, { confirm: passkeyConfirm(passkey) })` |
162
353
 
163
354
  ## Development
164
355
 
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The node's routes as a typed client, generated from core's OpenAPI document
3
+ * (`openapi/core-openapi.json`, types in `src/generated/api.ts` by
4
+ * `pnpm gen:api`), run by `openapi-fetch` over this package's runtime:
5
+ *
6
+ * - its `fetch` is {@link transportFetch}: every request goes through a
7
+ * {@link NodeTransport}, so it is sealed to an attested node, carries the
8
+ * transport's credential (refreshed on a `401`), moves on past a
9
+ * `421 WRONG_NODE`, and a route the document marks retry-safe retries a
10
+ * `503` (D70); the two
11
+ * routes a node serves in the clear (`/attestation`, `/health`) go
12
+ * unsealed, without the credential;
13
+ * - the `412 CONFIRM_REQUIRED` step-up and the `428
14
+ * OPERATOR_SIGNATURE_REQUIRED` operator signature are middleware
15
+ * (`./step-up.ts`), for the whole client or one request.
16
+ *
17
+ * A node's refusal is the `error` of the result (`{ status, error, message,
18
+ * details? }`), typed per route; {@link unwrap} throws it as the typed
19
+ * {@link CalimeroError} instead. A transport failure (the node unreachable,
20
+ * an attestation the policy refuses, an envelope past the sealed cap) rejects.
21
+ * Streams (`GET /apps/{app}/events`, `/presence/stream`) are not routes of this
22
+ * client: read them with `transport.events`.
23
+ */
24
+ import { type Client, type Middleware } from 'openapi-fetch';
25
+ import type { paths } from '../generated/api.js';
26
+ import { type CalimeroError } from '../cloud-v2/errors.js';
27
+ import { type NodeTransport } from '../runtime/transport.js';
28
+ import { type ConfirmCallback, type OperatorProofCallback } from './step-up.js';
29
+ /** The typed client of every route of a Calimero node. */
30
+ export type ApiClient = Client<paths, 'application/json'>;
31
+ /** The node's API, path by path (the generated `paths`). */
32
+ export type { paths as ApiPaths } from '../generated/api.js';
33
+ /**
34
+ * The base URL the generated client builds request URLs on. It names no
35
+ * node: {@link transportFetch} sends the path and query to the node the
36
+ * transport uses now.
37
+ */
38
+ export declare const API_BASE_URL = "https://calimero-node.invalid";
39
+ /** What {@link createApiClient} sends through: a {@link NodeTransport}, or anything that answers like its `exchange`. */
40
+ export interface ApiTransport {
41
+ exchange: NodeTransport['exchange'];
42
+ /** `GET` of a route the node serves in the clear; without it those go sealed too. */
43
+ inTheClear?: NodeTransport['inTheClear'];
44
+ }
45
+ /** How {@link createApiClient} answers the node's challenges for every request. */
46
+ export interface ApiClientOptions {
47
+ /**
48
+ * Answers every `412 CONFIRM_REQUIRED` (say, `passkeyConfirm(browserPasskey())`).
49
+ * A request's own `stepUp` middleware answers first.
50
+ */
51
+ confirm?: ConfirmCallback;
52
+ /** Answers every `428 OPERATOR_SIGNATURE_REQUIRED` with the operator key's signature. */
53
+ operatorProof?: OperatorProofCallback;
54
+ }
55
+ /**
56
+ * A `fetch` that sends `openapi-fetch`'s request through `transport`: the
57
+ * path and query after {@link API_BASE_URL}, the body as it was serialised,
58
+ * and the request's signal. Headers other than `content-type` are not sent:
59
+ * the transport sets the credential. A call or a view is retried as D70 says
60
+ * (its confirmed attempt, carrying `confirm`, exactly once).
61
+ */
62
+ export declare function transportFetch(transport: ApiTransport): (request: Request) => Promise<Response>;
63
+ /**
64
+ * Gives a request to a route whose retries require an `idempotencyKey`
65
+ * (`x-calimero-retry-requires`: a call, a method by its path) one when it has
66
+ * none, made before it is first sent, so its D70 retries and its step-up's
67
+ * confirmed retry carry the same key.
68
+ */
69
+ export declare const idempotencyKeys: Middleware;
70
+ /**
71
+ * The typed client of the node's routes, sent through `transport` (a
72
+ * `CalimeroClient`'s is `client.transport`; its session is this client's).
73
+ *
74
+ * ```ts
75
+ * const api = createApiClient(client.transport);
76
+ * const { data, error } = await api.POST('/apps/{app}/intents', {
77
+ * params: { path: { app } },
78
+ * body: { method: 'set', args: { key: 'a', value: 'b' } },
79
+ * middleware: [stepUp(passkeyConfirm(passkey))],
80
+ * });
81
+ * ```
82
+ */
83
+ export declare function createApiClient(transport: ApiTransport, options?: ApiClientOptions): ApiClient;
84
+ /** What every method of {@link ApiClient} answers. */
85
+ export interface ApiResult<T> {
86
+ data?: T;
87
+ error?: unknown;
88
+ response: Response;
89
+ }
90
+ /**
91
+ * The `data` of a result, or its refusal thrown as the typed
92
+ * {@link CalimeroError} ({@link errorFrom}, the `Retry-After` header
93
+ * included). An empty answer is `{}`.
94
+ */
95
+ export declare function unwrap<T>(result: Promise<ApiResult<T>> | ApiResult<T>): Promise<NonNullable<T>>;
96
+ /** A refused result as the typed {@link CalimeroError}. */
97
+ export declare function refusalOf(response: Response, error: unknown): CalimeroError;
98
+ export type { Middleware };
@@ -0,0 +1,143 @@
1
+ /**
2
+ * The node's routes as a typed client, generated from core's OpenAPI document
3
+ * (`openapi/core-openapi.json`, types in `src/generated/api.ts` by
4
+ * `pnpm gen:api`), run by `openapi-fetch` over this package's runtime:
5
+ *
6
+ * - its `fetch` is {@link transportFetch}: every request goes through a
7
+ * {@link NodeTransport}, so it is sealed to an attested node, carries the
8
+ * transport's credential (refreshed on a `401`), moves on past a
9
+ * `421 WRONG_NODE`, and a route the document marks retry-safe retries a
10
+ * `503` (D70); the two
11
+ * routes a node serves in the clear (`/attestation`, `/health`) go
12
+ * unsealed, without the credential;
13
+ * - the `412 CONFIRM_REQUIRED` step-up and the `428
14
+ * OPERATOR_SIGNATURE_REQUIRED` operator signature are middleware
15
+ * (`./step-up.ts`), for the whole client or one request.
16
+ *
17
+ * A node's refusal is the `error` of the result (`{ status, error, message,
18
+ * details? }`), typed per route; {@link unwrap} throws it as the typed
19
+ * {@link CalimeroError} instead. A transport failure (the node unreachable,
20
+ * an attestation the policy refuses, an envelope past the sealed cap) rejects.
21
+ * Streams (`GET /apps/{app}/events`, `/presence/stream`) are not routes of this
22
+ * client: read them with `transport.events`.
23
+ */
24
+ import createClient from 'openapi-fetch';
25
+ import { errorFrom } from '../cloud-v2/errors.js';
26
+ import { newIdempotencyKey } from '../runtime/transport.js';
27
+ import { operatorSignature, stepUp } from './step-up.js';
28
+ import { RETRY_SAFE_ROUTES } from '../generated/methods.js';
29
+ /**
30
+ * The base URL the generated client builds request URLs on. It names no
31
+ * node: {@link transportFetch} sends the path and query to the node the
32
+ * transport uses now.
33
+ */
34
+ export const API_BASE_URL = 'https://calimero-node.invalid';
35
+ /**
36
+ * The routes a node serves outside the sealed channel (the document's
37
+ * `x-calimero-sealed: false`): `GET /attestation` and `GET /health`.
38
+ */
39
+ const IN_THE_CLEAR = new Set(['attestation', 'health']);
40
+ /**
41
+ * The routes a `503` is retried on (D70): those the document marks
42
+ * `x-calimero-retry-safe` (a call, a view, a method by its path), each
43
+ * carrying its idempotency key or reading. As path patterns, without the
44
+ * leading `/`.
45
+ */
46
+ const RETRIED = RETRY_SAFE_ROUTES.map((route) => ({
47
+ method: route.method,
48
+ pattern: new RegExp(`^${route.path.replace(/^\//, '').replace(/\{[^}]+\}/g, '[^/]+')}$`),
49
+ }));
50
+ /** The route templates that must carry an `idempotencyKey` to be retried. */
51
+ const NEEDS_KEY = new Set(RETRY_SAFE_ROUTES.filter((r) => r.requires === 'idempotencyKey').map((r) => `${r.method} ${r.path}`));
52
+ /**
53
+ * A `fetch` that sends `openapi-fetch`'s request through `transport`: the
54
+ * path and query after {@link API_BASE_URL}, the body as it was serialised,
55
+ * and the request's signal. Headers other than `content-type` are not sent:
56
+ * the transport sets the credential. A call or a view is retried as D70 says
57
+ * (its confirmed attempt, carrying `confirm`, exactly once).
58
+ */
59
+ export function transportFetch(transport) {
60
+ return async (request) => {
61
+ if (!request.url.startsWith(`${API_BASE_URL}/`)) {
62
+ throw new Error(`not a route of the generated client: ${request.url}`);
63
+ }
64
+ const url = new URL(request.url);
65
+ const path = url.pathname.replace(/^\/+/, '');
66
+ const query = {};
67
+ for (const [name, value] of url.searchParams)
68
+ (query[name] ?? (query[name] = [])).push(value);
69
+ const method = request.method;
70
+ if (method === 'GET' && IN_THE_CLEAR.has(path) && transport.inTheClear) {
71
+ return transport.inTheClear(path, { query, signal: request.signal });
72
+ }
73
+ const contentType = request.headers.get('content-type') ?? undefined;
74
+ const bytes = method === 'GET' ? undefined : new Uint8Array(await request.arrayBuffer());
75
+ const body = bytes && bytes.length > 0 ? bytes : undefined;
76
+ let retry = false;
77
+ if (RETRIED.some((route) => route.method === method && route.pattern.test(path))) {
78
+ const json = body ? JSON.parse(new TextDecoder().decode(body)) : {};
79
+ retry = json.confirm === undefined ? true : 'once';
80
+ }
81
+ return transport.exchange(method, path, {
82
+ query,
83
+ ...(body ? { bytes: body, contentType: contentType ?? 'application/octet-stream' } : {}),
84
+ retry,
85
+ signal: request.signal,
86
+ });
87
+ };
88
+ }
89
+ /**
90
+ * Gives a request to a route whose retries require an `idempotencyKey`
91
+ * (`x-calimero-retry-requires`: a call, a method by its path) one when it has
92
+ * none, made before it is first sent, so its D70 retries and its step-up's
93
+ * confirmed retry carry the same key.
94
+ */
95
+ export const idempotencyKeys = {
96
+ async onRequest({ request, schemaPath }) {
97
+ if (!NEEDS_KEY.has(`${request.method} ${schemaPath}`))
98
+ return undefined;
99
+ const text = await request.clone().text();
100
+ const body = text ? JSON.parse(text) : {};
101
+ if (body.idempotencyKey !== undefined)
102
+ return undefined;
103
+ return new Request(request, { body: JSON.stringify({ ...body, idempotencyKey: newIdempotencyKey() }) });
104
+ },
105
+ };
106
+ /**
107
+ * The typed client of the node's routes, sent through `transport` (a
108
+ * `CalimeroClient`'s is `client.transport`; its session is this client's).
109
+ *
110
+ * ```ts
111
+ * const api = createApiClient(client.transport);
112
+ * const { data, error } = await api.POST('/apps/{app}/intents', {
113
+ * params: { path: { app } },
114
+ * body: { method: 'set', args: { key: 'a', value: 'b' } },
115
+ * middleware: [stepUp(passkeyConfirm(passkey))],
116
+ * });
117
+ * ```
118
+ */
119
+ export function createApiClient(transport, options = {}) {
120
+ const api = createClient({ baseUrl: API_BASE_URL, fetch: transportFetch(transport) });
121
+ api.use(idempotencyKeys);
122
+ if (options.confirm)
123
+ api.use(stepUp(options.confirm));
124
+ if (options.operatorProof)
125
+ api.use(operatorSignature(options.operatorProof));
126
+ return api;
127
+ }
128
+ /**
129
+ * The `data` of a result, or its refusal thrown as the typed
130
+ * {@link CalimeroError} ({@link errorFrom}, the `Retry-After` header
131
+ * included). An empty answer is `{}`.
132
+ */
133
+ export async function unwrap(result) {
134
+ const { data, error, response } = await result;
135
+ if (!response.ok)
136
+ throw refusalOf(response, error);
137
+ return (data ?? {});
138
+ }
139
+ /** A refused result as the typed {@link CalimeroError}. */
140
+ export function refusalOf(response, error) {
141
+ const body = typeof error === 'string' ? (error ? { message: error } : {}) : error;
142
+ return errorFrom(response.status, body, response.headers.get('retry-after'));
143
+ }
@@ -0,0 +1,10 @@
1
+ export { API_BASE_URL, createApiClient, idempotencyKeys, refusalOf, transportFetch, unwrap, } from './client.js';
2
+ export type { ApiClient, ApiClientOptions, ApiPaths, ApiResult, ApiTransport, Middleware } from './client.js';
3
+ export { operatorSignature, passkeyConfirm, promptFailure, stepUp, userVerificationOf } from './step-up.js';
4
+ export type { ConfirmCallback, ConfirmChallenge, OperatorProof, OperatorProofCallback, OperatorStatement, PasskeyConfirmOptions, } from './step-up.js';
5
+ export { route } from './operation.js';
6
+ export type { ApiAnswer, ApiSchema } from './types.js';
7
+ export type { MethodOptions, RawBody, RouteShape } from './operation.js';
8
+ export { createRoutes } from '../generated/methods.js';
9
+ export type { AppsRoutes, AuthRoutes, ConsentRoutes, DeploymentsRoutes, OpsRoutes, OrgsRoutes, PackagesRoutes, PublicRoutes, Routes, } from '../generated/methods.js';
10
+ export type { components as ApiComponents, operations as ApiOperations } from '../generated/api.js';
@@ -0,0 +1,9 @@
1
+ // The generated route layer: core's OpenAPI document as one method per
2
+ // operation (`createRoutes`, `client.orgs.get({ org })`), over a typed
3
+ // `openapi-fetch` client on the runtime's sealed transport (`createApiClient`,
4
+ // low level), and the middleware that answers the node's step-up (`412`) and
5
+ // operator (`428`) challenges.
6
+ export { API_BASE_URL, createApiClient, idempotencyKeys, refusalOf, transportFetch, unwrap, } from './client.js';
7
+ export { operatorSignature, passkeyConfirm, promptFailure, stepUp, userVerificationOf } from './step-up.js';
8
+ export { route } from './operation.js';
9
+ export { createRoutes } from '../generated/methods.js';
@@ -0,0 +1,59 @@
1
+ /**
2
+ * What every generated method (`src/generated/methods.ts`, by
3
+ * `scripts/gen-methods.mjs`) runs: one flattened argument object split back
4
+ * into the route's path parameters, query and body, sent through the
5
+ * generated `openapi-fetch` client, and its answer unwrapped (a refusal thrown
6
+ * as the typed `CalimeroError`). The route types themselves all come from the
7
+ * generated `operations`; nothing here names a route.
8
+ */
9
+ import type { ApiClient } from './client.js';
10
+ import { type ConfirmCallback, type OperatorProofCallback } from './step-up.js';
11
+ /** What a generated method takes beside its arguments. */
12
+ export interface MethodOptions {
13
+ /**
14
+ * Answers this request's `412 CONFIRM_REQUIRED` (say,
15
+ * `passkeyConfirm(passkey)`), before the client's own `confirm`.
16
+ */
17
+ confirm?: ConfirmCallback;
18
+ /** Answers this request's `428 OPERATOR_SIGNATURE_REQUIRED`, before the client's own `operatorProof`. */
19
+ operatorProof?: OperatorProofCallback;
20
+ /** Aborts the request (and a step-up's prompt, when `confirm` reads it). */
21
+ signal?: AbortSignal;
22
+ }
23
+ /** A raw request body: the bytes as they are, sent with `contentType`. */
24
+ export interface RawBody {
25
+ body: Uint8Array | ArrayBuffer | Blob | string;
26
+ /** The body's media type. Default: the one the route documents. */
27
+ contentType?: string;
28
+ }
29
+ /** How a generated method's arguments map onto its route (written by the generator). */
30
+ export interface RouteShape {
31
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
32
+ path: string;
33
+ /** Names of the path parameters. */
34
+ pathParams: readonly string[];
35
+ /** Names of the query parameters. */
36
+ query: readonly string[];
37
+ /** The query is `args.query` (a query parameter is named like a path parameter). */
38
+ queryWhole?: boolean;
39
+ /**
40
+ * `fields`: the arguments other than the path and query are the JSON body;
41
+ * `whole`: the JSON body is `args.body`; `raw`: `args.body` is sent as it is,
42
+ * with `args.contentType` (or `media`); `none`: no body.
43
+ */
44
+ body: 'fields' | 'whole' | 'raw' | 'none';
45
+ /** Whether the route takes no body at all as well (`fields`: an empty one is left out). */
46
+ optionalBody: boolean;
47
+ /** The raw body's documented media type. */
48
+ media?: string;
49
+ /** How the answer is read. */
50
+ reply: 'json' | 'bytes' | 'text';
51
+ /** The route answers `412 CONFIRM_REQUIRED` first (`x-calimero-step-up`). */
52
+ stepUp?: boolean;
53
+ /** The user verification its step-up asks the passkey for (`x-calimero-user-verification`). */
54
+ userVerification?: 'required' | 'preferred' | 'discouraged';
55
+ /** The route answers `428 OPERATOR_SIGNATURE_REQUIRED` first (`x-calimero-operator`). */
56
+ operator?: boolean;
57
+ }
58
+ /** Send one generated route: split `args`, send it, answer its payload or throw its refusal. */
59
+ export declare function route(api: ApiClient, shape: RouteShape, args: Record<string, unknown> | undefined, options?: MethodOptions): Promise<unknown>;