@hadoku/service-kernel 0.1.245 → 0.1.246

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.
@@ -77,8 +77,8 @@ export declare function tierOf(req: Request): string;
77
77
  * anything else that reports who someone is; a gate reads `tierOf`.
78
78
  */
79
79
  export declare function edgeTierOf(req: Request): string;
80
- /** The caller's userId as the edge stamped it; null when the edge named nobody. */
81
- export declare function callerIdOf(req: Request): string | null;
80
+ /** A header the edge sent once and not empty; null for a missing, empty or repeated one. */
81
+ export declare function headerValue(headers: IncomingHttpHeaders, name: string): string | null;
82
82
  export declare function userIdOf(req: Request): string;
83
83
  /**
84
84
  * The caller's own live key (`X-User-Key`), edge-stamped and stripped from an
@@ -118,16 +118,15 @@ export function tierOf(req) {
118
118
  * anything else that reports who someone is; a gate reads `tierOf`.
119
119
  */
120
120
  export function edgeTierOf(req) {
121
- const t = req.headers['x-hadoku-tier'];
122
- return typeof t === 'string' && t !== '' ? t : 'public';
121
+ return headerValue(req.headers, 'x-hadoku-tier') ?? 'public';
123
122
  }
124
- /** The caller's userId as the edge stamped it; null when the edge named nobody. */
125
- export function callerIdOf(req) {
126
- const u = req.headers['x-user-id'];
127
- return typeof u === 'string' && u !== '' ? u : null;
123
+ /** A header the edge sent once and not empty; null for a missing, empty or repeated one. */
124
+ export function headerValue(headers, name) {
125
+ const v = headers[name];
126
+ return typeof v === 'string' && v !== '' ? v : null;
128
127
  }
129
128
  export function userIdOf(req) {
130
- return callerIdOf(req) ?? 'anon';
129
+ return accountIdOf(req) ?? 'anon';
131
130
  }
132
131
  /**
133
132
  * The caller's own live key (`X-User-Key`), edge-stamped and stripped from an
@@ -135,16 +134,14 @@ export function userIdOf(req) {
135
134
  * edge sent none.
136
135
  */
137
136
  export function userKeyOf(req) {
138
- const k = req.headers['x-user-key'];
139
- return typeof k === 'string' && k !== '' ? k : null;
137
+ return headerValue(req.headers, 'x-user-key');
140
138
  }
141
139
  /**
142
140
  * The caller's registry userId (`X-User-Id`), edge-stamped and stripped from
143
141
  * an unvouched request. null when the edge sent none, never a stand-in word.
144
142
  */
145
143
  export function accountIdOf(req) {
146
- const u = req.headers['x-user-id'];
147
- return typeof u === 'string' && u !== '' ? u : null;
144
+ return headerValue(req.headers, 'x-user-id');
148
145
  }
149
146
  /**
150
147
  * The caller's DISPLAY NAME, edge-injected beside `X-User-Id` (same trust
@@ -156,8 +153,8 @@ export function userNameOf(req) {
156
153
  }
157
154
  /** `userNameOf` for a socket's handshake, whose headers went through the same sanitizing. */
158
155
  export function userNameFromHeaders(headers) {
159
- const n = headers['x-user-name'];
160
- return typeof n === 'string' && n !== '' ? utf8HeaderValue(n) : null;
156
+ const n = headerValue(headers, 'x-user-name');
157
+ return n === null ? null : utf8HeaderValue(n);
161
158
  }
162
159
  const STRICT_UTF8 = new TextDecoder('utf-8', { fatal: true });
163
160
  /**
@@ -1,4 +1,3 @@
1
- import type { NextFunction, Request, Response } from 'express';
2
1
  import { type Report } from '../telemetry/telemetry.js';
3
2
  import { type HostPressure } from './host-pressure.js';
4
3
  export declare const CAPACITY_WINDOW_MS: number;
@@ -22,8 +21,8 @@ export interface CapacityDeps {
22
21
  pressure?: () => HostPressure;
23
22
  }
24
23
  export interface CapacitySampler {
25
- /** Express middleware: counts each finished request and its duration. */
26
- requests: (req: Request, res: Response, next: NextFunction) => void;
24
+ /** One finished request: its path, how long it took and its status. The server times it once, for this and its access log. */
25
+ record(path: string, ms: number, status: number): void;
27
26
  /** Begin sampling. Called once the server listens: the gauges read what boot builds. */
28
27
  start(): void;
29
28
  sample(): void;
@@ -96,19 +96,14 @@ export function capacitySampler(deps) {
96
96
  };
97
97
  let timers = [];
98
98
  return {
99
- requests: (req, res, next) => {
100
- if (uncountedPath(req.path)) {
99
+ record: (path, ms, status) => {
100
+ if (uncountedPath(path)) {
101
101
  uncounted += 1;
102
- next();
103
102
  return;
104
103
  }
105
- const t = process.hrtime.bigint();
106
- res.on('finish', () => {
107
- durations.push(Number(process.hrtime.bigint() - t) / 1e6);
108
- if (res.statusCode >= 500)
109
- errors += 1;
110
- });
111
- next();
104
+ durations.push(ms);
105
+ if (status >= 500)
106
+ errors += 1;
112
107
  },
113
108
  start: () => {
114
109
  if (timers.length > 0)
@@ -55,7 +55,7 @@ import { closeSync, writeSync } from 'node:fs';
55
55
  import { createServer } from 'node:http';
56
56
  import express from 'express';
57
57
  import { Server as SocketIOServer } from 'socket.io';
58
- import { callerIdOf, tierOf, userIdOf } from "../auth/index.js";
58
+ import { accountIdOf, edgeTierOf, tierOf, userIdOf } from "../auth/index.js";
59
59
  import { capacitySampler, hostPressureFile, readHostPressure } from "../capacity/index.js";
60
60
  import { createAccountErase, ERASE_PATH, MERGE_PATH } from "../erase/index.js";
61
61
  import { healthResponse, readCommit, serviceIdOf } from "../health/index.js";
@@ -108,19 +108,18 @@ export async function createGameServer({ id, config, state, plugins }) {
108
108
  const accountErase = createAccountErase({ log, edgeSealed: config.edgeAuth.edgeSealed, deriveParticipantId: config.erase.deriveParticipantId });
109
109
  let seen;
110
110
  app.use(config.edgeAuth.edgeProvenance);
111
- app.use(capacity.requests);
111
+ // One timing per request, for the capacity window and the access log; the uncounted path is counted there and logs nothing.
112
112
  app.use((req, res, next) => {
113
- if (quiet(req.path)) {
114
- next();
115
- return;
116
- }
117
113
  const start = process.hrtime.bigint();
118
114
  // Read now: a mounted router strips its prefix from req.path while it routes, so on finish an /api route reads "/".
119
115
  const path = req.path;
120
116
  res.on('finish', () => {
121
117
  const ms = Number(process.hrtime.bigint() - start) / 1e6;
122
- // The identity the handlers saw, post-sanitize: a spoofed request logs as public.
123
- console.log(JSON.stringify({ t: new Date().toISOString(), svc: id, method: req.method, path, status: res.statusCode, ms: Math.round(ms), user: userIdOf(req), tier: tierOf(req) }));
118
+ capacity.record(path, ms, res.statusCode);
119
+ if (quiet(path))
120
+ return;
121
+ // The identity the handlers saw, post-sanitize: a spoofed request logs as public. The tier is the edge's own word.
122
+ console.log(JSON.stringify({ t: new Date().toISOString(), svc: id, method: req.method, path, status: res.statusCode, ms: Math.round(ms), user: userIdOf(req), tier: edgeTierOf(req) }));
124
123
  });
125
124
  next();
126
125
  });
@@ -199,7 +198,7 @@ export async function createGameServer({ id, config, state, plugins }) {
199
198
  stamp(phase);
200
199
  };
201
200
  await runPhase('config');
202
- seen = firstSeen({ file: config.firstSeen.file, userIdOf: callerIdOf, tierOf, log: config.firstSeen.log });
201
+ seen = firstSeen({ file: config.firstSeen.file, userIdOf: accountIdOf, tierOf, log: config.firstSeen.log });
203
202
  const callersSeen = seen;
204
203
  accountErase.register({
205
204
  what: 'callersSeen',
@@ -1 +1,2 @@
1
- export { callerContext, firstSeen, installTelemetry, monitoringSink, report, reportingAlerts, reportSealRefused, siteOf, userAgentOf, type FirstSeen, type FirstSeenOptions, type JsonLog, type Level, type Report, type SinkOptions, type TelemetryContext, type TelemetryValue, } from './telemetry.js';
1
+ export { callerContext, firstSeen, installTelemetry, monitoringSink, report, reportingAlerts, reportSealRefused, siteOf, userAgentOf, type FirstSeen, type FirstSeenOptions, type Level, type Report, type SinkOptions, type TelemetryContext, type TelemetryValue, } from './telemetry.js';
2
+ export type { JsonLog } from '../log/log.js';
@@ -11,11 +11,7 @@
11
11
  * scanner hammering the seal costs monitoring one row a minute, not one per request.
12
12
  */
13
13
  import type { NextFunction, Request, Response } from 'express';
14
- /**
15
- * A log line: one object a reader can grep by its own fields. This module never imports a
16
- * concrete logger (another lane owns that), so it takes whatever shape fits.
17
- */
18
- export type JsonLog = (entry: Record<string, unknown>) => void;
14
+ import type { JsonLog } from '../log/log.js';
19
15
  export type TelemetryValue = string | number | boolean | null | TelemetryValue[] | {
20
16
  [key: string]: TelemetryValue;
21
17
  };
@@ -11,6 +11,7 @@
11
11
  * scanner hammering the seal costs monitoring one row a minute, not one per request.
12
12
  */
13
13
  import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
14
+ import { headerValue } from "../auth/index.js";
14
15
  import { arrivedVia } from "../lifecycle/busy.js";
15
16
  /** What `report` does before boot installs a sink, and in every test that installs none. */
16
17
  const NOOP = () => { };
@@ -128,13 +129,9 @@ export function monitoringSink(opts) {
128
129
  }));
129
130
  };
130
131
  }
131
- function header(headers, name) {
132
- const v = headers[name];
133
- return typeof v === 'string' && v !== '' ? v : null;
134
- }
135
132
  /** The caller's user agent, cut short: enough to tell a browser from a script. */
136
133
  export function userAgentOf(headers) {
137
- return header(headers, 'user-agent')?.slice(0, 160) ?? null;
134
+ return headerValue(headers, 'user-agent')?.slice(0, 160) ?? null;
138
135
  }
139
136
  /**
140
137
  * Who a request or handshake says it is, from the edge's headers AFTER
@@ -143,8 +140,8 @@ export function userAgentOf(headers) {
143
140
  */
144
141
  export function callerContext(headers) {
145
142
  return {
146
- userId: header(headers, 'x-user-id'),
147
- tier: header(headers, 'x-hadoku-tier') ?? 'public',
143
+ userId: headerValue(headers, 'x-user-id'),
144
+ tier: headerValue(headers, 'x-hadoku-tier') ?? 'public',
148
145
  ua: userAgentOf(headers),
149
146
  };
150
147
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/service-kernel",
3
- "version": "0.1.245",
4
- "gitHead": "a9e2641a46c10f8803503badaf42ec88a15b23e9",
3
+ "version": "0.1.246",
4
+ "gitHead": "d8a95c3583ef6c967ef63ade32c57ae9a3b6272b",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any game keeps: edge auth and the tier gate, base path and bundle check, health and the busy probe, lifecycle, the JSON logger, the state directory, telemetry and capacity, per-caller limits, the browser relays, the erase registry, and createGameServer, which boots a game from its config and plugins. Knows no game; the app binds its service id, prefix and env names. MIT; imports only node built-ins, express, socket.io, platform-wire and @wolffm/*.",
@@ -56,7 +56,7 @@
56
56
  }
57
57
  },
58
58
  "dependencies": {
59
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.212",
59
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.213",
60
60
  "express": "^5.1.0",
61
61
  "socket.io": "^4.8.3"
62
62
  },