@owlmeans/auth-common 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@ Predefined authentication protocols, guards, and constants shared between server
12
12
  ## Installation
13
13
 
14
14
  ```bash
15
- bun add @owlmeans/auth-common@^0.2.2
15
+ bun add @owlmeans/auth-common@^0.2.3
16
16
  ```
17
17
 
18
18
  ## Usage
@@ -122,7 +122,7 @@ This package ships embedded agent skills under `agent-meta/`. After installing y
122
122
  your project's skill store (`.agents/skills/`):
123
123
 
124
124
  ```sh
125
- npx @owlmeans/agent-skills@^0.2.2
125
+ npx @owlmeans/agent-skills@^0.2.3
126
126
  ```
127
127
 
128
128
  The embedded files are version-matched to this package release. Do not edit them
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 3,
3
3
  "package": "@owlmeans/auth-common",
4
- "version": "0.2.2",
5
- "generatedAt": "2026-11-21T09:26:21.977Z",
4
+ "version": "0.2.3",
5
+ "generatedAt": "2026-11-23T12:48:29.714Z",
6
6
  "canonicalRepo": "https://github.com/owlmeans/common",
7
7
  "entries": [
8
8
  {
@@ -8,7 +8,7 @@ user-invocable: false
8
8
  # @owlmeans/auth-common
9
9
 
10
10
  **Layer:** Core
11
- **Install:** `"@owlmeans/auth-common": "^0.2.2"` in `dependencies`
11
+ **Install:** `"@owlmeans/auth-common": "^0.2.3"` in `dependencies`
12
12
 
13
13
  Everything a server and a browser must agree on to talk authentication: aliases, the shared
14
14
  protocol declarations, the signature guard, and the contract for resolving the organization
@@ -28,7 +28,7 @@ entity a token names.
28
28
  | `ENTITY_RESOLVER` | `'entity-resolver'` — the organization-entity resolver's service alias |
29
29
  | `ENTITY_SLUG_PATTERN` | A lowercase DNS label. Slugs compose hostnames, cluster object names and OIDC client ids, so anything needing sanitising is rejected where it is chosen |
30
30
  | `RELY_PIN_PERFIX`, `RELY_TOKEN_PREFIX`, `RELY_CALL_TIMEOUT`, `RELY_ACTION_TIMEOUT` | Rely-handshake constants |
31
- | `BED255_TIME_HEADER`, `BED255_NONCE_HEADER`, `BED255_SIG_TTL`, `BED255_CASHE_RESOURCE` | Ed25519 signature-guard headers, replay window and nonce-cache alias |
31
+ | `BED255_TIME_HEADER`, `BED255_NONCE_HEADER`, `BED255_SIG_TTL`, `BED255_DELIVERY_TTL`, `BED255_CASHE_RESOURCE` | Ed25519 signature-guard headers, replay window, a queued claim's lifetime and nonce-cache alias |
32
32
  | `authApi` | Alias tree for the manager API entrypoints (`profile`, `entity`, `auth`) |
33
33
 
34
34
  ### Entrypoints, guard and middleware
@@ -142,6 +142,22 @@ token's slug only; both write `'-'` when neither is available. Read the gate you
142
142
  accepts only canonical timestamps inside its symmetric 60-second window and claims the
143
143
  credential-and-nonce pair until that timestamp's absolute expiry; a replay-store error refuses
144
144
  authentication rather than disabling deduplication.
145
+ - **A queued request's redelivery is not a replay.** A request the queue bridge rebuilt from a job
146
+ carries `delivery` (`{ id: '<queue>:<job id>', attempt }`, in-process only, never from the wire).
147
+ Its claim is bound to that id (`claim(id, expiresAt, owner)`) and lives `deliveryTtl` (default
148
+ `BED255_DELIVERY_TTL`, 1 h) past the first admission. The SAME job at a later attempt (a stall, a
149
+ retry) is admitted on the claim it holds (`holder(id) === delivery.id`) — inside the window and,
150
+ because the claim proves an in-window first admission, past it. The same nonce on another job, on
151
+ the same job's first attempt, or over HTTP stays a replay (`nonce`), and a request past the window
152
+ with no such claim stays `expired`. A custom `SignedRequestReplayStore` without `holder` (or a
153
+ resource without `load`) recognises no redelivery.
154
+ - **A queued request is judged fresh at its enqueue.** A delivery carrying `enqueuedAt` (the broker's
155
+ own stamp) AND `maxAge` (the queue's `envelopeTtl`) is fresh when its signature lies within 60 s of
156
+ that enqueue and the enqueue within `maxAge` of now — a job that waited behind a backlog or a deploy
157
+ gap is admitted; one past the queue's window is `expired`, redelivery or not. Its claim then lives
158
+ until `signedAt + 60 s + maxAge` (or `deliveryTtl` from now, whichever is later), so a copy of it
159
+ that could still pass the enqueue test always meets the claim. A delivery without both, and every
160
+ HTTP request, keeps the 60-second window at arrival.
145
161
  - A process that holds a trusted record's private key but no context (a Node test helper, a
146
162
  script) signs with `signBasicEd25519Request`, never a re-derived copy: `credential` is the
147
163
  record's `id` (OwlMeans deployments use the key's address, `ed25519:<address>`), `key` a
@@ -2,5 +2,11 @@ export declare const GUARD_ED25519 = "guard:ed25519-basic-signature";
2
2
  export declare const BED255_TIME_HEADER = "X-Auth-Time";
3
3
  export declare const BED255_NONCE_HEADER = "X-Auth-Nonce";
4
4
  export declare const BED255_SIG_TTL: number;
5
+ /**
6
+ * How long a nonce claimed by a QUEUED request (one that carries `delivery`) stays bound to its job:
7
+ * the broker's own redelivery of that job (a stall, a retry) is admitted on that claim — past the
8
+ * signature's window too — for this long after the first admission.
9
+ */
10
+ export declare const BED255_DELIVERY_TTL: number;
5
11
  export declare const BED255_CASHE_RESOURCE = "basic-ed25519-nonce-cache";
6
12
  //# sourceMappingURL=consts.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/consts.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa,kCAAqD,CAAA;AAE/E,eAAO,MAAM,kBAAkB,gBAAgB,CAAA;AAC/C,eAAO,MAAM,mBAAmB,iBAAiB,CAAA;AAEjD,eAAO,MAAM,cAAc,QAAY,CAAA;AAEvC,eAAO,MAAM,qBAAqB,8BAA8B,CAAA"}
1
+ {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/consts.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa,kCAAqD,CAAA;AAE/E,eAAO,MAAM,kBAAkB,gBAAgB,CAAA;AAC/C,eAAO,MAAM,mBAAmB,iBAAiB,CAAA;AAEjD,eAAO,MAAM,cAAc,QAAY,CAAA;AAEvC;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,QAAiB,CAAA;AAEjD,eAAO,MAAM,qBAAqB,8BAA8B,CAAA"}
@@ -3,5 +3,11 @@ export const GUARD_ED25519 = `guard:${AuthroizationType.Ed25519BasicSignature}`;
3
3
  export const BED255_TIME_HEADER = 'X-Auth-Time';
4
4
  export const BED255_NONCE_HEADER = 'X-Auth-Nonce';
5
5
  export const BED255_SIG_TTL = 60 * 1000;
6
+ /**
7
+ * How long a nonce claimed by a QUEUED request (one that carries `delivery`) stays bound to its job:
8
+ * the broker's own redelivery of that job (a stall, a retry) is admitted on that claim — past the
9
+ * signature's window too — for this long after the first admission.
10
+ */
11
+ export const BED255_DELIVERY_TTL = 60 * 60 * 1000;
6
12
  export const BED255_CASHE_RESOURCE = 'basic-ed25519-nonce-cache';
7
13
  //# sourceMappingURL=consts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"consts.js","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/consts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAElD,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,iBAAiB,CAAC,qBAAqB,EAAE,CAAA;AAE/E,MAAM,CAAC,MAAM,kBAAkB,GAAG,aAAa,CAAA;AAC/C,MAAM,CAAC,MAAM,mBAAmB,GAAG,cAAc,CAAA;AAEjD,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,CAAA;AAEvC,MAAM,CAAC,MAAM,qBAAqB,GAAG,2BAA2B,CAAA"}
1
+ {"version":3,"file":"consts.js","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/consts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAElD,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,iBAAiB,CAAC,qBAAqB,EAAE,CAAA;AAE/E,MAAM,CAAC,MAAM,kBAAkB,GAAG,aAAa,CAAA;AAC/C,MAAM,CAAC,MAAM,mBAAmB,GAAG,cAAc,CAAA;AAEjD,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,CAAA;AAEvC;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA;AAEjD,MAAM,CAAC,MAAM,qBAAqB,GAAG,2BAA2B,CAAA"}
@@ -8,7 +8,8 @@ export declare const makeMemorySignedRequestReplayStore: () => SignedRequestRepl
8
8
  /**
9
9
  * Adapt a create-once Resource to signed-request replay protection. Redis resources honour the
10
10
  * absolute expiry and make the claim atomic across replicas (`SET NX`); other resource failures
11
- * remain failures rather than being mistaken for successful claims.
11
+ * remain failures rather than being mistaken for successful claims. The claim's `owner` is stored
12
+ * on the record, and read back through `load` when the resource has one.
12
13
  */
13
14
  export declare const makeResourceSignedRequestReplayStore: (resource: SignedRequestReplayResource) => SignedRequestReplayStore;
14
15
  //# sourceMappingURL=replay.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"replay.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/replay.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAEvF;;;;GAIG;AACH,eAAO,MAAM,kCAAkC,QAAO,wBAwBrD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oCAAoC,aACrC,2BAA2B,KACpC,wBAaD,CAAA"}
1
+ {"version":3,"file":"replay.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/replay.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAGvF;;;;GAIG;AACH,eAAO,MAAM,kCAAkC,QAAO,wBA+BrD,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,oCAAoC,aACrC,2BAA2B,KACpC,wBAyBF,CAAA"}
@@ -6,44 +6,61 @@ import { RecordExists } from '@owlmeans/resource';
6
6
  */
7
7
  export const makeMemorySignedRequestReplayStore = () => {
8
8
  const claims = new Map();
9
+ const live = (id) => {
10
+ const current = claims.get(id);
11
+ return current != null && current.expiry > Date.now() ? current : null;
12
+ };
9
13
  return {
10
- claim: async (id, expiresAt) => {
11
- const now = Date.now();
12
- const current = claims.get(id);
13
- if (current != null && current > now) {
14
+ claim: async (id, expiresAt, owner) => {
15
+ if (live(id) != null) {
14
16
  return false;
15
17
  }
18
+ const now = Date.now();
16
19
  const expiry = expiresAt.getTime();
17
- claims.set(id, expiry);
20
+ const claim = owner != null ? { expiry, owner } : { expiry };
21
+ claims.set(id, claim);
18
22
  const timer = setTimeout(() => {
19
- if (claims.get(id) === expiry) {
23
+ if (claims.get(id) === claim) {
20
24
  claims.delete(id);
21
25
  }
22
26
  }, Math.max(0, expiry - now));
23
27
  const unref = timer.unref;
24
28
  unref?.call(timer);
25
29
  return true;
26
- }
30
+ },
31
+ holder: async (id) => live(id)?.owner ?? null,
27
32
  };
28
33
  };
29
34
  /**
30
35
  * Adapt a create-once Resource to signed-request replay protection. Redis resources honour the
31
36
  * absolute expiry and make the claim atomic across replicas (`SET NX`); other resource failures
32
- * remain failures rather than being mistaken for successful claims.
37
+ * remain failures rather than being mistaken for successful claims. The claim's `owner` is stored
38
+ * on the record, and read back through `load` when the resource has one.
33
39
  */
34
- export const makeResourceSignedRequestReplayStore = (resource) => ({
35
- claim: async (id, expiresAt) => {
36
- try {
37
- await resource.create({ id }, { ttl: expiresAt });
38
- return true;
39
- }
40
- catch (error) {
41
- if (error instanceof RecordExists
42
- || error?.type === RecordExists.typeName) {
43
- return false;
40
+ export const makeResourceSignedRequestReplayStore = (resource) => {
41
+ const store = {
42
+ claim: async (id, expiresAt, owner) => {
43
+ try {
44
+ // The owner rides the record beside its id: a claim is a plain record to the resource.
45
+ const record = owner != null ? { id, owner } : { id };
46
+ await resource.create(record, { ttl: expiresAt });
47
+ return true;
44
48
  }
45
- throw error;
46
- }
49
+ catch (error) {
50
+ if (error instanceof RecordExists
51
+ || error?.type === RecordExists.typeName) {
52
+ return false;
53
+ }
54
+ throw error;
55
+ }
56
+ },
57
+ };
58
+ if (resource.load != null) {
59
+ store.holder = async (id) => {
60
+ const owner = (await resource.load?.(id))?.owner;
61
+ return typeof owner === 'string' && owner !== '' ? owner : null;
62
+ };
47
63
  }
48
- });
64
+ return store;
65
+ };
49
66
  //# sourceMappingURL=replay.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"replay.js","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/replay.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAGjD;;;;GAIG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,GAA6B,EAAE;IAC/E,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAA;IAExC,OAAO;QACL,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE;YAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;YACtB,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;YAC9B,IAAI,OAAO,IAAI,IAAI,IAAI,OAAO,GAAG,GAAG,EAAE,CAAC;gBACrC,OAAO,KAAK,CAAA;YACd,CAAC;YAED,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,EAAE,CAAA;YAClC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;YACtB,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBAC5B,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,MAAM,EAAE,CAAC;oBAC9B,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;gBACnB,CAAC;YACH,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,CAAC,CAAA;YAC7B,MAAM,KAA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IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,CAAA;gBACzE,MAAM,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC,CAAA;gBACjD,OAAO,IAAI,CAAA;YACb,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,KAAK,YAAY,YAAY;uBAC3B,KAAmC,EAAE,IAAI,KAAK,YAAY,CAAC,QAAQ,EAAE,CAAC;oBAC1E,OAAO,KAAK,CAAA;gBACd,CAAC;gBACD,MAAM,KAAK,CAAA;YACb,CAAC;QACH,CAAC;KACF,CAAA;IACD,IAAI,QAAQ,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;QAC1B,KAAK,CAAC,MAAM,GAAG,KAAK,EAAC,EAAE,EAAC,EAAE;YACxB,MAAM,KAAK,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,CAA4C,CAAA,EAAE,KAAK,CAAA;YAC1F,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;QACjE,CAAC,CAAA;IACH,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/service.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAW7E,eAAO,MAAM,qBAAqB,aAAc,MAAM,SAAS,wBAAwB,KAAG,iBA+HzF,CAAA"}
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/service.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAY7E,eAAO,MAAM,qBAAqB,aAAc,MAAM,SAAS,wBAAwB,KAAG,iBA+JzF,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { createService } from '@owlmeans/context';
2
2
  import { assertContext } from '@owlmeans/context';
3
- import { BED255_CASHE_RESOURCE, GUARD_ED25519, BED255_SIG_TTL } from './consts.js';
3
+ import { BED255_CASHE_RESOURCE, BED255_DELIVERY_TTL, GUARD_ED25519, BED255_SIG_TTL } from './consts.js';
4
4
  import { nonceKey, timeKey } from './consts.local.js';
5
5
  import { trust } from '../../utils/trusted.js';
6
6
  import { AuthenPayloadError, AuthroizationType, AuthRole } from '@owlmeans/auth';
@@ -72,22 +72,54 @@ export const makeBasicEd25519Guard = (resource, opts) => {
72
72
  if (!Number.isFinite(signedAt) || createdAt.toISOString() !== timestamp) {
73
73
  throw new AuthenPayloadError('timestamp');
74
74
  }
75
- if (Math.abs(Date.now() - signedAt) > BED255_SIG_TTL) {
76
- throw new AuthenPayloadError('expired');
77
- }
75
+ const now = Date.now();
76
+ const delivery = req.delivery;
77
+ // A request the queue delivers is judged fresh at its ENQUEUE — the broker's own record of when
78
+ // it took the job in (never the job's data) — and stays deliverable for the queue's own window
79
+ // (`maxAge`): a job that waited behind a backlog or a deploy gap is not refused for the wait.
80
+ // Without both, and for every HTTP request, the signature is judged at arrival, as always.
81
+ const queued = delivery?.enqueuedAt != null && delivery.maxAge != null
82
+ && Number.isFinite(delivery.enqueuedAt) && Number.isFinite(delivery.maxAge) && delivery.maxAge > 0
83
+ ? { enqueuedAt: delivery.enqueuedAt, maxAge: delivery.maxAge } : null;
84
+ const expired = queued != null
85
+ ? Math.abs(queued.enqueuedAt - signedAt) > BED255_SIG_TTL || queued.enqueuedAt - now > BED255_SIG_TTL
86
+ || now - queued.enqueuedAt > queued.maxAge
87
+ : Math.abs(now - signedAt) > BED255_SIG_TTL;
78
88
  if (typeof nonce !== 'string' || nonce.length === 0) {
79
- throw new AuthenPayloadError('nonce');
89
+ throw new AuthenPayloadError(expired ? 'expired' : 'nonce');
80
90
  }
81
- try {
82
- // The replay identity is the signing credential plus its nonce. A nonce used by one
83
- // trusted service does not block another, while a captured request can be admitted once.
84
- const claimed = await replay(context).claim(`${signature.credential.length}:${signature.credential}${nonce}`, new Date(signedAt + BED255_SIG_TTL));
85
- if (!claimed) {
86
- throw new AuthenPayloadError('nonce');
91
+ // The replay identity is the signing credential plus its nonce. A nonce used by one trusted
92
+ // service does not block another, while a captured request can be admitted once.
93
+ const claimId = `${signature.credential.length}:${signature.credential}${nonce}`;
94
+ const store = replay(context);
95
+ // A queued request names its delivery (`<queue>:<job id>`, set in-process by the queue bridge,
96
+ // never from the wire). Its claim is bound to that job, and only the broker's own redelivery
97
+ // of the SAME job — a later attempt, after a stall or a failed attempt — presents it again
98
+ // and is admitted: the same nonce on another job, or over HTTP, is still a replay.
99
+ const redelivered = async () => delivery != null && delivery.attempt > 1 && store.holder != null
100
+ && await store.holder(claimId) === delivery.id;
101
+ if (expired) {
102
+ // Past the window only a redelivery stands, and only where the queue sets no window of its
103
+ // own: its claim proves the job was admitted inside the signature's.
104
+ if (queued != null || !await redelivered().catch(() => false)) {
105
+ throw new AuthenPayloadError('expired');
87
106
  }
88
107
  }
89
- catch {
90
- throw new AuthenPayloadError('nonce');
108
+ else {
109
+ try {
110
+ // A queued claim outlives every moment a copy of the request could still be admitted: a
111
+ // copy enqueued within the signature's window of its signing stays deliverable for the
112
+ // queue's window after it — so the claim lives that long (and `deliveryTtl` at least).
113
+ const claimed = await store.claim(claimId, delivery != null
114
+ ? new Date(Math.max(signedAt + BED255_SIG_TTL + (queued?.maxAge ?? 0), now + (opts?.deliveryTtl ?? BED255_DELIVERY_TTL)))
115
+ : new Date(signedAt + BED255_SIG_TTL), delivery?.id);
116
+ if (!claimed && !await redelivered()) {
117
+ throw new AuthenPayloadError('nonce');
118
+ }
119
+ }
120
+ catch {
121
+ throw new AuthenPayloadError('nonce');
122
+ }
91
123
  }
92
124
  res.resolve({
93
125
  token: authorization,
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAEjD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAClF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAA;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AAG9C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEhF,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAC9D,OAAO,EACL,kCAAkC,EAAE,oCAAoC,EACzE,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAE9C,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,QAAgB,EAAE,IAA+B,EAAqB,EAAE;IAC5G,MAAM,YAAY,GAAG,kCAAkC,EAAE,CAAA;IAEzD,MAAM,MAAM,GAAG,CAAC,OAAgB,EAA4B,EAAE;QAC5D,IAAI,IAAI,EAAE,MAAM,IAAI,IAAI,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC,MAAM,CAAA;QACpB,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,EAAE,KAAK,IAAI,qBAAqB,CAAA;QAClD,IAAI,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO,oCAAoC,CACzC,OAAO,CAAC,QAAQ,CAA8B,KAAK,CAAC,CACrD,CAAA;QACH,CAAC;QACD,OAAO,YAAY,CAAA;IACrB,CAAC,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AC,MAAM,WAAW,EAAE,EAAE,CAAC;wBACrC,MAAM,IAAI,kBAAkB,CAAC,OAAO,CAAC,CAAA;oBACvC,CAAC;gBACH,CAAC;gBAAC,MAAM,CAAC;oBACP,MAAM,IAAI,kBAAkB,CAAC,OAAO,CAAC,CAAA;gBACvC,CAAC;YACH,CAAC;YAED,GAAG,CAAC,OAAO,CAAC;gBACV,KAAK,EAAE,aAAa;gBACpB,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE;gBACvB,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE;gBAC1B,UAAU,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU;gBACnC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE;gBAC5D,IAAI,EAAE,iBAAiB,CAAC,qBAAqB;gBAC7C,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,OAAO;gBAC3B;;mBAEG;gBACH,IAAI,EAAE,QAAQ,CAAC,OAAO;gBACtB,MAAM,EAAE,KAAK;gBACb,SAAS,EAAE,IAAI,IAAI,EAAE;aACtB,CAAC,CAAA;YAEF,OAAO,IAAS,CAAA;QAClB,CAAC;KACF,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,IAAI,EAAE;QACrB,KAAK,CAAC,WAAW,GAAG,IAAI,CAAA;IAC1B,CAAC,CAAC,CAAA;IAEF,OAAO,KAAK,CAAA;AACd,CAAC,CAAA"}
@@ -12,14 +12,33 @@ export interface BasicEd25519GuardOptions {
12
12
  cache?: string;
13
13
  /** Explicit replay store, for consumers that do not register a Resource on the context. */
14
14
  replay?: SignedRequestReplayStore;
15
+ /**
16
+ * How long (ms) a nonce claimed by a queued request stays bound to its job at least, so the broker's
17
+ * own redelivery of that job is admitted on it. Default {@link BED255_DELIVERY_TTL}. A delivery that
18
+ * carries the queue's window (`RequestDelivery.maxAge`) keeps its claim until that window after the
19
+ * signature has passed, whichever is later.
20
+ */
21
+ deliveryTtl?: number;
15
22
  }
16
23
  /** A create-once claim over one signed request identity. */
17
24
  export interface SignedRequestReplayStore {
18
- claim: (id: string, expiresAt: Date) => Promise<boolean>;
25
+ /**
26
+ * Claim `id` until `expiresAt`. `owner` binds the claim to one delivery of the request (a queued
27
+ * job, `RequestDelivery.id`); a claim another caller already holds answers `false` — whoever holds it.
28
+ */
29
+ claim: (id: string, expiresAt: Date, owner?: string) => Promise<boolean>;
30
+ /**
31
+ * The owner a live claim was bound to — `null` when the claim is gone or was taken without an
32
+ * owner (an HTTP request). A store without it never recognises a redelivery: every second
33
+ * presentation of a nonce is a replay there.
34
+ */
35
+ holder?: (id: string) => Promise<string | null>;
19
36
  }
20
37
  /** The small Resource surface needed by the Redis-compatible replay adapter. */
21
38
  export interface SignedRequestReplayResource extends BasicResource {
22
39
  create: (record: Partial<ResourceRecord>, opts?: WriteOptions) => Promise<ResourceRecord>;
40
+ /** Reads a claim back for {@link SignedRequestReplayStore.holder}; without it no redelivery is recognised. */
41
+ load?: (id: string) => Promise<ResourceRecord | null>;
23
42
  }
24
43
  /** What `signBasicEd25519Request` signs: the request body and the signer's identity. */
25
44
  export interface BasicEd25519SignInput {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAExD,MAAM,WAAW,iBAAkB,SAAQ,YAAY;CACtD;AAED,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,KAAK,CAAC,EA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C,EAAE,wBAAwB,CAAA;IACjC;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,4DAA4D;AAC5D,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IACxE;;;;OAIG;IACH,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAA;CAChD;AAED,gFAAgF;AAChF,MAAM,WAAW,2BAA4B,SAAQ,aAAa;IAChE,MAAM,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,cAAc,CAAC,EAAE,IAAI,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,cAAc,CAAC,CAAA;IACzF,8GAA8G;IAC9G,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAA;CACtD;AAED,wFAAwF;AACxF,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,kFAAkF;IAClF,UAAU,EAAE,MAAM,CAAA;IAClB,gGAAgG;IAChG,GAAG,EAAE,YAAY,CAAA;CAClB;AAED,6DAA6D;AAC7D,MAAM,WAAW,yBAAyB;IACxC,mGAAmG;IACnG,aAAa,EAAE,MAAM,CAAA;IACrB,iGAAiG;IACjG,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAChC"}
@@ -1,3 +1,4 @@
1
+ import type { ResourceRecord } from '@owlmeans/resource';
1
2
  /** What `GUARD_ED25519` signs and verifies — built by `signedPayloadOf` on both halves. */
2
3
  export interface BasicEd25519Payload {
3
4
  /** The JSON body as sent; `{}` for an absent body and for raw bytes (a streamed-body route). */
@@ -5,4 +6,19 @@ export interface BasicEd25519Payload {
5
6
  /** The time, then the nonce — key order is part of the signed bytes. */
6
7
  headers: Record<string, unknown>;
7
8
  }
9
+ /** A nonce claim as the replay resource stores it: the claim's id, and the delivery it is bound to. */
10
+ export interface SignedRequestClaim extends Partial<ResourceRecord> {
11
+ /** `RequestDelivery.id` of the queued request that claimed it; absent for an HTTP request. */
12
+ owner?: string;
13
+ }
14
+ /** A claim the process-local replay store holds: its absolute expiry and the delivery it is bound to. */
15
+ export interface MemoryReplayClaim {
16
+ expiry: number;
17
+ owner?: string;
18
+ }
19
+ /** The enqueue a queued request's freshness is judged at, and the queue's window after it (ms). */
20
+ export interface SignedDeliveryWindow {
21
+ enqueuedAt: number;
22
+ maxAge: number;
23
+ }
8
24
  //# sourceMappingURL=types.local.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.local.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/types.local.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,MAAM,WAAW,mBAAmB;IAClC,gGAAgG;IAChG,IAAI,EAAE,OAAO,CAAA;IACb,wEAAwE;IACxE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACjC"}
1
+ {"version":3,"file":"types.local.d.ts","sourceRoot":"","sources":["../../../src/guards/basic-ed25519/types.local.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAExD,2FAA2F;AAC3F,MAAM,WAAW,mBAAmB;IAClC,gGAAgG;IAChG,IAAI,EAAE,OAAO,CAAA;IACb,wEAAwE;IACxE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACjC;AAED,uGAAuG;AACvG,MAAM,WAAW,kBAAmB,SAAQ,OAAO,CAAC,cAAc,CAAC;IACjE,8FAA8F;IAC9F,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED,yGAAyG;AACzG,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED,mGAAmG;AACnG,MAAM,WAAW,oBAAoB;IACnC,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,MAAM,CAAA;CACf"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owlmeans/auth-common",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "license": "MIT",
5
5
  "homepage": "https://owlmeans.com/docs/",
6
6
  "repository": {
@@ -39,19 +39,19 @@
39
39
  }
40
40
  },
41
41
  "dependencies": {
42
- "@owlmeans/auth": "^0.2.2",
43
- "@owlmeans/auth-common": "^0.2.2",
44
- "@owlmeans/basic-ids": "^0.2.2",
45
- "@owlmeans/basic-keys": "^0.2.2",
46
- "@owlmeans/client-entrypoint": "^0.2.2",
47
- "@owlmeans/context": "^0.2.2",
48
- "@owlmeans/entrypoint": "^0.2.2",
49
- "@owlmeans/resource": "^0.2.2",
50
- "@owlmeans/route": "^0.2.2"
42
+ "@owlmeans/auth": "^0.2.3",
43
+ "@owlmeans/auth-common": "^0.2.3",
44
+ "@owlmeans/basic-ids": "^0.2.3",
45
+ "@owlmeans/basic-keys": "^0.2.3",
46
+ "@owlmeans/client-entrypoint": "^0.2.3",
47
+ "@owlmeans/context": "^0.2.3",
48
+ "@owlmeans/entrypoint": "^0.2.3",
49
+ "@owlmeans/resource": "^0.2.3",
50
+ "@owlmeans/route": "^0.2.3"
51
51
  },
52
52
  "devDependencies": {
53
- "@owlmeans/dep-config": "^0.2.2",
54
- "@owlmeans/test-auth": "^0.2.2",
53
+ "@owlmeans/dep-config": "^0.2.3",
54
+ "@owlmeans/test-auth": "^0.2.3",
55
55
  "@types/bun": "^1.4.4",
56
56
  "nodemon": "^3.1.14",
57
57
  "typescript": "^7.0.2"
@@ -7,4 +7,11 @@ export const BED255_NONCE_HEADER = 'X-Auth-Nonce'
7
7
 
8
8
  export const BED255_SIG_TTL = 60 * 1000
9
9
 
10
+ /**
11
+ * How long a nonce claimed by a QUEUED request (one that carries `delivery`) stays bound to its job:
12
+ * the broker's own redelivery of that job (a stall, a retry) is admitted on that claim — past the
13
+ * signature's window too — for this long after the first admission.
14
+ */
15
+ export const BED255_DELIVERY_TTL = 60 * 60 * 1000
16
+
10
17
  export const BED255_CASHE_RESOURCE = 'basic-ed25519-nonce-cache'
@@ -1,5 +1,6 @@
1
1
  import { RecordExists } from '@owlmeans/resource'
2
2
  import type { SignedRequestReplayResource, SignedRequestReplayStore } from './types.js'
3
+ import type { MemoryReplayClaim, SignedRequestClaim } from './types.local.js'
3
4
 
4
5
  /**
5
6
  * Process-local replay protection used when a deployment has not supplied a shared resource.
@@ -7,20 +8,25 @@ import type { SignedRequestReplayResource, SignedRequestReplayStore } from './ty
7
8
  * replay window rather than by process lifetime.
8
9
  */
9
10
  export const makeMemorySignedRequestReplayStore = (): SignedRequestReplayStore => {
10
- const claims = new Map<string, number>()
11
+ const claims = new Map<string, MemoryReplayClaim>()
12
+
13
+ const live = (id: string): MemoryReplayClaim | null => {
14
+ const current = claims.get(id)
15
+ return current != null && current.expiry > Date.now() ? current : null
16
+ }
11
17
 
12
18
  return {
13
- claim: async (id, expiresAt) => {
14
- const now = Date.now()
15
- const current = claims.get(id)
16
- if (current != null && current > now) {
19
+ claim: async (id, expiresAt, owner) => {
20
+ if (live(id) != null) {
17
21
  return false
18
22
  }
19
23
 
24
+ const now = Date.now()
20
25
  const expiry = expiresAt.getTime()
21
- claims.set(id, expiry)
26
+ const claim: MemoryReplayClaim = owner != null ? { expiry, owner } : { expiry }
27
+ claims.set(id, claim)
22
28
  const timer = setTimeout(() => {
23
- if (claims.get(id) === expiry) {
29
+ if (claims.get(id) === claim) {
24
30
  claims.delete(id)
25
31
  }
26
32
  }, Math.max(0, expiry - now))
@@ -28,28 +34,43 @@ export const makeMemorySignedRequestReplayStore = (): SignedRequestReplayStore =
28
34
  unref?.call(timer)
29
35
 
30
36
  return true
31
- }
37
+ },
38
+
39
+ holder: async id => live(id)?.owner ?? null,
32
40
  }
33
41
  }
34
42
 
35
43
  /**
36
44
  * Adapt a create-once Resource to signed-request replay protection. Redis resources honour the
37
45
  * absolute expiry and make the claim atomic across replicas (`SET NX`); other resource failures
38
- * remain failures rather than being mistaken for successful claims.
46
+ * remain failures rather than being mistaken for successful claims. The claim's `owner` is stored
47
+ * on the record, and read back through `load` when the resource has one.
39
48
  */
40
49
  export const makeResourceSignedRequestReplayStore = (
41
50
  resource: SignedRequestReplayResource
42
- ): SignedRequestReplayStore => ({
43
- claim: async (id, expiresAt) => {
44
- try {
45
- await resource.create({ id }, { ttl: expiresAt })
46
- return true
47
- } catch (error) {
48
- if (error instanceof RecordExists
49
- || (error as { type?: unknown } | null)?.type === RecordExists.typeName) {
50
- return false
51
+ ): SignedRequestReplayStore => {
52
+ const store: SignedRequestReplayStore = {
53
+ claim: async (id, expiresAt, owner) => {
54
+ try {
55
+ // The owner rides the record beside its id: a claim is a plain record to the resource.
56
+ const record: SignedRequestClaim = owner != null ? { id, owner } : { id }
57
+ await resource.create(record, { ttl: expiresAt })
58
+ return true
59
+ } catch (error) {
60
+ if (error instanceof RecordExists
61
+ || (error as { type?: unknown } | null)?.type === RecordExists.typeName) {
62
+ return false
63
+ }
64
+ throw error
51
65
  }
52
- throw error
66
+ },
67
+ }
68
+ if (resource.load != null) {
69
+ store.holder = async id => {
70
+ const owner = (await resource.load?.(id) as { owner?: unknown } | null | undefined)?.owner
71
+ return typeof owner === 'string' && owner !== '' ? owner : null
53
72
  }
54
73
  }
55
- })
74
+
75
+ return store
76
+ }
@@ -1,7 +1,7 @@
1
1
  import { createService } from '@owlmeans/context'
2
2
  import type { AbstractRequest, AbstractResponse } from '@owlmeans/entrypoint'
3
3
  import { assertContext } from '@owlmeans/context'
4
- import { BED255_CASHE_RESOURCE, GUARD_ED25519, BED255_SIG_TTL } from './consts.js'
4
+ import { BED255_CASHE_RESOURCE, BED255_DELIVERY_TTL, GUARD_ED25519, BED255_SIG_TTL } from './consts.js'
5
5
  import { nonceKey, timeKey } from './consts.local.js'
6
6
  import { trust } from '../../utils/trusted.js'
7
7
  import type { Config, Context } from '../../utils/types.js'
@@ -13,6 +13,7 @@ import {
13
13
  makeMemorySignedRequestReplayStore, makeResourceSignedRequestReplayStore
14
14
  } from './replay.js'
15
15
  import type { SignedRequestReplayResource, SignedRequestReplayStore } from './types.js'
16
+ import type { SignedDeliveryWindow } from './types.local.js'
16
17
  import { signBasicEd25519Request } from './sign.js'
17
18
  import { signedPayloadOf } from './payload.js'
18
19
 
@@ -98,26 +99,58 @@ export const makeBasicEd25519Guard = (resource: string, opts?: BasicEd25519Guard
98
99
  throw new AuthenPayloadError('timestamp')
99
100
  }
100
101
 
101
- if (Math.abs(Date.now() - signedAt) > BED255_SIG_TTL) {
102
- throw new AuthenPayloadError('expired')
103
- }
104
-
102
+ const now = Date.now()
103
+ const delivery = req.delivery
104
+ // A request the queue delivers is judged fresh at its ENQUEUE — the broker's own record of when
105
+ // it took the job in (never the job's data) — and stays deliverable for the queue's own window
106
+ // (`maxAge`): a job that waited behind a backlog or a deploy gap is not refused for the wait.
107
+ // Without both, and for every HTTP request, the signature is judged at arrival, as always.
108
+ const queued: SignedDeliveryWindow | null = delivery?.enqueuedAt != null && delivery.maxAge != null
109
+ && Number.isFinite(delivery.enqueuedAt) && Number.isFinite(delivery.maxAge) && delivery.maxAge > 0
110
+ ? { enqueuedAt: delivery.enqueuedAt, maxAge: delivery.maxAge } : null
111
+ const expired = queued != null
112
+ ? Math.abs(queued.enqueuedAt - signedAt) > BED255_SIG_TTL || queued.enqueuedAt - now > BED255_SIG_TTL
113
+ || now - queued.enqueuedAt > queued.maxAge
114
+ : Math.abs(now - signedAt) > BED255_SIG_TTL
105
115
  if (typeof nonce !== 'string' || nonce.length === 0) {
106
- throw new AuthenPayloadError('nonce')
116
+ throw new AuthenPayloadError(expired ? 'expired' : 'nonce')
107
117
  }
108
118
 
109
- try {
110
- // The replay identity is the signing credential plus its nonce. A nonce used by one
111
- // trusted service does not block another, while a captured request can be admitted once.
112
- const claimed = await replay(context).claim(
113
- `${signature.credential.length}:${signature.credential}${nonce}`,
114
- new Date(signedAt + BED255_SIG_TTL)
115
- )
116
- if (!claimed) {
119
+ // The replay identity is the signing credential plus its nonce. A nonce used by one trusted
120
+ // service does not block another, while a captured request can be admitted once.
121
+ const claimId = `${signature.credential.length}:${signature.credential}${nonce}`
122
+ const store = replay(context)
123
+ // A queued request names its delivery (`<queue>:<job id>`, set in-process by the queue bridge,
124
+ // never from the wire). Its claim is bound to that job, and only the broker's own redelivery
125
+ // of the SAME job — a later attempt, after a stall or a failed attempt — presents it again
126
+ // and is admitted: the same nonce on another job, or over HTTP, is still a replay.
127
+ const redelivered = async (): Promise<boolean> =>
128
+ delivery != null && delivery.attempt > 1 && store.holder != null
129
+ && await store.holder(claimId) === delivery.id
130
+
131
+ if (expired) {
132
+ // Past the window only a redelivery stands, and only where the queue sets no window of its
133
+ // own: its claim proves the job was admitted inside the signature's.
134
+ if (queued != null || !await redelivered().catch(() => false)) {
135
+ throw new AuthenPayloadError('expired')
136
+ }
137
+ } else {
138
+ try {
139
+ // A queued claim outlives every moment a copy of the request could still be admitted: a
140
+ // copy enqueued within the signature's window of its signing stays deliverable for the
141
+ // queue's window after it — so the claim lives that long (and `deliveryTtl` at least).
142
+ const claimed = await store.claim(claimId, delivery != null
143
+ ? new Date(Math.max(
144
+ signedAt + BED255_SIG_TTL + (queued?.maxAge ?? 0),
145
+ now + (opts?.deliveryTtl ?? BED255_DELIVERY_TTL),
146
+ ))
147
+ : new Date(signedAt + BED255_SIG_TTL), delivery?.id)
148
+ if (!claimed && !await redelivered()) {
149
+ throw new AuthenPayloadError('nonce')
150
+ }
151
+ } catch {
117
152
  throw new AuthenPayloadError('nonce')
118
153
  }
119
- } catch {
120
- throw new AuthenPayloadError('nonce')
121
154
  }
122
155
 
123
156
  res.resolve({
@@ -1,3 +1,5 @@
1
+ import type { ResourceRecord } from '@owlmeans/resource'
2
+
1
3
  /** What `GUARD_ED25519` signs and verifies — built by `signedPayloadOf` on both halves. */
2
4
  export interface BasicEd25519Payload {
3
5
  /** The JSON body as sent; `{}` for an absent body and for raw bytes (a streamed-body route). */
@@ -5,3 +7,21 @@ export interface BasicEd25519Payload {
5
7
  /** The time, then the nonce — key order is part of the signed bytes. */
6
8
  headers: Record<string, unknown>
7
9
  }
10
+
11
+ /** A nonce claim as the replay resource stores it: the claim's id, and the delivery it is bound to. */
12
+ export interface SignedRequestClaim extends Partial<ResourceRecord> {
13
+ /** `RequestDelivery.id` of the queued request that claimed it; absent for an HTTP request. */
14
+ owner?: string
15
+ }
16
+
17
+ /** A claim the process-local replay store holds: its absolute expiry and the delivery it is bound to. */
18
+ export interface MemoryReplayClaim {
19
+ expiry: number
20
+ owner?: string
21
+ }
22
+
23
+ /** The enqueue a queued request's freshness is judged at, and the queue's window after it (ms). */
24
+ export interface SignedDeliveryWindow {
25
+ enqueuedAt: number
26
+ maxAge: number
27
+ }
@@ -14,16 +14,35 @@ export interface BasicEd25519GuardOptions {
14
14
  cache?: string
15
15
  /** Explicit replay store, for consumers that do not register a Resource on the context. */
16
16
  replay?: SignedRequestReplayStore
17
+ /**
18
+ * How long (ms) a nonce claimed by a queued request stays bound to its job at least, so the broker's
19
+ * own redelivery of that job is admitted on it. Default {@link BED255_DELIVERY_TTL}. A delivery that
20
+ * carries the queue's window (`RequestDelivery.maxAge`) keeps its claim until that window after the
21
+ * signature has passed, whichever is later.
22
+ */
23
+ deliveryTtl?: number
17
24
  }
18
25
 
19
26
  /** A create-once claim over one signed request identity. */
20
27
  export interface SignedRequestReplayStore {
21
- claim: (id: string, expiresAt: Date) => Promise<boolean>
28
+ /**
29
+ * Claim `id` until `expiresAt`. `owner` binds the claim to one delivery of the request (a queued
30
+ * job, `RequestDelivery.id`); a claim another caller already holds answers `false` — whoever holds it.
31
+ */
32
+ claim: (id: string, expiresAt: Date, owner?: string) => Promise<boolean>
33
+ /**
34
+ * The owner a live claim was bound to — `null` when the claim is gone or was taken without an
35
+ * owner (an HTTP request). A store without it never recognises a redelivery: every second
36
+ * presentation of a nonce is a replay there.
37
+ */
38
+ holder?: (id: string) => Promise<string | null>
22
39
  }
23
40
 
24
41
  /** The small Resource surface needed by the Redis-compatible replay adapter. */
25
42
  export interface SignedRequestReplayResource extends BasicResource {
26
43
  create: (record: Partial<ResourceRecord>, opts?: WriteOptions) => Promise<ResourceRecord>
44
+ /** Reads a claim back for {@link SignedRequestReplayStore.holder}; without it no redelivery is recognised. */
45
+ load?: (id: string) => Promise<ResourceRecord | null>
27
46
  }
28
47
 
29
48
  /** What `signBasicEd25519Request` signs: the request body and the signer's identity. */
@@ -2,11 +2,11 @@ import { describe, expect, test } from 'bun:test'
2
2
  import { Readable } from 'node:stream'
3
3
  import { AuthenPayloadError, AuthroizationType } from '@owlmeans/auth'
4
4
  import {
5
- BED255_NONCE_HEADER, BED255_SIG_TTL, BED255_TIME_HEADER, makeBasicEd25519Guard,
6
- makeResourceSignedRequestReplayStore, signBasicEd25519Request
5
+ BED255_DELIVERY_TTL, BED255_NONCE_HEADER, BED255_SIG_TTL, BED255_TIME_HEADER, makeBasicEd25519Guard,
6
+ makeMemorySignedRequestReplayStore, makeResourceSignedRequestReplayStore, signBasicEd25519Request
7
7
  } from '@owlmeans/auth-common'
8
- import type { BasicEd25519Guard, SignedRequestReplayResource } from '@owlmeans/auth-common'
9
- import type { AbstractRequest, AbstractResponse } from '@owlmeans/entrypoint'
8
+ import type { BasicEd25519Guard, SignedRequestReplayResource, SignedRequestReplayStore } from '@owlmeans/auth-common'
9
+ import type { AbstractRequest, AbstractResponse, RequestDelivery } from '@owlmeans/entrypoint'
10
10
  import type { Auth } from '@owlmeans/auth'
11
11
  import { RecordExists } from '@owlmeans/resource'
12
12
  import { makeTrustFixture, TRUSTED_ALIAS } from './context.js'
@@ -99,6 +99,209 @@ describe('@owlmeans/auth-common — signed request freshness and replay protecti
99
99
  })
100
100
  })
101
101
 
102
+ /**
103
+ * A queue hands a job back after its worker died (a stall) or after a failed attempt (a retry). The
104
+ * job is the SAME signed request: its nonce was claimed by the first attempt, and the broker's own
105
+ * redelivery must not read as a replay — while the same nonce on another job, or over HTTP, still does.
106
+ */
107
+ describe('@owlmeans/auth-common — a queued request\'s redelivery is not a replay', () => {
108
+ const delivered = (req: AbstractRequest, delivery?: RequestDelivery): AbstractRequest =>
109
+ ({ ...req, ...(delivery != null ? { delivery } : {}) })
110
+ const claimIdOf = (credential: string, nonce: string) => `${credential.length}:${credential}${nonce}`
111
+
112
+ test('the same job delivered again after a stall is admitted on the claim its first attempt took', async () => {
113
+ const signed = await request(new Date().toISOString(), 'stalled-job')
114
+
115
+ const first = await handle(signed.guard, delivered(signed.req, { id: 'agent-ops:story-develop-1', attempt: 1 }))
116
+ const again = await handle(signed.guard, delivered(signed.req, { id: 'agent-ops:story-develop-1', attempt: 2 }))
117
+
118
+ expect(first?.userId).toBe(signed.fixture.authRecord.id)
119
+ expect(again?.userId).toBe(signed.fixture.authRecord.id)
120
+ })
121
+
122
+ test('the same nonce on ANOTHER job is a replay', async () => {
123
+ const signed = await request(new Date().toISOString(), 'copied-to-another-job')
124
+ await handle(signed.guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 1 }))
125
+
126
+ await expect(handle(signed.guard, delivered(signed.req, { id: 'agent-ops:job-b', attempt: 2 })))
127
+ .rejects.toThrow(/nonce/)
128
+ await expect(handle(signed.guard, delivered(signed.req, { id: 'agent-ops:job-b', attempt: 1 })))
129
+ .rejects.toThrow(/nonce/)
130
+ })
131
+
132
+ test('the same nonce over HTTP — no delivery — is a replay, both after a job and before one', async () => {
133
+ const queued = await request(new Date().toISOString(), 'job-then-http')
134
+ await handle(queued.guard, delivered(queued.req, { id: 'agent-ops:job-a', attempt: 1 }))
135
+ await expect(handle(queued.guard, queued.req)).rejects.toThrow(/nonce/)
136
+
137
+ const http = await request(new Date().toISOString(), 'http-then-job')
138
+ await handle(http.guard, http.req)
139
+ await expect(handle(http.guard, delivered(http.req, { id: 'agent-ops:job-a', attempt: 2 })))
140
+ .rejects.toThrow(/nonce/)
141
+ })
142
+
143
+ test('a first delivery never re-presents a claim — only a later attempt of the job does', async () => {
144
+ const signed = await request(new Date().toISOString(), 'first-twice')
145
+ await handle(signed.guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 1 }))
146
+
147
+ await expect(handle(signed.guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 1 })))
148
+ .rejects.toThrow(/nonce/)
149
+ })
150
+
151
+ test('past the signature window only the job\'s own redelivery stands, and only while its claim lives', async () => {
152
+ const replay = makeMemorySignedRequestReplayStore()
153
+ const signed = await request(new Date(Date.now() - 2 * BED255_SIG_TTL).toISOString(), 'redelivered-late')
154
+ const guard = makeBasicEd25519Guard(TRUSTED_ALIAS, { replay })
155
+ signed.fixture.ctx.registerService(guard)
156
+ const claimId = claimIdOf(signed.fixture.authRecord.id, 'redelivered-late')
157
+
158
+ // No claim yet: nothing proves the job was ever admitted inside the window.
159
+ await expect(handle(guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 2 }))).rejects.toThrow(/expired/)
160
+
161
+ expect(await replay.claim(claimId, new Date(Date.now() + BED255_DELIVERY_TTL), 'agent-ops:job-a')).toBe(true)
162
+ expect((await handle(guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 2 })))?.userId)
163
+ .toBe(signed.fixture.authRecord.id)
164
+ await expect(handle(guard, delivered(signed.req, { id: 'agent-ops:job-b', attempt: 2 }))).rejects.toThrow(/expired/)
165
+ await expect(handle(guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 1 }))).rejects.toThrow(/expired/)
166
+ await expect(handle(guard, signed.req)).rejects.toThrow(/expired/)
167
+ })
168
+
169
+ test('a queued claim is bound to its delivery and outlives the signature window; an HTTP claim does not', async () => {
170
+ const claims: Array<{ expiresAt: Date, owner?: string }> = []
171
+ const replay: SignedRequestReplayStore = {
172
+ claim: async (_id, expiresAt, owner) => { claims.push({ expiresAt, ...(owner != null ? { owner } : {}) }); return true },
173
+ }
174
+ const queued = await request(new Date().toISOString(), 'bound-claim')
175
+ const guard = makeBasicEd25519Guard(TRUSTED_ALIAS, { replay, deliveryTtl: 600_000 })
176
+ queued.fixture.ctx.registerService(guard)
177
+ const before = Date.now()
178
+
179
+ await handle(guard, delivered(queued.req, { id: 'agent-ops:job-a', attempt: 1 }))
180
+ await handle(guard, queued.req)
181
+
182
+ expect(claims[0]?.owner).toBe('agent-ops:job-a')
183
+ expect(claims[0]!.expiresAt.getTime()).toBeGreaterThanOrEqual(before + 600_000)
184
+ expect(claims[1]?.owner).toBeUndefined()
185
+ expect(claims[1]!.expiresAt.getTime()).toBeLessThanOrEqual(Date.now() + BED255_SIG_TTL)
186
+ })
187
+
188
+ test('a store without `holder` recognises no redelivery: the second presentation is a replay', async () => {
189
+ const taken = new Set<string>()
190
+ const replay: SignedRequestReplayStore = {
191
+ claim: async id => { if (taken.has(id)) return false; taken.add(id); return true },
192
+ }
193
+ const signed = await request(new Date().toISOString(), 'no-holder')
194
+ const guard = makeBasicEd25519Guard(TRUSTED_ALIAS, { replay })
195
+ signed.fixture.ctx.registerService(guard)
196
+
197
+ await handle(guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 1 }))
198
+ await expect(handle(guard, delivered(signed.req, { id: 'agent-ops:job-a', attempt: 2 }))).rejects.toThrow(/nonce/)
199
+ })
200
+
201
+ test('the resource adapter stores the owner on the claim and reads it back through `load`', async () => {
202
+ const records = new Map<string, Record<string, unknown>>()
203
+ const resource = {
204
+ create: async (record: { id?: string }) => {
205
+ if (records.has(record.id!)) throw new RecordExists(record.id!)
206
+ records.set(record.id!, { ...record })
207
+ return record
208
+ },
209
+ load: async (id: string) => records.get(id) ?? null,
210
+ } as SignedRequestReplayResource
211
+ const replay = makeResourceSignedRequestReplayStore(resource)
212
+ const expiresAt = new Date(Date.now() + BED255_DELIVERY_TTL)
213
+
214
+ expect(await replay.claim('owned', expiresAt, 'agent-ops:job-a')).toBe(true)
215
+ expect(await replay.claim('anonymous', expiresAt)).toBe(true)
216
+ expect(records.get('owned')).toEqual({ id: 'owned', owner: 'agent-ops:job-a' })
217
+ expect(await replay.holder?.('owned')).toBe('agent-ops:job-a')
218
+ expect(await replay.holder?.('anonymous')).toBeNull()
219
+ expect(await replay.holder?.('missing')).toBeNull()
220
+ expect(makeResourceSignedRequestReplayStore({ create: resource.create } as SignedRequestReplayResource).holder)
221
+ .toBeUndefined()
222
+ })
223
+ })
224
+
225
+ /**
226
+ * A queued job can wait — behind a backlog, a busy lane, a deploy gap — before any worker picks it up.
227
+ * Its signature is judged at its ENQUEUE (the broker's own timestamp, carried as `delivery.enqueuedAt`)
228
+ * and the job stays deliverable for the queue's own window (`delivery.maxAge`); HTTP keeps 60 seconds.
229
+ */
230
+ describe('@owlmeans/auth-common — a queued signature is judged at its enqueue, inside the queue\'s window', () => {
231
+ const DAY = 86_400_000
232
+ const queuedAt = (req: AbstractRequest, delivery: RequestDelivery): AbstractRequest => ({ ...req, delivery })
233
+
234
+ test('a job picked up 10 minutes after it was enqueued is admitted', async () => {
235
+ const enqueuedAt = Date.now() - 10 * 60_000
236
+ const signed = await request(new Date(enqueuedAt - 5).toISOString(), 'waited-ten-minutes')
237
+
238
+ const auth = await handle(signed.guard, queuedAt(signed.req, { id: 'agent-ops:job-a', attempt: 1, enqueuedAt, maxAge: DAY }))
239
+
240
+ expect(auth?.userId).toBe(signed.fixture.authRecord.id)
241
+ })
242
+
243
+ test('a signature older than the window around its enqueue is refused, and so is a job past the queue\'s window', async () => {
244
+ const enqueuedAt = Date.now() - 10 * 60_000
245
+ const stale = await request(new Date(enqueuedAt - BED255_SIG_TTL - 1_000).toISOString(), 'signed-long-before-enqueue')
246
+ const future = await request(new Date(enqueuedAt + BED255_SIG_TTL + 1_000).toISOString(), 'signed-long-after-enqueue')
247
+ const tooOld = Date.now() - DAY - 60_000
248
+ const late = await request(new Date(tooOld).toISOString(), 'past-the-queue-window')
249
+
250
+ await expect(handle(stale.guard, queuedAt(stale.req, { id: 'agent-ops:job-a', attempt: 1, enqueuedAt, maxAge: DAY })))
251
+ .rejects.toThrow(/expired/)
252
+ await expect(handle(future.guard, queuedAt(future.req, { id: 'agent-ops:job-b', attempt: 1, enqueuedAt, maxAge: DAY })))
253
+ .rejects.toThrow(/expired/)
254
+ await expect(handle(late.guard, queuedAt(late.req, { id: 'agent-ops:job-c', attempt: 2, enqueuedAt: tooOld, maxAge: DAY })))
255
+ .rejects.toThrow(/expired/)
256
+ })
257
+
258
+ test('without the queue\'s window — or its enqueue time — a queued signature is judged at arrival, as over HTTP', async () => {
259
+ const enqueuedAt = Date.now() - 10 * 60_000
260
+ const signed = await request(new Date(enqueuedAt).toISOString(), 'no-window')
261
+
262
+ await expect(handle(signed.guard, queuedAt(signed.req, { id: 'agent-ops:job-a', attempt: 1, enqueuedAt })))
263
+ .rejects.toThrow(/expired/)
264
+ await expect(handle(signed.guard, queuedAt(signed.req, { id: 'agent-ops:job-a', attempt: 1, maxAge: DAY })))
265
+ .rejects.toThrow(/expired/)
266
+ })
267
+
268
+ test('HTTP is unchanged: a request signed 10 minutes ago is expired, a fresh one admitted once', async () => {
269
+ const old = await request(new Date(Date.now() - 10 * 60_000).toISOString(), 'http-old')
270
+ const fresh = await request(new Date().toISOString(), 'http-fresh')
271
+
272
+ await expect(handle(old.guard, old.req)).rejects.toThrow(/expired/)
273
+ expect((await handle(fresh.guard, fresh.req))?.userId).toBe(fresh.fixture.authRecord.id)
274
+ await expect(handle(fresh.guard, fresh.req)).rejects.toThrow(/nonce/)
275
+ })
276
+
277
+ test('the claim outlives every moment a copy could still be admitted: a copy on another job is a replay', async () => {
278
+ const claims: Array<{ expiresAt: Date, owner?: string }> = []
279
+ const memory = makeMemorySignedRequestReplayStore()
280
+ const replay: SignedRequestReplayStore = {
281
+ claim: async (id, expiresAt, owner) => {
282
+ claims.push({ expiresAt, ...(owner != null ? { owner } : {}) })
283
+ return await memory.claim(id, expiresAt, owner)
284
+ },
285
+ holder: memory.holder,
286
+ }
287
+ const enqueuedAt = Date.now() - 10 * 60_000
288
+ const signedAt = enqueuedAt - 5
289
+ const signed = await request(new Date(signedAt).toISOString(), 'copied-after-a-wait')
290
+ const guard = makeBasicEd25519Guard(TRUSTED_ALIAS, { replay })
291
+ signed.fixture.ctx.registerService(guard)
292
+
293
+ await handle(guard, queuedAt(signed.req, { id: 'agent-ops:job-a', attempt: 1, enqueuedAt, maxAge: DAY }))
294
+ // The broker's own redelivery of the same job, later still: the same enqueue, the same claim.
295
+ expect((await handle(guard, queuedAt(signed.req, { id: 'agent-ops:job-a', attempt: 2, enqueuedAt, maxAge: DAY })))?.userId)
296
+ .toBe(signed.fixture.authRecord.id)
297
+ await expect(handle(guard, queuedAt(signed.req, { id: 'agent-ops:job-b', attempt: 1, enqueuedAt, maxAge: DAY })))
298
+ .rejects.toThrow(/nonce/)
299
+
300
+ expect(claims[0]?.owner).toBe('agent-ops:job-a')
301
+ expect(claims[0]!.expiresAt.getTime()).toBeGreaterThanOrEqual(signedAt + BED255_SIG_TTL + DAY)
302
+ })
303
+ })
304
+
102
305
  describe('@owlmeans/auth-common — signBasicEd25519Request', () => {
103
306
  const signedRequest = async (signedBody: object, sentBody: object = signedBody) => {
104
307
  const fixture = makeTrustFixture({ withSecret: true, name: 'auth-common-tests' })