@calimero-network/mero-js 29.16.0 → 29.17.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 +79 -17
- package/dist/api/client.d.ts +98 -0
- package/dist/api/client.js +143 -0
- package/dist/api/index.d.ts +9 -0
- package/dist/api/index.js +9 -0
- package/dist/api/operation.d.ts +59 -0
- package/dist/api/operation.js +70 -0
- package/dist/api/step-up.d.ts +81 -0
- package/dist/api/step-up.js +137 -0
- package/dist/cloud-v2/client.d.ts +434 -56
- package/dist/cloud-v2/client.js +550 -236
- package/dist/cloud-v2/index.d.ts +1 -1
- package/dist/cloud-v2/index.js +1 -1
- package/dist/generated/api.d.ts +15324 -0
- package/dist/generated/api.js +5 -0
- package/dist/generated/methods.d.ts +1315 -0
- package/dist/generated/methods.js +1298 -0
- package/dist/index.browser.mjs +6 -6
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.cjs +2551 -284
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +1 -0
- package/dist/index.js +6 -1
- package/dist/index.mjs +2551 -284
- package/dist/index.mjs.map +4 -4
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/transport.d.ts +31 -3
- package/dist/runtime/transport.js +74 -60
- package/dist/sealed/release.d.ts +1 -1
- package/package.json +9 -4
package/README.md
CHANGED
|
@@ -97,6 +97,12 @@ Pinned measurements go through `policy.verifyQuote` (`createQuoteVerifier`).
|
|
|
97
97
|
|
|
98
98
|
## The API
|
|
99
99
|
|
|
100
|
+
Every route of the node is a generated method (`client.orgs.get({ org })`,
|
|
101
|
+
[below](#the-runtime-and-the-route-layer)). The methods listed here are the
|
|
102
|
+
hand-written ones, which now call those; the single-route ones are deprecated and
|
|
103
|
+
go once the apps have moved.
|
|
104
|
+
|
|
105
|
+
|
|
100
106
|
- **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
107
|
- **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
108
|
- **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`).
|
|
@@ -108,7 +114,7 @@ Pinned measurements go through `policy.verifyQuote` (`createQuoteVerifier`).
|
|
|
108
114
|
- **Owner decisions** (passkey approval, never from an app's frontend): `upgradeOrg`, `upgradeRun`, `retryUpgradeRun`, `approveRelease`, `approveOutbound`, `bindPublisher`, `upgradePublished`.
|
|
109
115
|
- **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
116
|
- **Operator** (ops token): `opsApps`, `opsOrgs`, `opsServedOrigins` (every custom domain the log holds, by package label), `setReleaseDeadline`, `liftReleaseDeadline`.
|
|
111
|
-
- **Any route**: `get`, `post`, `put`, `delete
|
|
117
|
+
- **Any route**: its generated method (below). The untyped `get`, `post`, `put`, `delete`, `postConfirmed` and `deleteConfirmed` are deprecated.
|
|
112
118
|
|
|
113
119
|
Refusals are typed (`LoginRequired`, `PasskeyUnknownHere`, `WrongNode`, `NotFound`, `ConfirmRequired`, `ConfirmCancelled`, `ConfirmPromptBlocked`,
|
|
114
120
|
`ArgsTooLarge`, `IdempotencyMismatch`, `ReleaseDeadlineError`, `RuntimeTooOld`, `ConsentStale`, `AppError`, `TrapError`,
|
|
@@ -130,9 +136,67 @@ the client for mero-tee's private agent gate (`attestAgent`, `provisionAgent`,
|
|
|
130
136
|
The client is two layers. The **runtime** (`@calimero-network/mero-js/runtime`,
|
|
131
137
|
`src/runtime/`) is everything that is not a route: the node's attestation, the
|
|
132
138
|
sealed channel, the credential and the session's refresh on a `401`, moving on
|
|
133
|
-
`421 WRONG_NODE`, D70 retries and failover,
|
|
134
|
-
|
|
135
|
-
|
|
139
|
+
`421 WRONG_NODE`, D70 retries and failover, error mapping and server-sent
|
|
140
|
+
events. The **route layer** is generated from core's OpenAPI document
|
|
141
|
+
(`openapi/core-openapi.json`, the node's `docs/public/openapi.json`) by
|
|
142
|
+
`pnpm gen:api`: `openapi-typescript` writes the types (`src/generated/api.ts`)
|
|
143
|
+
and `scripts/gen-methods.mjs` one method per operation
|
|
144
|
+
(`src/generated/methods.ts`), grouped by the operation's tag. `CalimeroClient`
|
|
145
|
+
exposes the groups, which share `client.transport`'s session:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { passkeyConfirm } from '@calimero-network/mero-js';
|
|
149
|
+
|
|
150
|
+
const org = await client.orgs.get({ org: orgId }); // the typed payload
|
|
151
|
+
const { result } = await client.apps.call({ app, method: 'set', args: { key: 'a' } });
|
|
152
|
+
const { token } = await client.orgs.inviteCreate( // a step-up (412)
|
|
153
|
+
{ org: orgId, role: 'member' },
|
|
154
|
+
{ confirm: passkeyConfirm(passkey) },
|
|
155
|
+
);
|
|
156
|
+
await client.apps.blobUpload({ app, body: bytes, contentType: 'image/png' });
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
- **Groups**: `client.apps`, `client.auth`, `client.orgs`, `client.packages`,
|
|
160
|
+
`client.deployments`, `client.consent`, `client.ops`, `client.public`.
|
|
161
|
+
- **One argument object**: path parameters, query parameters and body fields
|
|
162
|
+
merged, all typed from the document. The body goes whole under `body` when it is
|
|
163
|
+
raw bytes (with an optional `contentType`) or when its field names would collide.
|
|
164
|
+
A route whose query parameter is named like a path parameter takes its query
|
|
165
|
+
under `query`.
|
|
166
|
+
- **The answer** is the route's typed success payload (a `Blob` for a download).
|
|
167
|
+
A refusal is thrown as the typed `CalimeroError` (`NotFound`, `ConfirmRequired`, ...).
|
|
168
|
+
- **Challenges**: the second argument `{ confirm?, operatorProof?, signal? }`
|
|
169
|
+
answers this call's `412 CONFIRM_REQUIRED` (`passkeyConfirm(passkey)`) or
|
|
170
|
+
`428 OPERATOR_SIGNATURE_REQUIRED` (the operator key's signature over the
|
|
171
|
+
statement). The client's own `new CalimeroClient(options, { confirm, operatorProof })`
|
|
172
|
+
answers every call that gives none.
|
|
173
|
+
- **Retries**: a route the document marks `x-calimero-retry-safe` (a call, a
|
|
174
|
+
view, a method by its path) is sent again on a `503` as D70 says; one whose
|
|
175
|
+
retries require an `idempotencyKey` gets one when it has none, which its retries
|
|
176
|
+
and its confirmed retry share. A `421 WRONG_NODE` moves to the next node.
|
|
177
|
+
- **Step-ups** ask the passkey for the route's own user verification
|
|
178
|
+
(`x-calimero-user-verification`: `preferred` for the sign-up's confirmation,
|
|
179
|
+
`required` elsewhere).
|
|
180
|
+
- **Streams** (`events`, `presenceStream`) stay hand-written on the runtime.
|
|
181
|
+
- `createRoutes(createApiClient(transport, { confirm, operatorProof }))` builds
|
|
182
|
+
the same groups on any `NodeTransport`.
|
|
183
|
+
|
|
184
|
+
`client.api` is the **low-level** escape hatch: the raw `openapi-fetch`
|
|
185
|
+
client the methods run on (`client.api.GET('/orgs/{org}', { params: { path: {
|
|
186
|
+
org } } })` answers `{ data, error, response }`). Its `fetch` is
|
|
187
|
+
`transportFetch(transport)`: the path, query and body go through the transport
|
|
188
|
+
(sealed, with the credential), and the two routes served in the clear
|
|
189
|
+
(`/attestation`, `/health`) go unsealed. `stepUp(...)` and
|
|
190
|
+
`operatorSignature(...)` are its middleware; `unwrap(result)` throws a refusal.
|
|
191
|
+
Apps should not write against it.
|
|
192
|
+
|
|
193
|
+
The **hand-written methods** of `CalimeroClient` (`createOrg`, `call`, ...) are
|
|
194
|
+
now thin calls onto the generated methods, kept, `@deprecated` (each names its
|
|
195
|
+
replacement), until the apps have moved. The ceremonies (`signUp`, `signIn`, `addPasskey`,
|
|
196
|
+
account and organization recovery, `openConsentPage`, ...) stay as flows.
|
|
197
|
+
|
|
198
|
+
The runtime's own surface toward routes is still one interface, for a route
|
|
199
|
+
layer of your own:
|
|
136
200
|
|
|
137
201
|
```ts
|
|
138
202
|
interface Transport {
|
|
@@ -144,21 +208,19 @@ interface Transport {
|
|
|
144
208
|
// userVerification?, retry?: true | 'once' (D70), signal?, promptSignal? }
|
|
145
209
|
```
|
|
146
210
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
```ts
|
|
154
|
-
import { routePath } from '@calimero-network/mero-js/runtime';
|
|
211
|
+
`NodeTransport` implements it, and `exchange(method, path, options)` answers a
|
|
212
|
+
refusal as the node's response instead of throwing it (what the generated
|
|
213
|
+
client sends through). The `/runtime` entry re-exports the package's own bundle,
|
|
214
|
+
so its error classes are the ones `CalimeroClient` throws (`instanceof` holds
|
|
215
|
+
across both imports).
|
|
155
216
|
|
|
156
|
-
|
|
157
|
-
await client.transport.json('DELETE', routePath('orgs/{org}', { org }), { body: {}, passkey });
|
|
158
|
-
```
|
|
217
|
+
### Refreshing the OpenAPI document
|
|
159
218
|
|
|
160
|
-
|
|
161
|
-
|
|
219
|
+
`openapi/core-openapi.json` is vendored from core at the commit `openapi/SOURCE`
|
|
220
|
+
names. `scripts/refresh-openapi.sh [<core ref>]` (`pnpm refresh:openapi`)
|
|
221
|
+
fetches it again, records the commit and regenerates `src/generated/`;
|
|
222
|
+
`pnpm check:api` fails when the generated types or methods are not those of the
|
|
223
|
+
vendored document.
|
|
162
224
|
|
|
163
225
|
## Development
|
|
164
226
|
|
|
@@ -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,9 @@
|
|
|
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 { MethodOptions, RawBody, RouteShape } from './operation.js';
|
|
7
|
+
export { createRoutes } from '../generated/methods.js';
|
|
8
|
+
export type { AppsRoutes, AuthRoutes, ConsentRoutes, DeploymentsRoutes, OpsRoutes, OrgsRoutes, PackagesRoutes, PublicRoutes, Routes, } from '../generated/methods.js';
|
|
9
|
+
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>;
|
|
@@ -0,0 +1,70 @@
|
|
|
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 { unwrap } from './client.js';
|
|
10
|
+
import { operatorSignature, stepUp } from './step-up.js';
|
|
11
|
+
/** Send one generated route: split `args`, send it, answer its payload or throw its refusal. */
|
|
12
|
+
export async function route(api, shape, args, options = {}) {
|
|
13
|
+
const given = args ?? {};
|
|
14
|
+
const path = {};
|
|
15
|
+
const query = {};
|
|
16
|
+
const rest = {};
|
|
17
|
+
for (const [name, value] of Object.entries(given)) {
|
|
18
|
+
if (shape.pathParams.includes(name))
|
|
19
|
+
path[name] = value;
|
|
20
|
+
else if (shape.queryWhole && name === 'query')
|
|
21
|
+
Object.assign(query, value);
|
|
22
|
+
else if (!shape.queryWhole && shape.query.includes(name))
|
|
23
|
+
query[name] = value;
|
|
24
|
+
else
|
|
25
|
+
rest[name] = value;
|
|
26
|
+
}
|
|
27
|
+
for (const name of shape.pathParams) {
|
|
28
|
+
if (path[name] === undefined)
|
|
29
|
+
throw new TypeError(`${shape.method} ${shape.path}: no value for ${name}`);
|
|
30
|
+
}
|
|
31
|
+
const init = { params: { path, query } };
|
|
32
|
+
if (shape.body === 'fields') {
|
|
33
|
+
const empty = Object.values(rest).every((value) => value === undefined);
|
|
34
|
+
if (!(empty && shape.optionalBody))
|
|
35
|
+
init.body = rest;
|
|
36
|
+
}
|
|
37
|
+
else if (shape.body === 'whole') {
|
|
38
|
+
if (rest.body !== undefined || !shape.optionalBody)
|
|
39
|
+
init.body = rest.body;
|
|
40
|
+
}
|
|
41
|
+
else if (shape.body === 'raw') {
|
|
42
|
+
init.body = rest.body;
|
|
43
|
+
init.bodySerializer = (body) => body;
|
|
44
|
+
init.headers = { 'Content-Type': rest.contentType ?? shape.media ?? 'application/octet-stream' };
|
|
45
|
+
}
|
|
46
|
+
if (shape.reply === 'bytes')
|
|
47
|
+
init.parseAs = 'blob';
|
|
48
|
+
else if (shape.reply === 'text')
|
|
49
|
+
init.parseAs = 'text';
|
|
50
|
+
const middleware = [];
|
|
51
|
+
if (options.confirm) {
|
|
52
|
+
const confirm = options.confirm;
|
|
53
|
+
// The route's own user verification, where the node's challenge names none
|
|
54
|
+
// (a sign-up's confirmation takes `preferred`, every other step-up `required`).
|
|
55
|
+
const answer = shape.userVerification
|
|
56
|
+
? (challenge, context) => confirm({ userVerification: shape.userVerification, ...challenge }, context)
|
|
57
|
+
: confirm;
|
|
58
|
+
middleware.push(stepUp(answer));
|
|
59
|
+
}
|
|
60
|
+
if (options.operatorProof)
|
|
61
|
+
middleware.push(operatorSignature(options.operatorProof));
|
|
62
|
+
if (middleware.length)
|
|
63
|
+
init.middleware = middleware;
|
|
64
|
+
if (options.signal)
|
|
65
|
+
init.signal = options.signal;
|
|
66
|
+
// The shape was written from the same document as `api`'s types; the
|
|
67
|
+
// generated method's own signature carries them.
|
|
68
|
+
const send = api.request;
|
|
69
|
+
return unwrap(send(shape.method.toLowerCase(), shape.path, init));
|
|
70
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The answers to the two challenges a node puts before a request it will only
|
|
3
|
+
* take with a proof: the `412 CONFIRM_REQUIRED` passkey step-up and the
|
|
4
|
+
* `428 OPERATOR_SIGNATURE_REQUIRED` operator signature (core
|
|
5
|
+
* `crates/node/src/api/openapi.rs`, components `ConfirmRequired`, `Confirm`,
|
|
6
|
+
* `OperatorSignatureRequired`, `OperatorProof`).
|
|
7
|
+
*
|
|
8
|
+
* Each is an `openapi-fetch` middleware: it keeps a copy of the request it
|
|
9
|
+
* sees go out, and when the node answers the challenge it asks a callback the
|
|
10
|
+
* caller supplied for the proof, then sends the same JSON body again with the
|
|
11
|
+
* proof beside it (`confirm`, `operatorProof`) and answers that response in
|
|
12
|
+
* place of the challenge. Without a callback (or when the callback is not
|
|
13
|
+
* given for that request) the challenge reaches the caller as the
|
|
14
|
+
* `{ error }` of the response.
|
|
15
|
+
*/
|
|
16
|
+
import type { Middleware } from 'openapi-fetch';
|
|
17
|
+
import type { components } from '../generated/api.js';
|
|
18
|
+
import { type AssertionJSON, type PasskeyProvider, type PasskeyUserVerification } from '../cloud-v2/passkey.js';
|
|
19
|
+
/**
|
|
20
|
+
* `details` of a `412 CONFIRM_REQUIRED`: the WebAuthn challenge to sign.
|
|
21
|
+
* `userVerification` is read when a node names it (core does not today).
|
|
22
|
+
*/
|
|
23
|
+
export type ConfirmChallenge = components['schemas']['ConfirmRequired'] & {
|
|
24
|
+
userVerification?: unknown;
|
|
25
|
+
};
|
|
26
|
+
/** `details` of a `428 OPERATOR_SIGNATURE_REQUIRED`: the statement and its exact bytes (`message`, base64). */
|
|
27
|
+
export type OperatorStatement = components['schemas']['OperatorSignatureRequired'];
|
|
28
|
+
/** The operator key's proof the retry carries: its Ed25519 signature (hex) over `message`, with the statement's nonce. */
|
|
29
|
+
export type OperatorProof = components['schemas']['OperatorProof'];
|
|
30
|
+
/** What a confirmation answers a `412` with: an assertion over the challenge. */
|
|
31
|
+
export type ConfirmCallback = (challenge: ConfirmChallenge, context: {
|
|
32
|
+
request: Request;
|
|
33
|
+
}) => Promise<AssertionJSON>;
|
|
34
|
+
/** What a `428` is answered with: the operator key's signature over the statement. */
|
|
35
|
+
export type OperatorProofCallback = (statement: OperatorStatement, context: {
|
|
36
|
+
request: Request;
|
|
37
|
+
}) => Promise<OperatorProof>;
|
|
38
|
+
/**
|
|
39
|
+
* The user verification a confirmation asks the passkey for: what the node's
|
|
40
|
+
* `412` details name, if it names one WebAuthn knows, else `fallback` (the
|
|
41
|
+
* flow's own requirement: `required` for a step-up, which the node takes only
|
|
42
|
+
* with the user verified; `preferred` for the sign-up confirmation, which it
|
|
43
|
+
* takes with the user present).
|
|
44
|
+
*/
|
|
45
|
+
export declare function userVerificationOf(named: unknown, fallback: PasskeyUserVerification): PasskeyUserVerification;
|
|
46
|
+
/**
|
|
47
|
+
* What a failed confirmation prompt means to the caller. The browser or a
|
|
48
|
+
* password manager refusing to show the prompt (the page not focused because
|
|
49
|
+
* an extension's popup still holds focus, or another prompt still open) is
|
|
50
|
+
* {@link ConfirmPromptBlocked}; the user dismissing it (`NotAllowedError`, or
|
|
51
|
+
* `AbortError` when it was aborted) is {@link ConfirmCancelled}; anything
|
|
52
|
+
* else is a real failure, passed through.
|
|
53
|
+
*/
|
|
54
|
+
export declare function promptFailure(error: unknown): unknown;
|
|
55
|
+
/** How {@link passkeyConfirm} prompts. */
|
|
56
|
+
export interface PasskeyConfirmOptions {
|
|
57
|
+
/** The user verification asked for when the node names none. Default `required` (a step-up). */
|
|
58
|
+
userVerification?: PasskeyUserVerification;
|
|
59
|
+
/** Aborts the passkey prompt. */
|
|
60
|
+
signal?: AbortSignal;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* `passkey`'s assertion over a `412` challenge: the {@link ConfirmCallback}
|
|
64
|
+
* of a passkey. A prompt the user dismissed rejects with
|
|
65
|
+
* {@link ConfirmCancelled}, one the browser would not show with
|
|
66
|
+
* {@link ConfirmPromptBlocked}.
|
|
67
|
+
*/
|
|
68
|
+
export declare function passkeyConfirm(passkey: PasskeyProvider, options?: PasskeyConfirmOptions): ConfirmCallback;
|
|
69
|
+
/**
|
|
70
|
+
* The `412 CONFIRM_REQUIRED` step-up: `confirm` signs the node's challenge and
|
|
71
|
+
* the same body goes again with `confirm: { challengeId, assertion }`. Add it
|
|
72
|
+
* to a client (`api.use(stepUp(...))`) or to one request (`{ middleware:
|
|
73
|
+
* [stepUp(passkeyConfirm(passkey))] }`).
|
|
74
|
+
*/
|
|
75
|
+
export declare function stepUp(confirm: ConfirmCallback): Middleware;
|
|
76
|
+
/**
|
|
77
|
+
* The `428 OPERATOR_SIGNATURE_REQUIRED` operator signature: `sign` signs the
|
|
78
|
+
* statement's `message` with the operator key and the same body goes again
|
|
79
|
+
* with `operatorProof: { nonce, signature }`.
|
|
80
|
+
*/
|
|
81
|
+
export declare function operatorSignature(sign: OperatorProofCallback): Middleware;
|