@ultimat3/core 31.51.0 → 31.53.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/README.md +3 -1
- package/package.json +2 -2
- package/src/adapter.ts +2 -0
- package/src/config-defaults.ts +2 -1
- package/src/config-outbound.ts +81 -0
- package/src/config.ts +12 -12
- package/src/framework-env.ts +2 -0
- package/src/index.ts +1 -1
- package/src/keyed-fingerprint.ts +39 -10
- package/src/nearest-name.ts +4 -0
- package/src/outbound-attempt.ts +8 -3
- package/src/outbound-default-proxy.ts +112 -0
- package/src/outbound-errors.ts +20 -4
- package/src/outbound-refusal-headers.ts +95 -0
- package/src/outbound-subpath.ts +6 -3
- package/src/outbound-types.ts +13 -0
- package/src/outbound.ts +6 -1
- package/src/page.ts +1 -1
- package/src/telemetry.ts +32 -1
- package/src/theme-storage.ts +7 -0
- package/src/type-pins.ts +17 -0
package/README.md
CHANGED
|
@@ -87,6 +87,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
|
|
|
87
87
|
| semconv names: `SEMCONV` (span attribute keys), `SEMCONV_VALUES`, `SEMCONV_METRICS` | `instrument-semconv.ts` |
|
|
88
88
|
| `subscribeSemconvMetrics()` — the semconv histograms (`db_client_operation_duration_seconds`, `job_duration_seconds`, `gen_ai_client_token_usage`) as one bus subscriber; boot calls it once | `metrics-semconv.ts` |
|
|
89
89
|
| OTel-shaped spans, always on; a SAMPLED span goes out as `span.end` on the bus. `configureTelemetry({ exporter })` and `noopExporter` are gone (31.0): `subscribe('span.end', (e) => exporter.export(e.payload))` | `telemetry.ts` |
|
|
90
|
+
| One service resource on every signal: unconfigured, OTel's `unknown_service` at `APP_VERSION`'s `dev` (never an invented name). `configureTelemetry({ serviceName, serviceVersion })` sets it (`installTelemetry` on `@ultimat3/core/adapter` is the same and returns its release); the container boot names it — `OTEL_SERVICE_NAME` › `OTEL_RESOURCE_ATTRIBUTES` › the app's `name`, version from the attributes › the build id › `APP_VERSION`. Core reads no env for it | `telemetry.ts` |
|
|
90
91
|
| the sampling decision, and `OTEL_TRACES_SAMPLER*` | `sampler.ts` |
|
|
91
92
|
| OTLP/HTTP JSON: endpoint, headers, value encoding | `otlp.ts` |
|
|
92
93
|
| one OTLP POST, retried on the specification's transient answers | `otlp-post.ts` |
|
|
@@ -957,8 +958,9 @@ Server-only, on its own subpath: `import { outbound, screenDial } from '@ultimat
|
|
|
957
958
|
|
|
958
959
|
| Export | The one answer | The question it settles |
|
|
959
960
|
|---|---|---|
|
|
960
|
-
| `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker?, proxy?, refusal? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and twelve `X_OUTBOUND_*` codes whose causes carry no query and no header. `dial: 'public'` is the SSRF screen for a user-supplied URL (resolve, classify every address, pin, re-screen each hop): never a hand-written guard. `proxy` (a URL, `{ url, headers }`, or a per-hop resolver `(target) => … \| undefined`, types `OutboundProxy`, `OutboundProxyTarget`, `OutboundProxyInit`) is chosen AFTER the screen, so a public dial is tunnelled to the approved address with `tls.serverName` intact; its credential is never logged; a bad one is `X_OUTBOUND_PROXY_INVALID`. Inventory and rotation are app code. `deps` injects `fetch`, `resolve`, `sleep`, `now`, `random`, `timer`, `env`. `fetch` is a production seam too: it is handed the screened url and `redirect: 'manual'`, the caps and rules stay `outbound()`'s, and an answer it reached by following a redirect itself is `X_OUTBOUND_TRANSPORT_REDIRECTED`. `refusal` (`OutboundRefusalRead`): `{ schema }` reads a non-2xx body whole, within `maxBytes`, and puts the schema's redacted answer at `meta.fields`; `{ detail: false }` keeps `meta.detail` at `''` |
|
|
961
|
+
| `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker?, proxy?, refusal? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and twelve `X_OUTBOUND_*` codes whose causes carry no query and no header. `dial: 'public'` is the SSRF screen for a user-supplied URL (resolve, classify every address, pin, re-screen each hop): never a hand-written guard. `proxy` (a URL, `{ url, headers }`, or a per-hop resolver `(target) => … \| undefined`, types `OutboundProxy`, `OutboundProxyTarget`, `OutboundProxyInit`) is chosen AFTER the screen, so a public dial is tunnelled to the approved address with `tls.serverName` intact; its credential is never logged; a bad one is `X_OUTBOUND_PROXY_INVALID`. Inventory and rotation are app code. `deps` injects `fetch`, `resolve`, `sleep`, `now`, `random`, `timer`, `env`. `fetch` is a production seam too: it is handed the screened url and `redirect: 'manual'`, the caps and rules stay `outbound()`'s, and an answer it reached by following a redirect itself is `X_OUTBOUND_TRANSPORT_REDIRECTED`. `refusal` (`OutboundRefusalRead`): `{ schema }` reads a non-2xx body whole, within `maxBytes`, and puts the schema's redacted answer at `meta.fields`; `{ detail: false }` keeps `meta.detail` at `''`; `{ headers: ['x-request-id'] }` keeps those response headers (lowercased, redacted, 200 characters each, credential-named ones refused as `X_INVARIANT`) at `meta.headers` |
|
|
961
962
|
| `screenDial(url, { resolve?, allowPrivate? })` → `{ pin } \| { refused } \| { unresolved }` | where a dial may land | every resolved address classified by `classifyAddress`, the connection pinned with `tls.serverName`. The framework's one `Bun.dns.lookup` (`resolveDialHost`); `@ultimat3/jobs`' webhook target and `@ultimat3/scraping` call it and keep their own codes |
|
|
963
|
+
| `configureOutboundProxy({ proxy?, direct? })` → release (type `OutboundProxyConfig`) | the app-wide egress proxy | `app.config.ts`'s `outbound` block, installed once by the container boot — an app never calls it. A call with no `proxy` goes through it; a call's own `proxy` wins; `proxy: () => undefined` dials direct; loopback, `*.localhost` and each `direct` host (and every name under it) never take it. The boot line shows the URL's userinfo as `***` |
|
|
962
964
|
| `deadlineSignal(ms, outer?, timer?)` | one attempt's signal | a deadline plus the caller's signal, undone on dispose (no listener left on `outer`, no timer armed) |
|
|
963
965
|
| `breaker({ name, failures, cooldownMs, classify?, clock? })` → `admit`, `succeeded`, `failed`, `released`, `state`, `failures`, `judge`, `refusal`, `run` | is a dependency down | one state machine, the trigger stays the caller's. One probe in `half-open`, lapsing after `cooldownMs`; `X_BREAKER_OPEN` names `retryAfterSeconds`; `breaker_transitions_total{name,to}`. Per process |
|
|
964
966
|
| `retryBudgetOf(breaker)` → `called()`, `spend()` | retries as a share of calls, per breaker key | whether one more retry may go out during a partial outage the breaker cannot see: a call earns 1 token, a retry costs 5 (retries ≤ 20% of calls), a quiet key starts with a burst of 10 retries. Keyed by breaker identity, per process; `outbound` consults it, and a refused retry answers the last error |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/core",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.53.0",
|
|
4
4
|
"description": "Ultimate's foundation: errors, context, env, config, clock, ids, logging, telemetry, lifecycle",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -55,6 +55,6 @@
|
|
|
55
55
|
"test": "bun test"
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@ultimat3/schema": "31.
|
|
58
|
+
"@ultimat3/schema": "31.53.0"
|
|
59
59
|
}
|
|
60
60
|
}
|
package/src/adapter.ts
CHANGED
|
@@ -26,3 +26,5 @@ export {
|
|
|
26
26
|
} from './secret-source';
|
|
27
27
|
export { SecretsKeyMissingError } from './secrets-errors';
|
|
28
28
|
export { installClock, noWaitClock, systemClock } from './sleep-clock';
|
|
29
|
+
/** The service identity, sampler and clock, with the release the boot's stop calls. */
|
|
30
|
+
export { installTelemetry } from './telemetry';
|
package/src/config-defaults.ts
CHANGED
|
@@ -15,7 +15,7 @@ import { ROLES } from './roles';
|
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* The keys their own files default: `config-site.ts`, `-navigation`, `-islands`, `-mail`,
|
|
18
|
-
* `-client-errors`, `-assets`, `-failure-capture`, `-time`.
|
|
18
|
+
* `-client-errors`, `-assets`, `-failure-capture`, `-time`, `-outbound`.
|
|
19
19
|
*/
|
|
20
20
|
type Sectioned =
|
|
21
21
|
| 'name'
|
|
@@ -27,6 +27,7 @@ type Sectioned =
|
|
|
27
27
|
| 'clientErrors'
|
|
28
28
|
| 'failureCapture'
|
|
29
29
|
| 'time'
|
|
30
|
+
| 'outbound'
|
|
30
31
|
| 'assets';
|
|
31
32
|
|
|
32
33
|
export function configDefaults(): Omit<AppConfig, Sectioned> {
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Single responsibility: the `outbound` block of `app.config.ts` — the app-wide egress proxy every
|
|
2
|
+
// `outbound()` call takes unless it names its own, and the hosts that never do. Shape, merge and
|
|
3
|
+
// screen are one subject; `config.ts` is full. The boot installs it (`outbound-default-proxy.ts`).
|
|
4
|
+
|
|
5
|
+
import { describeValue, renderCauseValue } from './error-render';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* NO PROXY BY DEFAULT: a deploy behind an egress gateway says so. `proxy` is an `http:`/`https:`
|
|
9
|
+
* URL; its credential belongs in the environment (`proxy: env.EGRESS_PROXY`, through
|
|
10
|
+
* `defineEnv`), never a literal in a committed file. `direct` hosts — and every name under each, and loopback always —
|
|
11
|
+
* dial without it: an in-cluster collector or sidecar is not egress.
|
|
12
|
+
*/
|
|
13
|
+
export interface OutboundConfig {
|
|
14
|
+
readonly proxy: string | undefined;
|
|
15
|
+
readonly direct: readonly string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const OUTBOUND_DEFAULTS: OutboundConfig = Object.freeze({ proxy: undefined, direct: [] });
|
|
19
|
+
|
|
20
|
+
export interface OutboundSection {
|
|
21
|
+
readonly outbound: OutboundConfig;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface OutboundSectionInput {
|
|
25
|
+
readonly outbound?:
|
|
26
|
+
| {
|
|
27
|
+
readonly proxy?: string | undefined;
|
|
28
|
+
readonly direct?: readonly string[] | undefined;
|
|
29
|
+
}
|
|
30
|
+
| undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Each key is the last layer that said it; `direct` is one list, replaced whole like `roles`. */
|
|
34
|
+
export function mergeOutbound(layers: readonly OutboundSectionInput[]): OutboundSection {
|
|
35
|
+
let { proxy, direct } = OUTBOUND_DEFAULTS;
|
|
36
|
+
for (const layer of layers) {
|
|
37
|
+
if (layer.outbound?.proxy !== undefined) proxy = layer.outbound.proxy;
|
|
38
|
+
if (layer.outbound?.direct !== undefined) direct = layer.outbound.direct;
|
|
39
|
+
}
|
|
40
|
+
return { outbound: { proxy, direct } };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The schemes Bun's `fetch` tunnels through — `outbound-proxy.ts` refuses the rest per hop. */
|
|
44
|
+
const PROXY_SCHEMES: ReadonlySet<string> = new Set(['http:', 'https:']);
|
|
45
|
+
|
|
46
|
+
/** A bare host name or IPv4 literal, or a bracketed IPv6 one: what a URL's `hostname` holds. */
|
|
47
|
+
const HOST =
|
|
48
|
+
/^(?:\[[0-9a-f:.]+\]|[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*)$/i;
|
|
49
|
+
|
|
50
|
+
/** Why `proxy` cannot be used, in words that never quote it: the URL may carry a password. */
|
|
51
|
+
function proxyIssue(proxy: unknown): string | undefined {
|
|
52
|
+
if (proxy === undefined) return undefined;
|
|
53
|
+
const rule = 'outbound.proxy must be an absolute http: or https: URL';
|
|
54
|
+
if (typeof proxy !== 'string') return `${rule}, not ${describeValue(proxy)}`;
|
|
55
|
+
let url: URL;
|
|
56
|
+
try {
|
|
57
|
+
url = new URL(proxy);
|
|
58
|
+
} catch {
|
|
59
|
+
return `${rule}; the value set is not a URL (not echoed: it may hold a credential)`;
|
|
60
|
+
}
|
|
61
|
+
return PROXY_SCHEMES.has(url.protocol) ? undefined : `${rule}, not ${url.protocol}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Appends every refusal the section earns to `issues`, `config.ts`' one list. */
|
|
65
|
+
export function outboundIssues(
|
|
66
|
+
config: { readonly outbound?: OutboundConfig | undefined },
|
|
67
|
+
issues: string[],
|
|
68
|
+
): void {
|
|
69
|
+
const section = config.outbound ?? OUTBOUND_DEFAULTS;
|
|
70
|
+
// `unknown`: an untyped config file reaches this validator with whatever it wrote.
|
|
71
|
+
const proxy: unknown = section.proxy;
|
|
72
|
+
const issue = proxyIssue(proxy);
|
|
73
|
+
if (issue !== undefined) issues.push(issue);
|
|
74
|
+
for (const entry of section.direct as readonly unknown[]) {
|
|
75
|
+
if (typeof entry !== 'string' || !HOST.test(entry)) {
|
|
76
|
+
issues.push(
|
|
77
|
+
`outbound.direct holds ${typeof entry === 'string' ? renderCauseValue(entry) : describeValue(entry)}, not a bare host name (no scheme, path, port or *)`,
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { type MailConfig, type MailSectionInput, mailIssues, mergeMail } from '.
|
|
|
23
23
|
import { type Input, lastSaid, layered } from './config-merge';
|
|
24
24
|
import type { NavigationConfig, NavigationSectionInput } from './config-navigation';
|
|
25
25
|
import { mergeNavigation, navigationIssues } from './config-navigation';
|
|
26
|
+
import * as outboundSection from './config-outbound';
|
|
26
27
|
import type { PwaConfig, PwaOfflineConfig } from './config-pwa';
|
|
27
28
|
import { PWA_FIX, PWA_PUSH_FIX, pwaIssues, pwaPushIssues } from './config-pwa';
|
|
28
29
|
import { removedKeyFix, removedKeyIssue, removedKeysIn } from './config-removed';
|
|
@@ -130,12 +131,8 @@ export interface DatabaseConfig {
|
|
|
130
131
|
* place. It was also the second exported type called `CacheTier` in the tree; the other is
|
|
131
132
|
* `@ultimat3/cache`'s tier INTERFACE, which is the one every implementation names.
|
|
132
133
|
*
|
|
133
|
-
* No `driver` and no `urlEnv` either
|
|
134
|
-
*
|
|
135
|
-
* beside `tiers: ['request-memo', 'lru']` was a second selector that selected nothing — the shape
|
|
136
|
-
* `examples/dummy/app.config.ts` shipped. `urlEnv` was `database.urlEnv` verbatim: the Redis tier
|
|
137
|
-
* reads the literal `REDIS_URL`, so `urlEnv: 'MY_REDIS'` made nothing read `MY_REDIS`. Which rungs
|
|
138
|
-
* exist is `cache.tiers` and only that; a rung the environment cannot supply refuses the boot.
|
|
134
|
+
* No `driver` and no `urlEnv` either (deleted 2026-08-22): selectors that selected nothing. Which
|
|
135
|
+
* rungs exist is `cache.tiers` and only that; a rung the environment cannot supply refuses the boot.
|
|
139
136
|
*/
|
|
140
137
|
export interface CacheConfig {
|
|
141
138
|
/** At least 1: the rungs refuse a lease of no length, so 0 is refused here rather than at boot. */
|
|
@@ -189,12 +186,9 @@ export interface JobsConfig {
|
|
|
189
186
|
}
|
|
190
187
|
|
|
191
188
|
/**
|
|
192
|
-
* No `heartbeatMs`
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
* No `transport` and no `urlEnv` either (deleted in 31.0.0): the bus is the `transport` adapter
|
|
196
|
-
* port — `NATS_URL` set builds NATS, unset builds the in-process bus, and any other `Transport` is
|
|
197
|
-
* `runtime.ts`'s `transport` — so a closed two-member union here could only refuse a third bus.
|
|
189
|
+
* No `heartbeatMs`, `tier`, `transport` or `urlEnv` (deleted 2026-08 and in 31.0.0): read by
|
|
190
|
+
* nothing. The beats are the client's and derived, the tier is what an app DECLARES, and the bus
|
|
191
|
+
* is the `transport` adapter port (`NATS_URL` set builds NATS, else the in-process bus).
|
|
198
192
|
*/
|
|
199
193
|
export interface RealtimeConfig {
|
|
200
194
|
readonly enabled: boolean;
|
|
@@ -240,6 +234,8 @@ export interface AppConfig {
|
|
|
240
234
|
readonly clientErrors: clientErrors.ClientErrorsConfig;
|
|
241
235
|
readonly failureCapture: failureCapture.FailureCaptureConfig;
|
|
242
236
|
readonly time: timeSection.AppTimeConfig;
|
|
237
|
+
/** Optional in the TYPE only (a pre-31.52 literal compiles): `defineConfig` always fills it. */
|
|
238
|
+
readonly outbound?: outboundSection.OutboundConfig | undefined;
|
|
243
239
|
}
|
|
244
240
|
|
|
245
241
|
/**
|
|
@@ -263,6 +259,8 @@ export interface AppConfigInput
|
|
|
263
259
|
failureCapture.FailureCaptureSectionInput,
|
|
264
260
|
timeSection.TimeSectionInput {
|
|
265
261
|
readonly name: string;
|
|
262
|
+
/** A member, not an `extends`: the interface's heading is part of its 31.x public API. */
|
|
263
|
+
readonly outbound?: outboundSection.OutboundSectionInput['outbound'];
|
|
266
264
|
readonly theme?: Input<ThemeConfig> | undefined;
|
|
267
265
|
readonly auth?: Input<AuthConfig> | undefined;
|
|
268
266
|
readonly pwa?: PwaConfigInput | undefined;
|
|
@@ -361,6 +359,7 @@ function validate(config: AppConfig): void {
|
|
|
361
359
|
clientErrors.clientErrorsIssues(config, issues);
|
|
362
360
|
failureCapture.failureCaptureIssues(config, issues);
|
|
363
361
|
timeSection.timeIssues(config, issues);
|
|
362
|
+
outboundSection.outboundIssues(config, issues);
|
|
364
363
|
|
|
365
364
|
if (cacheTierIssues(config.cache.tiers, issues)) tierFix.push(CACHE_TIER_FIX);
|
|
366
365
|
|
|
@@ -451,6 +450,7 @@ function merge(name: string, layers: readonly AppConfigOverlay[]): AppConfig {
|
|
|
451
450
|
...clientErrors.mergeClientErrors(layers),
|
|
452
451
|
...failureCapture.mergeFailureCapture(layers),
|
|
453
452
|
...timeSection.mergeTime(layers),
|
|
453
|
+
...outboundSection.mergeOutbound(layers),
|
|
454
454
|
};
|
|
455
455
|
}
|
|
456
456
|
|
package/src/framework-env.ts
CHANGED
|
@@ -60,6 +60,8 @@ export const FRAMEWORK_ENV: readonly FrameworkEnvName[] = [
|
|
|
60
60
|
// libpq's own TLS mode: stated, it keeps `database.ssl` from adding `sslmode=require`.
|
|
61
61
|
...contract('cli', 'PGSSLMODE'),
|
|
62
62
|
...toggles('cli', 'OTEL_SDK_DISABLED'),
|
|
63
|
+
// The OTel service identity, read once at boot (`serve-boot-telemetry.ts`), before the app name.
|
|
64
|
+
...contract('cli', 'OTEL_SERVICE_NAME', 'OTEL_RESOURCE_ATTRIBUTES'),
|
|
63
65
|
...internal('cli', 'ULTIMATE_SEED_TIER', 'ULTIMATE_STATE_DIR', 'ULTIMATE_BUILD_CAPTURE'),
|
|
64
66
|
...internal('cli', 'ULTIMATE_TASK_RUN'),
|
|
65
67
|
...internal('cli', 'ULTIMATE_DEV_CHILD', 'ULTIMATE_DEV_SUPERVISOR_PID', 'X_ENV'),
|
package/src/index.ts
CHANGED
|
@@ -1004,7 +1004,7 @@ export { ambientClock, noWaitClock } from './sleep-clock';
|
|
|
1004
1004
|
export { endOfLiteral, maskLiterals, QUOTES, stripComments } from './source-mask';
|
|
1005
1005
|
export type { StoreMode } from './store-mode';
|
|
1006
1006
|
export { storeMode, withStoreMode } from './store-mode';
|
|
1007
|
-
export { THEME_STORAGE_KEY } from './theme-storage';
|
|
1007
|
+
export { MOTION_STORAGE_KEY, THEME_STORAGE_KEY } from './theme-storage';
|
|
1008
1008
|
export { timingSafeEqual } from './timing-safe-equal';
|
|
1009
1009
|
export type { ToolDescriptionSource } from './tool-description';
|
|
1010
1010
|
// A projected tool's description: `@ultimat3/mcp`'s and `@ultimat3/ai`'s, one tier apart from neither.
|
package/src/keyed-fingerprint.ts
CHANGED
|
@@ -22,17 +22,46 @@ export const KEYED_FINGERPRINT_VERSION = 'h1';
|
|
|
22
22
|
*/
|
|
23
23
|
export type FingerprintMatch = 'match' | 'mismatch' | 'unverifiable';
|
|
24
24
|
|
|
25
|
+
/** Purposes are few and static; this is a backstop against a caller minting them from input. */
|
|
26
|
+
export const KEYED_FINGERPRINT_KEY_CACHE_MAX = 64;
|
|
27
|
+
|
|
28
|
+
interface DerivedKey {
|
|
29
|
+
readonly key: string;
|
|
30
|
+
readonly id: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Module-private and never exported: the secret it is compared against stays out of anything a log
|
|
34
|
+
// or `x doctor` can serialise. Two hashes per call were the cost of not keeping it (realtime signs
|
|
35
|
+
// one cursor per subscriber per patch). A rotation is noticed by a constant-time compare (a secret), and drops
|
|
36
|
+
// every key derived under the old one — never a stale key.
|
|
37
|
+
let cachedSecret = '';
|
|
38
|
+
const cache = new Map<string, DerivedKey>();
|
|
39
|
+
|
|
25
40
|
/** One key per purpose, derived from the signing secret, so no two uses share a MAC key. */
|
|
26
|
-
function derivedKey(purpose: string):
|
|
27
|
-
|
|
41
|
+
function derivedKey(purpose: string): DerivedKey {
|
|
42
|
+
const secret = currentSigningSecret();
|
|
43
|
+
if (!timingSafeEqual(secret, cachedSecret)) {
|
|
44
|
+
cache.clear();
|
|
45
|
+
cachedSecret = secret;
|
|
46
|
+
}
|
|
47
|
+
const hit = cache.get(purpose);
|
|
48
|
+
if (hit !== undefined) return hit;
|
|
49
|
+
const key = hmac('sha256', secret, `ultimate:keyed-fingerprint:${purpose}`, 'hex');
|
|
50
|
+
// Names the key a fingerprint was made under, so a rotation reads as `unverifiable` rather than
|
|
51
|
+
// as a mismatch. 32 bits of a hash of a 256-bit derived key: a label, useless for recovering it.
|
|
52
|
+
const id = new Bun.CryptoHasher('sha256').update(key).digest('hex').slice(0, 8);
|
|
53
|
+
if (cache.size >= KEYED_FINGERPRINT_KEY_CACHE_MAX) {
|
|
54
|
+
const oldest = cache.keys().next();
|
|
55
|
+
if (!oldest.done) cache.delete(oldest.value);
|
|
56
|
+
}
|
|
57
|
+
const derived = { key, id };
|
|
58
|
+
cache.set(purpose, derived);
|
|
59
|
+
return derived;
|
|
28
60
|
}
|
|
29
61
|
|
|
30
|
-
/**
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
*/
|
|
34
|
-
function keyId(key: string): string {
|
|
35
|
-
return new Bun.CryptoHasher('sha256').update(key).digest('hex').slice(0, 8);
|
|
62
|
+
/** Test seam: how many purposes hold a derived key now. */
|
|
63
|
+
export function keyedFingerprintKeyCacheSize(): number {
|
|
64
|
+
return cache.size;
|
|
36
65
|
}
|
|
37
66
|
|
|
38
67
|
/**
|
|
@@ -41,9 +70,9 @@ function keyId(key: string): string {
|
|
|
41
70
|
* public as `fingerprint()` — production boot refuses that secret (`X_CURSOR_SECRET_DEV`).
|
|
42
71
|
*/
|
|
43
72
|
export function keyedFingerprint(value: unknown, purpose: string): string {
|
|
44
|
-
const key = derivedKey(purpose);
|
|
73
|
+
const { key, id } = derivedKey(purpose);
|
|
45
74
|
const mac = hmac('sha256', key, canonicalJson(value), 'hex').slice(0, 32);
|
|
46
|
-
return `${KEYED_FINGERPRINT_VERSION}:${
|
|
75
|
+
return `${KEYED_FINGERPRINT_VERSION}:${id}:${mac}`;
|
|
47
76
|
}
|
|
48
77
|
|
|
49
78
|
/**
|
package/src/nearest-name.ts
CHANGED
|
@@ -44,6 +44,10 @@ export const nearestName = (input: string, candidates: readonly string[]): strin
|
|
|
44
44
|
let best: string | undefined;
|
|
45
45
|
let bestScore = MAX_EDITS + 1;
|
|
46
46
|
for (const candidate of candidates) {
|
|
47
|
+
// Edits are at least the length gap, so a gap past the cutoff can never answer — and skipping
|
|
48
|
+
// it BEFORE `distance` is what bounds the cost: the input may be a caller's (an unknown input
|
|
49
|
+
// key), and its grid is (input + 1) × (candidate + 1) numbers. A 1M-char key was ~300 MB.
|
|
50
|
+
if (Math.abs(input.length - candidate.length) > cutoff(input, candidate)) continue;
|
|
47
51
|
const score = distance(input, candidate);
|
|
48
52
|
if (score < bestScore && score <= cutoff(input, candidate)) {
|
|
49
53
|
best = candidate;
|
package/src/outbound-attempt.ts
CHANGED
|
@@ -24,6 +24,7 @@ import type { HopCall } from './outbound-hops';
|
|
|
24
24
|
import { redactedLocation, sendHops } from './outbound-hops';
|
|
25
25
|
import type { WatchedFailure } from './outbound-read';
|
|
26
26
|
import { watchedBody } from './outbound-read';
|
|
27
|
+
import { refusalHeadersOf } from './outbound-refusal-headers';
|
|
27
28
|
import type { OutboundRefusalRead } from './outbound-types';
|
|
28
29
|
import { readWithinLimit } from './read-capped';
|
|
29
30
|
import { isRetryableStatus } from './retryable-status';
|
|
@@ -39,6 +40,8 @@ export interface AttemptCall extends HopCall {
|
|
|
39
40
|
readonly read: 'bytes' | 'stream';
|
|
40
41
|
/** How a non-2xx body is read for the error; `undefined` is the default excerpt. */
|
|
41
42
|
readonly refusal: OutboundRefusalRead | undefined;
|
|
43
|
+
/** The `refusal.headers` names, validated and lowercased (`refusalHeaderNames`); none asked: `undefined`. */
|
|
44
|
+
readonly refusalHeaders: readonly string[] | undefined;
|
|
42
45
|
readonly now: () => number;
|
|
43
46
|
readonly timer: DeadlineTimer;
|
|
44
47
|
}
|
|
@@ -155,6 +158,8 @@ async function refusalOf(
|
|
|
155
158
|
): Promise<unknown> {
|
|
156
159
|
const { site, url } = call;
|
|
157
160
|
const { status, headers } = response;
|
|
161
|
+
const kept =
|
|
162
|
+
call.refusalHeaders === undefined ? undefined : refusalHeadersOf(call.refusalHeaders, headers);
|
|
158
163
|
if (status >= 300 && status < 400) {
|
|
159
164
|
await body.cancel().catch(() => undefined);
|
|
160
165
|
const location = headers.get('location');
|
|
@@ -165,11 +170,11 @@ async function refusalOf(
|
|
|
165
170
|
const after = retryAfterSecondsOf(headers.get('retry-after'), headers.get('date'));
|
|
166
171
|
const { detail, fields } = await refusalBodyOf(body, call.refusal, call.maxBytes);
|
|
167
172
|
return after === undefined
|
|
168
|
-
? outboundUnavailable(site, status, detail, fields)
|
|
169
|
-
: outboundThrottled(site, status, after, detail, fields);
|
|
173
|
+
? outboundUnavailable(site, status, detail, fields, kept)
|
|
174
|
+
: outboundThrottled(site, status, after, detail, fields, kept);
|
|
170
175
|
}
|
|
171
176
|
const { detail, fields } = await refusalBodyOf(body, call.refusal, call.maxBytes);
|
|
172
|
-
return outboundRefused(site, status, detail, fields);
|
|
177
|
+
return outboundRefused(site, status, detail, fields, kept);
|
|
173
178
|
}
|
|
174
179
|
|
|
175
180
|
export async function runAttempt(call: AttemptCall, attempt: number): Promise<AttemptAnswer> {
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Single responsibility: the app-wide egress proxy — `outbound.proxy` in `app.config.ts`, set once
|
|
2
|
+
// by the boot — as the resolver every `outbound()` call with no `proxy` of its own is handed.
|
|
3
|
+
// Loopback and the app's `direct` hosts never take it: an in-cluster collector or sidecar is not
|
|
4
|
+
// egress. A raw transport asks `ambientProxyFor`. Which proxy stays the app's; this carries it.
|
|
5
|
+
|
|
6
|
+
import { classifyAddress } from './address-class';
|
|
7
|
+
import { logger } from './logger';
|
|
8
|
+
import type { OutboundProxy } from './outbound-types';
|
|
9
|
+
|
|
10
|
+
/** The `outbound` block of `AppConfig`, as the boot hands it over. */
|
|
11
|
+
export interface OutboundProxyConfig {
|
|
12
|
+
readonly proxy?: string | undefined;
|
|
13
|
+
readonly direct?: readonly string[] | undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The installed resolver, or `undefined`: no ambient proxy, every call dials as it says. */
|
|
17
|
+
let ambient: ((target: URL) => string | undefined) | undefined;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `true` for a host that is never sent through the ambient proxy: `localhost`, `*.localhost`, a
|
|
21
|
+
* loopback literal, and each `direct` entry with every name under it (`cluster.local` covers
|
|
22
|
+
* `a.svc.cluster.local`, never `notcluster.local`) — the NO_PROXY reading, per label.
|
|
23
|
+
*/
|
|
24
|
+
export function isDirectHost(hostname: string, direct: readonly string[]): boolean {
|
|
25
|
+
const host = hostname.toLowerCase();
|
|
26
|
+
if (host === 'localhost' || host.endsWith('.localhost')) return true;
|
|
27
|
+
if (classifyAddress(host) === 'loopback') return true;
|
|
28
|
+
return direct.some((entry) => {
|
|
29
|
+
const name = entry.toLowerCase();
|
|
30
|
+
return host === name || host.endsWith(`.${name}`);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The proxy URL as a log line or a report may show it: the userinfo replaced, never printed. Not a
|
|
36
|
+
* URL at all is said as such — the raw text could be a credential with a typo in it.
|
|
37
|
+
*/
|
|
38
|
+
export function redactedProxyUrl(proxy: string): string {
|
|
39
|
+
let url: URL;
|
|
40
|
+
try {
|
|
41
|
+
url = new URL(proxy);
|
|
42
|
+
} catch {
|
|
43
|
+
return '(not a URL)';
|
|
44
|
+
}
|
|
45
|
+
const userinfo = url.username !== '' || url.password !== '' ? '***@' : '';
|
|
46
|
+
return `${url.protocol}//${userinfo}${url.host}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Hosts warned about, per installation: bounded, so a crawl of plain-http hosts is not a leak. */
|
|
50
|
+
const MAX_CLEARTEXT_WARNED = 256;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A plain-`http:` target sent through the proxy crosses it in CLEARTEXT — a bearer token or a SigV4
|
|
54
|
+
* signature included — which is what an in-cluster gateway or MinIO left out of `outbound.direct`
|
|
55
|
+
* does. The routing stays as declared (it may be meant); the first use per host says so, once.
|
|
56
|
+
* Host and port only: the path may carry a token, the proxy URL a credential.
|
|
57
|
+
*/
|
|
58
|
+
function cleartextWarner(): (target: URL) => void {
|
|
59
|
+
const warned = new Set<string>();
|
|
60
|
+
return (target) => {
|
|
61
|
+
if (target.protocol !== 'http:' || warned.has(target.host)) return;
|
|
62
|
+
if (warned.size >= MAX_CLEARTEXT_WARNED) return;
|
|
63
|
+
warned.add(target.host);
|
|
64
|
+
logger.warn('ultimate outbound proxy cleartext', {
|
|
65
|
+
host: target.host,
|
|
66
|
+
cause: `http://${target.host} is sent through outbound.proxy in cleartext: the proxy reads every header, credentials included`,
|
|
67
|
+
fix: `defineConfig({ outbound: { direct: ['${target.hostname}'] } }) // app.config.ts, when the host is reachable without the proxy; else serve it over https:`,
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Installs the ambient proxy and answers its release, which restores what was there. The boot's
|
|
74
|
+
* call alone (`serve-boot.ts`): an app declares `outbound` in `app.config.ts` and never calls this.
|
|
75
|
+
* The URL is checked per hop by `proxyFor`, so a `socks5:` here is still `X_OUTBOUND_PROXY_INVALID`.
|
|
76
|
+
*/
|
|
77
|
+
export function configureOutboundProxy(config: OutboundProxyConfig | undefined): () => void {
|
|
78
|
+
const before = ambient;
|
|
79
|
+
const proxy = config?.proxy;
|
|
80
|
+
const direct = [...(config?.direct ?? [])];
|
|
81
|
+
const warn = cleartextWarner();
|
|
82
|
+
ambient =
|
|
83
|
+
proxy === undefined || proxy === ''
|
|
84
|
+
? undefined
|
|
85
|
+
: (target: URL) => {
|
|
86
|
+
if (isDirectHost(target.hostname, direct)) return undefined;
|
|
87
|
+
warn(target);
|
|
88
|
+
return proxy;
|
|
89
|
+
};
|
|
90
|
+
if (ambient !== undefined && proxy !== undefined) {
|
|
91
|
+
logger.info('ultimate outbound proxy', { proxy: redactedProxyUrl(proxy), direct });
|
|
92
|
+
}
|
|
93
|
+
return () => {
|
|
94
|
+
ambient = before;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What a call that names no proxy of its own goes through: `outbound.ts`'s `prepare()`. */
|
|
99
|
+
export function ambientOutboundProxy(): OutboundProxy | undefined {
|
|
100
|
+
return ambient;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The same answer for a transport that cannot be `outbound()` — the AI providers' streams,
|
|
105
|
+
* storage's signed S3 calls — handed to Bun's `fetch` as `init.proxy`. `undefined`: no proxy
|
|
106
|
+
* installed, loopback, a `direct` host, or not a URL (that call's own error, not this reader's).
|
|
107
|
+
*/
|
|
108
|
+
export function ambientProxyFor(target: string | URL): string | undefined {
|
|
109
|
+
if (ambient === undefined) return undefined;
|
|
110
|
+
if (target instanceof URL) return ambient(target);
|
|
111
|
+
return URL.canParse(target) ? ambient(new URL(target)) : undefined;
|
|
112
|
+
}
|
package/src/outbound-errors.ts
CHANGED
|
@@ -122,18 +122,32 @@ export function outboundUnreachable(site: OutboundSite, error: unknown): Ultimat
|
|
|
122
122
|
const fieldsMeta = (fields: unknown): { readonly fields?: unknown } =>
|
|
123
123
|
fields === undefined ? {} : { fields };
|
|
124
124
|
|
|
125
|
+
/** `meta.headers` only when the caller's `refusal.headers` asked: absent, never `undefined`. */
|
|
126
|
+
const headersMeta = (
|
|
127
|
+
headers: Readonly<Record<string, string>> | undefined,
|
|
128
|
+
): { readonly headers?: Readonly<Record<string, string>> } =>
|
|
129
|
+
headers === undefined ? {} : { headers };
|
|
130
|
+
|
|
125
131
|
export function outboundThrottled(
|
|
126
132
|
site: OutboundSite,
|
|
127
133
|
status: number,
|
|
128
134
|
retryAfterSeconds: number,
|
|
129
135
|
detail = '',
|
|
130
136
|
fields?: unknown,
|
|
137
|
+
headers?: Readonly<Record<string, string>>,
|
|
131
138
|
): UltimateError {
|
|
132
139
|
return new UltimateError({
|
|
133
140
|
code: 'X_OUTBOUND_THROTTLED',
|
|
134
141
|
cause: `${siteLabel(site)} answered ${String(status)} and asked to wait ${String(retryAfterSeconds)} s`,
|
|
135
142
|
fix: `await Bun.sleep(${String(retryAfterSeconds * 1000)}) # then call ${site.vendor} again, or lower the call rate at the site that calls outbound()`,
|
|
136
|
-
meta: {
|
|
143
|
+
meta: {
|
|
144
|
+
...siteMeta(site),
|
|
145
|
+
status,
|
|
146
|
+
retryAfterSeconds,
|
|
147
|
+
detail,
|
|
148
|
+
...fieldsMeta(fields),
|
|
149
|
+
...headersMeta(headers),
|
|
150
|
+
},
|
|
137
151
|
});
|
|
138
152
|
}
|
|
139
153
|
|
|
@@ -142,12 +156,13 @@ export function outboundUnavailable(
|
|
|
142
156
|
status: number,
|
|
143
157
|
detail = '',
|
|
144
158
|
fields?: unknown,
|
|
159
|
+
headers?: Readonly<Record<string, string>>,
|
|
145
160
|
): UltimateError {
|
|
146
161
|
return new UltimateError({
|
|
147
162
|
code: 'X_OUTBOUND_UNAVAILABLE',
|
|
148
163
|
cause: `${siteLabel(site)} answered ${String(status)} on every attempt: the vendor's fault, not the request's`,
|
|
149
164
|
fix: `curl -sS -m 5 -o /dev/null -w '%{http_code}\\n' ${renderFixShellArg(site.origin, '<vendor origin>')} # the vendor's fault: re-run the call; if ${String(status)} persists, check ${site.vendor}'s status page`,
|
|
150
|
-
meta: { ...siteMeta(site), status, detail, ...fieldsMeta(fields) },
|
|
165
|
+
meta: { ...siteMeta(site), status, detail, ...fieldsMeta(fields), ...headersMeta(headers) },
|
|
151
166
|
});
|
|
152
167
|
}
|
|
153
168
|
|
|
@@ -156,6 +171,7 @@ export function outboundRefused(
|
|
|
156
171
|
status: number,
|
|
157
172
|
detail: string,
|
|
158
173
|
fields?: unknown,
|
|
174
|
+
headers?: Readonly<Record<string, string>>,
|
|
159
175
|
): UltimateError {
|
|
160
176
|
return new UltimateError({
|
|
161
177
|
code: 'X_OUTBOUND_REFUSED',
|
|
@@ -164,7 +180,7 @@ export function outboundRefused(
|
|
|
164
180
|
status === 401
|
|
165
181
|
? `outbound({ url, vendor: '${site.vendor}', headers: { authorization } }) # with a refreshed credential, then call again`
|
|
166
182
|
: `outbound({ url, vendor: '${site.vendor}', body }) # with the request fixed from meta.detail and meta.status`,
|
|
167
|
-
meta: { ...siteMeta(site), status, detail, ...fieldsMeta(fields) },
|
|
183
|
+
meta: { ...siteMeta(site), status, detail, ...fieldsMeta(fields), ...headersMeta(headers) },
|
|
168
184
|
});
|
|
169
185
|
}
|
|
170
186
|
|
|
@@ -216,7 +232,7 @@ export function outboundRetryUnsafe(site: OutboundSite): UltimateError {
|
|
|
216
232
|
return new UltimateError({
|
|
217
233
|
code: 'X_OUTBOUND_RETRY_UNSAFE',
|
|
218
234
|
cause: `${siteLabel(site)} was given a retry policy, and a ${site.method} replayed is a second write`,
|
|
219
|
-
fix: `
|
|
235
|
+
fix: `grep -rn "retry:" . # in that outbound() call, remove retry from the ${site.method}'s options and keep every other option (headers, body, deadlineMs); idempotent: true only if the vendor dedupes the write`,
|
|
220
236
|
meta: siteMeta(site),
|
|
221
237
|
});
|
|
222
238
|
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Single responsibility: the response headers a caller asks `outbound()` to keep on a refusal
|
|
2
|
+
// (`refusal: { headers }`), checked once at the call and read off the answer as `meta.headers`.
|
|
3
|
+
// A refusal never keeps a credential-named header, and no value is kept whole.
|
|
4
|
+
|
|
5
|
+
import { UltimateError } from './errors';
|
|
6
|
+
import { isRedactedKey } from './logger';
|
|
7
|
+
import type { OutboundSite } from './outbound-errors';
|
|
8
|
+
import { siteLabel } from './outbound-errors';
|
|
9
|
+
import { redactedValue } from './redact-values';
|
|
10
|
+
|
|
11
|
+
/** The most names one call may ask for: a request id and a few more, never the whole answer. */
|
|
12
|
+
export const REFUSAL_HEADERS_MAX = 16;
|
|
13
|
+
/** The longest header name, and how much of a value is kept. */
|
|
14
|
+
const NAME_CHARS = 64;
|
|
15
|
+
export const REFUSAL_HEADER_VALUE_CHARS = 200;
|
|
16
|
+
|
|
17
|
+
/** An RFC 9110 field name: a token. */
|
|
18
|
+
const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Credential carriers `isRedactedKey` does not name: a challenge repeats a realm and a nonce, and
|
|
22
|
+
* the second cookie header is a cookie all the same.
|
|
23
|
+
*/
|
|
24
|
+
const NEVER = new Set(['www-authenticate', 'proxy-authenticate', 'set-cookie2']);
|
|
25
|
+
|
|
26
|
+
const invalid = (site: OutboundSite, why: string, fix: string): never => {
|
|
27
|
+
throw new UltimateError({
|
|
28
|
+
code: 'X_INVARIANT',
|
|
29
|
+
cause: `${siteLabel(site)} was given refusal.headers that ${why}`,
|
|
30
|
+
fix,
|
|
31
|
+
meta: { vendor: site.vendor },
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The names to keep, lowercased and deduplicated. `undefined` when the call asked for none.
|
|
37
|
+
* Refused at the call, before a byte is sent: a request id that was never captured cannot be
|
|
38
|
+
* asked for again after the vendor's error.
|
|
39
|
+
*/
|
|
40
|
+
export function refusalHeaderNames(
|
|
41
|
+
names: unknown,
|
|
42
|
+
site: OutboundSite,
|
|
43
|
+
): readonly string[] | undefined {
|
|
44
|
+
if (names === undefined) return undefined;
|
|
45
|
+
if (!Array.isArray(names))
|
|
46
|
+
return invalid(
|
|
47
|
+
site,
|
|
48
|
+
`is not an array of header names (${typeof names})`,
|
|
49
|
+
"refusal: { headers: ['x-request-id'] }",
|
|
50
|
+
);
|
|
51
|
+
if (names.length > REFUSAL_HEADERS_MAX)
|
|
52
|
+
return invalid(
|
|
53
|
+
site,
|
|
54
|
+
`names ${String(names.length)} headers, more than the ${String(REFUSAL_HEADERS_MAX)} a refusal keeps`,
|
|
55
|
+
"refusal: { headers: ['x-request-id'] }",
|
|
56
|
+
);
|
|
57
|
+
const kept = new Set<string>();
|
|
58
|
+
for (const name of names as readonly unknown[]) {
|
|
59
|
+
if (typeof name !== 'string' || !TOKEN.test(name))
|
|
60
|
+
return invalid(
|
|
61
|
+
site,
|
|
62
|
+
'holds an entry that is not a header name',
|
|
63
|
+
"refusal: { headers: ['x-request-id'] }",
|
|
64
|
+
);
|
|
65
|
+
if (name.length > NAME_CHARS)
|
|
66
|
+
return invalid(
|
|
67
|
+
site,
|
|
68
|
+
`holds a header name longer than ${String(NAME_CHARS)} characters`,
|
|
69
|
+
"refusal: { headers: ['x-request-id'] }",
|
|
70
|
+
);
|
|
71
|
+
const lower = name.toLowerCase();
|
|
72
|
+
if (isRedactedKey(lower) || NEVER.has(lower))
|
|
73
|
+
return invalid(
|
|
74
|
+
site,
|
|
75
|
+
`asks for '${lower}', a credential-carrying header, and a refusal never keeps one`,
|
|
76
|
+
"refusal: { headers: ['x-request-id'] }",
|
|
77
|
+
);
|
|
78
|
+
kept.add(lower);
|
|
79
|
+
}
|
|
80
|
+
return [...kept];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The asked-for headers the answer carries, lowercased by name, each value redacted and capped. */
|
|
84
|
+
export function refusalHeadersOf(
|
|
85
|
+
names: readonly string[],
|
|
86
|
+
received: Headers,
|
|
87
|
+
): Record<string, string> {
|
|
88
|
+
const entries: [string, string][] = [];
|
|
89
|
+
for (const name of names) {
|
|
90
|
+
const value = received.get(name);
|
|
91
|
+
if (value !== null)
|
|
92
|
+
entries.push([name, redactedValue(value).slice(0, REFUSAL_HEADER_VALUE_CHARS)]);
|
|
93
|
+
}
|
|
94
|
+
return Object.fromEntries(entries);
|
|
95
|
+
}
|
package/src/outbound-subpath.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
// Single responsibility: the `@ultimat3/core/outbound` entry — the outbound call, the dial screen
|
|
2
|
-
//
|
|
3
|
-
// bundle graph and this reads `Bun.dns` (axiom 6).
|
|
1
|
+
// Single responsibility: the `@ultimat3/core/outbound` entry — the outbound call, the dial screen,
|
|
2
|
+
// the undoable deadline signal and the boot's app-wide proxy installer, and nothing else. A
|
|
3
|
+
// subpath, never the barrel: core is in every bundle graph and this reads `Bun.dns` (axiom 6).
|
|
4
|
+
// `outbound-subpath.test.ts` pins the split.
|
|
4
5
|
|
|
5
6
|
export type { DeadlineSignal, DeadlineTimer } from './deadline-signal';
|
|
6
7
|
export { deadlineSignal, platformDeadlineTimer } from './deadline-signal';
|
|
7
8
|
export { outbound, outboundResponse } from './outbound';
|
|
9
|
+
export type { OutboundProxyConfig } from './outbound-default-proxy';
|
|
10
|
+
export { ambientProxyFor, configureOutboundProxy } from './outbound-default-proxy';
|
|
8
11
|
export type { DialPin, DialResolve, DialVerdict, ScreenDialOptions } from './outbound-dial';
|
|
9
12
|
export { publicUrlRefusal, resolveDialHost, screenDial } from './outbound-dial';
|
|
10
13
|
export type { OutboundSite, OutboundTimeoutPhase } from './outbound-errors';
|
package/src/outbound-types.ts
CHANGED
|
@@ -76,6 +76,15 @@ export interface OutboundRefusalRead {
|
|
|
76
76
|
* filter `meta.fields`: a schema declares only fields that are safe to log.
|
|
77
77
|
*/
|
|
78
78
|
readonly detail?: boolean | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Response header names (case-insensitive) kept on the error: the ones the answer carries go to
|
|
81
|
+
* `meta.headers`, a record of lowercased name to value, each value redacted and cut at 200
|
|
82
|
+
* characters. Unset: no header is kept. For the vendor's request id, to quote in a support
|
|
83
|
+
* ticket. At most 16 names, each at most 64 characters; a credential-named one (`set-cookie`,
|
|
84
|
+
* `authorization`, `www-authenticate`, `x-api-key` …), an overlong name or a name that is not a
|
|
85
|
+
* header is `X_INVARIANT` at the call, before a byte is sent.
|
|
86
|
+
*/
|
|
87
|
+
readonly headers?: readonly string[] | undefined;
|
|
79
88
|
}
|
|
80
89
|
|
|
81
90
|
export interface OutboundRequest {
|
|
@@ -121,6 +130,10 @@ export interface OutboundRequest {
|
|
|
121
130
|
* Send each hop through an HTTP proxy (`CONNECT` for `https:`). Under `dial: 'public'` the screen
|
|
122
131
|
* still runs first and the tunnel is opened to the approved ADDRESS, the certificate still proven
|
|
123
132
|
* against the name; the proxy itself is the app's own choice, like a `'named'` host.
|
|
133
|
+
*
|
|
134
|
+
* Unset: the app-wide proxy, `outbound.proxy` in `app.config.ts`, when one is declared (never
|
|
135
|
+
* for loopback or an `outbound.direct` host). A resolver answering `undefined` — `proxy: () =>
|
|
136
|
+
* undefined` — dials this call direct regardless: the one spelling, so the field's type is 31.x's.
|
|
124
137
|
*/
|
|
125
138
|
readonly proxy?: OutboundProxy | undefined;
|
|
126
139
|
}
|
package/src/outbound.ts
CHANGED
|
@@ -15,10 +15,12 @@ import { isUltimateError } from './errors';
|
|
|
15
15
|
import { finiteCount } from './finite-option';
|
|
16
16
|
import type { AttemptAnswer, AttemptCall } from './outbound-attempt';
|
|
17
17
|
import { runAttempt } from './outbound-attempt';
|
|
18
|
+
import { ambientOutboundProxy } from './outbound-default-proxy';
|
|
18
19
|
import type { OutboundSite } from './outbound-errors';
|
|
19
20
|
import { isCallerBound, outboundBodyInvalid, outboundRetryUnsafe } from './outbound-errors';
|
|
20
21
|
import { redactedPath } from './outbound-hops';
|
|
21
22
|
import { instrumentedCall } from './outbound-instrument';
|
|
23
|
+
import { refusalHeaderNames } from './outbound-refusal-headers';
|
|
22
24
|
import type {
|
|
23
25
|
OutboundAnswer,
|
|
24
26
|
OutboundDeps,
|
|
@@ -86,13 +88,16 @@ function prepare(request: OutboundRequest, deps: OutboundDeps): AttemptCall {
|
|
|
86
88
|
local: isLocal({ env: deps.env, fallback: 'production' }),
|
|
87
89
|
fetch: send,
|
|
88
90
|
resolve: deps.resolve,
|
|
89
|
-
proxy
|
|
91
|
+
// Unsaid is the app-wide proxy (`outbound.proxy`, installed by the boot); a resolver
|
|
92
|
+
// answering `undefined` is direct.
|
|
93
|
+
proxy: request.proxy === undefined ? ambientOutboundProxy() : request.proxy,
|
|
90
94
|
endsAt: now() + deadlineMs,
|
|
91
95
|
deadlineMs,
|
|
92
96
|
idleMs: finiteCount('outbound()', 'idleMs', request.idleMs ?? OUTBOUND_IDLE_MS, 1),
|
|
93
97
|
maxBytes: finiteCount('outbound()', 'maxBytes', request.maxBytes ?? OUTBOUND_MAX_BYTES),
|
|
94
98
|
read: request.read ?? 'bytes',
|
|
95
99
|
refusal: request.refusal,
|
|
100
|
+
refusalHeaders: refusalHeaderNames(request.refusal?.headers, site),
|
|
96
101
|
signal: request.signal,
|
|
97
102
|
now,
|
|
98
103
|
timer: deps.timer ?? platformDeadlineTimer,
|
package/src/page.ts
CHANGED
|
@@ -93,7 +93,7 @@ export { fillTemplate, templateParams } from './route-path-template';
|
|
|
93
93
|
export { onSessionLost, sessionIsLost } from './session-lost';
|
|
94
94
|
export { isSessionRefusalCode } from './session-refusal';
|
|
95
95
|
// The key the theme boot script reads and the toggle island writes.
|
|
96
|
-
export { THEME_STORAGE_KEY } from './theme-storage';
|
|
96
|
+
export { MOTION_STORAGE_KEY, THEME_STORAGE_KEY } from './theme-storage';
|
|
97
97
|
export { trimTrailingSlashes } from './trailing-slashes';
|
|
98
98
|
// A poll a hidden tab and a lost session stop: here, so an island polling reaches no realtime.
|
|
99
99
|
export type { VisibleIntervalOptions } from './visible-interval';
|
package/src/telemetry.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// app with none pays nothing — and trace context is serialised explicitly (`traceparent`) so a
|
|
4
4
|
// trace survives HTTP -> job -> live query.
|
|
5
5
|
|
|
6
|
+
import { DEFAULT_APP_VERSION } from './app-version';
|
|
6
7
|
import { asyncContext } from './async-context';
|
|
7
8
|
import { type Clock, systemClock } from './clock';
|
|
8
9
|
import { tryUseContext } from './context';
|
|
@@ -145,9 +146,30 @@ const activeSpan = asyncContext<Span>('the active span');
|
|
|
145
146
|
let clock: Clock = systemClock;
|
|
146
147
|
let enabled = true;
|
|
147
148
|
let sampler: Sampler | undefined;
|
|
148
|
-
|
|
149
|
+
/**
|
|
150
|
+
* Unconfigured: OTel's own `unknown_service`, and the build `APP_VERSION` calls an unnamed one. It
|
|
151
|
+
* was `ultimate`/`0.0.1`, which made every app in one collector the same service at one version
|
|
152
|
+
* (#1361). The boot names it (`serve-boot-telemetry.ts`); core never reads the env for it.
|
|
153
|
+
*/
|
|
154
|
+
const UNNAMED: SpanResource = Object.freeze({
|
|
155
|
+
serviceName: 'unknown_service',
|
|
156
|
+
serviceVersion: DEFAULT_APP_VERSION,
|
|
157
|
+
});
|
|
158
|
+
let resource: SpanResource = UNNAMED;
|
|
149
159
|
|
|
160
|
+
/** Sets each option given, for the process. The boot's form, with a release: `installTelemetry`. */
|
|
150
161
|
export function configureTelemetry(options: TelemetryOptions): void {
|
|
162
|
+
installTelemetry(options);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* `configureTelemetry` returning its release: it puts back what THIS call replaced and nothing
|
|
167
|
+
* else, so a boot's stop hands the process the identity it found. On `./adapter` beside
|
|
168
|
+
* `installBuildId` — the boot is its caller — because a barrel `configureTelemetry` that answered
|
|
169
|
+
* a function would refuse `(): void => configureTelemetry(…)`, which compiled against 31.51.0.
|
|
170
|
+
*/
|
|
171
|
+
export function installTelemetry(options: TelemetryOptions): () => void {
|
|
172
|
+
const before = { clock, enabled, sampler, resource };
|
|
151
173
|
if (options.clock !== undefined) clock = options.clock;
|
|
152
174
|
if (options.enabled !== undefined) enabled = options.enabled;
|
|
153
175
|
if (options.sampler !== undefined) sampler = options.sampler;
|
|
@@ -157,12 +179,21 @@ export function configureTelemetry(options: TelemetryOptions): void {
|
|
|
157
179
|
serviceVersion: options.serviceVersion ?? resource.serviceVersion,
|
|
158
180
|
});
|
|
159
181
|
}
|
|
182
|
+
return () => {
|
|
183
|
+
if (options.clock !== undefined) clock = before.clock;
|
|
184
|
+
if (options.enabled !== undefined) enabled = before.enabled;
|
|
185
|
+
if (options.sampler !== undefined) sampler = before.sampler;
|
|
186
|
+
if (options.serviceName !== undefined || options.serviceVersion !== undefined) {
|
|
187
|
+
resource = before.resource;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
160
190
|
}
|
|
161
191
|
|
|
162
192
|
export function resetTelemetry(): void {
|
|
163
193
|
clock = systemClock;
|
|
164
194
|
enabled = true;
|
|
165
195
|
sampler = undefined;
|
|
196
|
+
resource = UNNAMED;
|
|
166
197
|
resetDefaultSampler();
|
|
167
198
|
}
|
|
168
199
|
|
package/src/theme-storage.ts
CHANGED
|
@@ -10,3 +10,10 @@
|
|
|
10
10
|
* wrote another, and a visitor's choice never survived a reload.
|
|
11
11
|
*/
|
|
12
12
|
export const THEME_STORAGE_KEY = 'ultimate.theme';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The `localStorage` key the reader's motion pause lives under (WCAG 2.2.2), for the same reason:
|
|
16
|
+
* `@ultimat3/ui`'s `MotionToggle` writes `"paused"` there, and `@ultimat3/render`'s inlined boot
|
|
17
|
+
* script reads it and stamps `html[data-motion="paused"]` before first paint.
|
|
18
|
+
*/
|
|
19
|
+
export const MOTION_STORAGE_KEY = 'ultimate.motion';
|
package/src/type-pins.ts
CHANGED
|
@@ -20,7 +20,9 @@ import type { Page } from './cursor-page';
|
|
|
20
20
|
import type { ErrorReporter, ErrorReportingOptions } from './error-reporter';
|
|
21
21
|
import type { SentryReporterHooks, SentryReporterOptions } from './error-reporter-sentry-hooks';
|
|
22
22
|
import { mapBounded } from './map-bounded';
|
|
23
|
+
import type { OutboundRequest } from './outbound-types';
|
|
23
24
|
import type { HydrateStrategy, OfflineStrategy, RenderMode, Surface } from './route-vocabulary';
|
|
25
|
+
import type { configureTelemetry, installTelemetry } from './telemetry';
|
|
24
26
|
|
|
25
27
|
/** Fails to compile when `T` is anything but `true`. The whole mechanism. */
|
|
26
28
|
type Assert<T extends true> = T;
|
|
@@ -298,3 +300,18 @@ type _SettleAllAnswersOutcomes = Assert<
|
|
|
298
300
|
Exact<Awaited<ReturnType<typeof settleAll>>, PromiseSettledResult<number>[]>
|
|
299
301
|
>;
|
|
300
302
|
type _DefaultAnswersValues = Assert<Exact<Awaited<ReturnType<typeof settleFirst>>, number[]>>;
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Three surfaces held at their 31.51.0 shape while the outbound proxy and the boot's telemetry
|
|
306
|
+
* release landed beside them: `(): void => configureTelemetry(…)` compiled (the release is
|
|
307
|
+
* `installTelemetry`, `./adapter`), an `AppConfig` literal had no `outbound`, and a reader of
|
|
308
|
+
* `OutboundRequest['proxy']` never met `null`.
|
|
309
|
+
*/
|
|
310
|
+
type _ConfigureTelemetryAnswersNothing = Assert<Exact<ReturnType<typeof configureTelemetry>, void>>;
|
|
311
|
+
type _InstallTelemetryAnswersItsRelease = Assert<
|
|
312
|
+
Exact<ReturnType<typeof installTelemetry>, () => void>
|
|
313
|
+
>;
|
|
314
|
+
type _AppConfigWithoutOutboundIsAnAppConfig = Assert<
|
|
315
|
+
Omit<AppConfig, 'outbound'> extends AppConfig ? true : false
|
|
316
|
+
>;
|
|
317
|
+
type _OutboundProxyIsNeverNull = Assert<null extends OutboundRequest['proxy'] ? false : true>;
|