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/dist/status.js CHANGED
@@ -11,11 +11,16 @@ import { inflateSync } from 'node:zlib';
11
11
  import { resolveSigningKeyAsync } from './trust.js';
12
12
  import { canonicalize, sha256 } from './encoding.js';
13
13
  const MAX_TOKEN_BYTES = 1_000_000;
14
- export const defaultStatusFetcher = async (uri) => {
14
+ export const defaultStatusFetcher = async (uri, opts) => {
15
15
  if (new URL(uri).protocol !== 'https:')
16
16
  throw new Error('status lists are fetched over https only');
17
+ const maxAge = opts?.maxAgeSeconds;
17
18
  const res = await fetch(uri, {
18
- headers: { accept: 'application/statuslist+jwt' },
19
+ headers: {
20
+ accept: 'application/statuslist+jwt',
21
+ // A request directive (RFC 9111): caches between here and the origin must not answer with an older copy.
22
+ ...(typeof maxAge === 'number' && Number.isFinite(maxAge) && maxAge >= 0 ? { 'cache-control': `max-age=${Math.floor(maxAge)}` } : {}),
23
+ },
19
24
  redirect: 'error',
20
25
  signal: AbortSignal.timeout(5_000),
21
26
  });
@@ -42,6 +47,11 @@ export const defaultStatusFetcher = async (uri) => {
42
47
  }
43
48
  return Buffer.concat(chunks).toString('utf8').trim();
44
49
  };
50
+ /**
51
+ * Default `ttl` of the status lists this library publishes, in seconds. Verifiers and HTTP caches may keep a
52
+ * list that long, so it is how long a revocation can go unnoticed; it matches the default `StatusListCache`.
53
+ */
54
+ export const DEFAULT_STATUS_TTL_SECONDS = 60;
45
55
  export const STATUS_VALID = 0;
46
56
  export const STATUS_INVALID = 1;
47
57
  export const STATUS_SUSPENDED = 2;
@@ -95,12 +105,21 @@ export class StatusListCache {
95
105
  constructor(maxAgeSeconds = 60) {
96
106
  this.maxAgeSeconds = maxAgeSeconds;
97
107
  }
98
- get(key, now) {
108
+ /**
109
+ * The cached list, unless it expired or, with `maxAgeSeconds`, was obtained more than that many seconds
110
+ * before `now`. This is what bounds how long a revocation can go unnoticed.
111
+ */
112
+ get(key, now, maxAgeSeconds) {
99
113
  const e = this.entries.get(key);
100
- return e && e.until > now ? e.list : undefined;
114
+ if (!e || e.until <= now)
115
+ return undefined;
116
+ // `0` means "obtained for this check": never served from the cache, whatever the clock resolution.
117
+ if (maxAgeSeconds !== undefined && (maxAgeSeconds === 0 || e.fetchedAt === undefined || now - e.fetchedAt > maxAgeSeconds))
118
+ return undefined;
119
+ return e.list;
101
120
  }
102
- set(key, list, until) {
103
- this.entries.set(key, { list, until });
121
+ set(key, list, until, fetchedAt) {
122
+ this.entries.set(key, { list, until, ...(fetchedAt !== undefined ? { fetchedAt } : {}) });
104
123
  }
105
124
  get maxAge() {
106
125
  return this.maxAgeSeconds;
@@ -155,11 +174,16 @@ export async function checkStatus(ref, opts) {
155
174
  const maxBytes = opts.maxListBytes ?? DEFAULT_MAX_STATUS_LIST_BYTES;
156
175
  // The bound is part of the key: a list accepted under a larger bound is not served to a stricter check.
157
176
  const key = JSON.stringify([trustId(opts.trust), opts.signer, uri, maxBytes]);
158
- let list = opts.cache?.get(key, opts.now);
177
+ const maxAge = opts.maxAgeSeconds;
178
+ if (maxAge !== undefined && (typeof maxAge !== 'number' || !Number.isFinite(maxAge) || maxAge < 0)) {
179
+ throw new Error('maxAgeSeconds must be a non-negative number');
180
+ }
181
+ let list = opts.cache?.get(key, opts.now, maxAge);
159
182
  if (!list) {
160
183
  let token;
161
184
  try {
162
- token = await (opts.fetcher ?? defaultStatusFetcher)(uri);
185
+ const fetcher = opts.fetcher ?? defaultStatusFetcher;
186
+ token = await (maxAge !== undefined ? fetcher(uri, { maxAgeSeconds: maxAge }) : fetcher(uri));
163
187
  }
164
188
  catch (e) {
165
189
  throw new StatusUnavailableError(e?.message ?? String(e));
@@ -178,7 +202,7 @@ export async function checkStatus(ref, opts) {
178
202
  if (opts.cache) {
179
203
  const ttl = typeof payload.ttl === 'number' && payload.ttl >= 0 ? payload.ttl : opts.cache.maxAge;
180
204
  const until = Math.min(opts.now + opts.cache.maxAge, opts.now + ttl, Number(payload.exp));
181
- opts.cache.set(key, list, until);
205
+ opts.cache.set(key, list, until, opts.now);
182
206
  }
183
207
  }
184
208
  return readStatus(list, idx);
@@ -235,7 +259,7 @@ export class StatusListPublisher {
235
259
  sub: this.opts.uri,
236
260
  iat: now,
237
261
  exp: now + (this.opts.lifetimeSeconds ?? 3600),
238
- ttl: this.opts.ttlSeconds ?? 300,
262
+ ttl: this.opts.ttlSeconds ?? DEFAULT_STATUS_TTL_SECONDS,
239
263
  ...(this.opts.iss ? { iss: this.opts.iss } : {}),
240
264
  }, { alg: 'ES256', typ: 'statuslist+jwt', ...(this.opts.x5c ? { x5c: this.opts.x5c } : {}) });
241
265
  return signCompactJwt(payload, header, this.opts.signingKey);
@@ -1,3 +1,3 @@
1
1
  export { nonceRetentionSeconds, serializeSession, deserializeSession, type ManagedRevocationRegistry, type MandateSessionStore, type ReservationInfo, type ReconcileOutcome, type ReservationState, } from './common.js';
2
- export { migratePostgres, postgresSchema, POSTGRES_SCHEMA_SQL, POSTGRES_SCHEMA_VERSION, PostgresSpendingLedger, PostgresNonceStore, PostgresRevocationRegistry, PostgresMandateSessionStore, createPostgresResponseSessionStore, type SqlClient, type PostgresNamingOptions, type PostgresLedgerOptions, type PostgresNonceOptions, } from './postgres.js';
3
- export { fromIoredis, fromNodeRedis, RedisSpendingLedger, RedisNonceStore, RedisRevocationRegistry, RedisMandateSessionStore, createRedisResponseSessionStore, type RedisClient, type IoredisLike, type NodeRedisLike, type RedisLedgerOptions, type RedisNonceOptions, } from './redis.js';
2
+ export { migratePostgres, postgresSchema, POSTGRES_SCHEMA_SQL, POSTGRES_SCHEMA_VERSION, PostgresSpendingLedger, PostgresNonceStore, PostgresRevocationRegistry, PostgresMandateSessionStore, PostgresIdempotencyStore, createPostgresResponseSessionStore, type SqlClient, type PostgresNamingOptions, type PostgresLedgerOptions, type PostgresNonceOptions, } from './postgres.js';
3
+ export { fromIoredis, fromNodeRedis, RedisSpendingLedger, RedisNonceStore, RedisRevocationRegistry, RedisMandateSessionStore, RedisIdempotencyStore, createRedisResponseSessionStore, type RedisClient, type IoredisLike, type NodeRedisLike, type RedisLedgerOptions, type RedisNonceOptions, } from './redis.js';
@@ -1,3 +1,3 @@
1
1
  export { nonceRetentionSeconds, serializeSession, deserializeSession, } from './common.js';
2
- export { migratePostgres, postgresSchema, POSTGRES_SCHEMA_SQL, POSTGRES_SCHEMA_VERSION, PostgresSpendingLedger, PostgresNonceStore, PostgresRevocationRegistry, PostgresMandateSessionStore, createPostgresResponseSessionStore, } from './postgres.js';
3
- export { fromIoredis, fromNodeRedis, RedisSpendingLedger, RedisNonceStore, RedisRevocationRegistry, RedisMandateSessionStore, createRedisResponseSessionStore, } from './redis.js';
2
+ export { migratePostgres, postgresSchema, POSTGRES_SCHEMA_SQL, POSTGRES_SCHEMA_VERSION, PostgresSpendingLedger, PostgresNonceStore, PostgresRevocationRegistry, PostgresMandateSessionStore, PostgresIdempotencyStore, createPostgresResponseSessionStore, } from './postgres.js';
3
+ export { fromIoredis, fromNodeRedis, RedisSpendingLedger, RedisNonceStore, RedisRevocationRegistry, RedisMandateSessionStore, RedisIdempotencyStore, createRedisResponseSessionStore, } from './redis.js';
@@ -1,6 +1,7 @@
1
1
  import type { MandateRequestSession } from '../openid4vp.js';
2
2
  import type { LedgerEntry, NonceStore, SpendingLedger } from '../registry.js';
3
3
  import type { Amount } from '../types.js';
4
+ import { type AttemptOutcome, type IdempotencyClaim, type IdempotencyRecord, type IdempotencyStore, type IdempotencyStoreOptions } from '../idempotency.js';
4
5
  import { type ManagedRevocationRegistry, type MandateSessionStore, type ReconcileOutcome, type ReservationInfo, type ReservationState } from './common.js';
5
6
  /** The part of a Postgres driver the stores use. `pg` Pool, `pg` Client and PGlite fit as they are. */
6
7
  export interface SqlClient {
@@ -15,7 +16,7 @@ export interface PostgresNamingOptions {
15
16
  schema?: string;
16
17
  }
17
18
  /** Bumped when the schema changes; recorded so a future migration knows where it starts from. */
18
- export declare const POSTGRES_SCHEMA_VERSION = 3;
19
+ export declare const POSTGRES_SCHEMA_VERSION = 4;
19
20
  /**
20
21
  * The schema as plain SQL, one statement after another, for psql or a migration tool.
21
22
  * Idempotent: every statement can run again on an existing schema.
@@ -158,3 +159,29 @@ export declare class PostgresMandateSessionStore implements MandateSessionStore
158
159
  limit?: number;
159
160
  }): Promise<number>;
160
161
  }
162
+ /**
163
+ * Idempotency keys shared by every instance. `claim` is one INSERT ... ON CONFLICT: under concurrency exactly
164
+ * one caller takes a free key, the others wait on the row and then see it held.
165
+ */
166
+ export declare class PostgresIdempotencyStore implements IdempotencyStore {
167
+ private readonly db;
168
+ private readonly n;
169
+ readonly retentionSeconds: number;
170
+ readonly leaseSeconds: number;
171
+ constructor(db: SqlClient, opts?: IdempotencyStoreOptions & PostgresNamingOptions);
172
+ /** Columns of a live record, with an abandoned attempt shown as unknown. Free and expired rows are not live. */
173
+ private select;
174
+ private record;
175
+ claim(key: string, fingerprint: string): Promise<IdempotencyClaim>;
176
+ attach(key: string, attempt: string, reservation: string): Promise<void>;
177
+ finish(key: string, attempt: string, outcome: AttemptOutcome, result?: string): Promise<void>;
178
+ resolve(key: string, outcome: 'executed' | 'not_executed', attempt: string): Promise<boolean>;
179
+ get(key: string): Promise<IdempotencyRecord | undefined>;
180
+ unresolved(opts?: {
181
+ limit?: number;
182
+ }): Promise<IdempotencyRecord[]>;
183
+ /** Deletes executed and free records past their retention. Returns how many were deleted. */
184
+ sweep(opts?: {
185
+ limit?: number;
186
+ }): Promise<number>;
187
+ }
@@ -1,16 +1,17 @@
1
1
  /**
2
2
  * Postgres implementations of the stateful interfaces, so several verifier instances can share
3
- * spending, nonces, revocations and OpenID4VP sessions.
3
+ * spending, nonces, idempotency keys, revocations and OpenID4VP sessions.
4
4
  *
5
5
  * No driver is imported: every store takes a {@link SqlClient}, which a `pg` Pool or Client and a
6
6
  * PGlite instance satisfy as they are. Every operation is a single SQL statement, so a pool can run it
7
7
  * on any connection and no transaction is ever left open by a crashed caller.
8
8
  */
9
9
  import { createHash, randomUUID } from 'node:crypto';
10
+ import { idempotencyDuration, isAttemptId, validateFingerprint, validateIdempotencyKey, validateOutcome, validateResult, } from '../idempotency.js';
10
11
  import { deserializeSession, durationSeconds, isReservationId, nonceDigest, normalizeEntries, positiveInt, serializeSession, toSafeInteger, validateAmount, validateCurrency, validateKey, validateMandateId, validateSessionId, } from './common.js';
11
12
  const IDENT_RE = /^[a-z_][a-z0-9_]{0,39}$/;
12
13
  /** Bumped when the schema changes; recorded so a future migration knows where it starts from. */
13
- export const POSTGRES_SCHEMA_VERSION = 3;
14
+ export const POSTGRES_SCHEMA_VERSION = 4;
14
15
  /** Identifiers are interpolated into SQL, so they are validated against a strict pattern first. */
15
16
  function names(opts = {}) {
16
17
  const prefix = opts.tablePrefix ?? 'plenipo_';
@@ -28,6 +29,7 @@ function names(opts = {}) {
28
29
  nonces: q('nonces'),
29
30
  revocations: q('revocations'),
30
31
  sessions: q('request_sessions'),
32
+ idempotency: q('idempotency'),
31
33
  meta: q('schema_meta'),
32
34
  reserve: q('ledger_reserve'),
33
35
  settle: q('ledger_settle'),
@@ -86,6 +88,10 @@ BEGIN
86
88
  ALTER TABLE ${n.reservations} ADD COLUMN IF NOT EXISTS corrected_at TIMESTAMPTZ;
87
89
  UPDATE ${n.meta} SET version = 3 WHERE id = 1;
88
90
  END IF;
91
+ -- Version 3 to 4: only a new table (idempotency keys), created below.
92
+ IF (SELECT version FROM ${n.meta} WHERE id = 1) < 4 THEN
93
+ UPDATE ${n.meta} SET version = 4 WHERE id = 1;
94
+ END IF;
89
95
  END
90
96
  $plenipo$`,
91
97
  `SELECT ${n.upgrade}()`,
@@ -107,6 +113,21 @@ $plenipo$`,
107
113
  expires_at TIMESTAMPTZ NOT NULL
108
114
  )`,
109
115
  `CREATE INDEX IF NOT EXISTS ${n.prefix}request_sessions_expiry_idx ON ${n.sessions} (expires_at)`,
116
+ // Idempotency keys. `free` keeps a released key until it expires, so a late "executed" still lands;
117
+ // in_progress and unknown rows never expire: they block their key until reconciled.
118
+ `CREATE TABLE IF NOT EXISTS ${n.idempotency} (
119
+ key TEXT COLLATE "C" PRIMARY KEY CHECK (length(key) BETWEEN 1 AND 256),
120
+ fingerprint TEXT NOT NULL CHECK (length(fingerprint) BETWEEN 1 AND 256),
121
+ state TEXT NOT NULL CHECK (state IN ('in_progress', 'unknown', 'executed', 'free')),
122
+ attempt UUID NOT NULL,
123
+ reservation TEXT CHECK (reservation IS NULL OR length(reservation) BETWEEN 1 AND 256),
124
+ result TEXT,
125
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
126
+ lease_until TIMESTAMPTZ,
127
+ expires_at TIMESTAMPTZ
128
+ )`,
129
+ `CREATE INDEX IF NOT EXISTS ${n.prefix}idempotency_open_idx ON ${n.idempotency} (lease_until) WHERE state IN ('in_progress', 'unknown')`,
130
+ `CREATE INDEX IF NOT EXISTS ${n.prefix}idempotency_expiry_idx ON ${n.idempotency} (expires_at) WHERE state IN ('executed', 'free')`,
110
131
  // Reserve: all or nothing over every entry of the chain. Rows are created and then locked in key
111
132
  // order, so two reservations over overlapping chains always queue instead of deadlocking.
112
133
  // Runs as one statement: in READ COMMITTED each query below sees the rows as last committed.
@@ -519,3 +540,123 @@ export class PostgresMandateSessionStore {
519
540
  return toSafeInteger(rows[0]?.n ?? 0, 'count');
520
541
  }
521
542
  }
543
+ /**
544
+ * Idempotency keys shared by every instance. `claim` is one INSERT ... ON CONFLICT: under concurrency exactly
545
+ * one caller takes a free key, the others wait on the row and then see it held.
546
+ */
547
+ export class PostgresIdempotencyStore {
548
+ db;
549
+ n;
550
+ retentionSeconds;
551
+ leaseSeconds;
552
+ constructor(db, opts = {}) {
553
+ this.db = db;
554
+ this.n = names(opts);
555
+ this.retentionSeconds = idempotencyDuration('retentionSeconds', opts.retentionSeconds, 24 * 3600);
556
+ this.leaseSeconds = idempotencyDuration('leaseSeconds', opts.leaseSeconds, 300);
557
+ }
558
+ /** Columns of a live record, with an abandoned attempt shown as unknown. Free and expired rows are not live. */
559
+ select(where) {
560
+ return `SELECT key, fingerprint, attempt::text AS attempt, reservation, result,
561
+ CASE WHEN state = 'in_progress' AND lease_until <= now() THEN 'unknown' ELSE state END AS state
562
+ FROM ${this.n.idempotency}
563
+ WHERE ${where} AND state <> 'free' AND NOT (state = 'executed' AND expires_at <= now())`;
564
+ }
565
+ record(row) {
566
+ const state = String(row.state);
567
+ if (state !== 'in_progress' && state !== 'unknown' && state !== 'executed')
568
+ throw new TypeError('invalid idempotency state from the database');
569
+ return {
570
+ key: String(row.key),
571
+ fingerprint: String(row.fingerprint),
572
+ state,
573
+ attempt: String(row.attempt),
574
+ ...(row.reservation !== null && row.reservation !== undefined ? { reservation: String(row.reservation) } : {}),
575
+ ...(row.result !== null && row.result !== undefined ? { result: String(row.result) } : {}),
576
+ };
577
+ }
578
+ async claim(key, fingerprint) {
579
+ validateIdempotencyKey(key);
580
+ validateFingerprint(fingerprint);
581
+ const t = this.n.idempotency;
582
+ // A row seen as free (or expired) by the first statement can be taken by another instance before the
583
+ // second: try again a few times, then report the key as held by whoever took it.
584
+ for (let i = 0; i < 3; i++) {
585
+ const attempt = randomUUID();
586
+ const taken = rowsOf(await this.db.query(`INSERT INTO ${t} AS t (key, fingerprint, state, attempt, lease_until)
587
+ VALUES ($1, $2, 'in_progress', $3::uuid, now() + make_interval(secs => $4::double precision))
588
+ ON CONFLICT (key) DO UPDATE
589
+ SET fingerprint = EXCLUDED.fingerprint, state = 'in_progress', attempt = EXCLUDED.attempt,
590
+ reservation = NULL, result = NULL, created_at = now(), lease_until = EXCLUDED.lease_until, expires_at = NULL
591
+ WHERE t.state = 'free' OR (t.state = 'executed' AND t.expires_at <= now())
592
+ RETURNING attempt::text AS attempt`, [key, fingerprint, attempt, this.leaseSeconds]));
593
+ if (taken.length === 1 && String(taken[0].attempt) === attempt)
594
+ return { claimed: true, attempt };
595
+ const held = rowsOf(await this.db.query(this.select('key = $1'), [key]));
596
+ if (held.length === 1)
597
+ return { claimed: false, record: this.record(held[0]) };
598
+ }
599
+ throw new Error('the idempotency key could not be claimed or read');
600
+ }
601
+ async attach(key, attempt, reservation) {
602
+ validateIdempotencyKey(key);
603
+ if (!isAttemptId(attempt) || typeof reservation !== 'string' || reservation.length === 0 || reservation.length > 256)
604
+ return;
605
+ await this.db.query(`UPDATE ${this.n.idempotency} SET reservation = $3 WHERE key = $1 AND attempt = $2::uuid AND state IN ('in_progress', 'unknown')`, [key, attempt, reservation]);
606
+ }
607
+ async finish(key, attempt, outcome, result) {
608
+ validateIdempotencyKey(key);
609
+ validateOutcome(outcome);
610
+ validateResult(result);
611
+ if (!isAttemptId(attempt))
612
+ return;
613
+ const t = this.n.idempotency;
614
+ if (outcome === 'executed') {
615
+ // Also from free: proof that the action ran wins over an earlier "did not run".
616
+ await this.db.query(`UPDATE ${t} SET state = 'executed', result = $3, lease_until = NULL,
617
+ expires_at = now() + make_interval(secs => $4::double precision)
618
+ WHERE key = $1 AND attempt = $2::uuid AND state IN ('in_progress', 'unknown', 'free')`, [key, attempt, result ?? null, this.retentionSeconds]);
619
+ }
620
+ else if (outcome === 'not_executed') {
621
+ await this.db.query(`UPDATE ${t} SET state = 'free', result = NULL, lease_until = NULL,
622
+ expires_at = now() + make_interval(secs => $3::double precision)
623
+ WHERE key = $1 AND attempt = $2::uuid AND state IN ('in_progress', 'unknown')`, [key, attempt, this.retentionSeconds]);
624
+ }
625
+ else {
626
+ await this.db.query(`UPDATE ${t} SET state = 'unknown' WHERE key = $1 AND attempt = $2::uuid AND state = 'in_progress'`, [key, attempt]);
627
+ }
628
+ }
629
+ async resolve(key, outcome, attempt) {
630
+ validateIdempotencyKey(key);
631
+ if (outcome !== 'executed' && outcome !== 'not_executed')
632
+ throw new RangeError('outcome must be executed or not_executed');
633
+ if (!isAttemptId(attempt))
634
+ throw new RangeError('resolve needs the attempt that holds the key');
635
+ const rows = rowsOf(await this.db.query(`UPDATE ${this.n.idempotency} SET state = $2, lease_until = NULL,
636
+ expires_at = now() + make_interval(secs => $3::double precision)
637
+ WHERE key = $1 AND attempt = $4::uuid AND state IN ('in_progress', 'unknown')
638
+ RETURNING 1 AS ok`, [key, outcome === 'executed' ? 'executed' : 'free', this.retentionSeconds, attempt]));
639
+ return rows.length === 1;
640
+ }
641
+ async get(key) {
642
+ validateIdempotencyKey(key);
643
+ const rows = rowsOf(await this.db.query(this.select('key = $1'), [key]));
644
+ return rows.length === 1 ? this.record(rows[0]) : undefined;
645
+ }
646
+ async unresolved(opts = {}) {
647
+ const limit = positiveInt('limit', opts.limit, 100, 10_000);
648
+ const rows = rowsOf(await this.db.query(`${this.select(`(state = 'unknown' OR (state = 'in_progress' AND lease_until <= now()))`)} ORDER BY created_at LIMIT $1::integer`, [limit]));
649
+ return rows.map((r) => this.record(r));
650
+ }
651
+ /** Deletes executed and free records past their retention. Returns how many were deleted. */
652
+ async sweep(opts = {}) {
653
+ const limit = positiveInt('limit', opts.limit, 10_000);
654
+ const t = this.n.idempotency;
655
+ const rows = rowsOf(await this.db.query(`WITH gone AS (
656
+ DELETE FROM ${t} WHERE ctid IN (
657
+ SELECT ctid FROM ${t} WHERE state IN ('executed', 'free') AND expires_at <= now() LIMIT $1::integer)
658
+ RETURNING 1)
659
+ SELECT count(*) AS n FROM gone`, [limit]));
660
+ return toSafeInteger(rows[0]?.n ?? 0, 'count');
661
+ }
662
+ }
@@ -1,6 +1,7 @@
1
1
  import type { MandateRequestSession } from '../openid4vp.js';
2
2
  import type { LedgerEntry, NonceStore, SpendingLedger } from '../registry.js';
3
3
  import type { Amount } from '../types.js';
4
+ import { type AttemptOutcome, type IdempotencyClaim, type IdempotencyRecord, type IdempotencyStore, type IdempotencyStoreOptions } from '../idempotency.js';
4
5
  import { type ManagedRevocationRegistry, type MandateSessionStore, type ReconcileOutcome, type ReservationInfo, type ReservationState } from './common.js';
5
6
  /** The commands the stores need, in a driver-neutral shape. Arguments are always strings. */
6
7
  export interface RedisClient {
@@ -130,3 +131,27 @@ export declare class RedisMandateSessionStore implements MandateSessionStore {
130
131
  get(id: string): Promise<MandateRequestSession | undefined>;
131
132
  delete(id: string): Promise<void>;
132
133
  }
134
+ /** Idempotency keys in Redis: every operation is one Lua script, so a claim and its check cannot interleave. */
135
+ export declare class RedisIdempotencyStore implements IdempotencyStore {
136
+ private readonly redis;
137
+ private readonly tag;
138
+ readonly retentionSeconds: number;
139
+ readonly leaseSeconds: number;
140
+ constructor(redis: RedisClient, opts?: IdempotencyStoreOptions & {
141
+ prefix?: string;
142
+ });
143
+ /** Keys are hashed into names, so a caller-chosen key cannot inject a hash tag or grow keys. */
144
+ private member;
145
+ private rec;
146
+ private get open();
147
+ private parse;
148
+ private get retentionMs();
149
+ claim(key: string, fingerprint: string): Promise<IdempotencyClaim>;
150
+ attach(key: string, attempt: string, reservation: string): Promise<void>;
151
+ finish(key: string, attempt: string, outcome: AttemptOutcome, result?: string): Promise<void>;
152
+ resolve(key: string, outcome: 'executed' | 'not_executed', attempt: string): Promise<boolean>;
153
+ get(key: string): Promise<IdempotencyRecord | undefined>;
154
+ unresolved(opts?: {
155
+ limit?: number;
156
+ }): Promise<IdempotencyRecord[]>;
157
+ }
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { createHash, randomUUID } from 'node:crypto';
14
14
  import { sha256 } from '../encoding.js';
15
+ import { idempotencyDuration, isAttemptId, validateFingerprint, validateIdempotencyKey, validateOutcome, validateResult, } from '../idempotency.js';
15
16
  import { deserializeSession, durationSeconds, isReservationId, nonceDigest, normalizeEntries, positiveInt, serializeSession, toSafeInteger, validateAmount, validateCurrency, validateKey, validateMandateId, validateSessionId, } from './common.js';
16
17
  /** Adapts an ioredis `Redis` or `Cluster` instance. */
17
18
  export function fromIoredis(client) {
@@ -404,3 +405,183 @@ export class RedisMandateSessionStore {
404
405
  await DEL.run(this.redis, [this.k(id)], []);
405
406
  }
406
407
  }
408
+ // Idempotency records: one hash per key, `{<prefix>:idem}:k:<sha256(key)>`, with fields key, fp, state,
409
+ // attempt, res, result, lease (ms). Executed and free records carry a TTL; in_progress and unknown records
410
+ // carry none and sit in the `open` sorted set (score: lease end for in_progress, 0 for unknown), which is
411
+ // what `unresolved` reads. `free` keeps a released key until it expires, so a late "executed" still lands.
412
+ // Reads a live record into a flat reply: {state, key, fp, attempt, res, hasResult, result}, or nil.
413
+ const IDEM_READ = `
414
+ local function read(rec)
415
+ local st = redis.call('HGET', rec, 'state')
416
+ if not st or st == 'free' then return nil end
417
+ if st == 'in_progress' and tonumber(redis.call('HGET', rec, 'lease') or '0') <= now then st = 'unknown' end
418
+ local v = redis.call('HMGET', rec, 'key', 'fp', 'attempt', 'res', 'result')
419
+ local hasResult = '0'
420
+ if v[5] then hasResult = '1' end
421
+ return {st, v[1] or '', v[2] or '', v[3] or '', v[4] or '', hasResult, v[5] or ''}
422
+ end
423
+ `;
424
+ // KEYS: record, open. ARGV: key, fingerprint, attempt, lease ms, member.
425
+ const IDEM_CLAIM = new Script(`${NOW}${IDEM_READ}
426
+ local held = read(KEYS[1])
427
+ if held then return {0, held} end
428
+ redis.call('DEL', KEYS[1])
429
+ local lease = now + tonumber(ARGV[4])
430
+ redis.call('HSET', KEYS[1], 'key', ARGV[1], 'fp', ARGV[2], 'state', 'in_progress', 'attempt', ARGV[3], 'lease', lease)
431
+ redis.call('ZADD', KEYS[2], lease, ARGV[5])
432
+ return {1}
433
+ `);
434
+ // KEYS: record. ARGV: attempt, reservation.
435
+ const IDEM_ATTACH = new Script(`
436
+ local st = redis.call('HGET', KEYS[1], 'state')
437
+ if (st == 'in_progress' or st == 'unknown') and redis.call('HGET', KEYS[1], 'attempt') == ARGV[1] then
438
+ redis.call('HSET', KEYS[1], 'res', ARGV[2])
439
+ return 1
440
+ end
441
+ return 0
442
+ `);
443
+ // KEYS: record, open. ARGV: attempt, outcome, retention ms, member, hasResult, result.
444
+ const IDEM_FINISH = new Script(`
445
+ local st = redis.call('HGET', KEYS[1], 'state')
446
+ if not st or st == 'executed' or redis.call('HGET', KEYS[1], 'attempt') ~= ARGV[1] then return 0 end
447
+ local outcome = ARGV[2]
448
+ if outcome == 'executed' then
449
+ -- Also from free: proof that the action ran wins over an earlier "did not run".
450
+ redis.call('HSET', KEYS[1], 'state', 'executed')
451
+ if ARGV[5] == '1' then redis.call('HSET', KEYS[1], 'result', ARGV[6]) end
452
+ redis.call('HDEL', KEYS[1], 'lease')
453
+ redis.call('PEXPIRE', KEYS[1], tonumber(ARGV[3]))
454
+ redis.call('ZREM', KEYS[2], ARGV[4])
455
+ return 1
456
+ end
457
+ if st == 'free' then return 0 end
458
+ if outcome == 'not_executed' then
459
+ redis.call('HSET', KEYS[1], 'state', 'free')
460
+ redis.call('HDEL', KEYS[1], 'result', 'lease')
461
+ redis.call('PEXPIRE', KEYS[1], tonumber(ARGV[3]))
462
+ redis.call('ZREM', KEYS[2], ARGV[4])
463
+ return 1
464
+ end
465
+ if st == 'in_progress' then
466
+ redis.call('HSET', KEYS[1], 'state', 'unknown')
467
+ redis.call('ZADD', KEYS[2], 0, ARGV[4])
468
+ end
469
+ return 1
470
+ `);
471
+ // KEYS: record, open. ARGV: outcome (executed | not_executed), retention ms, member, attempt.
472
+ const IDEM_RESOLVE = new Script(`
473
+ local st = redis.call('HGET', KEYS[1], 'state')
474
+ if st ~= 'in_progress' and st ~= 'unknown' then return 0 end
475
+ if redis.call('HGET', KEYS[1], 'attempt') ~= ARGV[4] then return 0 end
476
+ if ARGV[1] == 'executed' then redis.call('HSET', KEYS[1], 'state', 'executed') else redis.call('HSET', KEYS[1], 'state', 'free') end
477
+ redis.call('HDEL', KEYS[1], 'lease')
478
+ redis.call('PEXPIRE', KEYS[1], tonumber(ARGV[2]))
479
+ redis.call('ZREM', KEYS[2], ARGV[3])
480
+ return 1
481
+ `);
482
+ // KEYS: record. Reads one live record.
483
+ const IDEM_GET = new Script(`${NOW}${IDEM_READ}
484
+ local r = read(KEYS[1])
485
+ if r then return r end
486
+ return false
487
+ `);
488
+ // KEYS: open. ARGV: limit. Members whose attempt is unknown or past its lease.
489
+ const IDEM_OPEN = new Script(`${NOW}
490
+ return redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now, 'LIMIT', 0, tonumber(ARGV[1]))
491
+ `);
492
+ /** Idempotency keys in Redis: every operation is one Lua script, so a claim and its check cannot interleave. */
493
+ export class RedisIdempotencyStore {
494
+ redis;
495
+ tag;
496
+ retentionSeconds;
497
+ leaseSeconds;
498
+ constructor(redis, opts = {}) {
499
+ this.redis = redis;
500
+ this.tag = `{${checkPrefix(opts.prefix)}:idem}`;
501
+ this.retentionSeconds = idempotencyDuration('retentionSeconds', opts.retentionSeconds, 24 * 3600);
502
+ this.leaseSeconds = idempotencyDuration('leaseSeconds', opts.leaseSeconds, 300);
503
+ }
504
+ /** Keys are hashed into names, so a caller-chosen key cannot inject a hash tag or grow keys. */
505
+ member(key) {
506
+ validateIdempotencyKey(key);
507
+ return sha256(key);
508
+ }
509
+ rec(member) {
510
+ return `${this.tag}:k:${member}`;
511
+ }
512
+ get open() {
513
+ return `${this.tag}:open`;
514
+ }
515
+ parse(reply) {
516
+ if (!Array.isArray(reply))
517
+ return undefined;
518
+ const [state, key, fingerprint, attempt, res, hasResult, result] = reply.map((x) => (x === null || x === undefined ? '' : String(x)));
519
+ if (state !== 'in_progress' && state !== 'unknown' && state !== 'executed')
520
+ throw new TypeError('invalid idempotency state from Redis');
521
+ return {
522
+ key,
523
+ fingerprint,
524
+ state: state,
525
+ attempt,
526
+ ...(res ? { reservation: res } : {}),
527
+ ...(hasResult === '1' ? { result } : {}),
528
+ };
529
+ }
530
+ get retentionMs() {
531
+ return Math.max(1, Math.round(this.retentionSeconds * 1000));
532
+ }
533
+ async claim(key, fingerprint) {
534
+ validateFingerprint(fingerprint);
535
+ const m = this.member(key);
536
+ const attempt = randomUUID();
537
+ const r = await IDEM_CLAIM.run(this.redis, [this.rec(m), this.open], [key, fingerprint, attempt, String(Math.max(1, Math.round(this.leaseSeconds * 1000))), m]);
538
+ if (!Array.isArray(r))
539
+ throw new TypeError('unexpected reply from Redis');
540
+ if (Number(r[0]) === 1)
541
+ return { claimed: true, attempt };
542
+ const record = this.parse(r[1]);
543
+ if (!record)
544
+ throw new TypeError('unexpected reply from Redis');
545
+ return { claimed: false, record };
546
+ }
547
+ async attach(key, attempt, reservation) {
548
+ const m = this.member(key);
549
+ if (!isAttemptId(attempt) || typeof reservation !== 'string' || reservation.length === 0 || reservation.length > 256)
550
+ return;
551
+ await IDEM_ATTACH.run(this.redis, [this.rec(m)], [attempt, reservation]);
552
+ }
553
+ async finish(key, attempt, outcome, result) {
554
+ const m = this.member(key);
555
+ validateOutcome(outcome);
556
+ validateResult(result);
557
+ if (!isAttemptId(attempt))
558
+ return;
559
+ await IDEM_FINISH.run(this.redis, [this.rec(m), this.open], [attempt, outcome, String(this.retentionMs), m, result === undefined ? '0' : '1', result ?? '']);
560
+ }
561
+ async resolve(key, outcome, attempt) {
562
+ const m = this.member(key);
563
+ if (outcome !== 'executed' && outcome !== 'not_executed')
564
+ throw new RangeError('outcome must be executed or not_executed');
565
+ if (!isAttemptId(attempt))
566
+ throw new RangeError('resolve needs the attempt that holds the key');
567
+ const r = await IDEM_RESOLVE.run(this.redis, [this.rec(m), this.open], [outcome, String(this.retentionMs), m, attempt]);
568
+ return Number(r) === 1;
569
+ }
570
+ async get(key) {
571
+ const m = this.member(key);
572
+ return this.parse(await IDEM_GET.run(this.redis, [this.rec(m)], []));
573
+ }
574
+ async unresolved(opts = {}) {
575
+ const limit = positiveInt('limit', opts.limit, 100, 10_000);
576
+ const members = await IDEM_OPEN.run(this.redis, [this.open], [String(limit)]);
577
+ if (!Array.isArray(members))
578
+ return [];
579
+ const out = [];
580
+ for (const m of members) {
581
+ const r = this.parse(await IDEM_GET.run(this.redis, [this.rec(String(m))], []));
582
+ if (r && r.state === 'unknown')
583
+ out.push(r);
584
+ }
585
+ return out;
586
+ }
587
+ }
package/dist/types.d.ts CHANGED
@@ -107,6 +107,11 @@ export interface InvocationPayload {
107
107
  args_hash?: string;
108
108
  /** Hash of the mandate chain presented with the invocation (see `chainHash`). Required by the verifier. */
109
109
  chain_hash: string;
110
+ /**
111
+ * Idempotency key: the same value in every attempt of one intention, so that at most one attempt runs
112
+ * (see `src/idempotency.ts`). Requires `args_hash`.
113
+ */
114
+ idem?: string;
110
115
  }
111
116
  export interface TrustedIssuer {
112
117
  iss: string;
@@ -120,6 +125,14 @@ export interface TrustedIssuer {
120
125
  export type DenyCode = 'CONFIGURATION' | 'MALFORMED' | 'INVOCATION_MISMATCH' | 'ROOT_INVALID' | 'PID_ISSUER_UNTRUSTED' | 'PID_REVOKED' | 'TX_DATA_MISMATCH' | 'LIFETIME_POLICY' | 'DELEGATION_SIGNATURE_INVALID' | 'DELEGATION_PARENT_MISMATCH' | 'DELEGATION_NOT_ALLOWED' | 'ATTENUATION_VIOLATION' | 'NOT_YET_VALID' | 'EXPIRED' | 'REVOKED' | 'INVOCATION_SIGNATURE_INVALID' | 'INVOCATION_MANDATE_MISMATCH' | 'INVOCATION_STALE' | 'AUDIENCE_MISMATCH' | 'REPLAY' | 'ACTION_NOT_PERMITTED' | 'COUNTERPARTY_NOT_PERMITTED' | 'CURRENCY_MISMATCH' | 'LIMIT_PER_OPERATION' | 'LIMIT_TOTAL' | 'DISPLAY_MISMATCH' | 'ROOT_POLICY' | 'ATTESTATION_UNTRUSTED' | 'ATTESTATION_INVALID' | 'ATTESTATION_REVOKED' | 'ROLE_EXCEEDED'
121
126
  /** A status list or revocation source could not be fetched or verified. Still a denial; a retry may succeed. */
122
127
  | 'STATUS_UNAVAILABLE'
128
+ /** The idempotency key was already used for a different request. */
129
+ | 'IDEMPOTENCY_CONFLICT'
130
+ /** An attempt with this idempotency key is still running; a retry later may get its result. */
131
+ | 'IDEMPOTENCY_IN_PROGRESS'
132
+ /** An attempt with this idempotency key ended with an unknown outcome; the service must reconcile it first. */
133
+ | 'IDEMPOTENCY_UNRESOLVED'
134
+ /** An attempt with this idempotency key already executed; the decision may carry its stored result. */
135
+ | 'ALREADY_EXECUTED'
123
136
  /** An unexpected error (a store or registry that threw). Details only in `detail`. */
124
137
  | 'INTERNAL';
125
138
  export interface PathEntry {
@@ -151,6 +164,15 @@ export type Decision = {
151
164
  * after performing the action, or release it if the action does not happen.
152
165
  */
153
166
  reservation?: string;
167
+ /**
168
+ * Present when the invocation carries an idempotency key: the attempt that now holds it. The caller
169
+ * must end it on the idempotency store with the outcome of the action (`finish`), as it settles the
170
+ * reservation; an attempt never ended blocks the key until reconciled.
171
+ */
172
+ idempotency?: {
173
+ key: string;
174
+ attempt: string;
175
+ };
154
176
  /**
155
177
  * RFC 7638 SHA-256 thumbprint of the PID holder key (`cnf.jwk`). Distinguishes people with the same
156
178
  * name; a wallet that uses a fresh key per PID copy yields a different value per copy.
@@ -165,6 +187,10 @@ export type Decision = {
165
187
  /** Internal detail for logs (network errors, library messages). The MCP guard never returns it. */
166
188
  detail?: string;
167
189
  path: PathEntry[];
190
+ /** With `ALREADY_EXECUTED`: what the service stored when the first attempt ran, if it kept anything. */
191
+ replay?: {
192
+ result?: string;
193
+ };
168
194
  };
169
195
  /** Principal of a Decision whose root mandate was given on behalf of a legal person. */
170
196
  export interface LegalPersonPrincipal {
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. */