plenipo 0.4.1 → 0.5.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 +17 -11
- package/dist/http/errors.d.ts +2 -2
- package/dist/http/errors.js +7 -2
- package/dist/http/gateway.d.ts +36 -4
- package/dist/http/gateway.js +185 -7
- package/dist/http/status-service.d.ts +6 -1
- package/dist/http/status-service.js +2 -2
- package/dist/idempotency.d.ts +128 -0
- package/dist/idempotency.js +227 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/invocation.d.ts +5 -0
- package/dist/invocation.js +9 -0
- package/dist/mcp.d.ts +15 -0
- package/dist/mcp.js +78 -6
- package/dist/root.d.ts +3 -0
- package/dist/root.js +8 -1
- package/dist/scope.js +14 -0
- package/dist/status.d.ts +23 -4
- package/dist/status.js +34 -10
- package/dist/stores/index.d.ts +2 -2
- package/dist/stores/index.js +2 -2
- package/dist/stores/postgres.d.ts +28 -1
- package/dist/stores/postgres.js +143 -2
- package/dist/stores/redis.d.ts +25 -0
- package/dist/stores/redis.js +181 -0
- package/dist/types.d.ts +26 -0
- package/dist/verify.d.ts +14 -0
- package/dist/verify.js +110 -21
- package/package.json +1 -1
- package/src/stores/schema.sql +22 -2
package/README.md
CHANGED
|
@@ -13,11 +13,11 @@ Plenipo gives AI agents the same thing, with one difference: the powers are neve
|
|
|
13
13
|
Every mandate has a scope, limits and an expiry, every sub-delegation can only narrow it,
|
|
14
14
|
and the person can revoke it at any time.
|
|
15
15
|
|
|
16
|
-
> Status: 0.
|
|
17
|
-
> the examples and the sandbox are test doubles. The code went through
|
|
18
|
-
>
|
|
19
|
-
> has not yet been audited by an external security firm. Do not use it
|
|
20
|
-
> data yet.
|
|
16
|
+
> Status: 0.5, experimental. The cryptography is real; wallets, PID providers and banks in
|
|
17
|
+
> the examples and the sandbox are test doubles. The code went through security reviews by independent
|
|
18
|
+
> AI review agents (two rounds for 0.3, one for 0.5), and their findings are fixed (see
|
|
19
|
+
> [CHANGELOG.md](CHANGELOG.md)); it has not yet been audited by an external security firm. Do not use it
|
|
20
|
+
> to protect real money or real data yet.
|
|
21
21
|
|
|
22
22
|
## Why Plenipo
|
|
23
23
|
|
|
@@ -59,7 +59,7 @@ a mandate, and the person can revoke it at any time.
|
|
|
59
59
|
path of authority and only the PID claims the person chose to disclose.
|
|
60
60
|
|
|
61
61
|
The wire formats and verification rules are specified in [docs/spec.md](docs/spec.md), with
|
|
62
|
-
[test vectors](test-vectors/plenipo-0.
|
|
62
|
+
[test vectors](test-vectors/plenipo-0.2.json) for other implementations. The reasons behind them are
|
|
63
63
|
in [docs/design.md](docs/design.md).
|
|
64
64
|
|
|
65
65
|
## Install
|
|
@@ -164,7 +164,8 @@ const bookTrain = guardTool<{ route: string; price_cents: number }>(handler, {
|
|
|
164
164
|
| Experimental: Delegate SD-JWT links, TS12 e-mandate roots, legal persons and roles | `plenipo/experimental` | [delegation](docs/delegation.md), [root](docs/root.md) |
|
|
165
165
|
| Trust: x5c chains, EU Lists of Trusted Entities (ETSI TS 119 602), CRL and OCSP | `plenipo` | [trust](docs/trust.md) |
|
|
166
166
|
| Keys in a KMS or HSM (`ExternalSigner`) | `plenipo` | this README |
|
|
167
|
-
| Shared stores on Postgres and Redis: ledger, nonces, sessions, revocation | `plenipo` | [stores](docs/stores.md) |
|
|
167
|
+
| Shared stores on Postgres and Redis: ledger, nonces, idempotency keys, sessions, revocation | `plenipo` | [stores](docs/stores.md) |
|
|
168
|
+
| Idempotent retries: one signed key per intention, at most one attempt runs | `plenipo` | [spec](docs/spec.md), [integration](docs/integration.md) |
|
|
168
169
|
| Bank integration: HTTP gateway, problem+json errors, status list service, audit log, OPA and Cedar export | `plenipo` | [integration](docs/integration.md) |
|
|
169
170
|
| MCP guard | `plenipo/mcp` | [design](docs/design.md) |
|
|
170
171
|
| Test PID provider, wallet and CA (development only) | `plenipo/testing` | [examples](examples/README.md) |
|
|
@@ -187,9 +188,11 @@ See [ROADMAP.md](ROADMAP.md). Changes by version are in [CHANGELOG.md](CHANGELOG
|
|
|
187
188
|
|
|
188
189
|
## Limits
|
|
189
190
|
|
|
190
|
-
-
|
|
191
|
-
|
|
192
|
-
|
|
191
|
+
- One third-party wallet so far: walt.id Wallet API 2, a server-side wallet, approved a
|
|
192
|
+
`plenipo_mandate` and a TS12 e-mandate bound to the PID, with a test PID from the sandbox, and the
|
|
193
|
+
sandbox bank enforced them ([docs/interop.md](docs/interop.md)). No phone wallet yet: the EUDI
|
|
194
|
+
reference wallet core declares accepted types since release 0.31.0; IT-Wallet does not accept
|
|
195
|
+
custom types.
|
|
193
196
|
- With TS12, the e-mandate is approved with a bank's SCA attestation, not the PID. Tying that
|
|
194
197
|
attestation to the PID holder needs the same holder key or identity claims the bank includes;
|
|
195
198
|
see [docs/root.md](docs/root.md).
|
|
@@ -199,7 +202,10 @@ See [ROADMAP.md](ROADMAP.md). Changes by version are in [CHANGELOG.md](CHANGELOG
|
|
|
199
202
|
(the EU LOTL and national TSLs) are refused.
|
|
200
203
|
- Delegate SD-JWT follows individual draft -00, which expired on 23 October 2026 without a
|
|
201
204
|
successor; it is experimental and off by default.
|
|
202
|
-
- Status lists are cached up to a bounded age, which is the revocation latency verifiers accept
|
|
205
|
+
- Status lists are cached up to a bounded age, which is the revocation latency verifiers accept
|
|
206
|
+
(60 s by default; calls that move money can require a fresher list with `maxStatusAgeSeconds`).
|
|
207
|
+
- An idempotency key whose first attempt has an unknown outcome blocks retries until the service
|
|
208
|
+
reconciles it; the library lists such keys but does not reconcile them with a core banking system.
|
|
203
209
|
|
|
204
210
|
## Contributing and security
|
|
205
211
|
|
package/dist/http/errors.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export declare const PROBLEM_CONTENT_TYPE = "application/problem+json";
|
|
|
11
11
|
/**
|
|
12
12
|
* Broad class of a failure. `authentication`: the presented chain or invocation is not valid credentials.
|
|
13
13
|
* `authorization`: valid credentials that do not cover this request. `request`: the HTTP request itself is
|
|
14
|
-
* unusable. `conflict`: replay. `infrastructure`: a dependency could not be reached, retry may succeed.
|
|
14
|
+
* unusable. `conflict`: replay, or another attempt with the same idempotency key. `infrastructure`: a dependency could not be reached, retry may succeed.
|
|
15
15
|
* `configuration`: the service is misconfigured; the caller cannot fix it.
|
|
16
16
|
*/
|
|
17
17
|
export type ProblemKind = 'authentication' | 'authorization' | 'request' | 'conflict' | 'infrastructure' | 'configuration';
|
|
@@ -81,6 +81,6 @@ export interface ProblemResponseOptions {
|
|
|
81
81
|
}
|
|
82
82
|
/**
|
|
83
83
|
* Builds the HTTP response for a problem. 401 responses carry a `WWW-Authenticate: Plenipo` challenge, as
|
|
84
|
-
* RFC 9110 requires; 503 responses carry `Retry-After`. Problems are never cached.
|
|
84
|
+
* RFC 9110 requires; 503 responses and `idempotency_in_progress` carry `Retry-After`. Problems are never cached.
|
|
85
85
|
*/
|
|
86
86
|
export declare function problemResponse(p: ProblemDetails, opts?: ProblemResponseOptions): Response;
|
package/dist/http/errors.js
CHANGED
|
@@ -38,6 +38,10 @@ export const DENY_PROBLEMS = Object.freeze({
|
|
|
38
38
|
ATTESTATION_REVOKED: spec(401, 'attestation_revoked', 'An attestation is revoked or suspended', 'authentication'),
|
|
39
39
|
ROLE_EXCEEDED: spec(403, 'role_exceeded', 'The mandate exceeds the representative role', 'authorization'),
|
|
40
40
|
STATUS_UNAVAILABLE: spec(503, 'status_unavailable', 'A status list could not be checked', 'infrastructure'),
|
|
41
|
+
IDEMPOTENCY_CONFLICT: spec(422, 'idempotency_conflict', 'The idempotency key was used for a different request', 'request'),
|
|
42
|
+
IDEMPOTENCY_IN_PROGRESS: spec(409, 'idempotency_in_progress', 'An attempt with this idempotency key is still running', 'conflict'),
|
|
43
|
+
IDEMPOTENCY_UNRESOLVED: spec(409, 'idempotency_unresolved', 'The outcome of an earlier attempt with this idempotency key is not known yet', 'conflict'),
|
|
44
|
+
ALREADY_EXECUTED: spec(409, 'already_executed', 'An earlier attempt with this idempotency key already executed', 'conflict'),
|
|
41
45
|
INTERNAL: spec(500, 'internal', 'The request could not be processed', 'infrastructure'),
|
|
42
46
|
});
|
|
43
47
|
/** Problems raised by the HTTP layer, before or after `verifyAuthorization`. */
|
|
@@ -89,7 +93,7 @@ export function problemForDecision(d) {
|
|
|
89
93
|
}
|
|
90
94
|
/**
|
|
91
95
|
* Builds the HTTP response for a problem. 401 responses carry a `WWW-Authenticate: Plenipo` challenge, as
|
|
92
|
-
* RFC 9110 requires; 503 responses carry `Retry-After`. Problems are never cached.
|
|
96
|
+
* RFC 9110 requires; 503 responses and `idempotency_in_progress` carry `Retry-After`. Problems are never cached.
|
|
93
97
|
*/
|
|
94
98
|
export function problemResponse(p, opts = {}) {
|
|
95
99
|
const headers = new Headers({
|
|
@@ -102,7 +106,8 @@ export function problemResponse(p, opts = {}) {
|
|
|
102
106
|
const realm = opts.realm && /^[\x20-\x7e]*$/.test(opts.realm) && !/["\\]/.test(opts.realm) ? `realm="${opts.realm}", ` : '';
|
|
103
107
|
headers.set('www-authenticate', `Plenipo ${realm}error="${p.code}"`);
|
|
104
108
|
}
|
|
105
|
-
|
|
109
|
+
// A running attempt usually ends within seconds: tell the agent when to ask again.
|
|
110
|
+
if (p.status === 503 || p.code === 'idempotency_in_progress')
|
|
106
111
|
headers.set('retry-after', String(opts.retryAfterSeconds ?? 5));
|
|
107
112
|
return new Response(JSON.stringify(p), { status: p.status, headers });
|
|
108
113
|
}
|
package/dist/http/gateway.d.ts
CHANGED
|
@@ -14,6 +14,11 @@ export type DenyDecision = Extract<Decision, {
|
|
|
14
14
|
* It overrides the status-code rule and is removed before the response reaches the client.
|
|
15
15
|
*/
|
|
16
16
|
export declare const OUTCOME_HEADER = "plenipo-outcome";
|
|
17
|
+
/**
|
|
18
|
+
* Response header set to `true` on the stored response of an earlier attempt with the same idempotency key,
|
|
19
|
+
* returned instead of calling the API again.
|
|
20
|
+
*/
|
|
21
|
+
export declare const REPLAY_HEADER = "plenipo-replay";
|
|
17
22
|
/** What a route mapping function sees. The body has already been read, within the size limit. */
|
|
18
23
|
export interface RouteContext {
|
|
19
24
|
request: Request;
|
|
@@ -63,6 +68,12 @@ export interface GatewayRoute {
|
|
|
63
68
|
* when the action, counterparty and amount fully determine the operation.
|
|
64
69
|
*/
|
|
65
70
|
args?: Extractor<unknown> | null;
|
|
71
|
+
/**
|
|
72
|
+
* Maximum age of a cached status list for requests on this route, in seconds; overrides
|
|
73
|
+
* `verify.maxStatusAgeSeconds`. Set it low on routes that move money, so a revoked mandate stops there
|
|
74
|
+
* within this bound whatever the cache lifetime; `0` checks the list on every request.
|
|
75
|
+
*/
|
|
76
|
+
maxStatusAgeSeconds?: number;
|
|
66
77
|
}
|
|
67
78
|
export interface GatewayRequestInfo {
|
|
68
79
|
method: string;
|
|
@@ -119,6 +130,14 @@ export interface GatewayOptions extends HeaderLimits, ProblemResponseOptions {
|
|
|
119
130
|
policy?: PolicyHook;
|
|
120
131
|
/** Forward the Plenipo headers to the downstream handler. Default false: they carry PID data. */
|
|
121
132
|
forwardAuthorizationHeaders?: boolean;
|
|
133
|
+
/**
|
|
134
|
+
* Largest response kept for idempotent replays (`verify.idempotency`), in bytes of body. Default 65536,
|
|
135
|
+
* at most `MAX_REPLAY_BODY_BYTES` (what a store accepts once encoded); `0` keeps none. Only requests that
|
|
136
|
+
* carry an idempotency key are kept. A response that is larger, or whose body does not arrive within a
|
|
137
|
+
* second, is passed through untouched and not kept: a retry then gets `already_executed` without it.
|
|
138
|
+
* Kept responses live in the idempotency store with whatever personal data they carry.
|
|
139
|
+
*/
|
|
140
|
+
maxReplayBytes?: number;
|
|
122
141
|
}
|
|
123
142
|
/**
|
|
124
143
|
* How an allowed request ended. `status` applies the status rule (2xx commit, 4xx release by default,
|
|
@@ -131,6 +150,17 @@ export type SettleInput = {
|
|
|
131
150
|
} | {
|
|
132
151
|
outcome: SettlementOutcome;
|
|
133
152
|
};
|
|
153
|
+
/** A response to keep for idempotent replays, as given to `settle` in authorize mode. */
|
|
154
|
+
export interface ReplayResponse {
|
|
155
|
+
status: number;
|
|
156
|
+
contentType?: string;
|
|
157
|
+
body: Uint8Array | string;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Largest body `maxReplayBytes` may allow: a stored response is base64 inside JSON, and a store accepts
|
|
161
|
+
* `MAX_STORED_RESULT_BYTES` at most.
|
|
162
|
+
*/
|
|
163
|
+
export declare const MAX_REPLAY_BODY_BYTES: number;
|
|
134
164
|
export type AuthorizeResult = {
|
|
135
165
|
kind: 'deny';
|
|
136
166
|
response: Response;
|
|
@@ -151,11 +181,13 @@ export type AuthorizeResult = {
|
|
|
151
181
|
*/
|
|
152
182
|
request: Request;
|
|
153
183
|
/**
|
|
154
|
-
* Settles the reservation. `commit` and `release` are final; later calls are
|
|
155
|
-
* that the outcome is unknown and leaves
|
|
156
|
-
* still applies. A reservation never settled stays pending and counts against the
|
|
184
|
+
* Settles the reservation and the idempotency key. `commit` and `release` are final; later calls are
|
|
185
|
+
* ignored. `pending` records that the outcome is unknown and leaves both to reconciliation; a later
|
|
186
|
+
* commit or release still applies. A reservation never settled stays pending and counts against the
|
|
187
|
+
* limits, and its key blocks retries until reconciled. With `replay`, a committed request that carries
|
|
188
|
+
* an idempotency key keeps that response for replays (body within `maxReplayBytes`).
|
|
157
189
|
*/
|
|
158
|
-
settle(input: SettleInput): Promise<void>;
|
|
190
|
+
settle(input: SettleInput, replay?: ReplayResponse): Promise<void>;
|
|
159
191
|
};
|
|
160
192
|
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
161
193
|
/**
|
package/dist/http/gateway.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEFAULT_MAX_REPLAY_BYTES, MAX_STORED_RESULT_BYTES } from '../idempotency.js';
|
|
1
2
|
import { verifyAuthorization } from '../verify.js';
|
|
2
3
|
import { GATEWAY_PROBLEMS, DENY_PROBLEMS, problemFromSpec, problemResponse, problemSpecForDecision, } from './errors.js';
|
|
3
4
|
import { CHAIN_HEADER, INVOCATION_HEADER, parseAuthorizationHeaders } from './transport.js';
|
|
@@ -7,6 +8,16 @@ import { pathProblem } from './target.js';
|
|
|
7
8
|
* It overrides the status-code rule and is removed before the response reaches the client.
|
|
8
9
|
*/
|
|
9
10
|
export const OUTCOME_HEADER = 'plenipo-outcome';
|
|
11
|
+
/**
|
|
12
|
+
* Response header set to `true` on the stored response of an earlier attempt with the same idempotency key,
|
|
13
|
+
* returned instead of calling the API again.
|
|
14
|
+
*/
|
|
15
|
+
export const REPLAY_HEADER = 'plenipo-replay';
|
|
16
|
+
/**
|
|
17
|
+
* Largest body `maxReplayBytes` may allow: a stored response is base64 inside JSON, and a store accepts
|
|
18
|
+
* `MAX_STORED_RESULT_BYTES` at most.
|
|
19
|
+
*/
|
|
20
|
+
export const MAX_REPLAY_BODY_BYTES = Math.floor(((MAX_STORED_RESULT_BYTES - 1024) * 3) / 4);
|
|
10
21
|
export const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
|
|
11
22
|
const METHOD_RE = /^[A-Z]+$/;
|
|
12
23
|
const ACTION_RE = /^[a-z0-9_-]+(\.[a-z0-9_-]+)*$/;
|
|
@@ -37,6 +48,9 @@ function compileRoute(route) {
|
|
|
37
48
|
}
|
|
38
49
|
if (route.args !== undefined && route.args !== null && typeof route.args !== 'function')
|
|
39
50
|
throw new Error('route args must be a function or null');
|
|
51
|
+
const age = route.maxStatusAgeSeconds;
|
|
52
|
+
if (age !== undefined && (typeof age !== 'number' || !Number.isFinite(age) || age < 0))
|
|
53
|
+
throw new Error('route maxStatusAgeSeconds must be a non-negative number');
|
|
40
54
|
const raw = route.path.length > 1 && route.path.endsWith('/') ? route.path.slice(0, -1) : route.path;
|
|
41
55
|
const segments = raw
|
|
42
56
|
.split('/')
|
|
@@ -335,6 +349,111 @@ export function outcomeFromHeader(value) {
|
|
|
335
349
|
return undefined;
|
|
336
350
|
}
|
|
337
351
|
}
|
|
352
|
+
/**
|
|
353
|
+
* Reads the body of a response to keep it for replays, up to `max` bytes and one second. No tee: the body is
|
|
354
|
+
* read once, and the response handed back to the client is rebuilt from the bytes read so far followed by the
|
|
355
|
+
* rest of the stream, so a large or never-ending body reaches the client as it would have without capture.
|
|
356
|
+
*/
|
|
357
|
+
async function captureResponse(response, max) {
|
|
358
|
+
const contentType = response.headers.get('content-type') ?? undefined;
|
|
359
|
+
const replayOf = (body) => ({ status: response.status, ...(contentType ? { contentType } : {}), body });
|
|
360
|
+
if (!response.body)
|
|
361
|
+
return { response, replay: replayOf(new Uint8Array(0)) };
|
|
362
|
+
if (Number(response.headers.get('content-length') ?? '0') > max)
|
|
363
|
+
return { response };
|
|
364
|
+
// A body someone already read or holds a reader on cannot be captured: pass the response on untouched,
|
|
365
|
+
// and the attempt is still settled (executed, without a stored response).
|
|
366
|
+
if (response.bodyUsed || response.body.locked)
|
|
367
|
+
return { response };
|
|
368
|
+
let reader;
|
|
369
|
+
try {
|
|
370
|
+
reader = response.body.getReader();
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
return { response };
|
|
374
|
+
}
|
|
375
|
+
const chunks = [];
|
|
376
|
+
let size = 0;
|
|
377
|
+
let pending;
|
|
378
|
+
let timer;
|
|
379
|
+
const timeout = new Promise((r) => {
|
|
380
|
+
timer = setTimeout(() => r('timeout'), 1000);
|
|
381
|
+
});
|
|
382
|
+
const rebuild = (complete) => {
|
|
383
|
+
const prefix = chunks.slice();
|
|
384
|
+
const stream = new ReadableStream({
|
|
385
|
+
start(c) {
|
|
386
|
+
for (const chunk of prefix)
|
|
387
|
+
c.enqueue(chunk);
|
|
388
|
+
if (complete)
|
|
389
|
+
c.close();
|
|
390
|
+
},
|
|
391
|
+
async pull(c) {
|
|
392
|
+
// A read started during capture and still pending comes first, or its bytes would be lost.
|
|
393
|
+
const next = await (pending ?? reader.read());
|
|
394
|
+
pending = undefined;
|
|
395
|
+
if (next.done)
|
|
396
|
+
c.close();
|
|
397
|
+
else
|
|
398
|
+
c.enqueue(next.value);
|
|
399
|
+
},
|
|
400
|
+
cancel(reason) {
|
|
401
|
+
return reader.cancel(reason);
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
return new Response(stream, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
405
|
+
};
|
|
406
|
+
try {
|
|
407
|
+
for (;;) {
|
|
408
|
+
pending = reader.read();
|
|
409
|
+
const next = await Promise.race([pending, timeout]);
|
|
410
|
+
if (next === 'timeout')
|
|
411
|
+
return { response: rebuild(false) };
|
|
412
|
+
pending = undefined;
|
|
413
|
+
if (next.done) {
|
|
414
|
+
const body = new Uint8Array(size);
|
|
415
|
+
let off = 0;
|
|
416
|
+
for (const c of chunks) {
|
|
417
|
+
body.set(c, off);
|
|
418
|
+
off += c.byteLength;
|
|
419
|
+
}
|
|
420
|
+
return { response: rebuild(true), replay: replayOf(body) };
|
|
421
|
+
}
|
|
422
|
+
chunks.push(next.value);
|
|
423
|
+
size += next.value.byteLength;
|
|
424
|
+
if (size > max)
|
|
425
|
+
return { response: rebuild(false) };
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
// The body failed while being read: hand the client what arrived, then the same failure.
|
|
430
|
+
pending = Promise.reject(new Error('the response body could not be read'));
|
|
431
|
+
pending.catch(() => undefined);
|
|
432
|
+
return { response: rebuild(false) };
|
|
433
|
+
}
|
|
434
|
+
finally {
|
|
435
|
+
clearTimeout(timer);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
/** The stored response of an earlier attempt, or undefined when none was kept or it cannot be read. */
|
|
439
|
+
function replayResponse(result) {
|
|
440
|
+
if (result === undefined)
|
|
441
|
+
return undefined;
|
|
442
|
+
try {
|
|
443
|
+
const r = JSON.parse(result);
|
|
444
|
+
if (r?.v !== 1 || !Number.isInteger(r.status) || r.status < 200 || r.status > 599 || typeof r.body !== 'string')
|
|
445
|
+
return undefined;
|
|
446
|
+
const headers = new Headers({ 'cache-control': 'no-store', [REPLAY_HEADER]: 'true' });
|
|
447
|
+
if (typeof r.content_type === 'string' && /^[\x20-\x7e]+$/.test(r.content_type))
|
|
448
|
+
headers.set('content-type', r.content_type);
|
|
449
|
+
const body = Buffer.from(r.body, 'base64');
|
|
450
|
+
return new Response(r.status === 204 || r.status === 205 || r.status === 304 ? null : body, { status: r.status, headers });
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
return undefined;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
const ATTEMPT_OUTCOME = { commit: 'executed', release: 'not_executed', pending: 'unknown' };
|
|
338
457
|
export function createGateway(opts) {
|
|
339
458
|
if (!opts?.verify)
|
|
340
459
|
throw new Error('gateway needs verify options');
|
|
@@ -345,6 +464,11 @@ export function createGateway(opts) {
|
|
|
345
464
|
const routes = opts.routes.map(compileRoute);
|
|
346
465
|
const maxBody = opts.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
347
466
|
const ledger = opts.verify.ledger;
|
|
467
|
+
const idempotency = opts.verify.idempotency;
|
|
468
|
+
const maxReplay = opts.maxReplayBytes ?? DEFAULT_MAX_REPLAY_BYTES;
|
|
469
|
+
if (!Number.isSafeInteger(maxReplay) || maxReplay < 0 || maxReplay > MAX_REPLAY_BODY_BYTES) {
|
|
470
|
+
throw new Error(`maxReplayBytes must be an integer from 0 to ${MAX_REPLAY_BODY_BYTES}, what a store accepts once encoded`);
|
|
471
|
+
}
|
|
348
472
|
const safe = (fn) => {
|
|
349
473
|
try {
|
|
350
474
|
fn();
|
|
@@ -384,6 +508,36 @@ export function createGateway(opts) {
|
|
|
384
508
|
emit({ phase: 'decision', request: info, decision: audit.decision, problem });
|
|
385
509
|
return { kind: 'deny', response: problemResponse(problem, opts), problem, decision: audit.decision };
|
|
386
510
|
}
|
|
511
|
+
/** Ends the attempt holding the idempotency key. A store that fails leaves the key blocked: safe side. */
|
|
512
|
+
async function finishAttempt(decision, outcome, result) {
|
|
513
|
+
if (!decision.idempotency || !idempotency)
|
|
514
|
+
return;
|
|
515
|
+
const { key, attempt } = decision.idempotency;
|
|
516
|
+
try {
|
|
517
|
+
await idempotency.finish(key, attempt, outcome, result);
|
|
518
|
+
}
|
|
519
|
+
catch (e) {
|
|
520
|
+
reportError(e, 'idempotency');
|
|
521
|
+
// A store that refuses the response must still learn that the request ran.
|
|
522
|
+
if (result !== undefined)
|
|
523
|
+
await idempotency.finish(key, attempt, outcome).catch((e2) => reportError(e2, 'idempotency'));
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
/** The stored form of a response to keep, or undefined when it is too large or not a usable status. */
|
|
527
|
+
function storedReplay(replay) {
|
|
528
|
+
if (!replay || maxReplay <= 0)
|
|
529
|
+
return undefined;
|
|
530
|
+
const body = typeof replay.body === 'string' ? new TextEncoder().encode(replay.body) : replay.body;
|
|
531
|
+
if (!(body instanceof Uint8Array) || body.byteLength > maxReplay || !Number.isInteger(replay.status))
|
|
532
|
+
return undefined;
|
|
533
|
+
const stored = {
|
|
534
|
+
v: 1,
|
|
535
|
+
status: replay.status,
|
|
536
|
+
...(typeof replay.contentType === 'string' ? { content_type: replay.contentType } : {}),
|
|
537
|
+
body: Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('base64'),
|
|
538
|
+
};
|
|
539
|
+
return JSON.stringify(stored);
|
|
540
|
+
}
|
|
387
541
|
async function settleReservation(reservation, outcome) {
|
|
388
542
|
if (!reservation || !ledger)
|
|
389
543
|
return;
|
|
@@ -448,7 +602,11 @@ export function createGateway(opts) {
|
|
|
448
602
|
}
|
|
449
603
|
let decision;
|
|
450
604
|
try {
|
|
451
|
-
decision = await verifyAuthorization(parsed.chain, parsed.invocation, {
|
|
605
|
+
decision = await verifyAuthorization(parsed.chain, parsed.invocation, {
|
|
606
|
+
...opts.verify,
|
|
607
|
+
...(route.maxStatusAgeSeconds !== undefined ? { maxStatusAgeSeconds: route.maxStatusAgeSeconds } : {}),
|
|
608
|
+
expected,
|
|
609
|
+
});
|
|
452
610
|
}
|
|
453
611
|
catch (e) {
|
|
454
612
|
// verifyAuthorization does not throw by contract; if it ever does, refuse without detail.
|
|
@@ -456,12 +614,22 @@ export function createGateway(opts) {
|
|
|
456
614
|
return deny(info, GATEWAY_PROBLEMS.processing_error, { reason: 'verifier threw', invocation: parsed.invocation });
|
|
457
615
|
}
|
|
458
616
|
if (decision.decision === 'DENY') {
|
|
459
|
-
|
|
617
|
+
const denied = await deny(info, problemSpecForDecision(decision), { decision, invocation: parsed.invocation }, decision.at);
|
|
618
|
+
// A retry of a request that already ran gets that request's stored response, and the API is not called.
|
|
619
|
+
if (decision.code === 'ALREADY_EXECUTED' && denied.kind === 'deny') {
|
|
620
|
+
const replay = replayResponse(decision.replay?.result);
|
|
621
|
+
if (replay)
|
|
622
|
+
return { ...denied, response: replay };
|
|
623
|
+
}
|
|
624
|
+
return denied;
|
|
460
625
|
}
|
|
461
626
|
// From here on an ALLOW holds a reservation. Until the API is called, the action certainly has not run,
|
|
462
627
|
// so every refusal below releases it; after that, settle() decides.
|
|
463
628
|
const allowed = decision;
|
|
464
|
-
const release = () =>
|
|
629
|
+
const release = async () => {
|
|
630
|
+
await settleReservation(allowed.reservation, 'release');
|
|
631
|
+
await finishAttempt(allowed, 'not_executed');
|
|
632
|
+
};
|
|
465
633
|
// A route without a counterparty or amount must not run an invocation that names one: the mandate would
|
|
466
634
|
// have been checked against a value the request does not carry.
|
|
467
635
|
if ((route.counterparty === null && allowed.invocation.counterparty !== undefined) || (route.amount === null && allowed.invocation.amount !== undefined)) {
|
|
@@ -524,7 +692,7 @@ export function createGateway(opts) {
|
|
|
524
692
|
}
|
|
525
693
|
emit({ phase: 'decision', request: info, decision: allowed });
|
|
526
694
|
let final = false;
|
|
527
|
-
const settle = async (input) => {
|
|
695
|
+
const settle = async (input, replay) => {
|
|
528
696
|
if (final)
|
|
529
697
|
return;
|
|
530
698
|
let outcome;
|
|
@@ -537,10 +705,11 @@ export function createGateway(opts) {
|
|
|
537
705
|
}
|
|
538
706
|
else
|
|
539
707
|
outcome = 'pending';
|
|
540
|
-
if (outcome !== 'pending')
|
|
708
|
+
if (outcome !== 'pending')
|
|
541
709
|
final = true;
|
|
710
|
+
await finishAttempt(allowed, ATTEMPT_OUTCOME[outcome], outcome === 'commit' ? storedReplay(replay) : undefined);
|
|
711
|
+
if (outcome !== 'pending')
|
|
542
712
|
await settleReservation(allowed.reservation, outcome);
|
|
543
|
-
}
|
|
544
713
|
if (opts.audit) {
|
|
545
714
|
try {
|
|
546
715
|
await opts.audit.recordSettlement({
|
|
@@ -600,7 +769,16 @@ export function createGateway(opts) {
|
|
|
600
769
|
headers.delete(OUTCOME_HEADER);
|
|
601
770
|
response = new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
602
771
|
}
|
|
603
|
-
|
|
772
|
+
const input = explicit ? { outcome: explicit } : { status: response.status };
|
|
773
|
+
// Only a request whose key the store keeps, and that committed, is worth reading the body of.
|
|
774
|
+
let replay;
|
|
775
|
+
const commits = explicit ? explicit === 'commit' : outcomeForStatus(response.status) === 'commit';
|
|
776
|
+
if (commits && result.decision.idempotency && idempotency && maxReplay > 0) {
|
|
777
|
+
const captured = await captureResponse(response, maxReplay);
|
|
778
|
+
response = captured.response;
|
|
779
|
+
replay = captured.replay;
|
|
780
|
+
}
|
|
781
|
+
await result.settle(input, replay);
|
|
604
782
|
return response;
|
|
605
783
|
}
|
|
606
784
|
return { authorize, handle, outcomeForStatus };
|
|
@@ -63,7 +63,12 @@ export interface ManagedStatusListOptions {
|
|
|
63
63
|
x5c?: string[];
|
|
64
64
|
/** Token lifetime in seconds. Default 1 hour. */
|
|
65
65
|
lifetimeSeconds?: number;
|
|
66
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* Cache hint for verifiers and HTTP caches, in seconds (the token `ttl`, and the bound on `Cache-Control`).
|
|
68
|
+
* It is how long a revocation may go unnoticed by a verifier that caches. Default 60
|
|
69
|
+
* (`DEFAULT_STATUS_TTL_SECONDS`); for payment tools, verifiers can also require a fresher list per call
|
|
70
|
+
* with `maxStatusAgeSeconds`.
|
|
71
|
+
*/
|
|
67
72
|
ttlSeconds?: number;
|
|
68
73
|
}
|
|
69
74
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { decodeJwt } from 'jose';
|
|
2
2
|
import { randomInt } from 'node:crypto';
|
|
3
3
|
import { sha256 } from '../encoding.js';
|
|
4
|
-
import { StatusListPublisher, STATUS_INVALID, STATUS_SUSPENDED, STATUS_VALID } from '../status.js';
|
|
4
|
+
import { DEFAULT_STATUS_TTL_SECONDS, StatusListPublisher, STATUS_INVALID, STATUS_SUSPENDED, STATUS_VALID } from '../status.js';
|
|
5
5
|
import { GATEWAY_PROBLEMS, problemFromSpec, problemResponse } from './errors.js';
|
|
6
6
|
const CODE = { valid: STATUS_VALID, invalid: STATUS_INVALID, suspended: STATUS_SUSPENDED };
|
|
7
7
|
const OP_STATUS = { revoke: 'invalid', suspend: 'suspended', reinstate: 'valid' };
|
|
@@ -104,7 +104,7 @@ export class ManagedStatusList {
|
|
|
104
104
|
const state = await this.opts.store.get(this.opts.id);
|
|
105
105
|
if (!state)
|
|
106
106
|
throw new Error('status list state is missing');
|
|
107
|
-
const ttl = this.opts.ttlSeconds ??
|
|
107
|
+
const ttl = this.opts.ttlSeconds ?? DEFAULT_STATUS_TTL_SECONDS;
|
|
108
108
|
const lifetime = this.opts.lifetimeSeconds ?? 3600;
|
|
109
109
|
const c = this.cached;
|
|
110
110
|
if (c && c.version === state.version && now >= c.iat && now < c.iat + Math.min(ttl, Math.floor(lifetime / 2)))
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { InvocationPayload } from './types.js';
|
|
2
|
+
/** Syntax of an idempotency key: 16 to 128 characters of the base64url alphabet. A UUID without dashes fits. */
|
|
3
|
+
export declare const IDEMPOTENCY_KEY_RE: RegExp;
|
|
4
|
+
/** Default bound on a stored result, in bytes of its UTF-8 text. Larger results are not kept for replay. */
|
|
5
|
+
export declare const DEFAULT_MAX_REPLAY_BYTES: number;
|
|
6
|
+
/** Hard bound a store accepts for a stored result, whatever the caller asks. */
|
|
7
|
+
export declare const MAX_STORED_RESULT_BYTES: number;
|
|
8
|
+
/**
|
|
9
|
+
* `in_progress`: an attempt holds the key and is running. `unknown`: an attempt ended without knowing
|
|
10
|
+
* whether the action ran, or stayed `in_progress` longer than the store's lease. `executed`: it ran.
|
|
11
|
+
*/
|
|
12
|
+
export type IdempotencyState = 'in_progress' | 'unknown' | 'executed';
|
|
13
|
+
/** How an attempt ended. `not_executed` frees the key: the action certainly did not run. */
|
|
14
|
+
export type AttemptOutcome = 'executed' | 'not_executed' | 'unknown';
|
|
15
|
+
export interface IdempotencyRecord {
|
|
16
|
+
/** The scoped key (see `idempotencyScope`). */
|
|
17
|
+
key: string;
|
|
18
|
+
/** What the key was first used for (see `requestFingerprint`). */
|
|
19
|
+
fingerprint: string;
|
|
20
|
+
state: IdempotencyState;
|
|
21
|
+
/** Id of the attempt that holds the key. */
|
|
22
|
+
attempt: string;
|
|
23
|
+
/** Ledger reservation of that attempt, when it reserved spending. */
|
|
24
|
+
reservation?: string;
|
|
25
|
+
/** The result the service stored for replays, as opaque text. Absent when none was kept. */
|
|
26
|
+
result?: string;
|
|
27
|
+
}
|
|
28
|
+
export type IdempotencyClaim = {
|
|
29
|
+
claimed: true;
|
|
30
|
+
attempt: string;
|
|
31
|
+
} | {
|
|
32
|
+
claimed: false;
|
|
33
|
+
record: IdempotencyRecord;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Where a service keeps idempotency keys. Every operation is atomic: under concurrency exactly one
|
|
37
|
+
* `claim` of a free key succeeds, across processes for a shared store.
|
|
38
|
+
*
|
|
39
|
+
* Records of executed attempts are kept for `retentionSeconds`, after which a retry runs again. Records of
|
|
40
|
+
* attempts whose outcome is not known are never forgotten: they block the key until resolved.
|
|
41
|
+
*/
|
|
42
|
+
export interface IdempotencyStore {
|
|
43
|
+
/** Claims a free key for a new attempt, or returns the record that holds it. */
|
|
44
|
+
claim(key: string, fingerprint: string): Promise<IdempotencyClaim>;
|
|
45
|
+
/** Records the ledger reservation of the attempt holding the key. No effect when another attempt holds it. */
|
|
46
|
+
attach(key: string, attempt: string, reservation: string): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Ends an attempt. `executed` keeps the record, with `result` for replays; it also applies when the key
|
|
49
|
+
* was freed in the meantime and nobody claimed it again, because proof that the action ran wins.
|
|
50
|
+
* `not_executed` frees the key, which a later `claim` can take.
|
|
51
|
+
* `unknown` leaves the key blocked until `resolve`. No effect on a key held by another attempt, and an
|
|
52
|
+
* executed record is final.
|
|
53
|
+
*/
|
|
54
|
+
finish(key: string, attempt: string, outcome: AttemptOutcome, result?: string): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* Reconciliation of a key whose attempt is `in_progress` or `unknown`: `executed` marks it executed (with
|
|
57
|
+
* no stored result), `not_executed` frees it. Only when `attempt` still holds the key: an outcome learned
|
|
58
|
+
* about one attempt must never settle a newer one. Returns whether the record changed.
|
|
59
|
+
*/
|
|
60
|
+
resolve(key: string, outcome: 'executed' | 'not_executed', attempt: string): Promise<boolean>;
|
|
61
|
+
get(key: string): Promise<IdempotencyRecord | undefined>;
|
|
62
|
+
/**
|
|
63
|
+
* Records blocked on an unknown outcome (including abandoned attempts), for a reconciliation job. Each
|
|
64
|
+
* names its attempt: pass it to `resolve`.
|
|
65
|
+
*/
|
|
66
|
+
unresolved(opts?: {
|
|
67
|
+
limit?: number;
|
|
68
|
+
}): Promise<IdempotencyRecord[]>;
|
|
69
|
+
/** How long an executed record is kept, in seconds. */
|
|
70
|
+
readonly retentionSeconds: number;
|
|
71
|
+
/** How long an attempt may stay `in_progress` before it counts as abandoned (`unknown`), in seconds. */
|
|
72
|
+
readonly leaseSeconds: number;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The key under which a service stores an invocation's `idem`: bound to the service audience and to the
|
|
76
|
+
* whole mandate chain, so keys of different agents, people or services never meet.
|
|
77
|
+
*/
|
|
78
|
+
export declare function idempotencyScope(audience: string, chainHashValue: string, idem: string): string;
|
|
79
|
+
/**
|
|
80
|
+
* What an attempt does, for comparing attempts that share a key: action, counterparty, amount and the
|
|
81
|
+
* argument hash. Nonce and `iat` are left out, since every attempt has its own.
|
|
82
|
+
*/
|
|
83
|
+
export declare function requestFingerprint(inv: Pick<InvocationPayload, 'action' | 'counterparty' | 'amount' | 'args_hash'>): string;
|
|
84
|
+
/** A fresh idempotency key for one intention of an agent: 32 characters, from a random UUID. */
|
|
85
|
+
export declare function newIdempotencyKey(): string;
|
|
86
|
+
/** Input checks shared by every store: values may come from anywhere. */
|
|
87
|
+
export declare function validateIdempotencyKey(key: unknown): asserts key is string;
|
|
88
|
+
export declare function validateFingerprint(fp: unknown): asserts fp is string;
|
|
89
|
+
export declare function isAttemptId(x: unknown): x is string;
|
|
90
|
+
export declare function validateOutcome(o: unknown): asserts o is AttemptOutcome;
|
|
91
|
+
export declare function validateResult(result: unknown): asserts result is string | undefined;
|
|
92
|
+
export declare function idempotencyDuration(name: string, value: number | undefined, fallback: number): number;
|
|
93
|
+
export interface IdempotencyStoreOptions {
|
|
94
|
+
/** How long an executed record is kept, in seconds. Default 86400 (one day). */
|
|
95
|
+
retentionSeconds?: number;
|
|
96
|
+
/**
|
|
97
|
+
* How long an attempt may stay `in_progress` before it counts as abandoned, in seconds. Must exceed the
|
|
98
|
+
* longest time between ALLOW and the end of the action. Default 300.
|
|
99
|
+
*/
|
|
100
|
+
leaseSeconds?: number;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* In-memory store for development, tests and single-process services. Operations are synchronous inside,
|
|
104
|
+
* so they are atomic within one Node.js process.
|
|
105
|
+
*/
|
|
106
|
+
export declare class InMemoryIdempotencyStore implements IdempotencyStore {
|
|
107
|
+
readonly retentionSeconds: number;
|
|
108
|
+
readonly leaseSeconds: number;
|
|
109
|
+
private readonly entries;
|
|
110
|
+
private readonly clock;
|
|
111
|
+
private nextSweep;
|
|
112
|
+
constructor(opts?: IdempotencyStoreOptions & {
|
|
113
|
+
now?: () => number;
|
|
114
|
+
});
|
|
115
|
+
/** Deletes executed and free records past their retention. Returns how many were deleted. */
|
|
116
|
+
sweep(): number;
|
|
117
|
+
/** The entry with time applied: expired records dropped, abandoned attempts turned unknown. */
|
|
118
|
+
private current;
|
|
119
|
+
private view;
|
|
120
|
+
claim(key: string, fingerprint: string): Promise<IdempotencyClaim>;
|
|
121
|
+
attach(key: string, attempt: string, reservation: string): Promise<void>;
|
|
122
|
+
finish(key: string, attempt: string, outcome: AttemptOutcome, result?: string): Promise<void>;
|
|
123
|
+
resolve(key: string, outcome: 'executed' | 'not_executed', attempt: string): Promise<boolean>;
|
|
124
|
+
get(key: string): Promise<IdempotencyRecord | undefined>;
|
|
125
|
+
unresolved(opts?: {
|
|
126
|
+
limit?: number;
|
|
127
|
+
}): Promise<IdempotencyRecord[]>;
|
|
128
|
+
}
|