axiam-sdk 1.0.0-alpha
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/LICENSE +201 -0
- package/README.md +231 -0
- package/dist/amqp/index.d.cts +246 -0
- package/dist/amqp/index.d.ts +246 -0
- package/dist/amqp/index.js +179 -0
- package/dist/amqp/index.js.map +1 -0
- package/dist/amqp/index.mjs +166 -0
- package/dist/amqp/index.mjs.map +1 -0
- package/dist/client-B2SB-C7c.d.cts +207 -0
- package/dist/client-B2SB-C7c.d.ts +207 -0
- package/dist/grpc/index.d.cts +106 -0
- package/dist/grpc/index.d.ts +106 -0
- package/dist/grpc/index.js +908 -0
- package/dist/grpc/index.js.map +1 -0
- package/dist/grpc/index.mjs +868 -0
- package/dist/grpc/index.mjs.map +1 -0
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +561 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +552 -0
- package/dist/index.mjs.map +1 -0
- package/dist/jwks-CX-nhD6A.d.cts +29 -0
- package/dist/jwks-CX-nhD6A.d.ts +29 -0
- package/dist/middleware/index.d.cts +153 -0
- package/dist/middleware/index.d.ts +153 -0
- package/dist/middleware/index.js +232 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/index.mjs +220 -0
- package/dist/middleware/index.mjs.map +1 -0
- package/dist/node/index.d.cts +103 -0
- package/dist/node/index.d.ts +103 -0
- package/dist/node/index.js +717 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/index.mjs +700 -0
- package/dist/node/index.mjs.map +1 -0
- package/dist/rest/index.d.cts +27 -0
- package/dist/rest/index.d.ts +27 -0
- package/dist/rest/index.js +561 -0
- package/dist/rest/index.js.map +1 -0
- package/dist/rest/index.mjs +552 -0
- package/dist/rest/index.mjs.map +1 -0
- package/dist/sensitive-CWBH_tHr.d.cts +12 -0
- package/dist/sensitive-CWBH_tHr.d.ts +12 -0
- package/package.json +145 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { S as Sensitive } from '../sensitive-CWBH_tHr.js';
|
|
2
|
+
import { ConsumeMessage } from 'amqplib';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Compute the hex-encoded HMAC-SHA256 of `payloadJson` using `key`.
|
|
6
|
+
*
|
|
7
|
+
* `payloadJson` MUST be the canonical JSON bytes of the message body with
|
|
8
|
+
* `hmac_signature` already removed — otherwise the signature is computed
|
|
9
|
+
* over a payload that includes a placeholder signature, making verification
|
|
10
|
+
* impossible (matches the server's `sign_payload` doc comment).
|
|
11
|
+
*/
|
|
12
|
+
declare function signPayload(key: Buffer, payloadJson: Buffer): string;
|
|
13
|
+
/**
|
|
14
|
+
* Verify a hex-encoded HMAC-SHA256 signature over `payloadJson` using `key`.
|
|
15
|
+
*
|
|
16
|
+
* Returns `true` only if the signature matches, comparing in constant time
|
|
17
|
+
* via `timingSafeEqual`. Never throws: malformed hex or a length mismatch
|
|
18
|
+
* both return `false`.
|
|
19
|
+
*/
|
|
20
|
+
declare function verifyPayload(key: Buffer, payloadJson: Buffer, signatureHex: string): boolean;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Authorization check request received from `axiam.authz.request`.
|
|
24
|
+
*
|
|
25
|
+
* Field declaration order matches the server's `AuthzRequest`
|
|
26
|
+
* (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:
|
|
27
|
+
* correlation_id, tenant_id, subject_id, action, resource_id, scope,
|
|
28
|
+
* key_version, nonce, issued_at, hmac_signature. `key_version`, `nonce`, and
|
|
29
|
+
* `issued_at` are always emitted (never omitted) so they fall inside the
|
|
30
|
+
* HMAC-signed bytes — see CONTRACT.md §8 "v2 — Replay Protection".
|
|
31
|
+
*/
|
|
32
|
+
interface AuthzRequest {
|
|
33
|
+
/** Caller-provided ID to correlate request with response. */
|
|
34
|
+
correlation_id: string;
|
|
35
|
+
tenant_id: string;
|
|
36
|
+
subject_id: string;
|
|
37
|
+
action: string;
|
|
38
|
+
resource_id: string;
|
|
39
|
+
scope?: string;
|
|
40
|
+
/**
|
|
41
|
+
* HKDF master-key rotation version (SECHRD-08 / D-05b). The server
|
|
42
|
+
* rejects (nack, requeue:false) any message with `key_version < 2` — v1
|
|
43
|
+
* predates the mandatory `nonce`/`issued_at` replay-protection fields and
|
|
44
|
+
* has no grace-window acceptance path (NEW-4, hard cutover).
|
|
45
|
+
*/
|
|
46
|
+
key_version: number;
|
|
47
|
+
/**
|
|
48
|
+
* Per-message unique value (UUIDv4) for replay protection (NEW-4).
|
|
49
|
+
* Always emitted so it is covered by the HMAC. A nonce already seen
|
|
50
|
+
* within the freshness window is a replay and MUST be rejected.
|
|
51
|
+
*/
|
|
52
|
+
nonce: string;
|
|
53
|
+
/**
|
|
54
|
+
* Producer send time (RFC3339/ISO8601 UTC), always emitted so it is
|
|
55
|
+
* covered by the HMAC (NEW-4). A message outside ±skew (default 5
|
|
56
|
+
* minutes) of the verifier's clock MUST be rejected as stale.
|
|
57
|
+
*/
|
|
58
|
+
issued_at: string;
|
|
59
|
+
/**
|
|
60
|
+
* HMAC-SHA256 of the JSON-serialized message body (this field removed
|
|
61
|
+
* before signing). Computed with the per-tenant AMQP signing key
|
|
62
|
+
* (CONTRACT.md §8). The consumer MUST verify this before processing; a
|
|
63
|
+
* missing signature is rejected in strict mode (the default).
|
|
64
|
+
*/
|
|
65
|
+
hmac_signature?: string;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Authorization decision published to `axiam.authz.response`.
|
|
69
|
+
*
|
|
70
|
+
* Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types
|
|
71
|
+
* table).
|
|
72
|
+
*/
|
|
73
|
+
interface AuthzResponse {
|
|
74
|
+
correlation_id: string;
|
|
75
|
+
allowed: boolean;
|
|
76
|
+
reason?: string;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Audit event received from external services via `axiam.audit.events`.
|
|
80
|
+
*
|
|
81
|
+
* Field declaration order matches the server's `AuditEventMessage`
|
|
82
|
+
* (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:
|
|
83
|
+
* tenant_id, actor_id, actor_type, action, resource_id, outcome, ip_address,
|
|
84
|
+
* metadata, key_version, nonce, issued_at, hmac_signature. `key_version`,
|
|
85
|
+
* `nonce`, and `issued_at` are always emitted (never omitted) so they fall
|
|
86
|
+
* inside the HMAC-signed bytes — see CONTRACT.md §8 "v2 — Replay
|
|
87
|
+
* Protection".
|
|
88
|
+
*/
|
|
89
|
+
interface AuditEventMessage {
|
|
90
|
+
tenant_id: string;
|
|
91
|
+
actor_id: string;
|
|
92
|
+
actor_type: string;
|
|
93
|
+
action: string;
|
|
94
|
+
resource_id?: string;
|
|
95
|
+
outcome: string;
|
|
96
|
+
ip_address?: string;
|
|
97
|
+
metadata?: Record<string, unknown>;
|
|
98
|
+
/**
|
|
99
|
+
* HKDF master-key rotation version (SECHRD-08 / D-05b). The server
|
|
100
|
+
* rejects (nack, requeue:false) any message with `key_version < 2` — v1
|
|
101
|
+
* predates the mandatory `nonce`/`issued_at` replay-protection fields and
|
|
102
|
+
* has no grace-window acceptance path (NEW-4, hard cutover).
|
|
103
|
+
*/
|
|
104
|
+
key_version: number;
|
|
105
|
+
/**
|
|
106
|
+
* Per-message unique value (UUIDv4) for replay protection (NEW-4).
|
|
107
|
+
* Always emitted so it is covered by the HMAC. A nonce already seen
|
|
108
|
+
* within the freshness window is a replay and MUST be rejected.
|
|
109
|
+
*/
|
|
110
|
+
nonce: string;
|
|
111
|
+
/**
|
|
112
|
+
* Producer send time (RFC3339/ISO8601 UTC), always emitted so it is
|
|
113
|
+
* covered by the HMAC (NEW-4). A message outside ±skew (default 5
|
|
114
|
+
* minutes) of the verifier's clock MUST be rejected as stale.
|
|
115
|
+
*/
|
|
116
|
+
issued_at: string;
|
|
117
|
+
/** HMAC-SHA256 of the JSON-serialized message body (CONTRACT.md §8). */
|
|
118
|
+
hmac_signature?: string;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Notification event published to `axiam.notifications`.
|
|
122
|
+
*
|
|
123
|
+
* Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types
|
|
124
|
+
* table).
|
|
125
|
+
*/
|
|
126
|
+
interface NotificationEvent {
|
|
127
|
+
event_type: string;
|
|
128
|
+
tenant_id: string;
|
|
129
|
+
actor_id: string;
|
|
130
|
+
resource_id?: string;
|
|
131
|
+
timestamp: string;
|
|
132
|
+
data?: Record<string, unknown>;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Message type names subject to HMAC verification per CONTRACT.md §8's
|
|
136
|
+
* message-types table (`axiam.authz.request` -> AuthzRequest,
|
|
137
|
+
* `axiam.audit.events` -> AuditEventMessage). `AuthzResponse` and
|
|
138
|
+
* `NotificationEvent` are server-published and never carry
|
|
139
|
+
* `hmac_signature`.
|
|
140
|
+
*/
|
|
141
|
+
declare const HMAC_SIGNED_MESSAGE_TYPES: readonly ["AuthzRequest", "AuditEventMessage"];
|
|
142
|
+
type HmacSignedMessageType = (typeof HMAC_SIGNED_MESSAGE_TYPES)[number];
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Default freshness skew for `issued_at` acceptance (NEW-4): a message is
|
|
146
|
+
* accepted only when its `issued_at` lies within ±5 minutes of the
|
|
147
|
+
* verifier's clock, matching the server's
|
|
148
|
+
* `DEFAULT_FRESHNESS_SKEW_SECS = 300` / `AXIAM__AMQP__REPLAY_SKEW_SECS`
|
|
149
|
+
* (CONTRACT.md §8 v2).
|
|
150
|
+
*/
|
|
151
|
+
declare const DEFAULT_REPLAY_SKEW_MS: number;
|
|
152
|
+
/**
|
|
153
|
+
* Nonce replay-dedup store (NEW-4). `checkAndRecord` returns `true` when
|
|
154
|
+
* `nonce` has already been recorded and its dedup entry has not yet
|
|
155
|
+
* expired (i.e. this delivery is a replay); otherwise it records the nonce
|
|
156
|
+
* with the given TTL and returns `false`.
|
|
157
|
+
*/
|
|
158
|
+
interface NonceStore {
|
|
159
|
+
checkAndRecord(nonce: string, ttlMs: number): boolean;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Default in-memory nonce dedup store (NEW-4). Naturally bounded: each
|
|
163
|
+
* entry expires after `ttlMs` (the caller passes 2x the freshness skew, so
|
|
164
|
+
* a nonce can never still be "fresh" once its dedup entry has lapsed) and
|
|
165
|
+
* expired entries are pruned opportunistically on each check — no
|
|
166
|
+
* background timer and no unbounded growth under sustained traffic.
|
|
167
|
+
*
|
|
168
|
+
* Share ONE instance across every delivery from the same consumer (as
|
|
169
|
+
* `consume()` does by default) — a fresh store per call provides no
|
|
170
|
+
* cross-message replay protection.
|
|
171
|
+
*/
|
|
172
|
+
declare class InMemoryNonceStore implements NonceStore {
|
|
173
|
+
private readonly seenUntilMs;
|
|
174
|
+
checkAndRecord(nonce: string, ttlMs: number): boolean;
|
|
175
|
+
private prune;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Minimal seam over the channel operations this module needs
|
|
179
|
+
* (ack/nack/consume). `amqplib`'s `Channel` implements this directly;
|
|
180
|
+
* tests provide a recording fake that never touches a live broker, so the
|
|
181
|
+
* security-sensitive nack-without-requeue behavior can be asserted without
|
|
182
|
+
* a running RabbitMQ instance.
|
|
183
|
+
*/
|
|
184
|
+
interface ConsumeChannel {
|
|
185
|
+
consume(queue: string, onMessage: (msg: ConsumeMessage | null) => void | Promise<void>): Promise<unknown>;
|
|
186
|
+
/** `channel.ack(msg, allUpTo?)` — allUpTo intentionally omitted/false here. */
|
|
187
|
+
ack(msg: ConsumeMessage): void;
|
|
188
|
+
/** `channel.nack(msg, allUpTo, requeue)` — positional booleans (Pitfall 4). */
|
|
189
|
+
nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;
|
|
190
|
+
}
|
|
191
|
+
interface ConsumeLogger {
|
|
192
|
+
warn(event: string, message: string, context?: Record<string, unknown>): void;
|
|
193
|
+
}
|
|
194
|
+
interface ConsumeOptions {
|
|
195
|
+
logger?: ConsumeLogger;
|
|
196
|
+
/**
|
|
197
|
+
* Strict mode (default true, CONTRACT.md §8.3): a message with no
|
|
198
|
+
* `hmac_signature` is treated as a verification failure (nack-no-requeue),
|
|
199
|
+
* not a pass-through. Lenient mode (false) is a temporary rolling-
|
|
200
|
+
* deployment measure only — strict MUST remain the default.
|
|
201
|
+
*/
|
|
202
|
+
strict?: boolean;
|
|
203
|
+
/**
|
|
204
|
+
* Freshness skew window for `issued_at` validation (NEW-4), in
|
|
205
|
+
* milliseconds. Defaults to {@link DEFAULT_REPLAY_SKEW_MS} (5 minutes),
|
|
206
|
+
* matching the server default (CONTRACT.md §8 v2).
|
|
207
|
+
*/
|
|
208
|
+
skewMs?: number;
|
|
209
|
+
/**
|
|
210
|
+
* Nonce replay-dedup store (NEW-4). Defaults to a fresh
|
|
211
|
+
* `InMemoryNonceStore` per call when omitted — `consume()` creates and
|
|
212
|
+
* shares ONE store across every delivery on that connection by default;
|
|
213
|
+
* callers invoking `verifyAndDispatch` directly across multiple messages
|
|
214
|
+
* must pass the same store explicitly for dedup to take effect.
|
|
215
|
+
*/
|
|
216
|
+
nonceStore?: NonceStore;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Verify a single delivery's HMAC signature (CONTRACT.md §8 steps a-g) and,
|
|
220
|
+
* only on success, invoke `handler` with the parsed body (hmac_signature
|
|
221
|
+
* removed) before acking. On any failure the delivery is nacked without
|
|
222
|
+
* requeue and a security event is emitted that never contains the HMAC
|
|
223
|
+
* value or the signing key.
|
|
224
|
+
*
|
|
225
|
+
* Exported (not just used internally) so it is the same separately-testable
|
|
226
|
+
* unit backing `consume`'s per-message loop, mirroring the Rust SDK's
|
|
227
|
+
* `verify_and_dispatch`.
|
|
228
|
+
*/
|
|
229
|
+
declare function verifyAndDispatch(channel: ConsumeChannel, msg: ConsumeMessage, signingKey: Buffer, handler: (event: Record<string, unknown>) => Promise<void>, options?: ConsumeOptions): Promise<void>;
|
|
230
|
+
/**
|
|
231
|
+
* Connect to the AMQP broker at `amqpUrl`, declare `queue` as durable, and
|
|
232
|
+
* consume from it — verifying each delivery's HMAC-SHA256 signature
|
|
233
|
+
* (CONTRACT.md §8) BEFORE invoking `handler`. The handler never sees an
|
|
234
|
+
* unverified message; verification failures are nacked without requeue and
|
|
235
|
+
* logged as a security event.
|
|
236
|
+
*
|
|
237
|
+
* `signingKey` is a required, caller-supplied `Sensitive<Buffer>` — the SDK
|
|
238
|
+
* does not fetch it from the server (no such endpoint exists; CONTRACT.md
|
|
239
|
+
* §8.1 assumes out-of-band provisioning).
|
|
240
|
+
*
|
|
241
|
+
* This function owns the full ack/nack loop; `handler` MUST NOT itself call
|
|
242
|
+
* ack/nack (there is no delivery handle exposed to it).
|
|
243
|
+
*/
|
|
244
|
+
declare function consume(amqpUrl: string, queue: string, signingKey: Sensitive<Buffer>, handler: (event: Record<string, unknown>) => Promise<void>, options?: ConsumeOptions): Promise<void>;
|
|
245
|
+
|
|
246
|
+
export { type AuditEventMessage, type AuthzRequest, type AuthzResponse, type ConsumeChannel, type ConsumeLogger, type ConsumeOptions, DEFAULT_REPLAY_SKEW_MS, HMAC_SIGNED_MESSAGE_TYPES, type HmacSignedMessageType, InMemoryNonceStore, type NonceStore, type NotificationEvent, Sensitive, consume, signPayload, verifyAndDispatch, verifyPayload };
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var amqp = require('amqplib');
|
|
5
|
+
|
|
6
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
7
|
+
|
|
8
|
+
var amqp__default = /*#__PURE__*/_interopDefault(amqp);
|
|
9
|
+
|
|
10
|
+
// src/core/sensitive.ts
|
|
11
|
+
var REDACTED = "[SENSITIVE]";
|
|
12
|
+
var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
13
|
+
var Sensitive = class {
|
|
14
|
+
#value;
|
|
15
|
+
constructor(value) {
|
|
16
|
+
this.#value = value;
|
|
17
|
+
}
|
|
18
|
+
/** @internal package-only accessor. Never pass the return value to a log/serialize sink. */
|
|
19
|
+
expose() {
|
|
20
|
+
return this.#value;
|
|
21
|
+
}
|
|
22
|
+
toString() {
|
|
23
|
+
return REDACTED;
|
|
24
|
+
}
|
|
25
|
+
toJSON() {
|
|
26
|
+
return REDACTED;
|
|
27
|
+
}
|
|
28
|
+
[NODE_INSPECT_CUSTOM]() {
|
|
29
|
+
return REDACTED;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
function signPayload(key, payloadJson) {
|
|
33
|
+
return crypto.createHmac("sha256", key).update(payloadJson).digest("hex");
|
|
34
|
+
}
|
|
35
|
+
function verifyPayload(key, payloadJson, signatureHex) {
|
|
36
|
+
const expected = crypto.createHmac("sha256", key).update(payloadJson).digest();
|
|
37
|
+
let received;
|
|
38
|
+
try {
|
|
39
|
+
received = Buffer.from(signatureHex, "hex");
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (received.length !== expected.length) return false;
|
|
44
|
+
return crypto.timingSafeEqual(received, expected);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/amqp/messages.ts
|
|
48
|
+
var HMAC_SIGNED_MESSAGE_TYPES = ["AuthzRequest", "AuditEventMessage"];
|
|
49
|
+
var DEFAULT_REPLAY_SKEW_MS = 5 * 60 * 1e3;
|
|
50
|
+
var InMemoryNonceStore = class {
|
|
51
|
+
seenUntilMs = /* @__PURE__ */ new Map();
|
|
52
|
+
checkAndRecord(nonce, ttlMs) {
|
|
53
|
+
const now = Date.now();
|
|
54
|
+
this.prune(now);
|
|
55
|
+
const expiry = this.seenUntilMs.get(nonce);
|
|
56
|
+
if (expiry !== void 0 && expiry > now) {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
this.seenUntilMs.set(nonce, now + ttlMs);
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
prune(now) {
|
|
63
|
+
for (const [nonce, expiry] of this.seenUntilMs) {
|
|
64
|
+
if (expiry <= now) this.seenUntilMs.delete(nonce);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
function checkReplayProtection(body, skewMs, nonceStore) {
|
|
69
|
+
const keyVersion = body.key_version;
|
|
70
|
+
if (typeof keyVersion !== "number" || keyVersion < 2) {
|
|
71
|
+
return "key_version";
|
|
72
|
+
}
|
|
73
|
+
const issuedAtRaw = body.issued_at;
|
|
74
|
+
if (typeof issuedAtRaw !== "string") {
|
|
75
|
+
return "issued_at";
|
|
76
|
+
}
|
|
77
|
+
const issuedAtMs = Date.parse(issuedAtRaw);
|
|
78
|
+
if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {
|
|
79
|
+
return "issued_at";
|
|
80
|
+
}
|
|
81
|
+
const nonce = body.nonce;
|
|
82
|
+
if (typeof nonce !== "string" || nonce.length === 0) {
|
|
83
|
+
return "nonce";
|
|
84
|
+
}
|
|
85
|
+
if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {
|
|
86
|
+
return "nonce";
|
|
87
|
+
}
|
|
88
|
+
return void 0;
|
|
89
|
+
}
|
|
90
|
+
async function verifyAndDispatch(channel, msg, signingKey, handler, options = {}) {
|
|
91
|
+
const { logger, strict = true } = options;
|
|
92
|
+
let body;
|
|
93
|
+
try {
|
|
94
|
+
body = JSON.parse(msg.content.toString("utf8"));
|
|
95
|
+
} catch {
|
|
96
|
+
logger?.warn("axiam_sdk.security", "AMQP message body failed JSON parse; nacking without requeue", {
|
|
97
|
+
exchange: msg.fields.exchange,
|
|
98
|
+
routingKey: msg.fields.routingKey
|
|
99
|
+
});
|
|
100
|
+
channel.nack(msg, false, false);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const sig = typeof body.hmac_signature === "string" ? body.hmac_signature : void 0;
|
|
104
|
+
delete body.hmac_signature;
|
|
105
|
+
const canonical = Buffer.from(JSON.stringify(body), "utf8");
|
|
106
|
+
let verified;
|
|
107
|
+
if (sig !== void 0) {
|
|
108
|
+
verified = verifyPayload(signingKey, canonical, sig);
|
|
109
|
+
} else {
|
|
110
|
+
verified = !strict;
|
|
111
|
+
}
|
|
112
|
+
if (!verified) {
|
|
113
|
+
const tenantContext = {};
|
|
114
|
+
if (typeof body.tenant_id === "string") tenantContext.tenantId = body.tenant_id;
|
|
115
|
+
logger?.warn("axiam_sdk.security", "AMQP HMAC verification failed; nacking without requeue", {
|
|
116
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
117
|
+
exchange: msg.fields.exchange,
|
|
118
|
+
routingKey: msg.fields.routingKey,
|
|
119
|
+
...tenantContext
|
|
120
|
+
});
|
|
121
|
+
channel.nack(msg, false, false);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;
|
|
125
|
+
const nonceStore = options.nonceStore ?? new InMemoryNonceStore();
|
|
126
|
+
const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);
|
|
127
|
+
if (replayRejectReason) {
|
|
128
|
+
const tenantContext = {};
|
|
129
|
+
if (typeof body.tenant_id === "string") tenantContext.tenantId = body.tenant_id;
|
|
130
|
+
logger?.warn(
|
|
131
|
+
"axiam_sdk.security",
|
|
132
|
+
`AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,
|
|
133
|
+
{
|
|
134
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
135
|
+
exchange: msg.fields.exchange,
|
|
136
|
+
routingKey: msg.fields.routingKey,
|
|
137
|
+
...tenantContext
|
|
138
|
+
}
|
|
139
|
+
);
|
|
140
|
+
channel.nack(msg, false, false);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
await handler(body);
|
|
145
|
+
} catch (err) {
|
|
146
|
+
logger?.warn("axiam_sdk.security", "AMQP handler threw; nacking without requeue", {
|
|
147
|
+
exchange: msg.fields.exchange,
|
|
148
|
+
routingKey: msg.fields.routingKey,
|
|
149
|
+
error: err instanceof Error ? err.message : String(err)
|
|
150
|
+
});
|
|
151
|
+
channel.nack(msg, false, false);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
channel.ack(msg);
|
|
155
|
+
}
|
|
156
|
+
async function consume(amqpUrl, queue, signingKey, handler, options = {}) {
|
|
157
|
+
const connection = await amqp__default.default.connect(amqpUrl);
|
|
158
|
+
const channel = await connection.createChannel();
|
|
159
|
+
await channel.assertQueue(queue, { durable: true });
|
|
160
|
+
const sharedOptions = {
|
|
161
|
+
...options,
|
|
162
|
+
nonceStore: options.nonceStore ?? new InMemoryNonceStore()
|
|
163
|
+
};
|
|
164
|
+
await channel.consume(queue, (msg) => {
|
|
165
|
+
if (!msg) return;
|
|
166
|
+
void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
exports.DEFAULT_REPLAY_SKEW_MS = DEFAULT_REPLAY_SKEW_MS;
|
|
171
|
+
exports.HMAC_SIGNED_MESSAGE_TYPES = HMAC_SIGNED_MESSAGE_TYPES;
|
|
172
|
+
exports.InMemoryNonceStore = InMemoryNonceStore;
|
|
173
|
+
exports.Sensitive = Sensitive;
|
|
174
|
+
exports.consume = consume;
|
|
175
|
+
exports.signPayload = signPayload;
|
|
176
|
+
exports.verifyAndDispatch = verifyAndDispatch;
|
|
177
|
+
exports.verifyPayload = verifyPayload;
|
|
178
|
+
//# sourceMappingURL=index.js.map
|
|
179
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/sensitive.ts","../../src/amqp/hmac.ts","../../src/amqp/messages.ts","../../src/amqp/consumer.ts"],"names":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AAO,CAAC,GAAA,KAAQ;AACpC,IAAA,IAAI,CAAC,GAAA,EAAK;AACV,IAAA,KAAK,kBAAkB,OAAA,EAAS,GAAA,EAAK,WAAW,MAAA,EAAO,EAAG,SAAS,aAAa,CAAA;AAAA,EAClF,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\nexport class Sensitive<T> {\n readonly #value: T;\n\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n toString(): string {\n return REDACTED;\n }\n\n toJSON(): string {\n return REDACTED;\n }\n\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// AMQP HMAC-SHA256 sign/verify (CONTRACT.md §8, D-12).\n//\n// Mirror, never import. This module reproduces the server's algorithm in\n// crates/axiam-amqp/src/messages.rs:35-50 (and the Rust SDK's src/amqp/hmac.rs)\n// byte-for-byte using only Node's built-in `node:crypto` module, so the\n// SDK's HMAC output is wire-compatible with the AXIAM server for the same\n// key + canonical JSON payload bytes.\n//\n// Protocol (CONTRACT.md §8.2):\n// a. Extract hmac_signature from the message.\n// b. Set hmac_signature to null/absent in the body.\n// c. Serialize the remaining body to canonical JSON (declaration/insertion\n// order, no re-sorting — see messages.ts and Pitfall 5).\n// d. HMAC-SHA256(key, canonical_json_bytes), hex-encoded.\n// e. Constant-time compare against the received signature.\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/**\n * Compute the hex-encoded HMAC-SHA256 of `payloadJson` using `key`.\n *\n * `payloadJson` MUST be the canonical JSON bytes of the message body with\n * `hmac_signature` already removed — otherwise the signature is computed\n * over a payload that includes a placeholder signature, making verification\n * impossible (matches the server's `sign_payload` doc comment).\n */\nexport function signPayload(key: Buffer, payloadJson: Buffer): string {\n return createHmac('sha256', key).update(payloadJson).digest('hex');\n}\n\n/**\n * Verify a hex-encoded HMAC-SHA256 signature over `payloadJson` using `key`.\n *\n * Returns `true` only if the signature matches, comparing in constant time\n * via `timingSafeEqual`. Never throws: malformed hex or a length mismatch\n * both return `false`.\n */\nexport function verifyPayload(key: Buffer, payloadJson: Buffer, signatureHex: string): boolean {\n const expected = createHmac('sha256', key).update(payloadJson).digest();\n let received: Buffer;\n try {\n received = Buffer.from(signatureHex, 'hex');\n } catch {\n return false;\n }\n // timingSafeEqual requires equal-length buffers; a length mismatch is\n // itself not secret information, so a fast-path length check first is\n // safe and matches Rust's hmac crate `verify_slice` behavior.\n if (received.length !== expected.length) return false;\n return timingSafeEqual(received, expected);\n}\n","// AMQP message DTOs mirroring the server's wire format (CONTRACT.md §8).\n//\n// Mirror, never import. These interfaces reproduce field declaration order\n// byte-for-byte from crates/axiam-amqp/src/messages.rs (and\n// the Rust SDK's src/amqp/messages.rs) so that `JSON.stringify` on a parsed\n// object (after deleting `hmac_signature`) produces canonical JSON\n// byte-identical to what the server signs/verifies against — see\n// Pitfall 5: no schema-validator reconstruction step before HMAC\n// verification, or the field order (and therefore the signed bytes) could\n// silently diverge.\n\n/**\n * Authorization check request received from `axiam.authz.request`.\n *\n * Field declaration order matches the server's `AuthzRequest`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * correlation_id, tenant_id, subject_id, action, resource_id, scope,\n * key_version, nonce, issued_at, hmac_signature. `key_version`, `nonce`, and\n * `issued_at` are always emitted (never omitted) so they fall inside the\n * HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay Protection\".\n */\nexport interface AuthzRequest {\n /** Caller-provided ID to correlate request with response. */\n correlation_id: string;\n tenant_id: string;\n subject_id: string;\n action: string;\n resource_id: string;\n scope?: string;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /**\n * HMAC-SHA256 of the JSON-serialized message body (this field removed\n * before signing). Computed with the per-tenant AMQP signing key\n * (CONTRACT.md §8). The consumer MUST verify this before processing; a\n * missing signature is rejected in strict mode (the default).\n */\n hmac_signature?: string;\n}\n\n/**\n * Authorization decision published to `axiam.authz.response`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface AuthzResponse {\n correlation_id: string;\n allowed: boolean;\n reason?: string;\n}\n\n/**\n * Audit event received from external services via `axiam.audit.events`.\n *\n * Field declaration order matches the server's `AuditEventMessage`\n * (crates/axiam-amqp/src/messages.rs) v2 (`key_version = 2`, NEW-4) exactly:\n * tenant_id, actor_id, actor_type, action, resource_id, outcome, ip_address,\n * metadata, key_version, nonce, issued_at, hmac_signature. `key_version`,\n * `nonce`, and `issued_at` are always emitted (never omitted) so they fall\n * inside the HMAC-signed bytes — see CONTRACT.md §8 \"v2 — Replay\n * Protection\".\n */\nexport interface AuditEventMessage {\n tenant_id: string;\n actor_id: string;\n actor_type: string;\n action: string;\n resource_id?: string;\n outcome: string;\n ip_address?: string;\n metadata?: Record<string, unknown>;\n /**\n * HKDF master-key rotation version (SECHRD-08 / D-05b). The server\n * rejects (nack, requeue:false) any message with `key_version < 2` — v1\n * predates the mandatory `nonce`/`issued_at` replay-protection fields and\n * has no grace-window acceptance path (NEW-4, hard cutover).\n */\n key_version: number;\n /**\n * Per-message unique value (UUIDv4) for replay protection (NEW-4).\n * Always emitted so it is covered by the HMAC. A nonce already seen\n * within the freshness window is a replay and MUST be rejected.\n */\n nonce: string;\n /**\n * Producer send time (RFC3339/ISO8601 UTC), always emitted so it is\n * covered by the HMAC (NEW-4). A message outside ±skew (default 5\n * minutes) of the verifier's clock MUST be rejected as stale.\n */\n issued_at: string;\n /** HMAC-SHA256 of the JSON-serialized message body (CONTRACT.md §8). */\n hmac_signature?: string;\n}\n\n/**\n * Notification event published to `axiam.notifications`.\n *\n * Does not carry `hmac_signature` in v1.0 (CONTRACT.md §8, message-types\n * table).\n */\nexport interface NotificationEvent {\n event_type: string;\n tenant_id: string;\n actor_id: string;\n resource_id?: string;\n timestamp: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Message type names subject to HMAC verification per CONTRACT.md §8's\n * message-types table (`axiam.authz.request` -> AuthzRequest,\n * `axiam.audit.events` -> AuditEventMessage). `AuthzResponse` and\n * `NotificationEvent` are server-published and never carry\n * `hmac_signature`.\n */\nexport const HMAC_SIGNED_MESSAGE_TYPES = ['AuthzRequest', 'AuditEventMessage'] as const;\n\nexport type HmacSignedMessageType = (typeof HMAC_SIGNED_MESSAGE_TYPES)[number];\n","// Closure-handler AMQP consumer (D-12, CONTRACT.md §8.3g/§8.4).\n//\n// The SDK owns the full ack/nack loop. Every delivery is HMAC-verified\n// (CONTRACT.md §8) BEFORE the caller-supplied handler is ever invoked. On\n// any verification failure (signature mismatch, missing signature in the\n// default strict mode, or a body that fails to parse as JSON) the delivery\n// is nacked WITHOUT requeue and a security event is emitted — the event\n// never contains the received/expected HMAC value or the signing key. Only\n// a verified delivery reaches the handler, and only then is it acked.\n//\n// NEW-4 (CONTRACT.md §8 \"v2 — Replay Protection\", hard cutover): once the\n// HMAC verifies, the delivery is ADDITIONALLY rejected (same nack-without-\n// requeue path) when `key_version < 2`, `issued_at` falls outside the\n// ±skew freshness window, or `nonce` has already been seen. Because this\n// module verifies by re-serializing the parsed body (minus\n// `hmac_signature`) in insertion order (Pitfall 5), `nonce`/`issued_at` are\n// already covered by the HMAC bytes with no canonicalization change — only\n// the three validation gates below are new.\n//\n// This is the TS port of the already-tested Rust `verify_and_dispatch`/\n// `consume` (the Rust SDK's src/amqp/consumer.rs).\n\nimport amqp from 'amqplib';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport type { Sensitive } from '../core/index.js';\nimport { verifyPayload } from './hmac.js';\n\n/**\n * Default freshness skew for `issued_at` acceptance (NEW-4): a message is\n * accepted only when its `issued_at` lies within ±5 minutes of the\n * verifier's clock, matching the server's\n * `DEFAULT_FRESHNESS_SKEW_SECS = 300` / `AXIAM__AMQP__REPLAY_SKEW_SECS`\n * (CONTRACT.md §8 v2).\n */\nexport const DEFAULT_REPLAY_SKEW_MS = 5 * 60 * 1000;\n\n/**\n * Nonce replay-dedup store (NEW-4). `checkAndRecord` returns `true` when\n * `nonce` has already been recorded and its dedup entry has not yet\n * expired (i.e. this delivery is a replay); otherwise it records the nonce\n * with the given TTL and returns `false`.\n */\nexport interface NonceStore {\n checkAndRecord(nonce: string, ttlMs: number): boolean;\n}\n\n/**\n * Default in-memory nonce dedup store (NEW-4). Naturally bounded: each\n * entry expires after `ttlMs` (the caller passes 2x the freshness skew, so\n * a nonce can never still be \"fresh\" once its dedup entry has lapsed) and\n * expired entries are pruned opportunistically on each check — no\n * background timer and no unbounded growth under sustained traffic.\n *\n * Share ONE instance across every delivery from the same consumer (as\n * `consume()` does by default) — a fresh store per call provides no\n * cross-message replay protection.\n */\nexport class InMemoryNonceStore implements NonceStore {\n private readonly seenUntilMs = new Map<string, number>();\n\n checkAndRecord(nonce: string, ttlMs: number): boolean {\n const now = Date.now();\n this.prune(now);\n const expiry = this.seenUntilMs.get(nonce);\n if (expiry !== undefined && expiry > now) {\n return true;\n }\n this.seenUntilMs.set(nonce, now + ttlMs);\n return false;\n }\n\n private prune(now: number): void {\n for (const [nonce, expiry] of this.seenUntilMs) {\n if (expiry <= now) this.seenUntilMs.delete(nonce);\n }\n }\n}\n\ntype ReplayRejectReason = 'key_version' | 'issued_at' | 'nonce';\n\n/**\n * NEW-4 validation gates, checked only AFTER the HMAC has already verified.\n * Returns the failing gate's name, or `undefined` when all three pass.\n * `ttlMs` for the nonce store is 2x `skewMs` — the freshness window plus a\n * margin so a nonce cannot be replayed the instant its dedup entry expires\n * while `issued_at` might still (barely) be judged fresh by a differently-\n * skewed verifier.\n */\nfunction checkReplayProtection(\n body: Record<string, unknown>,\n skewMs: number,\n nonceStore: NonceStore,\n): ReplayRejectReason | undefined {\n const keyVersion = body.key_version;\n if (typeof keyVersion !== 'number' || keyVersion < 2) {\n return 'key_version';\n }\n\n const issuedAtRaw = body.issued_at;\n if (typeof issuedAtRaw !== 'string') {\n return 'issued_at';\n }\n const issuedAtMs = Date.parse(issuedAtRaw);\n if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {\n return 'issued_at';\n }\n\n const nonce = body.nonce;\n if (typeof nonce !== 'string' || nonce.length === 0) {\n return 'nonce';\n }\n if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {\n return 'nonce';\n }\n\n return undefined;\n}\n\n/**\n * Minimal seam over the channel operations this module needs\n * (ack/nack/consume). `amqplib`'s `Channel` implements this directly;\n * tests provide a recording fake that never touches a live broker, so the\n * security-sensitive nack-without-requeue behavior can be asserted without\n * a running RabbitMQ instance.\n */\nexport interface ConsumeChannel {\n consume(\n queue: string,\n onMessage: (msg: ConsumeMessage | null) => void | Promise<void>,\n ): Promise<unknown>;\n /** `channel.ack(msg, allUpTo?)` — allUpTo intentionally omitted/false here. */\n ack(msg: ConsumeMessage): void;\n /** `channel.nack(msg, allUpTo, requeue)` — positional booleans (Pitfall 4). */\n nack(msg: ConsumeMessage, allUpTo: boolean, requeue: boolean): void;\n}\n\nexport interface ConsumeLogger {\n warn(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface ConsumeOptions {\n logger?: ConsumeLogger;\n /**\n * Strict mode (default true, CONTRACT.md §8.3): a message with no\n * `hmac_signature` is treated as a verification failure (nack-no-requeue),\n * not a pass-through. Lenient mode (false) is a temporary rolling-\n * deployment measure only — strict MUST remain the default.\n */\n strict?: boolean;\n /**\n * Freshness skew window for `issued_at` validation (NEW-4), in\n * milliseconds. Defaults to {@link DEFAULT_REPLAY_SKEW_MS} (5 minutes),\n * matching the server default (CONTRACT.md §8 v2).\n */\n skewMs?: number;\n /**\n * Nonce replay-dedup store (NEW-4). Defaults to a fresh\n * `InMemoryNonceStore` per call when omitted — `consume()` creates and\n * shares ONE store across every delivery on that connection by default;\n * callers invoking `verifyAndDispatch` directly across multiple messages\n * must pass the same store explicitly for dedup to take effect.\n */\n nonceStore?: NonceStore;\n}\n\n/**\n * Verify a single delivery's HMAC signature (CONTRACT.md §8 steps a-g) and,\n * only on success, invoke `handler` with the parsed body (hmac_signature\n * removed) before acking. On any failure the delivery is nacked without\n * requeue and a security event is emitted that never contains the HMAC\n * value or the signing key.\n *\n * Exported (not just used internally) so it is the same separately-testable\n * unit backing `consume`'s per-message loop, mirroring the Rust SDK's\n * `verify_and_dispatch`.\n */\nexport async function verifyAndDispatch(\n channel: ConsumeChannel,\n msg: ConsumeMessage,\n signingKey: Buffer,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const { logger, strict = true } = options;\n\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(msg.content.toString('utf8')) as Record<string, unknown>;\n } catch {\n logger?.warn('axiam_sdk.security', 'AMQP message body failed JSON parse; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n const sig = typeof body.hmac_signature === 'string' ? body.hmac_signature : undefined;\n delete body.hmac_signature;\n const canonical = Buffer.from(JSON.stringify(body), 'utf8');\n\n // Strict mode (default, CONTRACT.md §8.3): a missing signature is treated\n // as a verification failure, not a pass-through. A present signature is\n // always verified regardless of strict/lenient mode; lenient mode only\n // changes the outcome for a MISSING signature (temporary rolling-\n // deployment measure — strict MUST remain the default).\n let verified: boolean;\n if (sig !== undefined) {\n verified = verifyPayload(signingKey, canonical, sig);\n } else {\n verified = !strict;\n }\n\n if (!verified) {\n // Security event (§8.4): timestamp, exchange, routing key, and tenant\n // context (if present in the body) — NEVER the signature value or the\n // signing key.\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn('axiam_sdk.security', 'AMQP HMAC verification failed; nacking without requeue', {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n // NEW-4 (CONTRACT.md §8 v2, hard cutover): only reached once the HMAC has\n // verified. `body` was re-serialized in insertion order to compute\n // `canonical` above, so `nonce`/`issued_at` are already inside the bytes\n // that were just verified — these are the three ADDITIONAL validation\n // gates (key_version, freshness, replay), not re-verification.\n const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;\n const nonceStore = options.nonceStore ?? new InMemoryNonceStore();\n const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);\n if (replayRejectReason) {\n const tenantContext: Record<string, unknown> = {};\n if (typeof body.tenant_id === 'string') tenantContext.tenantId = body.tenant_id;\n logger?.warn(\n 'axiam_sdk.security',\n `AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,\n {\n timestamp: new Date().toISOString(),\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n ...tenantContext,\n },\n );\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n try {\n await handler(body);\n } catch (err) {\n // Do not requeue a handler-crashing message into a hot loop.\n logger?.warn('axiam_sdk.security', 'AMQP handler threw; nacking without requeue', {\n exchange: msg.fields.exchange,\n routingKey: msg.fields.routingKey,\n error: err instanceof Error ? err.message : String(err),\n });\n // channel.nack(msg, /* allUpTo */ false, /* requeue */ false)\n channel.nack(msg, false, false);\n return;\n }\n\n channel.ack(msg);\n}\n\n/**\n * Connect to the AMQP broker at `amqpUrl`, declare `queue` as durable, and\n * consume from it — verifying each delivery's HMAC-SHA256 signature\n * (CONTRACT.md §8) BEFORE invoking `handler`. The handler never sees an\n * unverified message; verification failures are nacked without requeue and\n * logged as a security event.\n *\n * `signingKey` is a required, caller-supplied `Sensitive<Buffer>` — the SDK\n * does not fetch it from the server (no such endpoint exists; CONTRACT.md\n * §8.1 assumes out-of-band provisioning).\n *\n * This function owns the full ack/nack loop; `handler` MUST NOT itself call\n * ack/nack (there is no delivery handle exposed to it).\n */\nexport async function consume(\n amqpUrl: string,\n queue: string,\n signingKey: Sensitive<Buffer>,\n handler: (event: Record<string, unknown>) => Promise<void>,\n options: ConsumeOptions = {},\n): Promise<void> {\n const connection = await amqp.connect(amqpUrl);\n const channel: Channel = await connection.createChannel();\n await channel.assertQueue(queue, { durable: true });\n\n // NEW-4: one nonce store shared across every delivery on this consumer —\n // a fresh store per message (the per-call default in `verifyAndDispatch`)\n // would defeat replay dedup entirely.\n const sharedOptions: ConsumeOptions = {\n ...options,\n nonceStore: options.nonceStore ?? new InMemoryNonceStore(),\n };\n\n await channel.consume(queue, (msg) => {\n if (!msg) return;\n void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);\n });\n}\n"]}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'crypto';
|
|
2
|
+
import amqp from 'amqplib';
|
|
3
|
+
|
|
4
|
+
// src/core/sensitive.ts
|
|
5
|
+
var REDACTED = "[SENSITIVE]";
|
|
6
|
+
var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
7
|
+
var Sensitive = class {
|
|
8
|
+
#value;
|
|
9
|
+
constructor(value) {
|
|
10
|
+
this.#value = value;
|
|
11
|
+
}
|
|
12
|
+
/** @internal package-only accessor. Never pass the return value to a log/serialize sink. */
|
|
13
|
+
expose() {
|
|
14
|
+
return this.#value;
|
|
15
|
+
}
|
|
16
|
+
toString() {
|
|
17
|
+
return REDACTED;
|
|
18
|
+
}
|
|
19
|
+
toJSON() {
|
|
20
|
+
return REDACTED;
|
|
21
|
+
}
|
|
22
|
+
[NODE_INSPECT_CUSTOM]() {
|
|
23
|
+
return REDACTED;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
function signPayload(key, payloadJson) {
|
|
27
|
+
return createHmac("sha256", key).update(payloadJson).digest("hex");
|
|
28
|
+
}
|
|
29
|
+
function verifyPayload(key, payloadJson, signatureHex) {
|
|
30
|
+
const expected = createHmac("sha256", key).update(payloadJson).digest();
|
|
31
|
+
let received;
|
|
32
|
+
try {
|
|
33
|
+
received = Buffer.from(signatureHex, "hex");
|
|
34
|
+
} catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (received.length !== expected.length) return false;
|
|
38
|
+
return timingSafeEqual(received, expected);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// src/amqp/messages.ts
|
|
42
|
+
var HMAC_SIGNED_MESSAGE_TYPES = ["AuthzRequest", "AuditEventMessage"];
|
|
43
|
+
var DEFAULT_REPLAY_SKEW_MS = 5 * 60 * 1e3;
|
|
44
|
+
var InMemoryNonceStore = class {
|
|
45
|
+
seenUntilMs = /* @__PURE__ */ new Map();
|
|
46
|
+
checkAndRecord(nonce, ttlMs) {
|
|
47
|
+
const now = Date.now();
|
|
48
|
+
this.prune(now);
|
|
49
|
+
const expiry = this.seenUntilMs.get(nonce);
|
|
50
|
+
if (expiry !== void 0 && expiry > now) {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
this.seenUntilMs.set(nonce, now + ttlMs);
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
prune(now) {
|
|
57
|
+
for (const [nonce, expiry] of this.seenUntilMs) {
|
|
58
|
+
if (expiry <= now) this.seenUntilMs.delete(nonce);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
function checkReplayProtection(body, skewMs, nonceStore) {
|
|
63
|
+
const keyVersion = body.key_version;
|
|
64
|
+
if (typeof keyVersion !== "number" || keyVersion < 2) {
|
|
65
|
+
return "key_version";
|
|
66
|
+
}
|
|
67
|
+
const issuedAtRaw = body.issued_at;
|
|
68
|
+
if (typeof issuedAtRaw !== "string") {
|
|
69
|
+
return "issued_at";
|
|
70
|
+
}
|
|
71
|
+
const issuedAtMs = Date.parse(issuedAtRaw);
|
|
72
|
+
if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {
|
|
73
|
+
return "issued_at";
|
|
74
|
+
}
|
|
75
|
+
const nonce = body.nonce;
|
|
76
|
+
if (typeof nonce !== "string" || nonce.length === 0) {
|
|
77
|
+
return "nonce";
|
|
78
|
+
}
|
|
79
|
+
if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {
|
|
80
|
+
return "nonce";
|
|
81
|
+
}
|
|
82
|
+
return void 0;
|
|
83
|
+
}
|
|
84
|
+
async function verifyAndDispatch(channel, msg, signingKey, handler, options = {}) {
|
|
85
|
+
const { logger, strict = true } = options;
|
|
86
|
+
let body;
|
|
87
|
+
try {
|
|
88
|
+
body = JSON.parse(msg.content.toString("utf8"));
|
|
89
|
+
} catch {
|
|
90
|
+
logger?.warn("axiam_sdk.security", "AMQP message body failed JSON parse; nacking without requeue", {
|
|
91
|
+
exchange: msg.fields.exchange,
|
|
92
|
+
routingKey: msg.fields.routingKey
|
|
93
|
+
});
|
|
94
|
+
channel.nack(msg, false, false);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const sig = typeof body.hmac_signature === "string" ? body.hmac_signature : void 0;
|
|
98
|
+
delete body.hmac_signature;
|
|
99
|
+
const canonical = Buffer.from(JSON.stringify(body), "utf8");
|
|
100
|
+
let verified;
|
|
101
|
+
if (sig !== void 0) {
|
|
102
|
+
verified = verifyPayload(signingKey, canonical, sig);
|
|
103
|
+
} else {
|
|
104
|
+
verified = !strict;
|
|
105
|
+
}
|
|
106
|
+
if (!verified) {
|
|
107
|
+
const tenantContext = {};
|
|
108
|
+
if (typeof body.tenant_id === "string") tenantContext.tenantId = body.tenant_id;
|
|
109
|
+
logger?.warn("axiam_sdk.security", "AMQP HMAC verification failed; nacking without requeue", {
|
|
110
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
111
|
+
exchange: msg.fields.exchange,
|
|
112
|
+
routingKey: msg.fields.routingKey,
|
|
113
|
+
...tenantContext
|
|
114
|
+
});
|
|
115
|
+
channel.nack(msg, false, false);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;
|
|
119
|
+
const nonceStore = options.nonceStore ?? new InMemoryNonceStore();
|
|
120
|
+
const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);
|
|
121
|
+
if (replayRejectReason) {
|
|
122
|
+
const tenantContext = {};
|
|
123
|
+
if (typeof body.tenant_id === "string") tenantContext.tenantId = body.tenant_id;
|
|
124
|
+
logger?.warn(
|
|
125
|
+
"axiam_sdk.security",
|
|
126
|
+
`AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,
|
|
127
|
+
{
|
|
128
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
129
|
+
exchange: msg.fields.exchange,
|
|
130
|
+
routingKey: msg.fields.routingKey,
|
|
131
|
+
...tenantContext
|
|
132
|
+
}
|
|
133
|
+
);
|
|
134
|
+
channel.nack(msg, false, false);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
await handler(body);
|
|
139
|
+
} catch (err) {
|
|
140
|
+
logger?.warn("axiam_sdk.security", "AMQP handler threw; nacking without requeue", {
|
|
141
|
+
exchange: msg.fields.exchange,
|
|
142
|
+
routingKey: msg.fields.routingKey,
|
|
143
|
+
error: err instanceof Error ? err.message : String(err)
|
|
144
|
+
});
|
|
145
|
+
channel.nack(msg, false, false);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
channel.ack(msg);
|
|
149
|
+
}
|
|
150
|
+
async function consume(amqpUrl, queue, signingKey, handler, options = {}) {
|
|
151
|
+
const connection = await amqp.connect(amqpUrl);
|
|
152
|
+
const channel = await connection.createChannel();
|
|
153
|
+
await channel.assertQueue(queue, { durable: true });
|
|
154
|
+
const sharedOptions = {
|
|
155
|
+
...options,
|
|
156
|
+
nonceStore: options.nonceStore ?? new InMemoryNonceStore()
|
|
157
|
+
};
|
|
158
|
+
await channel.consume(queue, (msg) => {
|
|
159
|
+
if (!msg) return;
|
|
160
|
+
void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { DEFAULT_REPLAY_SKEW_MS, HMAC_SIGNED_MESSAGE_TYPES, InMemoryNonceStore, Sensitive, consume, signPayload, verifyAndDispatch, verifyPayload };
|
|
165
|
+
//# sourceMappingURL=index.mjs.map
|
|
166
|
+
//# sourceMappingURL=index.mjs.map
|