@ultimat3/core 30.8.0 → 31.0.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 (67) hide show
  1. package/CLAUDE.md +54 -58
  2. package/README.md +70 -27
  3. package/package.json +3 -2
  4. package/src/adapter-slot.ts +42 -0
  5. package/src/adapter.ts +24 -0
  6. package/src/audit.ts +31 -14
  7. package/src/aws-sigv4.ts +9 -3
  8. package/src/cache-vocabulary.ts +1 -1
  9. package/src/client-problem.ts +10 -3
  10. package/src/clock.ts +68 -14
  11. package/src/config-defaults.ts +4 -4
  12. package/src/config-keys.ts +1 -1
  13. package/src/config-removed.ts +11 -1
  14. package/src/config.ts +16 -20
  15. package/src/context.ts +2 -2
  16. package/src/cursor.ts +3 -11
  17. package/src/der.ts +65 -0
  18. package/src/error-render.ts +27 -1
  19. package/src/error-reporter-chain.ts +1 -1
  20. package/src/error-reporter-sentry-hooks.ts +85 -0
  21. package/src/error-reporter-sentry.ts +99 -7
  22. package/src/error-reporter.ts +39 -11
  23. package/src/errors.ts +3 -1
  24. package/src/exports/error-contract.ts +4 -14
  25. package/src/exports/observability.ts +57 -17
  26. package/src/exports/secrets.ts +4 -18
  27. package/src/failure-capture.ts +22 -13
  28. package/src/gate-shapes.ts +88 -0
  29. package/src/host-rules.ts +13 -1
  30. package/src/html-escape.ts +7 -1
  31. package/src/ids.ts +59 -10
  32. package/src/image/png-pixels.ts +14 -8
  33. package/src/index.ts +123 -136
  34. package/src/instrument-events.ts +272 -0
  35. package/src/instrument-semconv.ts +65 -0
  36. package/src/instrument-stacks.ts +38 -0
  37. package/src/instrument.ts +194 -0
  38. package/src/keyed-fingerprint.ts +7 -11
  39. package/src/lifecycle-signals.ts +5 -3
  40. package/src/lifecycle.ts +27 -0
  41. package/src/logger-record.ts +35 -0
  42. package/src/logger.ts +24 -16
  43. package/src/mcp-exposure.ts +17 -0
  44. package/src/metrics-semconv.ts +124 -0
  45. package/src/metrics.ts +19 -16
  46. package/src/otlp-batch.ts +78 -0
  47. package/src/otlp-log-exporter.ts +180 -0
  48. package/src/otlp-metric-exporter.ts +2 -1
  49. package/src/otlp-post.ts +22 -2
  50. package/src/otlp-span-exporter.ts +10 -59
  51. package/src/otlp.ts +27 -9
  52. package/src/outbound-instrument.ts +82 -0
  53. package/src/outbound.ts +5 -4
  54. package/src/page-meta.ts +6 -0
  55. package/src/page.ts +23 -5
  56. package/src/registrar.ts +269 -0
  57. package/src/route-vocabulary.ts +11 -2
  58. package/src/safe-url.ts +10 -8
  59. package/src/seal-errors.ts +14 -4
  60. package/src/seal-keys.ts +11 -7
  61. package/src/secret-source.ts +125 -0
  62. package/src/secrets-errors.ts +32 -12
  63. package/src/secrets-store.ts +30 -26
  64. package/src/sleep-clock.ts +70 -0
  65. package/src/telemetry.ts +90 -31
  66. package/src/type-pins.ts +19 -16
  67. package/src/log-tee.ts +0 -73
@@ -3,6 +3,7 @@
3
3
  // `@ultimat3/flags`' evaluations) record into it; a 5xx HOLDS the buffer on the thrown value, and
4
4
  // `reportError` releases it with the report's own fingerprint. With no store, nothing allocates.
5
5
 
6
+ import { adapterSlot } from './adapter-slot';
6
7
  import { asyncContext } from './async-context';
