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.
Files changed (45) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +231 -0
  3. package/dist/amqp/index.d.cts +246 -0
  4. package/dist/amqp/index.d.ts +246 -0
  5. package/dist/amqp/index.js +179 -0
  6. package/dist/amqp/index.js.map +1 -0
  7. package/dist/amqp/index.mjs +166 -0
  8. package/dist/amqp/index.mjs.map +1 -0
  9. package/dist/client-B2SB-C7c.d.cts +207 -0
  10. package/dist/client-B2SB-C7c.d.ts +207 -0
  11. package/dist/grpc/index.d.cts +106 -0
  12. package/dist/grpc/index.d.ts +106 -0
  13. package/dist/grpc/index.js +908 -0
  14. package/dist/grpc/index.js.map +1 -0
  15. package/dist/grpc/index.mjs +868 -0
  16. package/dist/grpc/index.mjs.map +1 -0
  17. package/dist/index.d.cts +3 -0
  18. package/dist/index.d.ts +3 -0
  19. package/dist/index.js +561 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/index.mjs +552 -0
  22. package/dist/index.mjs.map +1 -0
  23. package/dist/jwks-CX-nhD6A.d.cts +29 -0
  24. package/dist/jwks-CX-nhD6A.d.ts +29 -0
  25. package/dist/middleware/index.d.cts +153 -0
  26. package/dist/middleware/index.d.ts +153 -0
  27. package/dist/middleware/index.js +232 -0
  28. package/dist/middleware/index.js.map +1 -0
  29. package/dist/middleware/index.mjs +220 -0
  30. package/dist/middleware/index.mjs.map +1 -0
  31. package/dist/node/index.d.cts +103 -0
  32. package/dist/node/index.d.ts +103 -0
  33. package/dist/node/index.js +717 -0
  34. package/dist/node/index.js.map +1 -0
  35. package/dist/node/index.mjs +700 -0
  36. package/dist/node/index.mjs.map +1 -0
  37. package/dist/rest/index.d.cts +27 -0
  38. package/dist/rest/index.d.ts +27 -0
  39. package/dist/rest/index.js +561 -0
  40. package/dist/rest/index.js.map +1 -0
  41. package/dist/rest/index.mjs +552 -0
  42. package/dist/rest/index.mjs.map +1 -0
  43. package/dist/sensitive-CWBH_tHr.d.cts +12 -0
  44. package/dist/sensitive-CWBH_tHr.d.ts +12 -0
  45. package/package.json +145 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,231 @@
