@hivemagnus/hive-common 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +11 -0
  4. package/README.md +382 -2
  5. package/dist/context/index.d.ts +86 -0
  6. package/dist/context/index.js +189 -0
  7. package/dist/contracts/index.d.ts +117 -0
  8. package/dist/contracts/index.js +228 -0
  9. package/dist/errors/index.d.ts +91 -0
  10. package/dist/errors/index.js +309 -0
  11. package/dist/events/index.d.ts +107 -0
  12. package/dist/events/index.js +232 -0
  13. package/dist/health/index.d.ts +85 -0
  14. package/dist/health/index.js +113 -0
  15. package/dist/hono/index.d.ts +64 -0
  16. package/dist/hono/index.js +105 -0
  17. package/dist/log/index.d.ts +39 -0
  18. package/dist/log/index.js +80 -0
  19. package/dist/log/redact.d.ts +23 -0
  20. package/dist/log/redact.js +111 -0
  21. package/dist/node-http/index.d.ts +43 -0
  22. package/dist/node-http/index.js +88 -0
  23. package/dist/oathweave/claims.d.ts +63 -0
  24. package/dist/oathweave/claims.js +91 -0
  25. package/dist/oathweave/conformance.d.ts +88 -0
  26. package/dist/oathweave/conformance.js +124 -0
  27. package/dist/oathweave/endpoint.d.ts +15 -0
  28. package/dist/oathweave/endpoint.js +35 -0
  29. package/dist/oathweave/errors.d.ts +19 -0
  30. package/dist/oathweave/errors.js +70 -0
  31. package/dist/oathweave/index.d.ts +10 -0
  32. package/dist/oathweave/index.js +10 -0
  33. package/dist/oathweave/links.d.ts +61 -0
  34. package/dist/oathweave/links.js +131 -0
  35. package/dist/oathweave/stream.d.ts +26 -0
  36. package/dist/oathweave/stream.js +46 -0
  37. package/dist/oathweave/verifier.d.ts +69 -0
  38. package/dist/oathweave/verifier.js +226 -0
  39. package/dist/registry/index.d.ts +138 -0
  40. package/dist/registry/index.js +175 -0
  41. package/package.json +126 -4
  42. package/test-vectors/README.md +27 -0
  43. package/test-vectors/oathweave/jwks.json +12 -0
  44. package/test-vectors/oathweave/vectors.json +174 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@hivemagnus/hive-common` are recorded here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-12
10
+
11
+ First release: the shared server kit that replaces each product's own copy of the Oathweave
12
+ verifier and its own error, health and request-ID conventions.
13
+
14
+ ### Added
15
+
16
+ - `/oathweave`: Oathweave access-token verifier. RS256 only, JWKS with caching and refetch on an
17
+ unknown key ID, exact issuer (one or several) and audience, `exp`/`nbf`/`iat` with clock
18
+ tolerance, fifteen-minute lifetime limit, user and service principals (a service token's client
19
+ ID equals its subject), scopes, roles and permissions, optional online session check through
20
+ userinfo with a 10 s shared cache, stream re-check, identity links and permission helpers.
21
+ Refusals are `OathweaveError`s with a stable `reason` and 401, 403 or 503.
22
+ - `/oathweave/conformance` and `test-vectors/oathweave/`: twelve pre-signed conformance vectors at
23
+ a fixed clock and `runOathweaveConformance()`, so every product can test its verifier.
24
+ - `/errors`: `HiveError`, the `{ error: { code, message, requestId?, details? } }` envelope,
25
+ `toErrorResponse()`, and `parseHiveError()` for every legacy error shape in the suite.
26
+ Isomorphic.
27
+ - `/health`: `/health/live` and `/health/ready` with named, time-limited dependency checks,
28
+ 200/503, and optional legacy path aliases.
29
+ - `/context`: request IDs (`x-request-id`, accepting `x-hive-request-id` and `x-correlation-id`),
30
+ W3C `traceparent`, idempotency keys, an AsyncLocalStorage request context and
31
+ `outboundHeaders()`.
32
+ - `/registry`: typed Hive Registry client with custom CA or fetch injection.
33
+ - `/log`: structured JSON logger with request IDs from the context, and `redact()`.
34
+ - `/events`: HiveEvent feed helpers and `ChatterMostNotifier` (timeout, retries with backoff,
35
+ deduplication by event ID).
36
+ - `/contracts`: isomorphic types and dependency-free validators for the envelope, HiveEvent v1,
37
+ pagination and agent identity.
38
+ - `/hono` and `/node-http` adapters for auth, request context, the error envelope and health.
39
+
40
+ [Unreleased]: https://github.com/ChefTaco/HiveCommon/compare/v0.1.0...HEAD
41
+ [0.1.0]: https://github.com/ChefTaco/HiveCommon/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,11 @@
1
+ HiveCommon (@hivemagnus/hive-common)
2
+ Copyright 2026 ChefTaco and contributors
3
+
4
+ This product includes software developed by ChefTaco and contributors
5
+ (https://github.com/ChefTaco/HiveCommon).
6
+
7
+ The Oathweave access-token verification consolidates the verifiers of the Oathweave SDK
8
+ (https://github.com/ChefTaco/Oathweave), Magnus (https://github.com/ChefTaco/magnus) and the
9
+ other Hive:Magnus products, licensed under the Apache License 2.0.
10
+
11
+ JWT and JWKS handling uses jose (https://github.com/panva/jose), licensed under the MIT License.
package/README.md CHANGED
@@ -1,3 +1,383 @@
1
- # Temporary Holding Version
1
+ # HiveCommon
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@hivemagnus/hive-common` is the shared server kit of the Hive:Magnus suite. It gives every
4
+ product one Oathweave token verifier, one error envelope, one way to serve health, propagate
5
+ request IDs and trace context, read the Hive Registry, log safely and publish HiveEvents.
6
+
7
+ - ESM only, TypeScript with `.d.ts` output, strict types.
8
+ - One runtime dependency (`jose`); `hono` is an optional peer.
9
+ - Each module is its own subpath, so a product loads only what it uses.
10
+ - `/contracts` and `/errors` are isomorphic, so the browser UI can use them too.
11
+
12
+ ```bash
13
+ npm install @hivemagnus/hive-common
14
+ ```
15
+
16
+ | Subpath | What it is | Runs in |
17
+ | --- | --- | --- |
18
+ | [`/oathweave`](#oathweave) | Oathweave access-token verifier, identity links, permissions, stream re-check | Node |
19
+ | [`/oathweave/conformance`](#conformance-vectors) | Runs the shipped test vectors against any verifier | Node |
20
+ | [`/errors`](#errors) | `HiveError`, the envelope, `toErrorResponse()`, `parseHiveError()` | Node, browser |
21
+ | [`/health`](#health) | `/health/live` and `/health/ready` with dependency checks | Node |
22
+ | [`/context`](#context) | Request IDs, `traceparent`, idempotency keys, async request context | Node |
23
+ | [`/registry`](#registry) | Typed Hive Registry client | Node |
24
+ | [`/log`](#log) | Structured JSON logger and `redact()` | Node |
25
+ | [`/events`](#events) | HiveEvent feed helpers and the ChatterMost notifier | Node |
26
+ | [`/contracts`](#contracts) | Isomorphic types and validators | Node, browser |
27
+ | [`/hono`](#hono) | Hono middleware | Node |
28
+ | [`/node-http`](#node-http) | `node:http` helpers | Node |
29
+
30
+ ## Node support policy
31
+
32
+ HiveCommon supports the active and maintenance LTS lines of Node.js at their latest security
33
+ release: currently **Node.js 24.22.3+ and 26.13.1+** (`"engines": "^24.22.3 || ^26.13.1"`). When
34
+ Node publishes a security release, the minimums move up in the next HiveCommon release. A Node
35
+ line is dropped, in a minor release, when it reaches end of life. CI tests every supported line.
36
+
37
+ ## Standards
38
+
39
+ ### Error envelope
40
+
41
+ Every error response in the suite has this body, `Content-Type: application/json` and
42
+ `Cache-Control: no-store`:
43
+
44
+ ```json
45
+ { "error": { "code": "not_found", "message": "No such project", "requestId": "2f1c…", "details": { "id": "p1" } } }
46
+ ```
47
+
48
+ - `code`: stable, machine-readable, `lower_snake_case` for new codes.
49
+ - `message`: for people. Never contains secrets, stack traces or upstream bodies.
50
+ - `requestId`: the request's `x-request-id`, when known.
51
+ - `details`: optional structured data, such as validation `issues` or an auth `reason`.
52
+
53
+ Statuses: 400 malformed, 401 missing or invalid credentials (with `WWW-Authenticate`), 403 known
54
+ caller without access, 404, 409, 422 validation, 428 missing precondition (idempotency key), 429
55
+ (with `Retry-After`), 500 internal (generic message only), 503 dependency unavailable.
56
+
57
+ ### Headers
58
+
59
+ | Header | Rule |
60
+ | --- | --- |
61
+ | `x-request-id` | Read inbound; also accept `x-hive-request-id` and `x-correlation-id`. Generate a UUID when absent or unsafe (1-128 of `[A-Za-z0-9._:@/+=-]`). Echo it on the response and send it to peers. |
62
+ | `traceparent`, `tracestate` | W3C Trace Context. Continue a valid inbound trace with a new span; otherwise start one. Send this service's span to peers. |
63
+ | `Idempotency-Key` | Required on retried mutations; `x-idempotency-key` is accepted too. Both present and different is a 400. |
64
+ | `Authorization: Bearer` | Oathweave access token, RS256. |
65
+
66
+ ### Health
67
+
68
+ `GET /health/live` is 200 whenever the process can answer and never touches dependencies.
69
+ `GET /health/ready` runs the named checks and is 200 (`ready` or `degraded`) or 503 (`not_ready`):
70
+
71
+ ```json
72
+ { "status": "not_ready", "service": "hivemem", "version": "1.4.0", "time": "2026-11-12T08:00:00.000Z",
73
+ "checks": { "database": { "status": "down", "critical": true, "latencyMs": 2001, "error": "timeout" } } }
74
+ ```
75
+
76
+ ## Modules
77
+
78
+ ### oathweave
79
+
80
+ ```ts
81
+ import { createOathweaveVerifier, requireIdentityLink, parseIdentityLinks } from '@hivemagnus/hive-common/oathweave';
82
+
83
+ const verifier = createOathweaveVerifier({
84
+ issuer: process.env.OATHWEAVE_ISSUER!, // https only; an array accepts several issuers
85
+ audience: 'hivemem', // this product's resource audience, exact match
86
+ jwksUrl: process.env.OATHWEAVE_JWKS_URL!,
87
+ userinfoUrl: process.env.OATHWEAVE_USERINFO_URL, // online session check, recommended
88
+ accept: 'user', // default; 'service' or 'any' per route
89
+ });
90
+
91
+ const principal = await verifier.verifyAuthorization(request.headers.get('authorization'));
92
+ // principal.kind === 'user': subject, sessionId, clientId, roles, permissions, scopes, displayName, authTime…
93
+ // principal.kind === 'service': a client-credentials token whose client ID equals its subject.
94
+
95
+ const links = parseIdentityLinks(process.env.HIVEMEM_OATHWEAVE_IDENTITIES_JSON!, { roles: ['ADMIN', 'VIEWER'] });
96
+ const link = requireIdentityLink(links, principal); // 403 not_linked unless exactly one link matches
97
+ ```
98
+
99
+ What it checks, in order: a compact JWT of at most 16 KiB; header `alg` is `RS256` (so `none` and
100
+ HMAC key confusion never reach a key); signature against the JWKS (cached for 10 minutes and
101
+ refetched, at most every 30 s, when a token names an unknown `kid`); `iss` is one of the issuers;
102
+ `aud` is exactly the audience; `sub`, `iat`, `exp`, `jti` present; `exp`, `nbf` and `iat` within
103
+ 30 s of clock tolerance; `exp - iat` and token age at most 900 s; then the principal rules:
104
+
105
+ - **User:** `actorType: "USER"`, a `sessionId`, a `clientId` other than the subject, string-array
106
+ `permissions` and (optional) `roles`. With `userinfoUrl`, the session is confirmed online; the
107
+ answer is shared for 10 s from when the request started (failures for 2 s).
108
+ - **Service:** `clientId` (or `client_id`) equals `sub`, `actorType: "SERVICE_ACCOUNT"`,
109
+ `token_type: "access"`, no session.
110
+
111
+ Every refusal is an `OathweaveError` (a `HiveError`) with a stable `reason`:
112
+
113
+ | Status | Code | Reasons |
114
+ | --- | --- | --- |
115
+ | 401 | `unauthorized` | `missing_token` |
116
+ | 401 | `invalid_token` | `malformed_token`, `algorithm_not_allowed`, `unknown_key`, `invalid_signature`, `expired`, `not_yet_valid`, `invalid_issuer`, `invalid_audience`, `invalid_lifetime`, `invalid_claims`, `wrong_principal_kind`, `session_inactive`, `subject_mismatch` |
117
+ | 403 | `forbidden` / `insufficient_permission` | `not_linked`, `insufficient_permission` |
118
+ | 503 | `auth_unavailable` | `jwks_unavailable`, `identity_unavailable` |
119
+
120
+ Also: `hasPermissions()` (with `*` segment wildcards, like the Oathweave SDK), `requirePermissions()`,
121
+ `hasAnyRole()`, `hasScopes()`, `effectivePermissions()` (a link's ceiling), and
122
+ `watchStreamAuthorization()` for SSE and WebSocket connections:
123
+
124
+ ```ts
125
+ const watch = watchStreamAuthorization({
126
+ recheck: () => verifier.verify(token), // every 5 s; the session cache keeps it cheap
127
+ expiresAt: principal.expiresAt, // ends the stream at token expiry
128
+ onEnd: () => stream.close(), // sign-out takes effect within about 15 s
129
+ });
130
+ ```
131
+
132
+ Endpoints must be `https`. For tests against a loopback server, pass `allowInsecureLoopback: true`.
133
+
134
+ ### Conformance vectors
135
+
136
+ `test-vectors/oathweave/vectors.json` ships a test JWKS and twelve pre-signed tokens (valid user,
137
+ valid service, expired, not yet valid, wrong audience, wrong issuer, bad signature, unknown `kid`,
138
+ `alg: none`, HS256 key confusion, overlong lifetime, user without session), evaluated at a fixed
139
+ clock so they never expire. Run them against your product's verifier:
140
+
141
+ ```ts
142
+ import { runOathweaveConformance } from '@hivemagnus/hive-common/oathweave/conformance';
143
+
144
+ it('meets the Oathweave conformance vectors', async () => {
145
+ await runOathweaveConformance((token, ctx) => createProductVerifier({
146
+ issuer: ctx.issuer, audience: ctx.audience, jwksUrl: ctx.jwksUrl, userinfoUrl: ctx.userinfoUrl,
147
+ fetch: ctx.fetch, // serves the vectors' JWKS and userinfo
148
+ now: () => ctx.nowMs, // the fixed clock
149
+ })(token));
150
+ });
151
+ ```
152
+
153
+ It throws a readable error listing failed vectors. A refusal passes when the verifier rejects
154
+ (and any numeric `status` on the error matches); `strictReasons: true` also compares `reason`.
155
+
156
+ ### errors
157
+
158
+ ```ts
159
+ import { HiveError, toErrorResponse, parseHiveError, parseHiveErrorResponse } from '@hivemagnus/hive-common/errors';
160
+
161
+ throw new HiveError('quota_exceeded', 'Monthly quota reached', { status: 429, details: { limit: 1000 } });
162
+ throw HiveError.notFound('No such project');
163
+
164
+ const { status, body, headers } = toErrorResponse(error, { requestId, onUnexpected: e => log.error('unhandled', { err: e }) });
165
+
166
+ const error = await parseHiveErrorResponse(await fetch(url)); // any product, any legacy shape
167
+ if (HiveError.is(error, 'not_found')) { /* … */ }
168
+ ```
169
+
170
+ `parseHiveError(status, body)` accepts text, bytes or parsed JSON and recognises every shape the
171
+ suite has used; `error.shape` says which. Remote codes are kept as sent (compare with
172
+ `HiveError.is()`, case-insensitively); messages are bounded and cleaned; HTML error pages are
173
+ replaced by the status's default message.
174
+
175
+ | Shape | Body | Products |
176
+ | --- | --- | --- |
177
+ | `envelope` | `{error:{code,message,requestId?,details?}}` | Hive standard, Ardent, ArdentStudio, Registry |
178
+ | `magnus` | `{success:false,error:{code,message}}` | Magnus |
179
+ | `oathweave` | `{error:"CODE",message}` | Oathweave |
180
+ | `string` | `{error:"human text"}` | Emberpath, HiveSkills, Cindertrace |
181
+ | `code` | `{error:"CODE"}` | Embermend, OAuth without description |
182
+ | `fastapi` / `fastapi-validation` | `{detail:"text"}` / `{detail:[{loc,msg,type}]}` | HiveMem |
183
+ | `mattermost` | `{id,message,status_code,request_id}` | ChatterMost |
184
+ | `oauth` | `{error,error_description}` | OAuth 2.0 endpoints |
185
+ | `message`, `text`, `empty`, `unknown` | `{message}`, plain text, no body, anything else | proxies and others |
186
+
187
+ ### health
188
+
189
+ ```ts
190
+ import { createHealth } from '@hivemagnus/hive-common/health';
191
+
192
+ const health = createHealth({
193
+ service: 'hivemem', version: '1.4.0',
194
+ timeoutMs: 2000,
195
+ checks: [
196
+ { name: 'database', check: () => db.ping() },
197
+ { name: 'search', critical: false, check: signal => fetch(searchUrl, { signal }).then(r => r.ok) },
198
+ ],
199
+ aliases: true, // also serve /health, /healthz, /livez, /live, /api/health, /ready, /readyz
200
+ });
201
+ const response = await health.handle('/health/ready'); // { status: 200 | 503, body, headers } or undefined
202
+ ```
203
+
204
+ A check is down when it throws, returns `false` or `{ ok: false }`, or exceeds its timeout (its
205
+ `signal` aborts). Error text is hidden unless `exposeErrors: true`. Serve legacy aliases only
206
+ while old clients still call them.
207
+
208
+ ### context
209
+
210
+ ```ts
211
+ import { createRequestContext, runWithRequestContext, getRequestContext, outboundHeaders, readIdempotencyKey } from '@hivemagnus/hive-common/context';
212
+
213
+ const context = createRequestContext(req.headers); // { requestId, trace, parentTrace, tracestate, … }
214
+ await runWithRequestContext(context, () => handle(req));
215
+ // anywhere below:
216
+ await fetch(peerUrl, { headers: { ...outboundHeaders(), authorization } });
217
+ const key = readIdempotencyKey(req.headers); // string | undefined; 400 on malformed or conflicting
218
+ ```
219
+
220
+ Also `parseTraceparent()`, `formatTraceparent()`, `generateTraceparent()`, `childTraceparent()`,
221
+ `readRequestId()`, `requireIdempotencyKey()` (428 when missing). On an edge service exposed to the
222
+ internet, pass `trustInbound: false` so callers cannot choose IDs.
223
+
224
+ ### registry
225
+
226
+ ```ts
227
+ import { createRegistryClient } from '@hivemagnus/hive-common/registry';
228
+
229
+ const registry = createRegistryClient({
230
+ baseUrl: 'https://hive.example.com/api/registry', // or the native private-network URL with allowHttp
231
+ token: process.env.HIVE_REGISTRY_READ_TOKEN, // omit for the public view
232
+ ca: process.env.HIVE_REGISTRY_CA_PEM, // optional private CA; or pass fetch
233
+ trust: { emberpath: { ca: emberpathCaPem } }, // TLS trust per product, from local config
234
+ });
235
+ const installation = await registry.installation();
236
+ const installed = await registry.installedProducts();
237
+ const endpoint = await registry.endpoint('emberpath'); // { url, internal, trust } or undefined
238
+ ```
239
+
240
+ `product()` and `connection()` return `undefined` for unknown products; other failures are
241
+ `HiveError`s parsed from the registry's envelope. The registry stores no TLS material, so
242
+ `endpoint()` returns the trust you configure. `createCaFetch({ ca })` is a small `node:https`
243
+ fetch that trusts only the given CA.
244
+
245
+ ### log
246
+
247
+ ```ts
248
+ import { createLogger, redact } from '@hivemagnus/hive-common/log';
249
+
250
+ const log = createLogger({ bindings: { service: 'hivemem' } }); // level from LOG_LEVEL, default info
251
+ log.info('memory stored', { memoryId, bytes }); // adds requestId and traceId from the context
252
+ const jobLog = log.child({ job: 'reindex' });
253
+ log.error('upstream failed', { err, headers: req.headers }); // authorization and cookies masked
254
+ ```
255
+
256
+ `redact()` masks values under secret-looking keys (authorization, cookie, password, secret, token,
257
+ `*key`, credentials, webhook URLs, session IDs) and scrubs strings everywhere: bearer and basic
258
+ credentials, JWTs, provider token formats, private keys, URL credentials and secret query
259
+ parameters. Numbers and booleans under such keys are kept, so `inputTokens: 512` survives.
260
+
261
+ ### events
262
+
263
+ ```ts
264
+ import { ChatterMostNotifier, parseFeedQuery, feedPage, encodeCursor } from '@hivemagnus/hive-common/events';
265
+
266
+ // GET /v1/hive/events?after=<cursor>&limit=<n>
267
+ const { after, limit } = parseFeedQuery(url.searchParams); // limit 1-200, default 50
268
+ const rows = store.eventsAfter(after, limit + 1);
269
+ return Response.json(feedPage(rows.map(toHiveEvent), limit, event => encodeCursor({ id: event.id })));
270
+
271
+ const notifier = new ChatterMostNotifier({
272
+ webhookUrl: process.env.CHATTERMOST_WEBHOOK_URL!, // a secret; never logged
273
+ linkBaseUrl: 'https://hive.example.com',
274
+ });
275
+ await notifier.notify(event); // { status: 'sent' | 'duplicate' | 'failed', attempts }
276
+ ```
277
+
278
+ The notifier validates the event, posts a Mattermost incoming-webhook payload (Markdown and
279
+ mentions in event text are neutralised), times out each attempt, retries 408, 429 (honouring
280
+ `Retry-After`), 5xx and network errors with exponential backoff and jitter, and delivers each
281
+ event ID once per 24 h. Pass a shared `DedupeStore` to deduplicate across replicas.
282
+
283
+ ### contracts
284
+
285
+ ```ts
286
+ import { validateHiveEvent, type HiveEvent, type Page, type ErrorEnvelope } from '@hivemagnus/hive-common/contracts';
287
+
288
+ const result = validateHiveEvent(json); // { ok: true, value } | { ok: false, issues }
289
+ ```
290
+
291
+ HiveEvent v1:
292
+
293
+ ```ts
294
+ interface HiveEvent {
295
+ id: string; product: string; type: string; severity: 'info' | 'warning' | 'critical';
296
+ title: string; summary: string; occurredAt: string; // RFC 3339 UTC
297
+ subject?: { actorId?: string; agentRef?: string; nodeId?: string };
298
+ link: { product: string; path: string }; // same-origin console path
299
+ sourceRef?: string;
300
+ }
301
+ ```
302
+
303
+ Also `Page<T>` (`{ data, nextCursor }`), `AgentIdentity` (`{ agentRef: "<nodeId>~<profile>",
304
+ actorId }`, segments `[a-z0-9_-]{2,32}`), `ErrorEnvelope`, `HIVE_HEADERS`. Validators drop unknown
305
+ fields by default; producers should pass `{ strict: true }`. The validators are hand-written so
306
+ the browser bundle gains no dependency.
307
+
308
+ ### hono
309
+
310
+ ```ts
311
+ import { Hono } from 'hono';
312
+ import { requestContext, oathweaveAuth, requirePermission, errorHandler, notFoundHandler, registerHealthRoutes, requirePrincipal, type HiveEnv } from '@hivemagnus/hive-common/hono';
313
+
314
+ const app = new Hono<HiveEnv>();
315
+ app.use(requestContext());
316
+ registerHealthRoutes(app, { checks, aliases: true });
317
+ app.use('/v1/*', oathweaveAuth(verifier, { authorize: principal => { requireIdentityLink(links, principal); } }));
318
+ app.get('/v1/memories', requirePermission(['hivemem:read']), c => c.json(list(requirePrincipal(c))));
319
+ app.onError(errorHandler({ logger: log }));
320
+ app.notFound(notFoundHandler());
321
+ ```
322
+
323
+ Requires `hono` 4.13.18 or later, the suite minimum since a recent Hono security advisory.
324
+
325
+ ### node-http
326
+
327
+ ```ts
328
+ import http from 'node:http';
329
+ import { hiveHandler, authenticate, sendJson } from '@hivemagnus/hive-common/node-http';
330
+
331
+ http.createServer(hiveHandler(async (req, res) => {
332
+ const principal = await authenticate(req, verifier);
333
+ sendJson(res, 200, { subject: principal.subject });
334
+ }, { health: { checks }, logger: log })).listen(8080);
335
+ ```
336
+
337
+ `hiveHandler()` adds the request context, health routes and the error envelope; anything thrown
338
+ becomes an envelope, and a handler that sends nothing gets a 404.
339
+
340
+ ## Adopting HiveCommon in a product
341
+
342
+ 1. **Install** `@hivemagnus/hive-common` (and `hono` ≥ 4.13.18 for Hono products).
343
+ 2. **Replace the verifier copy.** Delete `oathweave.ts` / `oathweave-verifier.ts` and build the
344
+ verifier with `createOathweaveVerifier()` from the same `OATHWEAVE_*` settings. Use
345
+ `accept: 'service'` (or `'any'`) on routes that took the separate service verifier. Map
346
+ principals through `parseIdentityLinks()` / `requireIdentityLink()`.
347
+ 3. **Add the conformance test** with `runOathweaveConformance()` and keep the old verifier tests
348
+ that cover product-specific rules.
349
+ 4. **Adopt the envelope.** Throw `HiveError`s and install `errorHandler()` / `hiveHandler()`.
350
+ Keep the old body shape only for clients that still parse it, and plan its removal.
351
+ Clients (including HiveXUI) parse peers with `parseHiveError()`.
352
+ 5. **Adopt request context.** Install `requestContext()`, log with `createLogger()`, and pass
353
+ `outboundHeaders()` on calls to peers.
354
+ 6. **Serve `/health/live` and `/health/ready`**, with `aliases` for paths current deployments probe.
355
+ 7. **Publish HiveEvents** at `GET /v1/hive/events` with `feedPage()`, and announce through
356
+ `ChatterMostNotifier` where the product posts to ChatterMost today.
357
+
358
+ Behaviour that changes when a product adopts the shared verifier:
359
+
360
+ - Clock tolerance is 30 s (the copies used 0).
361
+ - An unreachable JWKS or userinfo is a 503 `auth_unavailable`, not a 401, so clients retry
362
+ instead of signing people out. Access is still refused.
363
+ - A missing `roles` claim means no roles instead of a refusal (ArdentStudio already allowed it).
364
+ - `authTime` is epoch seconds, `undefined` when absent or invalid (Magnus semantics; some copies
365
+ exposed `authenticatedAt` in milliseconds).
366
+ - Duplicate identity links fail at startup by default (`duplicates: 'ignore'` keeps the old
367
+ Magnus behaviour of granting nothing to that identity).
368
+
369
+ ## Development
370
+
371
+ ```bash
372
+ npm ci
373
+ npm run hooks:install
374
+ npm run verify # privacy tests, scans, typecheck, lint, tests, build, package check
375
+ npm run test:coverage
376
+ ```
377
+
378
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and [AGENTS.md](AGENTS.md). Security reports:
379
+ [SECURITY.md](SECURITY.md).
380
+
381
+ ## License
382
+
383
+ [Apache License 2.0](LICENSE). See [NOTICE](NOTICE).