@hivemagnus/hive-common 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/LICENSE +202 -0
- package/NOTICE +11 -0
- package/README.md +439 -2
- package/dist/context/index.d.ts +98 -0
- package/dist/context/index.js +191 -0
- package/dist/contracts/index.d.ts +117 -0
- package/dist/contracts/index.js +228 -0
- package/dist/errors/index.d.ts +91 -0
- package/dist/errors/index.js +309 -0
- package/dist/events/index.d.ts +107 -0
- package/dist/events/index.js +232 -0
- package/dist/health/index.d.ts +101 -0
- package/dist/health/index.js +126 -0
- package/dist/hono/index.d.ts +67 -0
- package/dist/hono/index.js +108 -0
- package/dist/log/index.d.ts +39 -0
- package/dist/log/index.js +80 -0
- package/dist/log/redact.d.ts +23 -0
- package/dist/log/redact.js +111 -0
- package/dist/node-http/index.d.ts +46 -0
- package/dist/node-http/index.js +91 -0
- package/dist/oathweave/claims.d.ts +79 -0
- package/dist/oathweave/claims.js +99 -0
- package/dist/oathweave/conformance.d.ts +88 -0
- package/dist/oathweave/conformance.js +124 -0
- package/dist/oathweave/endpoint.d.ts +15 -0
- package/dist/oathweave/endpoint.js +35 -0
- package/dist/oathweave/errors.d.ts +19 -0
- package/dist/oathweave/errors.js +70 -0
- package/dist/oathweave/index.d.ts +10 -0
- package/dist/oathweave/index.js +10 -0
- package/dist/oathweave/links.d.ts +63 -0
- package/dist/oathweave/links.js +138 -0
- package/dist/oathweave/stream.d.ts +26 -0
- package/dist/oathweave/stream.js +46 -0
- package/dist/oathweave/verifier.d.ts +83 -0
- package/dist/oathweave/verifier.js +237 -0
- package/dist/registry/index.d.ts +138 -0
- package/dist/registry/index.js +175 -0
- package/package.json +126 -4
- package/test-vectors/README.md +27 -0
- package/test-vectors/oathweave/jwks.json +12 -0
- package/test-vectors/oathweave/vectors.json +174 -0
package/README.md
CHANGED
|
@@ -1,3 +1,440 @@
|
|
|
1
|
-
#
|
|
1
|
+
# HiveCommon
|
|
2
2
|
|
|
3
|
-
|
|
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), or not at all with
|
|
108
|
+
`sessionCacheTtlMs: 0`.
|
|
109
|
+
- **Service:** `clientId` (or `client_id`) equals `sub`, `actorType: "SERVICE_ACCOUNT"`,
|
|
110
|
+
`token_type: "access"`, no session.
|
|
111
|
+
|
|
112
|
+
Every refusal is an `OathweaveError` (a `HiveError`) with a stable `reason`:
|
|
113
|
+
|
|
114
|
+
| Status | Code | Reasons |
|
|
115
|
+
| --- | --- | --- |
|
|
116
|
+
| 401 | `unauthorized` | `missing_token` |
|
|
117
|
+
| 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` |
|
|
118
|
+
| 403 | `forbidden` / `insufficient_permission` | `not_linked`, `insufficient_permission` |
|
|
119
|
+
| 503 | `auth_unavailable` | `jwks_unavailable`, `identity_unavailable` |
|
|
120
|
+
|
|
121
|
+
Also: `hasPermissions()` (with `*` segment wildcards, like the Oathweave SDK), `requirePermissions()`,
|
|
122
|
+
`hasAnyRole()`, `hasScopes()`, `effectivePermissions()` (a link's ceiling), and
|
|
123
|
+
`watchStreamAuthorization()` for SSE and WebSocket connections:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const watch = watchStreamAuthorization({
|
|
127
|
+
recheck: () => verifier.verify(token), // every 5 s; the session cache keeps it cheap
|
|
128
|
+
expiresAt: principal.expiresAt, // ends the stream at token expiry
|
|
129
|
+
onEnd: () => stream.close(), // sign-out takes effect within about 15 s
|
|
130
|
+
});
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Two options make the claim rules stricter for products that always required more:
|
|
134
|
+
|
|
135
|
+
- `requireRoles: true` refuses a token without a `roles` array. The default (`false`) treats an
|
|
136
|
+
absent `roles` claim as no roles. A `roles` claim that is not a string array is always refused.
|
|
137
|
+
- `clientIdClaim` chooses which claim names supply the client ID: `'clientId'` (Oathweave),
|
|
138
|
+
`'client_id'` (RFC 9068) or `'either'` (the default). When both claims are present they must
|
|
139
|
+
agree in every mode.
|
|
140
|
+
|
|
141
|
+
Identity links name the local account `localUserId`. `localId`, the name older deployment configs
|
|
142
|
+
use, is accepted as an alias; an entry that sets both to different values is refused. Parsed links
|
|
143
|
+
always carry `localUserId`.
|
|
144
|
+
|
|
145
|
+
Endpoints must be `https`. For tests against a loopback server, pass `allowInsecureLoopback: true`.
|
|
146
|
+
|
|
147
|
+
### Conformance vectors
|
|
148
|
+
|
|
149
|
+
`test-vectors/oathweave/vectors.json` ships a test JWKS and twelve pre-signed tokens (valid user,
|
|
150
|
+
valid service, expired, not yet valid, wrong audience, wrong issuer, bad signature, unknown `kid`,
|
|
151
|
+
`alg: none`, HS256 key confusion, overlong lifetime, user without session), evaluated at a fixed
|
|
152
|
+
clock so they never expire. Run them against your product's verifier:
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import { runOathweaveConformance } from '@hivemagnus/hive-common/oathweave/conformance';
|
|
156
|
+
|
|
157
|
+
it('meets the Oathweave conformance vectors', async () => {
|
|
158
|
+
await runOathweaveConformance((token, ctx) => createProductVerifier({
|
|
159
|
+
issuer: ctx.issuer, audience: ctx.audience, jwksUrl: ctx.jwksUrl, userinfoUrl: ctx.userinfoUrl,
|
|
160
|
+
fetch: ctx.fetch, // serves the vectors' JWKS and userinfo
|
|
161
|
+
now: () => ctx.nowMs, // the fixed clock
|
|
162
|
+
})(token));
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
It throws a readable error listing failed vectors. A refusal passes when the verifier rejects
|
|
167
|
+
(and any numeric `status` on the error matches); `strictReasons: true` also compares `reason`.
|
|
168
|
+
|
|
169
|
+
### errors
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
import { HiveError, toErrorResponse, parseHiveError, parseHiveErrorResponse } from '@hivemagnus/hive-common/errors';
|
|
173
|
+
|
|
174
|
+
throw new HiveError('quota_exceeded', 'Monthly quota reached', { status: 429, details: { limit: 1000 } });
|
|
175
|
+
throw HiveError.notFound('No such project');
|
|
176
|
+
|
|
177
|
+
const { status, body, headers } = toErrorResponse(error, { requestId, onUnexpected: e => log.error('unhandled', { err: e }) });
|
|
178
|
+
|
|
179
|
+
const error = await parseHiveErrorResponse(await fetch(url)); // any product, any legacy shape
|
|
180
|
+
if (HiveError.is(error, 'not_found')) { /* … */ }
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
`parseHiveError(status, body)` accepts text, bytes or parsed JSON and recognises every shape the
|
|
184
|
+
suite has used; `error.shape` says which. Remote codes are kept as sent (compare with
|
|
185
|
+
`HiveError.is()`, case-insensitively); messages are bounded and cleaned; HTML error pages are
|
|
186
|
+
replaced by the status's default message.
|
|
187
|
+
|
|
188
|
+
| Shape | Body | Products |
|
|
189
|
+
| --- | --- | --- |
|
|
190
|
+
| `envelope` | `{error:{code,message,requestId?,details?}}` | Hive standard, Ardent, ArdentStudio, Registry |
|
|
191
|
+
| `magnus` | `{success:false,error:{code,message}}` | Magnus |
|
|
192
|
+
| `oathweave` | `{error:"CODE",message}` | Oathweave |
|
|
193
|
+
| `string` | `{error:"human text"}` | Emberpath, HiveSkills, Cindertrace |
|
|
194
|
+
| `code` | `{error:"CODE"}` | Embermend, OAuth without description |
|
|
195
|
+
| `fastapi` / `fastapi-validation` | `{detail:"text"}` / `{detail:[{loc,msg,type}]}` | HiveMem |
|
|
196
|
+
| `mattermost` | `{id,message,status_code,request_id}` | ChatterMost |
|
|
197
|
+
| `oauth` | `{error,error_description}` | OAuth 2.0 endpoints |
|
|
198
|
+
| `message`, `text`, `empty`, `unknown` | `{message}`, plain text, no body, anything else | proxies and others |
|
|
199
|
+
|
|
200
|
+
### health
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { createHealth } from '@hivemagnus/hive-common/health';
|
|
204
|
+
|
|
205
|
+
const health = createHealth({
|
|
206
|
+
service: 'hivemem', version: '1.4.0',
|
|
207
|
+
timeoutMs: 2000,
|
|
208
|
+
checks: [
|
|
209
|
+
{ name: 'database', check: () => db.ping() },
|
|
210
|
+
{ name: 'search', critical: false, check: signal => fetch(searchUrl, { signal }).then(r => r.ok) },
|
|
211
|
+
],
|
|
212
|
+
aliases: true, // also serve /health, /healthz, /livez, /live, /api/health, /ready, /readyz
|
|
213
|
+
});
|
|
214
|
+
const response = await health.handle('/health/ready'); // { status: 200 | 503, body, headers } or undefined
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
A check is down when it throws, returns `false` or `{ ok: false }`, or exceeds its timeout (its
|
|
218
|
+
`signal` aborts). Error text is hidden unless `exposeErrors: true`. Serve legacy aliases only
|
|
219
|
+
while old clients still call them.
|
|
220
|
+
|
|
221
|
+
A product that has published its own liveness body can keep it with `liveBody`: an object served
|
|
222
|
+
as is, or a function that receives the standard body on every request. Status, headers and
|
|
223
|
+
readiness are unchanged, and liveness still never runs checks. `liveness()`, `createHealth()`,
|
|
224
|
+
`registerHealthRoutes()` and `hiveHandler({ health })` all take it.
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
createHealth({ service: 'studio', liveBody: { status: 'ok' } });
|
|
228
|
+
createHealth({ service: 'hive-skills', liveBody: standard => ({ status: 'ok', service: standard.service, protocol: 1 }) });
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### context
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
import { createRequestContext, runWithRequestContext, getRequestContext, outboundHeaders, readIdempotencyKey } from '@hivemagnus/hive-common/context';
|
|
235
|
+
|
|
236
|
+
const context = createRequestContext(req.headers); // { requestId, trace, parentTrace, tracestate, … }
|
|
237
|
+
await runWithRequestContext(context, () => handle(req));
|
|
238
|
+
// anywhere below:
|
|
239
|
+
await fetch(peerUrl, { headers: { ...outboundHeaders(), authorization } });
|
|
240
|
+
const key = readIdempotencyKey(req.headers); // string | undefined; 400 on malformed or conflicting
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Also `parseTraceparent()`, `formatTraceparent()`, `generateTraceparent()`, `childTraceparent()`,
|
|
244
|
+
`readRequestId()`, `requireIdempotencyKey()` (428 when missing). On an edge service exposed to the
|
|
245
|
+
internet, pass `trustInbound: false` so callers cannot choose IDs.
|
|
246
|
+
|
|
247
|
+
`trustInboundRequestId` and `trustInboundTrace` decide the request ID and the trace separately; each
|
|
248
|
+
defaults to `trustInbound` (itself `true`). An internet-facing service that should still join its
|
|
249
|
+
callers' traces passes `{ trustInboundRequestId: false, trustInboundTrace: true }`. The `/hono`
|
|
250
|
+
`requestContext()` middleware and the `/node-http` `hiveHandler()` and `requestContextFor()` take
|
|
251
|
+
the same options.
|
|
252
|
+
|
|
253
|
+
### registry
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
import { createRegistryClient } from '@hivemagnus/hive-common/registry';
|
|
257
|
+
|
|
258
|
+
const registry = createRegistryClient({
|
|
259
|
+
baseUrl: 'https://hive.example.com/api/registry', // or the native private-network URL with allowHttp
|
|
260
|
+
token: process.env.HIVE_REGISTRY_READ_TOKEN, // omit for the public view
|
|
261
|
+
ca: process.env.HIVE_REGISTRY_CA_PEM, // optional private CA; or pass fetch
|
|
262
|
+
trust: { emberpath: { ca: emberpathCaPem } }, // TLS trust per product, from local config
|
|
263
|
+
});
|
|
264
|
+
const installation = await registry.installation();
|
|
265
|
+
const installed = await registry.installedProducts();
|
|
266
|
+
const endpoint = await registry.endpoint('emberpath'); // { url, internal, trust } or undefined
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
`product()` and `connection()` return `undefined` for unknown products; other failures are
|
|
270
|
+
`HiveError`s parsed from the registry's envelope. The registry stores no TLS material, so
|
|
271
|
+
`endpoint()` returns the trust you configure. `createCaFetch({ ca })` is a small `node:https`
|
|
272
|
+
fetch that trusts only the given CA.
|
|
273
|
+
|
|
274
|
+
### log
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
import { createLogger, redact } from '@hivemagnus/hive-common/log';
|
|
278
|
+
|
|
279
|
+
const log = createLogger({ bindings: { service: 'hivemem' } }); // level from LOG_LEVEL, default info
|
|
280
|
+
log.info('memory stored', { memoryId, bytes }); // adds requestId and traceId from the context
|
|
281
|
+
const jobLog = log.child({ job: 'reindex' });
|
|
282
|
+
log.error('upstream failed', { err, headers: req.headers }); // authorization and cookies masked
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
`redact()` masks values under secret-looking keys (authorization, cookie, password, secret, token,
|
|
286
|
+
`*key`, credentials, webhook URLs, session IDs) and scrubs strings everywhere: bearer and basic
|
|
287
|
+
credentials, JWTs, provider token formats, private keys, URL credentials and secret query
|
|
288
|
+
parameters. Numbers and booleans under such keys are kept, so `inputTokens: 512` survives.
|
|
289
|
+
|
|
290
|
+
### events
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
import { ChatterMostNotifier, parseFeedQuery, feedPage, encodeCursor } from '@hivemagnus/hive-common/events';
|
|
294
|
+
|
|
295
|
+
// GET /v1/hive/events?after=<cursor>&limit=<n>
|
|
296
|
+
const { after, limit } = parseFeedQuery(url.searchParams); // limit 1-200, default 50
|
|
297
|
+
const rows = store.eventsAfter(after, limit + 1);
|
|
298
|
+
return Response.json(feedPage(rows.map(toHiveEvent), limit, event => encodeCursor({ id: event.id })));
|
|
299
|
+
|
|
300
|
+
const notifier = new ChatterMostNotifier({
|
|
301
|
+
webhookUrl: process.env.CHATTERMOST_WEBHOOK_URL!, // a secret; never logged
|
|
302
|
+
linkBaseUrl: 'https://hive.example.com',
|
|
303
|
+
});
|
|
304
|
+
await notifier.notify(event); // { status: 'sent' | 'duplicate' | 'failed', attempts }
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
The notifier validates the event, posts a Mattermost incoming-webhook payload (Markdown and
|
|
308
|
+
mentions in event text are neutralised), times out each attempt, retries 408, 429 (honouring
|
|
309
|
+
`Retry-After`), 5xx and network errors with exponential backoff and jitter, and delivers each
|
|
310
|
+
event ID once per 24 h. Pass a shared `DedupeStore` to deduplicate across replicas.
|
|
311
|
+
|
|
312
|
+
### contracts
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
import { validateHiveEvent, type HiveEvent, type Page, type ErrorEnvelope } from '@hivemagnus/hive-common/contracts';
|
|
316
|
+
|
|
317
|
+
const result = validateHiveEvent(json); // { ok: true, value } | { ok: false, issues }
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
HiveEvent v1:
|
|
321
|
+
|
|
322
|
+
```ts
|
|
323
|
+
interface HiveEvent {
|
|
324
|
+
id: string; product: string; type: string; severity: 'info' | 'warning' | 'critical';
|
|
325
|
+
title: string; summary: string; occurredAt: string; // RFC 3339 UTC
|
|
326
|
+
subject?: { actorId?: string; agentRef?: string; nodeId?: string };
|
|
327
|
+
link: { product: string; path: string }; // same-origin console path
|
|
328
|
+
sourceRef?: string;
|
|
329
|
+
}
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Also `Page<T>` (`{ data, nextCursor }`), `AgentIdentity` (`{ agentRef: "<nodeId>~<profile>",
|
|
333
|
+
actorId }`, segments `[a-z0-9_-]{2,32}`), `ErrorEnvelope`, `HIVE_HEADERS`. Validators drop unknown
|
|
334
|
+
fields by default; producers should pass `{ strict: true }`. The validators are hand-written so
|
|
335
|
+
the browser bundle gains no dependency.
|
|
336
|
+
|
|
337
|
+
### hono
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
import { Hono } from 'hono';
|
|
341
|
+
import { requestContext, oathweaveAuth, requirePermission, errorHandler, notFoundHandler, registerHealthRoutes, requirePrincipal, type HiveEnv } from '@hivemagnus/hive-common/hono';
|
|
342
|
+
|
|
343
|
+
const app = new Hono<HiveEnv>();
|
|
344
|
+
app.use(requestContext());
|
|
345
|
+
registerHealthRoutes(app, { checks, aliases: true });
|
|
346
|
+
app.use('/v1/*', oathweaveAuth(verifier, { authorize: principal => { requireIdentityLink(links, principal); } }));
|
|
347
|
+
app.get('/v1/memories', requirePermission(['hivemem:read']), c => c.json(list(requirePrincipal(c))));
|
|
348
|
+
app.onError(errorHandler({ logger: log }));
|
|
349
|
+
app.notFound(notFoundHandler());
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
Requires `hono` 4.13.18 or later, the suite minimum since a recent Hono security advisory.
|
|
353
|
+
|
|
354
|
+
### node-http
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
import http from 'node:http';
|
|
358
|
+
import { hiveHandler, authenticate, sendJson } from '@hivemagnus/hive-common/node-http';
|
|
359
|
+
|
|
360
|
+
http.createServer(hiveHandler(async (req, res) => {
|
|
361
|
+
const principal = await authenticate(req, verifier);
|
|
362
|
+
sendJson(res, 200, { subject: principal.subject });
|
|
363
|
+
}, { health: { checks }, logger: log })).listen(8080);
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
`hiveHandler()` adds the request context, health routes and the error envelope; anything thrown
|
|
367
|
+
becomes an envelope, and a handler that sends nothing gets a 404.
|
|
368
|
+
|
|
369
|
+
## Adopting HiveCommon in a product
|
|
370
|
+
|
|
371
|
+
1. **Install** `@hivemagnus/hive-common` (and `hono` ≥ 4.13.18 for Hono products).
|
|
372
|
+
2. **Replace the verifier copy.** Delete `oathweave.ts` / `oathweave-verifier.ts` and build the
|
|
373
|
+
verifier with `createOathweaveVerifier()` from the same `OATHWEAVE_*` settings. Use
|
|
374
|
+
`accept: 'service'` (or `'any'`) on routes that took the separate service verifier. Map
|
|
375
|
+
principals through `parseIdentityLinks()` / `requireIdentityLink()`.
|
|
376
|
+
3. **Add the conformance test** with `runOathweaveConformance()` and keep the old verifier tests
|
|
377
|
+
that cover product-specific rules.
|
|
378
|
+
4. **Adopt the envelope.** Throw `HiveError`s and install `errorHandler()` / `hiveHandler()`.
|
|
379
|
+
Keep the old body shape only for clients that still parse it, and plan its removal.
|
|
380
|
+
Clients (including HiveXUI) parse peers with `parseHiveError()`.
|
|
381
|
+
5. **Adopt request context.** Install `requestContext()`, log with `createLogger()`, and pass
|
|
382
|
+
`outboundHeaders()` on calls to peers.
|
|
383
|
+
6. **Serve `/health/live` and `/health/ready`**, with `aliases` for paths current deployments probe.
|
|
384
|
+
7. **Publish HiveEvents** at `GET /v1/hive/events` with `feedPage()`, and announce through
|
|
385
|
+
`ChatterMostNotifier` where the product posts to ChatterMost today.
|
|
386
|
+
|
|
387
|
+
Behaviour that changes when a product adopts the shared verifier:
|
|
388
|
+
|
|
389
|
+
- Clock tolerance is 30 s (the copies used 0).
|
|
390
|
+
- An unreachable JWKS or userinfo is a 503 `auth_unavailable`, not a 401, so clients retry
|
|
391
|
+
instead of signing people out. Access is still refused.
|
|
392
|
+
- A missing `roles` claim means no roles instead of a refusal (ArdentStudio already allowed it).
|
|
393
|
+
- `authTime` is epoch seconds, `undefined` when absent or invalid (Magnus semantics; some copies
|
|
394
|
+
exposed `authenticatedAt` in milliseconds).
|
|
395
|
+
- Duplicate identity links fail at startup by default (`duplicates: 'ignore'` keeps the old
|
|
396
|
+
Magnus behaviour of granting nothing to that identity).
|
|
397
|
+
|
|
398
|
+
## Choosing settings for an existing product
|
|
399
|
+
|
|
400
|
+
The defaults suit a new service. A product moving from its own code to HiveCommon can keep its
|
|
401
|
+
existing behaviour with these settings instead of wrapping the shared helpers:
|
|
402
|
+
|
|
403
|
+
| Setting | Default | Set it to keep |
|
|
404
|
+
| --- | --- | --- |
|
|
405
|
+
| `clockToleranceSec: 0` (verifier) | 30 | no clock skew allowance on `exp`, `nbf` and `iat` |
|
|
406
|
+
| `sessionCacheTtlMs: 0` (verifier) | 10 000 | an online session check on every request, so sign-out is immediate |
|
|
407
|
+
| `requireRoles: true` (verifier) | `false` | refusing tokens without a `roles` array |
|
|
408
|
+
| `clientIdClaim: 'clientId'` (verifier) | `'either'` | requiring the Oathweave `clientId` claim; RFC 9068 `client_id` alone is refused |
|
|
409
|
+
| `trustInboundRequestId: false` with `trustInboundTrace: true` (context, `/hono`, `/node-http`) | both `trustInbound` | generating every request ID on an internet-facing service while continuing callers' traces |
|
|
410
|
+
| `liveBody` (health, `/hono`, `/node-http`) | the standard body | a published `/health/live` body such as `{ status: 'ok' }` |
|
|
411
|
+
| `localId` in identity links | `localUserId` | existing link configs, unchanged |
|
|
412
|
+
| `duplicates: 'ignore'` (identity links) | `'reject'` | granting nothing to a duplicated identity instead of failing at startup |
|
|
413
|
+
|
|
414
|
+
```ts
|
|
415
|
+
const verifier = createOathweaveVerifier({
|
|
416
|
+
issuer, audience: 'chattermost', jwksUrl, userinfoUrl,
|
|
417
|
+
clockToleranceSec: 0, sessionCacheTtlMs: 0, requireRoles: true, clientIdClaim: 'clientId',
|
|
418
|
+
});
|
|
419
|
+
app.use(requestContext({ trustInboundRequestId: false, trustInboundTrace: true }));
|
|
420
|
+
registerHealthRoutes(app, { service: 'chattermost', liveBody: { status: 'ok' } });
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
Every refusal, including 503 `auth_unavailable`, is still an `OathweaveError`; a product that
|
|
424
|
+
answers 401 for all of them maps the error in its own handler.
|
|
425
|
+
|
|
426
|
+
## Development
|
|
427
|
+
|
|
428
|
+
```bash
|
|
429
|
+
npm ci
|
|
430
|
+
npm run hooks:install
|
|
431
|
+
npm run verify # privacy tests, scans, typecheck, lint, tests, build, package check
|
|
432
|
+
npm run test:coverage
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) and [AGENTS.md](AGENTS.md). Security reports:
|
|
436
|
+
[SECURITY.md](SECURITY.md).
|
|
437
|
+
|
|
438
|
+
## License
|
|
439
|
+
|
|
440
|
+
[Apache License 2.0](LICENSE). See [NOTICE](NOTICE).
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export { HIVE_HEADERS } from '../contracts/index.js';
|
|
2
|
+
/** Anything headers can be read from: fetch `Headers`, a Node `IncomingHttpHeaders` record, or a getter. */
|
|
3
|
+
export type HeaderSource = {
|
|
4
|
+
get(name: string): string | null | undefined;
|
|
5
|
+
} | Readonly<Record<string, string | readonly string[] | undefined>> | ((name: string) => string | null | undefined);
|
|
6
|
+
/** Read one header. A repeated header (array value) is treated as absent: it is ambiguous. */
|
|
7
|
+
export declare function readHeader(headers: HeaderSource, name: string): string | undefined;
|
|
8
|
+
/** Up to 128 printable characters that are safe in logs and headers. */
|
|
9
|
+
export declare const REQUEST_ID_PATTERN: RegExp;
|
|
10
|
+
export declare function isValidRequestId(value: unknown): value is string;
|
|
11
|
+
export declare function generateRequestId(): string;
|
|
12
|
+
/**
|
|
13
|
+
* The inbound request ID: `x-request-id`, else `x-hive-request-id`, else `x-correlation-id`.
|
|
14
|
+
* An invalid value (too long, unsafe characters) is ignored rather than propagated.
|
|
15
|
+
*/
|
|
16
|
+
export declare function readRequestId(headers: HeaderSource): string | undefined;
|
|
17
|
+
/** The inbound request ID, or a new one. */
|
|
18
|
+
export declare function resolveRequestId(headers: HeaderSource, generate?: () => string): string;
|
|
19
|
+
export interface Traceparent {
|
|
20
|
+
readonly version: string;
|
|
21
|
+
readonly traceId: string;
|
|
22
|
+
/** The parent-id field: the span ID of the caller. */
|
|
23
|
+
readonly spanId: string;
|
|
24
|
+
readonly flags: string;
|
|
25
|
+
readonly sampled: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** Parse a `traceparent` header per W3C Trace Context. Returns undefined when it is invalid. */
|
|
28
|
+
export declare function parseTraceparent(value: string | undefined | null): Traceparent | undefined;
|
|
29
|
+
export declare function isValidTraceparent(value: string | undefined | null): boolean;
|
|
30
|
+
export declare function generateTraceId(): string;
|
|
31
|
+
export declare function generateSpanId(): string;
|
|
32
|
+
export declare function formatTraceparent(trace: Pick<Traceparent, 'traceId' | 'spanId'> & {
|
|
33
|
+
readonly sampled?: boolean;
|
|
34
|
+
readonly flags?: string;
|
|
35
|
+
}): string;
|
|
36
|
+
/** A new root trace context. */
|
|
37
|
+
export declare function generateTraceparent(options?: {
|
|
38
|
+
readonly sampled?: boolean;
|
|
39
|
+
}): Traceparent;
|
|
40
|
+
/** A child span: same trace and flags, new span ID, always version 00 on output. */
|
|
41
|
+
export declare function childTraceparent(parent: Traceparent): Traceparent;
|
|
42
|
+
/** 1-255 visible ASCII characters. */
|
|
43
|
+
export declare const IDEMPOTENCY_KEY_PATTERN: RegExp;
|
|
44
|
+
/**
|
|
45
|
+
* The `Idempotency-Key` header, also accepting `x-idempotency-key`. Returns undefined when
|
|
46
|
+
* neither is present. Throws a 400 HiveError when the value is malformed or the two headers
|
|
47
|
+
* disagree, because silently picking one could apply a write twice.
|
|
48
|
+
*/
|
|
49
|
+
export declare function readIdempotencyKey(headers: HeaderSource): string | undefined;
|
|
50
|
+
/** Like `readIdempotencyKey()`, but a missing key is a 428 error. */
|
|
51
|
+
export declare function requireIdempotencyKey(headers: HeaderSource): string;
|
|
52
|
+
export interface RequestContext {
|
|
53
|
+
readonly requestId: string;
|
|
54
|
+
/** This service's span for the request: a child of the inbound trace, or a new root. */
|
|
55
|
+
readonly trace: Traceparent;
|
|
56
|
+
/** The inbound `traceparent`, when one was valid. */
|
|
57
|
+
readonly parentTrace: Traceparent | undefined;
|
|
58
|
+
/** The inbound `tracestate`, propagated unchanged when a valid traceparent came with it. */
|
|
59
|
+
readonly tracestate: string | undefined;
|
|
60
|
+
readonly startedAt: number;
|
|
61
|
+
/** Set by auth adapters once a caller is verified. */
|
|
62
|
+
principal?: unknown;
|
|
63
|
+
/** Extra fields that loggers add to every line for this request. */
|
|
64
|
+
readonly bindings: Record<string, unknown>;
|
|
65
|
+
}
|
|
66
|
+
export interface CreateRequestContextOptions {
|
|
67
|
+
/**
|
|
68
|
+
* Accept the inbound request ID and trace context. Defaults to true; set false on an edge
|
|
69
|
+
* service that must not let the public internet choose its IDs. The two settings below
|
|
70
|
+
* override it for one of the two.
|
|
71
|
+
*/
|
|
72
|
+
readonly trustInbound?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Accept an inbound `x-request-id` (or `x-hive-request-id`, `x-correlation-id`). Defaults to
|
|
75
|
+
* `trustInbound`. When false, every request gets a generated ID.
|
|
76
|
+
*/
|
|
77
|
+
readonly trustInboundRequestId?: boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Continue an inbound `traceparent` and `tracestate`. Defaults to `trustInbound`. When false,
|
|
80
|
+
* every request starts a new trace. An internet-facing service can set this true with
|
|
81
|
+
* `trustInboundRequestId: false` to join a caller's trace while choosing its own request IDs.
|
|
82
|
+
*/
|
|
83
|
+
readonly trustInboundTrace?: boolean;
|
|
84
|
+
readonly generateRequestId?: () => string;
|
|
85
|
+
readonly now?: () => number;
|
|
86
|
+
}
|
|
87
|
+
export declare function createRequestContext(headers: HeaderSource, options?: CreateRequestContextOptions): RequestContext;
|
|
88
|
+
/** Run `fn` with `context` as the current request context. */
|
|
89
|
+
export declare function runWithRequestContext<T>(context: RequestContext, fn: () => T): T;
|
|
90
|
+
/** The current request context, or undefined outside a request. */
|
|
91
|
+
export declare function getRequestContext(): RequestContext | undefined;
|
|
92
|
+
/** The current request ID, or undefined outside a request. */
|
|
93
|
+
export declare function currentRequestId(): string | undefined;
|
|
94
|
+
/**
|
|
95
|
+
* Headers to send to a peer service so it joins this request: `x-request-id`, `traceparent`
|
|
96
|
+
* (with this service's span as the parent) and `tracestate`. Empty outside a request.
|
|
97
|
+
*/
|
|
98
|
+
export declare function outboundHeaders(context?: RequestContext | undefined): Record<string, string>;
|