7
8
  import { tryUseContext } from './context';
8
9
  import { renderThrowable } from './error-render';
@@ -81,23 +82,31 @@ export type FailureFact =
81
82
  | { readonly kind: 'flag'; readonly key: string; readonly value: unknown };
82
83
 
83
84
  const buffers = asyncContext<Buffer>('failure capture');
84
- let store: FailureStore | null = null;
85
- let limits: FailureCaptureLimits = { perHour: 5, maxRows: 50, maxBytes: 64 * 1024 };
85
+ const DEFAULT_LIMITS: FailureCaptureLimits = { perHour: 5, maxRows: 50, maxBytes: 64 * 1024 };
86
+ /** One frame per install: the store and the limits in force with it. Nothing installed is "off". */
87
+ const installed = adapterSlot<{
88
+ readonly store: FailureStore | null;
89
+ readonly limits: FailureCaptureLimits;
90
+ }>(() => ({ store: null, limits: DEFAULT_LIMITS }));
86
91
  /** Held on the thrown value itself, so no request id has to survive the trip to the reporter. */
87
92
  const held = new WeakMap<object, HeldFailure>();
88
93
 
89
- /** Install the store (capture on) or `null` (off). Returns the previous one, for a harness. */
90
- export function setFailureStore(
94
+ /**
95
+ * Install the store (capture on) or `null` (off). Returns the release, which removes THIS
96
+ * install's frame (store and limits) whatever order installers stop in (`adapter-slot.ts`). On
97
+ * `@ultimat3/core/adapter` only, never the barrel: the boot calls it with `runtime.ts`'s
98
+ * `failureStore`, and `@ultimat3/testing` for one test — an app module calling it would race the
99
+ * boot, the split `X_RUNTIME_DRIVER_SPLIT` exists to refuse.
100
+ */
101
+ export function installFailureStore(
91
102
  next: FailureStore | null,
92
103
  options: Partial<FailureCaptureLimits> = {},
93
- ): FailureStore | null {
94
- const previous = store;
95
- store = next;
96
- limits = { ...limits, ...options };
97
- return previous;
104
+ ): () => void {
105
+ // Limits layer over the ones in force, so a store installed with `{ perHour: 2 }` keeps the rest.
106
+ return installed.install({ store: next, limits: { ...installed.current().limits, ...options } });
98
107
  }
99
108
 
100
- export const failureCaptureLimits = (): FailureCaptureLimits => limits;
109
+ export const failureCaptureLimits = (): FailureCaptureLimits => installed.current().limits;
101
110
 
102
111
  /** Whether a call in flight is being captured: a seam asks this before it builds anything. */
103
112
  export const failureCaptureActive = (): boolean => buffers.get() !== undefined;
@@ -110,7 +119,7 @@ export function recordFailureFact(fact: FailureFact): void {
110
119
  if (!buffer.flags.has(fact.key)) buffer.flags.set(fact.key, captureValue(fact.value).value);
111
120
  return;
112
121
  }
113
- if (buffer.reads.length >= limits.maxRows) {
122
+ if (buffer.reads.length >= failureCaptureLimits().maxRows) {
114
123
  buffer.truncated = true;
115
124
  return;
116
125
  }
@@ -167,7 +176,7 @@ export async function withFailureCapture<T>(
167
176
  statusOf: (code: string) => number,
168
177
  run: () => Promise<T>,
169
178
  ): Promise<T> {
170
- if (store === null || buffers.get() !== undefined) return run();
179
+ if (installed.current().store === null || buffers.get() !== undefined) return run();
171
180
  const buffer: Buffer = {
172
181
  primitive,
173
182
  name,
@@ -197,7 +206,7 @@ export function takeHeldFailure(error: unknown): HeldFailure | undefined {
197
206
  return found;
198
207
  }
199
208
 
200
- export const installedFailureStore = (): FailureStore | null => store;
209
+ export const installedFailureStore = (): FailureStore | null => installed.current().store;
201
210
 
202
211
  /** A store that refused is logged and never reaches the response that is already on its way. */
203
212
  export function failureStoreRefused(failure: unknown): void {
@@ -0,0 +1,88 @@
1
+ // The rate-limit and audit gate SHAPES `@ultimat3/action` and `@ultimat3/query` both use: types
2
+ // and pure rules, no I/O. The siblings cannot import each other, and each spelled these rules for
3
+ // itself until they drifted; the bucket store and the sink stay with their owners.
4
+
5
+ import { type Actor, isAnonymous } from './actor';
6
+ import type { AuditFailure, AuditOutcome, AuditPrimitive, AuditSurface } from './audit';
7
+ import { isUltimateError } from './errors';
8
+
9
+ /** The line both primitives write when a sink refuses a record — one alert rule over both. */
10
+ export const AUDIT_SINK_FAILED_EVENT = 'audit.sink.failed';
11
+
12
+ /**
13
+ * An authz refusal is `denied`; everything else that threw is `failed`. TOTAL: `isDenial` is an
14
+ * `instanceof`, which runs a `Proxy`'s trap inside a `catch` still holding the app's error, and a
15
+ * probe that throws there must not replace it. A value that refuses examination is not a denial.
16
+ */
17
+ export function auditOutcomeOf(
18
+ error: unknown,
19
+ isDenial: (error: unknown) => boolean,
20
+ ): AuditOutcome {
21
+ try {
22
+ return isDenial(error) ? 'denied' : 'failed';
23
+ } catch {
24
+ return 'failed';
25
+ }
26
+ }
27
+
28
+ /** Why a non-`allowed` attempt ended: its `X_*` code, or `null`, and the thrown value verbatim. */
29
+ export function auditFailureOf(error: unknown): AuditFailure {
30
+ try {
31
+ return { code: isUltimateError(error) ? error.code : null, error };
32
+ } catch {
33
+ return { code: null, error };
34
+ }
35
+ }
36
+
37
+ /** `'server'` is app code calling its own primitive in-process: not a caller from outside. */
38
+ export function rateLimitSpendsOn(surface: AuditSurface): boolean {
39
+ return surface !== 'server';
40
+ }
41
+
42
+ /** Namespaced, never the bare name: one key taken against two bucket shapes corrupts both. */
43
+ export function rateLimitScopeOf(kind: AuditPrimitive, name: string): string {
44
+ return `${kind}:${name}`;
45
+ }
46
+
47
+ export interface RateLimitSubject {
48
+ readonly actorId: string | null;
49
+ readonly orgId: string | null;
50
+ readonly ip: string | null;
51
+ }
52
+
53
+ /**
54
+ * Who a spend is charged to. The org is read off an anonymous actor too: a job run IS the
55
+ * worker's anonymous identity carrying the job's org, and charging every tenant's runs to one
56
+ * `ip:unknown` key let one tenant's backlog refuse everyone's.
57
+ */
58
+ export function rateLimitSubjectOf(actor: Actor, ip: string | null): RateLimitSubject {
59
+ return {
60
+ actorId: isAnonymous(actor) ? null : actor.id,
61
+ orgId: actor.orgId ?? null,
62
+ ip,
63
+ };
64
+ }
65
+
66
+ /** A declared limit: the burst, or one resolved per call (`({ ctx }) => planOf(ctx).perMinute`). */
67
+ export interface GateRateLimit<A = unknown> {
68
+ readonly limit: number | ((args: A) => number | Promise<number>);
69
+ readonly windowMs: number;
70
+ }
71
+
72
+ /**
73
+ * The number a call is held to. A non-number becomes `NaN`, so the bucket check refuses it by
74
+ * name (`X_RATE_LIMIT_INVALID`) rather than reading it as allow-all.
75
+ */
76
+ export async function resolvedRateLimitOf<A>(limit: GateRateLimit<A>, args: A): Promise<number> {
77
+ const resolved: unknown =
78
+ typeof limit.limit === 'function' ? await limit.limit(args) : limit.limit;
79
+ return typeof resolved === 'number' ? resolved : Number.NaN;
80
+ }
81
+
82
+ /** The declaration as data a contract can diff: the fixed pair, or `null` when resolved per call. */
83
+ export function fixedRateLimitOf<A>(
84
+ limit: GateRateLimit<A> | undefined,
85
+ ): { readonly limit: number; readonly windowMs: number } | null {
86
+ if (limit === undefined || typeof limit.limit === 'function') return null;
87
+ return { limit: limit.limit, windowMs: limit.windowMs };
88
+ }
package/src/host-rules.ts CHANGED
@@ -59,9 +59,20 @@ const isWildcard = (rule: HostRule): boolean => {
59
59
  return cleaned === ANY_HOST || cleaned.startsWith('*.');
60
60
  };
61
61
 
62
+ /**
63
+ * `localhost` and every `*.localhost` (RFC 6761 §6.3), trailing dot or not: loopback by NAME, so no
64
+ * resolver is needed to know it — and Chrome ≥ 72 sends these straight past `--proxy-server`
65
+ * (its implicit bypass rules), the one case where a session's egress proxy screened nothing. Part
66
+ * of the floor below for that reason: a wildcard never admits one, an exact rule still does.
67
+ */
68
+ const isLocalhostName = (host: string): boolean => {
69
+ const name = host.toLowerCase().replace(/\.$/, '');
70
+ return name === 'localhost' || name.endsWith('.localhost');
71
+ };
72
+
62
73
  /**
63
74
  * The address-class FLOOR. A wildcard means "any site", and an address literal inside the network
64
- * — loopback, RFC 1918, link-local, the metadata endpoint — is not a site: it is the request this
75
+ * — loopback, RFC 1918, link-local, the metadata endpoint — or a `localhost` name is not a site: it is the request this
65
76
  * module's header names. So a wildcard never admits one, and the opt-out is NAMING it: an exact
66
77
  * rule (`'127.0.0.1'`, `'[::1]'`) is a line a reviewer can see, which `'*'` is not.
67
78
  *
@@ -74,6 +85,7 @@ const isWildcard = (rule: HostRule): boolean => {
74
85
  function admits(host: string, rule: HostRule): boolean {
75
86
  if (!hostMatches(host, rule)) return false;
76
87
  if (!isWildcard(rule)) return true;
88
+ if (isLocalhostName(host)) return false;
77
89
  const kind = classifyAddress(host);
78
90
  return kind === undefined || kind === 'public';
79
91
  }
@@ -20,5 +20,11 @@ const HTML_SPECIAL = /[&<>"']/g;
20
20
  * the same thing in HTML 4, HTML 5 and XML. One pass, so `&` is never escaped twice.
21
21
  */
22
22
  export function escapeHtml(value: string): string {
23
- return value.replace(HTML_SPECIAL, (char) => HTML_ESCAPES.get(char) ?? char);
23
+ // Most text has nothing to escape, and a big page asks this ~10 times a row: a scan is a
24
+ // fraction of a replace with a callback (plan 101 slice 14). ONE global regex for both, which
25
+ // ships in every island: a failed `test` resets `lastIndex` to 0, and `replace` on a global
26
+ // regex starts at 0 and leaves it there — so no call ever sees another's position.
27
+ return HTML_SPECIAL.test(value)
28
+ ? value.replace(HTML_SPECIAL, (char) => HTML_ESCAPES.get(char) ?? char)
29
+ : value;
24
30
  }
package/src/ids.ts CHANGED
@@ -24,12 +24,42 @@ const COUNTER_MAX = 0xfff;
24
24
  let lastEpochMs = -1;
25
25
  let counter = 0;
26
26
 
27
+ /**
28
+ * CSPRNG bytes, drawn from a pool one `crypto.getRandomValues` fill at a time. Per call the fill
29
+ * was most of what an id cost — 974 ns for a trace id against the ≤ 1 µs a whole unsampled span
30
+ * may cost (plan 101 slice 20) — and the bytes are just as unpredictable 4 KiB at a time. A byte
31
+ * is handed out ONCE: the cursor only moves forward, and a request past the pool's tail refills
32
+ * rather than wrapping.
33
+ */
34
+ export const RANDOM_POOL_BYTES = 4096;
35
+
36
+ let pool = new Uint8Array(0);
37
+ let poolAt = 0;
38
+
39
+ /** Where `length` unhanded pool bytes start; the cursor is moved past them, so they are taken. */
40
+ function take(length: number): number {
41
+ if (poolAt + length > pool.length) {
42
+ pool = crypto.getRandomValues(new Uint8Array(RANDOM_POOL_BYTES));
43
+ poolAt = 0;
44
+ }
45
+ const at = poolAt;
46
+ poolAt += length;
47
+ return at;
48
+ }
49
+
27
50
  function randomBytes(length: number): Uint8Array {
28
- const bytes = new Uint8Array(length);
29
- crypto.getRandomValues(bytes);
30
- return bytes;
51
+ // A request too big to pool is drawn on its own rather than draining the pool for one caller.
52
+ if (length > RANDOM_POOL_BYTES / 4) return crypto.getRandomValues(new Uint8Array(length));
53
+ const at = take(length);
54
+ return pool.subarray(at, at + length);
31
55
  }
32
56
 
57
+ /** Every byte's two hex digits, so an id is one lookup per byte instead of two and a shift. */
58
+ const HEX_PAIRS: readonly string[] = Array.from(
59
+ { length: 256 },
60
+ (_, byte) => `${HEX[byte >> 4]}${HEX[byte & 0x0f]}`,
61
+ );
62
+
33
63
  /**
34
64
  * A full 10 bits, from both bytes. Reading `bytes[0]` alone masked an 8-bit value with a 10-bit
35
65
  * mask, so the seed only ever reached 255 while `COUNTER_SEED_MASK` declared 1023 — the constant
@@ -46,12 +76,25 @@ function seedCounter(): number {
46
76
  * same empty string, and every caller here (`uuidV7`, `traceId`, `spanId`) wants a width.
47
77
  */
48
78
  export function randomHex(byteLength: number): string {
49
- const bytes = randomBytes(finiteCount('randomHex', 'byteLength', byteLength, 1));
50
- let out = '';
51
- for (const byte of bytes) {
52
- out += HEX[byte >> 4];
53
- out += HEX[byte & 0x0f];
79
+ return hexOf(finiteCount('randomHex', 'byteLength', byteLength, 1));
80
+ }
81
+
82
+ /**
83
+ * The unscreened body, for this file's fixed widths: `finiteCount` builds its refusal's two
84
+ * messages on every call, a cost a trace id minted per span cannot carry.
85
+ */
86
+ function hexOf(byteLength: number): string {
87
+ if (byteLength > RANDOM_POOL_BYTES / 4) {
88
+ let out = '';
89
+ for (const byte of randomBytes(byteLength)) out += HEX_PAIRS[byte];
90
+ return out;
54
91
  }
92
+ // Indexed into the pool, never a `subarray` and `for…of`: the view and its iterator were most of
93
+ // what a 16-byte id cost (measured 585 ns against 190 ns).
94
+ const at = take(byteLength);
95
+ const bytes = pool;
96
+ let out = '';
97
+ for (let index = at; index < at + byteLength; index += 1) out += HEX_PAIRS[bytes[index] ?? 0];
55
98
  return out;
56
99
  }
57
100
 
@@ -151,11 +194,11 @@ export function parseId<K extends string>(kind: K, value: unknown): Id<K> {
151
194
 
152
195
  /** W3C trace-context ids: 16 bytes / 8 bytes of hex. */
153
196
  export function traceId(): string {
154
- return randomHex(16);
197
+ return hexOf(16);
155
198
  }
156
199
 
157
200
  export function spanId(): string {
158
- return randomHex(8);
201
+ return hexOf(8);
159
202
  }
160
203
 
161
204
  const TRACE_ID_RE = /^[0-9a-f]{32}$/;
@@ -180,6 +223,12 @@ export function isSpanId(value: unknown): boolean {
180
223
  }
181
224
 
182
225
  /** Test-only: reset the monotonic counter so a frozen clock produces a fresh sequence. */
226
+ /** TEST SEAM: drop the pool, so the next id draws a fresh fill. */
227
+ export function resetRandomPool(): void {
228
+ pool = new Uint8Array(0);
229
+ poolAt = 0;
230
+ }
231
+
183
232
  export function resetIdCounter(): void {
184
233
  lastEpochMs = -1;
185
234
  counter = 0;
@@ -3,13 +3,6 @@
3
3
  // safe zone `@ultimat3/pwa` promises is a composite. So this file exists for exactly that one hop:
4
4
  // Bun re-encodes to PNG, this reads the pixels back, `canvas.ts` blits, this writes them again.
5
5
 
6
- // why: `Bun.inflateSync` takes no output bound — measured, it ignores `maxOutputLength` and
7
- // returns the whole stream — and `DecompressionStream` is async where this seam is synchronous.
8
- // `node:zlib` is the one inflate here that can be told when to stop. A NAMESPACE import, never a
9
- // named one: the browser polyfill of this module has no `inflateRawSync`, and a named import of a
10
- // missing export fails the BUNDLE of every browser graph that reaches the barrel
11
- // (`async-context.test.ts` builds one) — for a function no browser ever calls.
12
- import * as zlib from 'node:zlib';
13
6
  import { stringField } from '../error-render';
14
7
  import { imageDecodeFailed, imageUnsupported } from './errors';
15
8
  import {
@@ -113,6 +106,19 @@ function readHeader(bytes: Uint8Array): PngHeader {
113
106
  return { width: readU32(bytes, 16), height: readU32(bytes, 20) };
114
107
  }
115
108
 
109
+ /**
110
+ * why: `Bun.inflateSync` takes no output bound — measured, it ignores `maxOutputLength` and returns
111
+ * the whole stream — and `DecompressionStream` is async where this seam is synchronous. `node:zlib`
112
+ * is the one inflate here that can be told when to stop. Resolved at the CALL, never imported: a
113
+ * static import puts `node:zlib` in every browser graph that parses core's barrel, and Bun's
114
+ * polyfill has no `inflateRawSync`, so each such build warned (`@ultimat3/action`'s
115
+ * `client-bundle.test.ts`) — for a function no browser ever calls.
116
+ */
117
+ function serverZlib(): typeof import('node:zlib') {
118
+ // why: Bun's inflate has no output bound, and a static import warns in every browser build.
119
+ return process.getBuiltinModule('node:zlib');
120
+ }
121
+
116
122
  /**
117
123
  * Every IDAT concatenated — a PNG may split its stream across any number of them — and inflated
118
124
  * to AT MOST `limit` bytes, which is what the header says the pixels need. Inflating first and
@@ -136,7 +142,7 @@ function idatStream(bytes: Uint8Array, limit: number): Uint8Array {
136
142
  try {
137
143
  // The 2-byte zlib header and the 4-byte Adler-32 trailer are PNG's envelope, stripped here
138
144
  // so the payload inflates as RAW deflate — see the encoder above for the mirror image.
139
- return zlib.inflateRawSync(unshared(stream.subarray(2, stream.length - 4)), {
145
+ return serverZlib().inflateRawSync(unshared(stream.subarray(2, stream.length - 4)), {
140
146
  maxOutputLength: limit,
141
147
  });
142
148
  } catch (error) {