plenipo 0.4.1 → 0.5.1

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/dist/verify.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type DelegationFormat } from './delegate-sdjwt.js';
2
2
  import type { NonceStore, RevocationRegistry, SpendingLedger } from './registry.js';
3
+ import { type IdempotencyStore } from './idempotency.js';
3
4
  import type { RepresentationVerifyOptions } from './legal.js';
4
5
  import { type EmandateVerifyOptions } from './root.js';
5
6
  import { type StatusFetcher, type StatusListCache } from './status.js';
@@ -45,6 +46,19 @@ export interface VerifyOptions {
45
46
  /** Fetches status list tokens. Default: HTTPS GET. */
46
47
  statusFetcher?: StatusFetcher;
47
48
  statusCache?: StatusListCache;
49
+ /**
50
+ * Maximum age, in seconds, of a cached status list (PID, attestations, mandates) for this verification.
51
+ * A cached list obtained earlier is fetched again, and the fetcher asks HTTP caches for a copy no older
52
+ * than that. Set it on calls that move money, so a revocation takes effect within this bound instead of
53
+ * the cache lifetime; `0` checks the origin on every call. Default: the cache decides.
54
+ */
55
+ maxStatusAgeSeconds?: number;
56
+ /**
57
+ * Keeps idempotency keys (see `src/idempotency.ts`). Needed to accept an invocation that carries `idem`:
58
+ * without a store the key would have no effect and a retry would run again, so such an invocation is
59
+ * refused with CONFIGURATION. On ALLOW the decision carries `idempotency`, the attempt the caller must end.
60
+ */
61
+ idempotency?: IdempotencyStore;
48
62
  /** This relying party's identifier; must equal the invocation `aud`. */
49
63
  audience: string;
50
64
  /** Single-use nonce store. Required: without it a captured invocation could be replayed. */
package/dist/verify.js CHANGED
@@ -3,6 +3,7 @@ import { mandateHash } from './encoding.js';
3
3
  import { DelegationError, isSdJwtDelegation, verifyDelegateSdJwt } from './delegate-sdjwt.js';
4
4
  import { argsHash, chainHash } from './invocation.js';
5
5
  import { nowSeconds } from './mandate.js';
6
+ import { idempotencyScope, requestFingerprint } from './idempotency.js';
6
7
  import { checkAttestationCertificates, checkAttestationStatus, checkPidStatus, RootError, verifyRoot } from './root.js';
7
8
  import { checkStatus, StatusUnavailableError, httpsOrigin } from './status.js';
8
9
  import { checkChainRevocation, TrustError } from './trust.js';
@@ -12,15 +13,74 @@ class Deny extends Error {
12
13
  code;
13
14
  at;
14
15
  detail;
16
+ replay;
15
17
  constructor(code, message, at,
16
18
  /** Internal detail for logs; never sent to the caller by the MCP guard. */
17
- detail) {
19
+ detail,
20
+ /** With ALREADY_EXECUTED: the stored result of the attempt that ran. */
21
+ replay) {
18
22
  super(message);
19
23
  this.code = code;
20
24
  this.at = at;
21
25
  this.detail = detail;
26
+ this.replay = replay;
22
27
  }
23
28
  }
29
+ function canLookUp(ledger) {
30
+ return typeof ledger?.reservation === 'function';
31
+ }
32
+ /**
33
+ * Claims the idempotency key of an invocation for this attempt, or explains why it cannot run. A key held by
34
+ * an attempt of unknown outcome follows the ledger when it can: a committed reservation means the action
35
+ * ran, a released one means it did not (the ledger releases only on certainty), which frees the key. The
36
+ * record is then read again, so the answer always describes the key as it is now.
37
+ */
38
+ async function claimIdempotencyKey(store, key, fingerprint, ledger, consumeNonce) {
39
+ const alreadyExecuted = async (record) => {
40
+ // The retry is a fresh invocation: burning its nonce keeps a copied retry from reading the result again.
41
+ await consumeNonce();
42
+ throw new Deny('ALREADY_EXECUTED', 'an earlier attempt with this idempotency key already executed', undefined, undefined, {
43
+ ...(record?.result !== undefined ? { result: record.result } : {}),
44
+ });
45
+ };
46
+ // Every refusal below answers a fresh retry: its nonce is spent, so a copy of it cannot come back later,
47
+ // once the first attempt has executed, to read the stored result.
48
+ const refuse = async (code, message) => {
49
+ await consumeNonce();
50
+ throw new Deny(code, message);
51
+ };
52
+ for (let round = 0; round < 3; round++) {
53
+ const claim = await store.claim(key, fingerprint);
54
+ if (claim.claimed)
55
+ return { key, attempt: claim.attempt };
56
+ const record = claim.record;
57
+ if (record.fingerprint !== fingerprint) {
58
+ return refuse('IDEMPOTENCY_CONFLICT', 'the idempotency key was already used for a different request');
59
+ }
60
+ if (record.state === 'executed')
61
+ return alreadyExecuted(record);
62
+ if (record.state === 'in_progress') {
63
+ return refuse('IDEMPOTENCY_IN_PROGRESS', 'an attempt with this idempotency key is still running');
64
+ }
65
+ // Unknown outcome, or an abandoned attempt. The ledger settles it only for the attempt that held the key
66
+ // when it was read: `resolve` is compare-and-set on that attempt, so a concurrent retry that has already
67
+ // freed and taken the key is never released or marked by this one.
68
+ if (record.reservation !== undefined && canLookUp(ledger)) {
69
+ const info = await ledger.reservation(record.reservation);
70
+ if (info?.state === 'committed') {
71
+ await store.resolve(key, 'executed', record.attempt);
72
+ continue;
73
+ }
74
+ if (info?.state === 'released') {
75
+ await store.resolve(key, 'not_executed', record.attempt);
76
+ continue;
77
+ }
78
+ }
79
+ return refuse('IDEMPOTENCY_UNRESOLVED', 'the outcome of an earlier attempt with this idempotency key is not known yet');
80
+ }
81
+ // The record changed under us twice (a concurrent retry freed and took the key): it is in use.
82
+ return refuse('IDEMPOTENCY_IN_PROGRESS', 'an attempt with this idempotency key is still running');
83
+ }
24
84
  function statusOriginsOf(trust) {
25
85
  if (trust.statusOrigins)
26
86
  return trust.statusOrigins;
@@ -41,6 +101,11 @@ export async function verifyAuthorization(chain, invocation, opts) {
41
101
  try {
42
102
  if (!opts?.nonces)
43
103
  throw new Deny('CONFIGURATION', 'a nonce store is required to prevent replay');
104
+ const maxStatusAge = opts.maxStatusAgeSeconds;
105
+ if (maxStatusAge !== undefined && (typeof maxStatusAge !== 'number' || !Number.isFinite(maxStatusAge) || maxStatusAge < 0)) {
106
+ throw new Deny('CONFIGURATION', 'maxStatusAgeSeconds must be a non-negative number of seconds');
107
+ }
108
+ const statusAge = maxStatusAge !== undefined ? { maxStatusAgeSeconds: maxStatusAge } : {};
44
109
  const now = opts.now ?? nowSeconds();
45
110
  const skew = opts.skewSeconds ?? 60;
46
111
  // A nonce must be remembered for as long as an invocation carrying it can still be accepted.
@@ -282,6 +347,7 @@ export async function verifyAuthorization(chain, invocation, opts) {
282
347
  now,
283
348
  statusFetcher: opts.statusFetcher,
284
349
  statusCache: opts.statusCache,
350
+ ...statusAge,
285
351
  });
286
352
  }
287
353
  catch (e) {
@@ -302,7 +368,7 @@ export async function verifyAuthorization(chain, invocation, opts) {
302
368
  }
303
369
  for (const d of root.deferredStatus ?? []) {
304
370
  try {
305
- await checkAttestationStatus(d, { now, statusFetcher: opts.statusFetcher, statusCache: opts.statusCache });
371
+ await checkAttestationStatus(d, { now, statusFetcher: opts.statusFetcher, statusCache: opts.statusCache, ...statusAge });
306
372
  }
307
373
  catch (e) {
308
374
  if (e instanceof RootError)
@@ -324,6 +390,7 @@ export async function verifyAuthorization(chain, invocation, opts) {
324
390
  fetcher: opts.statusFetcher,
325
391
  now,
326
392
  cache: opts.statusCache,
393
+ ...(maxStatusAge !== undefined ? { maxAgeSeconds: maxStatusAge } : {}),
327
394
  });
328
395
  }
329
396
  catch (e) {
@@ -332,31 +399,51 @@ export async function verifyAuthorization(chain, invocation, opts) {
332
399
  if (status !== 0)
333
400
  throw new Deny('REVOKED', `mandate ${i} is ${status === 2 ? 'suspended' : 'revoked'} in its status list`, i);
334
401
  }
335
- // 7. Atomic reservation against every total limit in the chain.
336
- let reservation;
337
- if (needsLedger && inv.amount && opts.ledger) {
338
- const entries = mandates.map((m) => ({ key: mandateHash(m), total: m.limits?.total }));
339
- const r = await opts.ledger.reserve(entries, inv.amount);
340
- if (r === null)
341
- throw new Deny('LIMIT_TOTAL', `amount ${inv.amount.value} would exceed a total limit in the chain`);
342
- reservation = r;
402
+ // 7. Idempotency. After every check that can refuse the call, so a refused attempt never claims or blocks
403
+ // a key; before the reservation, so the retry of an executed call is answered from its record instead
404
+ // of reserving again.
405
+ let nonceConsumed = false;
406
+ const consumeNonce = async () => {
407
+ const fresh = await opts.nonces.consume(inv.nonce);
408
+ if (!fresh)
409
+ throw new Deny('REPLAY', 'invocation nonce was already used or was not issued');
410
+ nonceConsumed = true;
411
+ };
412
+ let idem;
413
+ if (inv.idem !== undefined) {
414
+ if (!opts.idempotency) {
415
+ throw new Deny('CONFIGURATION', 'the invocation carries an idempotency key and this service keeps no idempotency store');
416
+ }
417
+ idem = await claimIdempotencyKey(opts.idempotency, idempotencyScope(opts.audience, inv.chain_hash, inv.idem), requestFingerprint(inv), opts.ledger, consumeNonce);
343
418
  }
344
- // 8. Replay. Checked last, so a denied invocation does not burn its nonce.
345
- // A store that throws must not leave the amount reserved: release, then let the error deny.
346
- let fresh;
419
+ // Until ALLOW is returned nothing has run: every failure below gives the reservation and the key back.
420
+ let reservation;
347
421
  try {
348
- fresh = await opts.nonces.consume(inv.nonce);
422
+ // 8. Atomic reservation against every total limit in the chain.
423
+ if (needsLedger && inv.amount && opts.ledger) {
424
+ const entries = mandates.map((m) => ({ key: mandateHash(m), total: m.limits?.total }));
425
+ const r = await opts.ledger.reserve(entries, inv.amount);
426
+ if (r === null)
427
+ throw new Deny('LIMIT_TOTAL', `amount ${inv.amount.value} would exceed a total limit in the chain`);
428
+ reservation = r;
429
+ if (idem)
430
+ await opts.idempotency.attach(idem.key, idem.attempt, r);
431
+ }
432
+ // 9. Replay. Checked last, so a denied invocation does not burn its nonce.
433
+ if (!nonceConsumed)
434
+ await consumeNonce();
349
435
  }
350
436
  catch (e) {
351
- if (reservation && opts.ledger)
352
- await opts.ledger.release(reservation);
437
+ // Best effort: the original failure is what the caller must see. A reservation left pending keeps
438
+ // counting (safe side); a key left in progress turns unresolved after the lease (safe side too).
439
+ const ledger = opts.ledger;
440
+ const store = opts.idempotency;
441
+ if (reservation && ledger)
442
+ await Promise.resolve().then(() => ledger.release(reservation)).catch(() => undefined);
443
+ if (idem && store)
444
+ await store.finish(idem.key, idem.attempt, 'not_executed').catch(() => undefined);
353
445
  throw e;
354
446
  }
355
- if (!fresh) {
356
- if (reservation && opts.ledger)
357
- await opts.ledger.release(reservation);
358
- throw new Deny('REPLAY', 'invocation nonce was already used or was not issued');
359
- }
360
447
  return {
361
448
  decision: 'ALLOW',
362
449
  principal: root.legalPrincipal ?? root.principal,
@@ -368,6 +455,7 @@ export async function verifyAuthorization(chain, invocation, opts) {
368
455
  mandates,
369
456
  invocation: inv,
370
457
  ...(reservation ? { reservation } : {}),
458
+ ...(idem ? { idempotency: idem } : {}),
371
459
  // Never throws: the reservation above must not be left behind by an identifier for policy engines.
372
460
  ...(root.holderJwk ? await calculateJwkThumbprint(root.holderJwk, 'sha256').then((t) => ({ pid_holder_jkt: t }), () => ({})) : {}),
373
461
  };
@@ -380,6 +468,7 @@ export async function verifyAuthorization(chain, invocation, opts) {
380
468
  reason: e.message,
381
469
  ...(e.at !== undefined ? { at: e.at } : {}),
382
470
  ...(e.detail !== undefined ? { detail: e.detail } : {}),
471
+ ...(e.replay !== undefined ? { replay: e.replay } : {}),
383
472
  path,
384
473
  };
385
474
  }
@@ -348,11 +348,16 @@ export async function checkCertificateRevocation(chain, opts, now) {
348
348
  }
349
349
  return report;
350
350
  }
351
+ const CRL_BEGIN = '-----BEGIN X509 CRL-----';
352
+ const CRL_END = '-----END X509 CRL-----';
353
+ /** PEM or base64 to DER. With indexOf, not a lazy regex, whose time grows with the square of a malformed input. */
351
354
  function toDer(c) {
352
355
  if (typeof c !== 'string')
353
356
  return c;
354
- const m = /-----BEGIN X509 CRL-----([\s\S]+?)-----END X509 CRL-----/.exec(c);
355
- return new Uint8Array(Buffer.from(m ? m[1] : c, 'base64'));
357
+ const start = c.indexOf(CRL_BEGIN);
358
+ const end = start < 0 ? -1 : c.indexOf(CRL_END, start + CRL_BEGIN.length);
359
+ const body = start >= 0 && end > start + CRL_BEGIN.length ? c.slice(start + CRL_BEGIN.length, end) : c;
360
+ return new Uint8Array(Buffer.from(body, 'base64'));
356
361
  }
357
362
  // --- OCSP -------------------------------------------------------------------------------------------------
358
363
  const SHA1 = '1.3.14.3.2.26';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plenipo",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Wallet-anchored mandates for AI agents: EUDI Wallet PID as root, enforced attenuation, expiry and revocation, MCP guard.",
5
5
  "keywords": [
6
6
  "eudi-wallet",
@@ -69,13 +69,13 @@
69
69
  "example:gateway": "tsx examples/bank-gateway.ts"
70
70
  },
71
71
  "dependencies": {
72
- "@owf/token-status-list": "^0.5.0",
73
- "@peculiar/asn1-ocsp": "^2.11.0",
74
- "@peculiar/asn1-schema": "^2.11.0",
75
- "@peculiar/asn1-x509": "^2.11.0",
76
- "@peculiar/x509": "^2.2.0",
72
+ "@owf/token-status-list": "^0.7.0",
73
+ "@peculiar/asn1-ocsp": "^3.0.0",
74
+ "@peculiar/asn1-schema": "^3.0.0",
75
+ "@peculiar/asn1-x509": "^3.0.0",
76
+ "@peculiar/x509": "^3.1.0",
77
77
  "@sd-jwt/crypto-nodejs": "^0.19.0",
78
- "@sd-jwt/sd-jwt-vc": "^0.23.0",
78
+ "@sd-jwt/sd-jwt-vc": "^0.24.3",
79
79
  "canonicalize": "^5.1.0",
80
80
  "jose": "^6.2.12",
81
81
  "reflect-metadata": "^0.2.2",
@@ -84,7 +84,7 @@
84
84
  "devDependencies": {
85
85
  "@electric-sql/pglite": "^0.5.10",
86
86
  "@modelcontextprotocol/sdk": "^1.32.1",
87
- "@owf/eudi-lote": "^0.5.0",
87
+ "@owf/eudi-lote": "^0.6.0",
88
88
  "@types/express": "^5.0.3",
89
89
  "@types/node": "^26.6.5",
90
90
  "@types/pg": "^8.23.1",
@@ -1,10 +1,10 @@
1
- -- Plenipo shared stores, schema version 3.
1
+ -- Plenipo shared stores, schema version 4.
2
2
  CREATE TABLE IF NOT EXISTS plenipo_schema_meta (
3
3
  id INTEGER PRIMARY KEY CHECK (id = 1),
4
4
  version INTEGER NOT NULL
5
5
  );
6
6
 
7
- INSERT INTO plenipo_schema_meta (id, version) VALUES (1, 3) ON CONFLICT (id) DO NOTHING;
7
+ INSERT INTO plenipo_schema_meta (id, version) VALUES (1, 4) ON CONFLICT (id) DO NOTHING;
8
8
 
9
9
  CREATE TABLE IF NOT EXISTS plenipo_ledger (
10
10
  mandate_key TEXT COLLATE "C" NOT NULL CHECK (length(mandate_key) BETWEEN 1 AND 256),
@@ -49,6 +49,10 @@ BEGIN
49
49
  ALTER TABLE plenipo_reservations ADD COLUMN IF NOT EXISTS corrected_at TIMESTAMPTZ;
50
50
  UPDATE plenipo_schema_meta SET version = 3 WHERE id = 1;
51
51
  END IF;
52
+ -- Version 3 to 4: only a new table (idempotency keys), created below.
53
+ IF (SELECT version FROM plenipo_schema_meta WHERE id = 1) < 4 THEN
54
+ UPDATE plenipo_schema_meta SET version = 4 WHERE id = 1;
55
+ END IF;
52
56
  END
53
57
  $plenipo$;
54
58
 
@@ -77,6 +81,22 @@ CREATE TABLE IF NOT EXISTS plenipo_request_sessions (
77
81
 
78
82
  CREATE INDEX IF NOT EXISTS plenipo_request_sessions_expiry_idx ON plenipo_request_sessions (expires_at);
79
83
 
84
+ CREATE TABLE IF NOT EXISTS plenipo_idempotency (
85
+ key TEXT COLLATE "C" PRIMARY KEY CHECK (length(key) BETWEEN 1 AND 256),
86
+ fingerprint TEXT NOT NULL CHECK (length(fingerprint) BETWEEN 1 AND 256),
87
+ state TEXT NOT NULL CHECK (state IN ('in_progress', 'unknown', 'executed', 'free')),
88
+ attempt UUID NOT NULL,
89
+ reservation TEXT CHECK (reservation IS NULL OR length(reservation) BETWEEN 1 AND 256),
90
+ result TEXT,
91
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
92
+ lease_until TIMESTAMPTZ,
93
+ expires_at TIMESTAMPTZ
94
+ );
95
+
96
+ CREATE INDEX IF NOT EXISTS plenipo_idempotency_open_idx ON plenipo_idempotency (lease_until) WHERE state IN ('in_progress', 'unknown');
97
+
98
+ CREATE INDEX IF NOT EXISTS plenipo_idempotency_expiry_idx ON plenipo_idempotency (expires_at) WHERE state IN ('executed', 'free');
99
+
80
100
  CREATE OR REPLACE FUNCTION plenipo_ledger_reserve(
81
101
  p_id UUID, p_keys TEXT[], p_totals BIGINT[], p_currency TEXT, p_amount BIGINT, p_ttl_seconds DOUBLE PRECISION
82
102
  ) RETURNS BOOLEAN LANGUAGE plpgsql AS $plenipo$