1
+ # axiam-sdk (TypeScript/JavaScript)
2
+
3
+ Official TypeScript/JavaScript client SDK for [AXIAM](https://github.com/ilpanich/axiam) — Access eXtended Identity and Authorization Management.
4
+
5
+ ## Package identity
6
+
7
+ - **npm package:** `axiam-sdk`
8
+ - **Registry:** [npmjs.com/package/axiam-sdk](https://www.npmjs.com/package/axiam-sdk) _(reserved, not yet published)_
9
+ - **Source:** [github.com/ilpanich/axiam-typescript-sdk](https://github.com/ilpanich/axiam-typescript-sdk)
10
+ - **License:** Apache-2.0
11
+
12
+ ## Contract conformance
13
+
14
+ This SDK conforms to CONTRACT.md §1–§10.
15
+
16
+ See [`CONTRACT.md`](./CONTRACT.md) for the full cross-language behavioral contract.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install axiam-sdk
22
+ ```
23
+
24
+ ## Two personas, tree-shaken subpath entries
25
+
26
+ `axiam-sdk` ships as **one package with two personas**, each reachable through its own
27
+ `package.json` subpath so a bundler only pulls in the transport code the caller actually
28
+ imports (proven in CI by the SC#1 bundle-and-grep gate — a `/rest`-only browser bundle
29
+ never contains `@grpc/grpc-js` or `amqplib`):
30
+
31
+ | Entry point | Persona | Contents |
32
+ |-------------------------|-----------------------------|---------------------------------------------------------------------------|
33
+ | `axiam-sdk` / `axiam-sdk/rest` | Browser + Node, REST-only | `AxiamClient`: `login`/`verifyMfa`/`refresh`/`logout`, `can`/`batchCheck` over the FND-04 REST authz endpoint |
34
+ | `axiam-sdk/grpc` | Node only | Everything in `/rest` plus `AuthzGrpcClient.checkAccess`/`batchCheck` over gRPC, the Node persona (`createNodeSession`), and the local-JWKS verifier |
35
+ | `axiam-sdk/amqp` | Node only | `consume()` — HMAC-verified AMQP audit/authz event consumer (CONTRACT.md §8) |
36
+ | `axiam-sdk/middleware` | Node only | `axiamMiddleware` (Express) / `axiamPlugin` (Fastify) — shared local-JWKS verify core (CONTRACT.md §10) |
37
+
38
+ **Browser code should only ever import from `axiam-sdk` or `axiam-sdk/rest`.** Importing
39
+ `axiam-sdk/grpc`, `axiam-sdk/amqp`, or `axiam-sdk/middleware` pulls in Node-only
40
+ dependencies (`@grpc/grpc-js`, `amqplib`, `jose`'s Node crypto, `express`/`fastify` types)
41
+ that do not belong in a browser bundle.
42
+
43
+ ## Construction
44
+
45
+ `tenantSlug` (or `tenantId`) is a non-optional constructor parameter (CONTRACT.md §5) —
46
+ there is no default tenant:
47
+
48
+ ```typescript
49
+ import { AxiamClient } from 'axiam-sdk';
50
+
51
+ const client = new AxiamClient({
52
+ baseUrl: 'https://iam.example.com',
53
+ tenantSlug: 'acme',
54
+ // customCa is optional — PEM-encoded CA cert for self-signed dev environments (§6)
55
+ // customCa: pemString,
56
+ });
57
+ ```
58
+
59
+ ## Usage per persona
60
+
61
+ ### Browser — login + authz (`axiam-sdk` / `axiam-sdk/rest`)
62
+
63
+ ```typescript
64
+ import { AxiamClient } from 'axiam-sdk';
65
+
66
+ const client = new AxiamClient({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
67
+
68
+ const result = await client.login(email, password);
69
+ switch (result.status) {
70
+ case 'mfa_required': {
71
+ const code = await promptForMfaCode(result.availableMethods);
72
+ const final = await client.verifyMfa(result.mfaToken, code);
73
+ if (final.status === 'authenticated') console.log(`Authenticated as ${final.user.username}`);
74
+ break;
75
+ }
76
+ case 'authenticated': {
77
+ console.log(`Authenticated as ${result.user.username}`);
78
+ break;
79
+ }
80
+ }
81
+
82
+ // Single access check (REST-backed, browser-safe)
83
+ const allowed = await client.can('read', 'doc:1');
84
+
85
+ // Batch check — results preserve input order
86
+ const decisions = await client.batchCheck([
87
+ { action: 'read', resourceId: 'doc:1' },
88
+ { action: 'write', resourceId: 'doc:1' },
89
+ ]);
90
+ ```
91
+
92
+ Tokens arrive exclusively via `httpOnly` `Set-Cookie` — no raw session token is ever
93
+ exposed to application code. CSRF forwarding (cookie double-submit, CONTRACT.md §3) and
94
+ single-flight refresh (CONTRACT.md §9) are handled automatically.
95
+
96
+ ### Node — gRPC authz (`axiam-sdk/grpc`)
97
+
98
+ ```typescript
99
+ import { AuthzGrpcClient, createNodeSession } from 'axiam-sdk/grpc';
100
+
101
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
102
+ const grpcClient = new AuthzGrpcClient(session, { baseUrl: 'https://iam.example.com' });
103
+
104
+ const decision = await grpcClient.checkAccess({
105
+ tenantId: 'tenant-1',
106
+ subjectId: 'user-1',
107
+ action: 'read',
108
+ resourceId: 'doc:1',
109
+ });
110
+
111
+ grpcClient.close();
112
+ ```
113
+
114
+ The gRPC channel is constructed once and reused; `UNAUTHENTICATED` responses transparently
115
+ share the same single-flight refresh guard as the REST persona (CONTRACT.md §9).
116
+
117
+ ### Node — AMQP consumer (`axiam-sdk/amqp`)
118
+
119
+ ```typescript
120
+ import { consume, Sensitive } from 'axiam-sdk/amqp';
121
+
122
+ const signingKey = new Sensitive(Buffer.from(process.env.AXIAM_AMQP_SIGNING_KEY ?? '', 'hex'));
123
+
124
+ await consume('amqp://localhost:5672', 'axiam.audit.events', signingKey, async (event) => {
125
+ // Only a verified event ever reaches this closure — HMAC-SHA256
126
+ // signature checked and stripped by the SDK before your handler runs
127
+ // (CONTRACT.md §8). Verification failures are nacked-without-requeue.
128
+ console.log('verified audit event:', event);
129
+ });
130
+ ```
131
+
132
+ ### Express middleware (`axiam-sdk/middleware`)
133
+
134
+ ```typescript
135
+ import express from 'express';
136
+ import { createNodeSession } from 'axiam-sdk/grpc';
137
+ import { axiamMiddleware, type AxiamRequest } from 'axiam-sdk/middleware';
138
+
139
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
140
+ const app = express();
141
+
142
+ app.use(axiamMiddleware(session));
143
+
144
+ app.get('/protected', (req, res) => {
145
+ const axiamUser = (req as AxiamRequest).axiamUser;
146
+ res.json({ userId: axiamUser?.userId, tenantId: axiamUser?.tenantId, roles: axiamUser?.roles });
147
+ });
148
+ ```
149
+
150
+ ### Fastify plugin (`axiam-sdk/middleware`)
151
+
152
+ ```typescript
153
+ import Fastify from 'fastify';
154
+ import { createNodeSession } from 'axiam-sdk/grpc';
155
+ import { axiamPlugin, type AxiamFastifyRequest } from 'axiam-sdk/middleware';
156
+
157
+ const session = createNodeSession({ baseUrl: 'https://iam.example.com', tenantSlug: 'acme' });
158
+ const app = Fastify();
159
+
160
+ app.register(axiamPlugin(session));
161
+
162
+ app.get('/protected', (request, reply) => {
163
+ const axiamUser = (request as AxiamFastifyRequest).axiamUser;
164
+ reply.send({ userId: axiamUser?.userId, tenantId: axiamUser?.tenantId, roles: axiamUser?.roles });
165
+ });
166
+ ```
167
+
168
+ Both middleware integrations verify the session against a locally-cached JWKS (no
169
+ `cookie-parser` / `@fastify/cookie` peer dependency required), inject the authenticated
170
+ identity into the request context, and surface `AuthError` as HTTP 401 / `AuthzError` as
171
+ HTTP 403 with a standardized JSON error body (CONTRACT.md §10).
172
+
173
+ More runnable examples (all compiling under `tsc --noEmit -p examples/tsconfig.json`) live
174
+ in `examples/` at the package root.
175
+
176
+ ## Error handling
177
+
178
+ Every persona throws exactly the three CONTRACT.md §2 error types — `AuthError`,
179
+ `AuthzError`, `NetworkError`:
180
+
181
+ ```typescript
182
+ import { AuthError, AuthzError, NetworkError } from 'axiam-sdk';
183
+
184
+ try {
185
+ await client.can('read', 'doc:1');
186
+ } catch (err) {
187
+ if (err instanceof AuthError) {
188
+ // re-authenticate
189
+ } else if (err instanceof AuthzError) {
190
+ // caller lacks permission
191
+ } else if (err instanceof NetworkError) {
192
+ // transport-level failure
193
+ }
194
+ }
195
+ ```
196
+
197
+ ## Security notes
198
+
199
+ - Token-carrying values are wrapped in `Sensitive<T>` — `toString()`/`toJSON()`/
200
+ `util.inspect` all redact to `[SENSITIVE]`; the raw value is only reachable via an
201
+ explicit accessor (CONTRACT.md §7).
202
+ - Strict TLS verification is always on; the only escape hatch is the constructor's
203
+ `customCa` option for self-signed development environments (CONTRACT.md §6).
204
+ - AMQP messages are HMAC-SHA256 verified before your handler ever sees them; verification
205
+ failures are nacked without requeue (CONTRACT.md §8).
206
+
207
+ ## Release / versioning
208
+
209
+ Tagged releases follow the plain `vX.Y.Z` convention (e.g. `v1.0.0`). CI runs the full
210
+ gate suite (build, test, SC#1 bundle-and-grep, CJS-require smoke, token-leak, TLS-lint,
211
+ `npm publish --dry-run`) on every pull request, and publishes to npm with
212
+ [provenance](https://docs.npmjs.com/generating-provenance-statements) only when a `vX.Y.Z`
213
+ tag is pushed from `main` and its version matches `package.json`. The same tag publishes
214
+ the TypeDoc API reference to this repo's GitHub Pages site.
215
+
216
+ ## Building from source
217
+
218
+ The gRPC stubs under `src/gen/` are generated from `proto/` by
219
+ [buf](https://buf.build) and are deliberately not committed, so a source build needs the
220
+ `buf` CLI on `PATH`:
221
+
222
+ ```bash
223
+ npm ci
224
+ npm run generate # buf generate → src/gen (also runs automatically via prebuild)
225
+ npm run build
226
+ npm test
227
+ ```
228
+
229
+ ## License
230
+
231
+ Apache-2.0 — see [`LICENSE`](./LICENSE).
@@ -0,0 +1,246 @@
1
+ import { S as Sensitive } from '../sensitive-CWBH_tHr.cjs';
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 };