dsh-taskbridge 1.7.0 → 1.8.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 (75) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -21
  3. package/README.md +150 -289
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +31 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +170 -627
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +119 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +13 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/plugin-market.md +30 -30
  17. package/docs/redaction-contract.md +170 -170
  18. package/docs/releases/1.7.0.zh.md +11 -11
  19. package/docs/releases/1.8.0.zh.md +16 -0
  20. package/docs/runtime-compatibility.md +1 -1
  21. package/docs/taskbridge-upgrade.md +28 -28
  22. package/docs/taskdispatch-upgrade.md +25 -25
  23. package/docs/workspace-contract.md +538 -538
  24. package/docs/workspace-grouping.md +126 -126
  25. package/icon.svg +1 -1
  26. package/lib/client.d.ts +733 -699
  27. package/lib/client.js +7 -7
  28. package/locale/en.json +1 -1
  29. package/locale/zh.json +1 -1
  30. package/package.json +149 -144
  31. package/src/antigravity/installer.js +1046 -0
  32. package/src/antigravity/seam.js +142 -0
  33. package/src/auth/fence.js +361 -361
  34. package/src/auth/grants.js +789 -789
  35. package/src/client/api.js +143 -0
  36. package/src/client/index.jsx +113 -3
  37. package/src/client/sidebar.jsx +862 -862
  38. package/src/client/styles.js +624 -624
  39. package/src/client/task-cleanup.js +304 -304
  40. package/src/client/task-records-table.jsx +217 -217
  41. package/src/client/task-view.js +307 -307
  42. package/src/client/workspace-groups.js +482 -482
  43. package/src/client/workspaces-browser.jsx +770 -770
  44. package/src/codex/agent-ownership.js +270 -270
  45. package/src/codex/installer.js +6 -0
  46. package/src/codex/toml.js +784 -784
  47. package/src/config/redact.js +245 -245
  48. package/src/config/store.js +186 -186
  49. package/src/credentials/seam.js +202 -202
  50. package/src/http/respond.js +6 -5
  51. package/src/http/user-plane.js +72 -0
  52. package/src/index.js +25 -0
  53. package/src/jobs/diagnostics.js +15 -15
  54. package/src/jobs/plan-store.js +1020 -1020
  55. package/src/jobs/review-note.js +63 -63
  56. package/src/jobs/task-descriptions.js +82 -82
  57. package/src/jobs/task-display.js +73 -73
  58. package/src/jobs/task-tree.js +786 -786
  59. package/src/jobs/title.js +134 -134
  60. package/src/mcp/continuation.js +317 -317
  61. package/src/mcp/server.js +12 -5
  62. package/src/model/connectivity.js +371 -371
  63. package/src/model/discovery.js +582 -582
  64. package/src/model/native-catalog.js +68 -68
  65. package/src/model/openai-adapter.js +671 -671
  66. package/src/model/probe.js +264 -264
  67. package/src/model/providers.js +756 -756
  68. package/src/model/routing.js +321 -321
  69. package/src/runtime/permissions.js +1619 -1619
  70. package/src/runtime/question-call.js +162 -162
  71. package/src/runtime/questions.js +909 -909
  72. package/src/runtime/worker-prompt.js +60 -53
  73. package/src/workspace/audit.js +775 -775
  74. package/src/workspace/preflight.js +424 -424
  75. package/src/workspace/worktrees.js +679 -679
package/src/auth/fence.js CHANGED
@@ -1,361 +1,361 @@
1
- // Transport-level trust primitives.
2
- //
3
- // This module holds only pure predicates. It decides whether a request is even
4
- // allowed to reach a handler; it never decides that a caller is authorized to
5
- // dispatch work. Authorization is a separate, server-side grant (see
6
- // src/auth/grants.js) — an Origin string or a client-supplied boolean is not
7
- // evidence of anything and is never consulted for a decision.
8
-
9
- import { createHash, timingSafeEqual } from 'node:crypto';
10
- import { isIPv4, isIPv6 } from 'node:net';
11
-
12
- /**
13
- * One dotted-quad IPv4 loopback literal. Each octet is range-checked, so
14
- * `127.300.0.1` and `127.0.0.256` are not accepted as loopback merely because
15
- * they start with `127`.
16
- */
17
- const IPV4_OCTET = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
18
- const IPV4_LOOPBACK = new RegExp(`^127(?:\\.${IPV4_OCTET}){3}$`);
19
-
20
- /**
21
- * One strict dotted-quad IPv4 literal: exactly four decimal octets, no leading
22
- * zeroes, each 0-255. `127.1`, `2130706433`, `0177.0.0.1` and `0x7f.0.0.1` all
23
- * fail this, so none of them can be smuggled in and silently normalised by the
24
- * URL parser into `127.0.0.1`.
25
- */
26
- const IPV4_STRICT = new RegExp(`^(?:${IPV4_OCTET})(?:\\.(?:${IPV4_OCTET})){3}$`);
27
-
28
- /** One DNS-style label: alphanumeric ends, hyphens inside. */
29
- const HOST_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
30
-
31
- /** A label the URL parser would read as a hexadecimal IPv4 component. */
32
- const HEX_LABEL = /^0x[0-9a-f]*$/i;
33
-
34
- /** A non-empty decimal port token within the valid range. */
35
- const PORT_TOKEN = /^[1-9]\d{0,4}$/;
36
-
37
- /**
38
- * Split a raw Host authority into its literal hostname and optional port.
39
- *
40
- * This is a syntactic split only — it decides nothing about locality. It exists
41
- * because the URL parser is deliberately lenient: it accepts `127.1`,
42
- * `2130706433` and `0x7f.0.0.1` as `127.0.0.1`, which would let a Host header
43
- * that is not a dotted-quad IPv4 be treated as loopback. Validating the raw text
44
- * first means a non-canonical spelling is refused instead of normalised.
45
- * @param {string} raw - already-whitespace-free authority.
46
- * @returns {{ hostname: string, port: string } | null} split authority, or null.
47
- */
48
- function splitRawAuthority(raw) {
49
- if (raw.startsWith('[')) {
50
- // Bracketed IPv6, optionally followed by exactly one port.
51
- const match = /^(\[[^[\]]*\])(?::([^:]*))?$/.exec(raw);
52
- if (match === null) return null;
53
- const hostname = match[1];
54
- // `[::1]:` names an empty port; the parser would silently drop it.
55
- if (match[2] === '') return null;
56
- const port = match[2] ?? '';
57
- if (!isIPv6(hostname.slice(1, -1))) return null;
58
- return { hostname, port };
59
- }
60
- const firstColon = raw.indexOf(':');
61
- if (firstColon === -1) return { hostname: raw, port: '' };
62
- const hostname = raw.slice(0, firstColon);
63
- const port = raw.slice(firstColon + 1);
64
- // A second colon means an unbracketed IPv6 literal, which is not an authority.
65
- if (port.includes(':')) return null;
66
- // `127.0.0.1:` names an empty port; refuse rather than let the parser drop it.
67
- if (port === '') return null;
68
- return { hostname, port };
69
- }
70
-
71
- /**
72
- * Whether a raw hostname token is a spelling this module accepts.
73
- *
74
- * Accepts only three spellings: a strict dotted-quad IPv4, a bracketed IPv6
75
- * literal, or a DNS-style name. Anything numeric-looking that is not a strict
76
- * quad is a shortcut the URL parser would expand, so it is refused here.
77
- * @param {string} hostname - raw host token (brackets kept for IPv6).
78
- * @returns {boolean} true when the spelling is exactly what it appears to be.
79
- */
80
- function isAcceptableRawHostname(hostname) {
81
- if (hostname === '') return false;
82
- if (hostname.startsWith('[') || hostname.endsWith(']')) return true;
83
- const labels = hostname.split('.');
84
- if (labels.every((label) => /^\d+$/.test(label))) {
85
- // Every label is decimal, so this is meant as an IPv4 literal: it must be a
86
- // strict quad. `127.1`, `2130706433` and `127.0.0.256` all fail here.
87
- return IPV4_STRICT.test(hostname) && isIPv4(hostname);
88
- }
89
- for (const label of labels) {
90
- if (!HOST_LABEL.test(label)) return false;
91
- if (HEX_LABEL.test(label)) return false;
92
- }
93
- return true;
94
- }
95
-
96
- /**
97
- * Characters that must never appear in a Host header.
98
- *
99
- * A raw Host value is not a URL. Letting the URL parser interpret it means
100
- * accepting things a Host header can never legally be: `user@host` (userinfo),
101
- * `host/path`, `host?query`, `host#fragment`, embedded whitespace or a
102
- * backslash. Any of those is an attempt to have one component read as another,
103
- * so each is refused before parsing rather than after.
104
- */
105
- const FORBIDDEN_AUTHORITY = /[\s\\/?#@%\u0000-\u001f\u007f]/;
106
-
107
- /** Hostnames accepted as "this machine" when resolved as names rather than literals. */
108
- const LOOPBACK_NAMES = new Set(['localhost']);
109
-
110
- /**
111
- * Whether an address literal is this machine's loopback.
112
- * @param {string | undefined} address - socket remote address.
113
- * @returns {boolean} true for 127.0.0.0/8 and ::1 (including v4-mapped form).
114
- */
115
- export function isLoopbackAddress(address) {
116
- if (typeof address !== 'string' || address === '') return false;
117
- const normalized = address.toLowerCase().split('%', 1)[0];
118
- if (normalized === '::1') return true;
119
- if (IPV4_LOOPBACK.test(normalized)) return true;
120
- if (!normalized.startsWith('::ffff:')) return false;
121
- return IPV4_LOOPBACK.test(normalized.slice(7));
122
- }
123
-
124
- /**
125
- * Whether a Host/authority name refers to this machine.
126
- *
127
- * Accepts a bracketed IPv6 literal because `URL.hostname` keeps the brackets;
128
- * accepts the unbracketed form because a caller may pass a socket-level name.
129
- * @param {string} hostname - hostname without port.
130
- * @returns {boolean} true for localhost and loopback literals.
131
- */
132
- export function isLoopbackHostname(hostname) {
133
- if (typeof hostname !== 'string' || hostname === '') return false;
134
- const name = hostname.toLowerCase();
135
- if (name === '::1' || name === '[::1]') return true;
136
- if (LOOPBACK_NAMES.has(name)) return true;
137
- if (name.startsWith('[') || name.endsWith(']')) return false;
138
- return IPV4_LOOPBACK.test(name);
139
- }
140
-
141
- /**
142
- * Canonical `host:port` authority for a raw Host header value.
143
- *
144
- * The header is validated as a bare authority first — no userinfo, path, query,
145
- * fragment, whitespace or backslash — and only then handed to the URL parser for
146
- * canonicalisation (case folding, default-port removal, IDNA). A value that
147
- * fails validation is `null`, which every caller treats as a refusal.
148
- * @param {unknown} hostHeader - raw Host header.
149
- * @returns {{ authority: string, hostname: string, port: string } | null} parsed authority, or null.
150
- */
151
- export function parseRequestAuthority(hostHeader) {
152
- if (typeof hostHeader !== 'string') return null;
153
- // No trimming: a Host header that carries leading or trailing whitespace is
154
- // not the authority it appears to be, and accepting it would let the parser
155
- // ignore bytes the client actually sent.
156
- if (hostHeader === '') return null;
157
- if (hostHeader !== hostHeader.trim()) return null;
158
- const raw = hostHeader;
159
- // A Host header is exactly one authority. Anything else is a smuggling attempt.
160
- if (FORBIDDEN_AUTHORITY.test(raw)) return null;
161
- if (raw.includes(',')) return null;
162
- // Validate the spelling before the URL parser can canonicalise a shortcut form.
163
- const split = splitRawAuthority(raw);
164
- if (split === null) return null;
165
- if (!isAcceptableRawHostname(split.hostname)) return null;
166
- if (split.port !== '') {
167
- if (!PORT_TOKEN.test(split.port)) return null;
168
- if (Number(split.port) > 65_535) return null;
169
- }
170
- let parsed;
171
- try {
172
- parsed = new URL(`http://${raw}`);
173
- } catch {
174
- return null;
175
- }
176
- // Refuse anything the parser invented around our input.
177
- if (parsed.username !== '' || parsed.password !== '') return null;
178
- if (parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '') return null;
179
- if (parsed.hostname === '') return null;
180
- return {
181
- authority: parsed.host.toLowerCase(),
182
- // `URL.hostname` strips the port and keeps IPv6 brackets, unlike a naive
183
- // `authority.split(':')[0]`, which would truncate `[::1]:3210` to `[`.
184
- hostname: parsed.hostname.toLowerCase(),
185
- port: parsed.port,
186
- };
187
- }
188
-
189
- /**
190
- * Canonical `host:port` authority for a raw Host header value.
191
- * @param {unknown} hostHeader - raw Host header.
192
- * @returns {string | null} canonical authority, or null when unparsable.
193
- */
194
- export function requestAuthority(hostHeader) {
195
- return parseRequestAuthority(hostHeader)?.authority ?? null;
196
- }
197
-
198
- /**
199
- * Whether a parsed browser Origin is this server's own origin.
200
- * @param {string} origin - raw Origin header.
201
- * @param {{ authority: string }} host - parsed Host header facts.
202
- * @returns {{ ok: true } | { ok: false, code: string }} verdict.
203
- */
204
- function originMatchesHost(origin, host, prefix) {
205
- let parsed;
206
- try {
207
- parsed = new URL(origin);
208
- } catch {
209
- return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
210
- }
211
- // `Origin` is a scheme plus authority, never a path: a value carrying userinfo,
212
- // a path, a query or a fragment is not a browser Origin at all.
213
- if (parsed.username !== '' || parsed.password !== '') return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
214
- if (parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '') {
215
- return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
216
- }
217
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
218
- return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
219
- }
220
- if (parsed.host.toLowerCase() !== host.authority) return { ok: false, code: `${prefix}_CROSS_ORIGIN` };
221
- if (!isLoopbackHostname(parsed.hostname.toLowerCase())) {
222
- return { ok: false, code: `${prefix}_ORIGIN_NOT_LOCAL` };
223
- }
224
- return { ok: true };
225
- }
226
-
227
- /**
228
- * Peer-side fence for external-connection endpoints.
229
- *
230
- * A connection credential is only meaningful when the peer is provably this
231
- * machine: the socket is loopback, the Host header names this machine, and a
232
- * browser-marked request is same-origin. Anything else is refused before the
233
- * credential is even examined.
234
- * @param {{socket?: {remoteAddress?: string}, headers?: Record<string, unknown>}} request - node request-like object.
235
- * @returns {{ ok: true } | { ok: false, code: string, status: number }} verdict.
236
- */
237
- export function fenceExternalConnection(request) {
238
- const remote = request?.socket?.remoteAddress;
239
- if (!isLoopbackAddress(remote)) {
240
- return { ok: false, code: 'CONNECTION_NOT_LOCAL', status: 403 };
241
- }
242
- const host = parseRequestAuthority(request?.headers?.host);
243
- if (host === null) return { ok: false, code: 'CONNECTION_HOST_INVALID', status: 403 };
244
- if (!isLoopbackHostname(host.hostname)) {
245
- return { ok: false, code: 'CONNECTION_HOST_NOT_LOCAL', status: 403 };
246
- }
247
- const fetchSite = String(request?.headers?.['sec-fetch-site'] ?? '').toLowerCase();
248
- if (fetchSite !== '' && fetchSite !== 'same-origin' && fetchSite !== 'none') {
249
- return { ok: false, code: 'CONNECTION_CROSS_ORIGIN', status: 403 };
250
- }
251
- const origin = request?.headers?.origin;
252
- if (typeof origin === 'string' && origin !== '') {
253
- const verdict = originMatchesHost(origin, host, 'CONNECTION');
254
- if (verdict.ok !== true) return { ok: false, code: verdict.code, status: 403 };
255
- }
256
- return { ok: true };
257
- }
258
-
259
- /**
260
- * Whether the listening posture still allows external-connection endpoints.
261
- * A non-loopback bind destroys the only locality proof these endpoints have, so
262
- * the plugin refuses to serve them rather than trusting a header assertion.
263
- * @param {string} bindHost - configured webserver bind host.
264
- * @returns {{ ok: boolean, code?: string }} verdict.
265
- */
266
- export function bindAllowsExternalConnections(bindHost) {
267
- if (bindHost === '127.0.0.1') return { ok: true };
268
- return {
269
- ok: false,
270
- code: 'CONNECTION_BIND_NOT_LOOPBACK',
271
- };
272
- }
273
-
274
- /**
275
- * User-plane fence for the authenticated native control surface.
276
- *
277
- * Two independent facts must hold: the request is a first-party same-origin
278
- * request (no cross-site form or script can forge it), and the native browser
279
- * session says the request speaks for the operator. This function performs the
280
- * first check itself and delegates the second, so a caller cannot satisfy it by
281
- * sending a header.
282
- *
283
- * The Origin rule is asymmetric on purpose:
284
- *
285
- * * a **write** (`POST` and anything else that is not `GET`/`HEAD`) must carry
286
- * a same-origin `Origin` and a JSON content type. Browsers always send
287
- * `Origin` on those requests, so a missing one is a non-browser caller trying
288
- * to look like one, and a non-JSON type is a cross-site form post;
289
- * * an authenticated **read** (`GET`/`HEAD`) may omit `Origin`, because
290
- * same-origin `GET` navigations legitimately do not send it. It still has to
291
- * pass the native authentication check, and a supplied `Origin` is still
292
- * required to match this server.
293
- *
294
- * This helper is not wired to the live user plane: that plane is registered on
295
- * the native `connection.fetch` carrier, which applies the harness's own fence
296
- * and browser-session authentication before any handler runs. This function
297
- * exists for a future plain-node user plane and for tests of the rule itself.
298
- * @param {{method?: string, headers?: Record<string, unknown>, socket?: {remoteAddress?: string}}} request - node request-like object.
299
- * @param {(request: object) => boolean | Promise<boolean>} isNativeAuthenticated - native authentication verdict.
300
- * @returns {Promise<{ ok: true } | { ok: false, code: string, status: number }>} verdict.
301
- */
302
- export async function fenceUserPlane(request, isNativeAuthenticated) {
303
- const remote = request?.socket?.remoteAddress;
304
- if (!isLoopbackAddress(remote)) return { ok: false, code: 'USER_PLANE_NOT_LOCAL', status: 403 };
305
- const host = parseRequestAuthority(request?.headers?.host);
306
- if (host === null) return { ok: false, code: 'USER_PLANE_HOST_INVALID', status: 403 };
307
- const method = String(request?.method ?? 'GET').toUpperCase();
308
- const isRead = method === 'GET' || method === 'HEAD';
309
- const origin = request?.headers?.origin;
310
- if (typeof origin !== 'string' || origin === '') {
311
- if (!isRead) {
312
- // A browser write always carries Origin; a non-browser local tool must not
313
- // reach this plane at all because it cannot prove a native session.
314
- return { ok: false, code: 'USER_PLANE_ORIGIN_REQUIRED', status: 403 };
315
- }
316
- } else {
317
- const verdict = originMatchesHost(origin, host, 'USER_PLANE');
318
- if (verdict.ok !== true) return { ok: false, code: verdict.code, status: 403 };
319
- }
320
- const fetchSite = String(request?.headers?.['sec-fetch-site'] ?? '').toLowerCase();
321
- if (fetchSite !== '' && fetchSite !== 'same-origin' && fetchSite !== 'none') {
322
- return { ok: false, code: 'USER_PLANE_CROSS_SITE', status: 403 };
323
- }
324
- if (!isRead) {
325
- const contentType = String(request?.headers?.['content-type'] ?? '').toLowerCase();
326
- if (!contentType.startsWith('application/json')) {
327
- return { ok: false, code: 'USER_PLANE_CONTENT_TYPE', status: 415 };
328
- }
329
- }
330
- let authenticated = false;
331
- try {
332
- authenticated = (await isNativeAuthenticated(request)) === true;
333
- } catch {
334
- authenticated = false;
335
- }
336
- if (!authenticated) return { ok: false, code: 'USER_PLANE_UNAUTHENTICATED', status: 401 };
337
- return { ok: true };
338
- }
339
-
340
- /**
341
- * Constant-time comparison of two strings of arbitrary length.
342
- * @param {string} a - first value.
343
- * @param {string} b - second value.
344
- * @returns {boolean} true when equal.
345
- */
346
- export function safeEqual(a, b) {
347
- if (typeof a !== 'string' || typeof b !== 'string') return false;
348
- const left = Buffer.from(a, 'utf8');
349
- const right = Buffer.from(b, 'utf8');
350
- if (left.byteLength !== right.byteLength) return false;
351
- return timingSafeEqual(left, right);
352
- }
353
-
354
- /**
355
- * SHA-256 of a value as lowercase hex. Only hashes of secrets are retained.
356
- * @param {string} value - value to digest.
357
- * @returns {string} hex digest.
358
- */
359
- export function sha256(value) {
360
- return createHash('sha256').update(String(value), 'utf8').digest('hex');
361
- }
1
+ // Transport-level trust primitives.
2
+ //
3
+ // This module holds only pure predicates. It decides whether a request is even
4
+ // allowed to reach a handler; it never decides that a caller is authorized to
5
+ // dispatch work. Authorization is a separate, server-side grant (see
6
+ // src/auth/grants.js) — an Origin string or a client-supplied boolean is not
7
+ // evidence of anything and is never consulted for a decision.
8
+
9
+ import { createHash, timingSafeEqual } from 'node:crypto';
10
+ import { isIPv4, isIPv6 } from 'node:net';
11
+
12
+ /**
13
+ * One dotted-quad IPv4 loopback literal. Each octet is range-checked, so
14
+ * `127.300.0.1` and `127.0.0.256` are not accepted as loopback merely because
15
+ * they start with `127`.
16
+ */
17
+ const IPV4_OCTET = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
18
+ const IPV4_LOOPBACK = new RegExp(`^127(?:\\.${IPV4_OCTET}){3}$`);
19
+
20
+ /**
21
+ * One strict dotted-quad IPv4 literal: exactly four decimal octets, no leading
22
+ * zeroes, each 0-255. `127.1`, `2130706433`, `0177.0.0.1` and `0x7f.0.0.1` all
23
+ * fail this, so none of them can be smuggled in and silently normalised by the
24
+ * URL parser into `127.0.0.1`.
25
+ */
26
+ const IPV4_STRICT = new RegExp(`^(?:${IPV4_OCTET})(?:\\.(?:${IPV4_OCTET})){3}$`);
27
+
28
+ /** One DNS-style label: alphanumeric ends, hyphens inside. */
29
+ const HOST_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
30
+
31
+ /** A label the URL parser would read as a hexadecimal IPv4 component. */
32
+ const HEX_LABEL = /^0x[0-9a-f]*$/i;
33
+
34
+ /** A non-empty decimal port token within the valid range. */
35
+ const PORT_TOKEN = /^[1-9]\d{0,4}$/;
36
+
37
+ /**
38
+ * Split a raw Host authority into its literal hostname and optional port.
39
+ *
40
+ * This is a syntactic split only — it decides nothing about locality. It exists
41
+ * because the URL parser is deliberately lenient: it accepts `127.1`,
42
+ * `2130706433` and `0x7f.0.0.1` as `127.0.0.1`, which would let a Host header
43
+ * that is not a dotted-quad IPv4 be treated as loopback. Validating the raw text
44
+ * first means a non-canonical spelling is refused instead of normalised.
45
+ * @param {string} raw - already-whitespace-free authority.
46
+ * @returns {{ hostname: string, port: string } | null} split authority, or null.
47
+ */
48
+ function splitRawAuthority(raw) {
49
+ if (raw.startsWith('[')) {
50
+ // Bracketed IPv6, optionally followed by exactly one port.
51
+ const match = /^(\[[^[\]]*\])(?::([^:]*))?$/.exec(raw);
52
+ if (match === null) return null;
53
+ const hostname = match[1];
54
+ // `[::1]:` names an empty port; the parser would silently drop it.
55
+ if (match[2] === '') return null;
56
+ const port = match[2] ?? '';
57
+ if (!isIPv6(hostname.slice(1, -1))) return null;
58
+ return { hostname, port };
59
+ }
60
+ const firstColon = raw.indexOf(':');
61
+ if (firstColon === -1) return { hostname: raw, port: '' };
62
+ const hostname = raw.slice(0, firstColon);
63
+ const port = raw.slice(firstColon + 1);
64
+ // A second colon means an unbracketed IPv6 literal, which is not an authority.
65
+ if (port.includes(':')) return null;
66
+ // `127.0.0.1:` names an empty port; refuse rather than let the parser drop it.
67
+ if (port === '') return null;
68
+ return { hostname, port };
69
+ }
70
+
71
+ /**
72
+ * Whether a raw hostname token is a spelling this module accepts.
73
+ *
74
+ * Accepts only three spellings: a strict dotted-quad IPv4, a bracketed IPv6
75
+ * literal, or a DNS-style name. Anything numeric-looking that is not a strict
76
+ * quad is a shortcut the URL parser would expand, so it is refused here.
77
+ * @param {string} hostname - raw host token (brackets kept for IPv6).
78
+ * @returns {boolean} true when the spelling is exactly what it appears to be.
79
+ */
80
+ function isAcceptableRawHostname(hostname) {
81
+ if (hostname === '') return false;
82
+ if (hostname.startsWith('[') || hostname.endsWith(']')) return true;
83
+ const labels = hostname.split('.');
84
+ if (labels.every((label) => /^\d+$/.test(label))) {
85
+ // Every label is decimal, so this is meant as an IPv4 literal: it must be a
86
+ // strict quad. `127.1`, `2130706433` and `127.0.0.256` all fail here.
87
+ return IPV4_STRICT.test(hostname) && isIPv4(hostname);
88
+ }
89
+ for (const label of labels) {
90
+ if (!HOST_LABEL.test(label)) return false;
91
+ if (HEX_LABEL.test(label)) return false;
92
+ }
93
+ return true;
94
+ }
95
+
96
+ /**
97
+ * Characters that must never appear in a Host header.
98
+ *
99
+ * A raw Host value is not a URL. Letting the URL parser interpret it means
100
+ * accepting things a Host header can never legally be: `user@host` (userinfo),
101
+ * `host/path`, `host?query`, `host#fragment`, embedded whitespace or a
102
+ * backslash. Any of those is an attempt to have one component read as another,
103
+ * so each is refused before parsing rather than after.
104
+ */
105
+ const FORBIDDEN_AUTHORITY = /[\s\\/?#@%\u0000-\u001f\u007f]/;
106
+
107
+ /** Hostnames accepted as "this machine" when resolved as names rather than literals. */
108
+ const LOOPBACK_NAMES = new Set(['localhost']);
109
+
110
+ /**
111
+ * Whether an address literal is this machine's loopback.
112
+ * @param {string | undefined} address - socket remote address.
113
+ * @returns {boolean} true for 127.0.0.0/8 and ::1 (including v4-mapped form).
114
+ */
115
+ export function isLoopbackAddress(address) {
116
+ if (typeof address !== 'string' || address === '') return false;
117
+ const normalized = address.toLowerCase().split('%', 1)[0];
118
+ if (normalized === '::1') return true;
119
+ if (IPV4_LOOPBACK.test(normalized)) return true;
120
+ if (!normalized.startsWith('::ffff:')) return false;
121
+ return IPV4_LOOPBACK.test(normalized.slice(7));
122
+ }
123
+
124
+ /**
125
+ * Whether a Host/authority name refers to this machine.
126
+ *
127
+ * Accepts a bracketed IPv6 literal because `URL.hostname` keeps the brackets;
128
+ * accepts the unbracketed form because a caller may pass a socket-level name.
129
+ * @param {string} hostname - hostname without port.
130
+ * @returns {boolean} true for localhost and loopback literals.
131
+ */
132
+ export function isLoopbackHostname(hostname) {
133
+ if (typeof hostname !== 'string' || hostname === '') return false;
134
+ const name = hostname.toLowerCase();
135
+ if (name === '::1' || name === '[::1]') return true;
136
+ if (LOOPBACK_NAMES.has(name)) return true;
137
+ if (name.startsWith('[') || name.endsWith(']')) return false;
138
+ return IPV4_LOOPBACK.test(name);
139
+ }
140
+
141
+ /**
142
+ * Canonical `host:port` authority for a raw Host header value.
143
+ *
144
+ * The header is validated as a bare authority first — no userinfo, path, query,
145
+ * fragment, whitespace or backslash — and only then handed to the URL parser for
146
+ * canonicalisation (case folding, default-port removal, IDNA). A value that
147
+ * fails validation is `null`, which every caller treats as a refusal.
148
+ * @param {unknown} hostHeader - raw Host header.
149
+ * @returns {{ authority: string, hostname: string, port: string } | null} parsed authority, or null.
150
+ */
151
+ export function parseRequestAuthority(hostHeader) {
152
+ if (typeof hostHeader !== 'string') return null;
153
+ // No trimming: a Host header that carries leading or trailing whitespace is
154
+ // not the authority it appears to be, and accepting it would let the parser
155
+ // ignore bytes the client actually sent.
156
+ if (hostHeader === '') return null;
157
+ if (hostHeader !== hostHeader.trim()) return null;
158
+ const raw = hostHeader;
159
+ // A Host header is exactly one authority. Anything else is a smuggling attempt.
160
+ if (FORBIDDEN_AUTHORITY.test(raw)) return null;
161
+ if (raw.includes(',')) return null;
162
+ // Validate the spelling before the URL parser can canonicalise a shortcut form.
163
+ const split = splitRawAuthority(raw);
164
+ if (split === null) return null;
165
+ if (!isAcceptableRawHostname(split.hostname)) return null;
166
+ if (split.port !== '') {
167
+ if (!PORT_TOKEN.test(split.port)) return null;
168
+ if (Number(split.port) > 65_535) return null;
169
+ }
170
+ let parsed;
171
+ try {
172
+ parsed = new URL(`http://${raw}`);
173
+ } catch {
174
+ return null;
175
+ }
176
+ // Refuse anything the parser invented around our input.
177
+ if (parsed.username !== '' || parsed.password !== '') return null;
178
+ if (parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '') return null;
179
+ if (parsed.hostname === '') return null;
180
+ return {
181
+ authority: parsed.host.toLowerCase(),
182
+ // `URL.hostname` strips the port and keeps IPv6 brackets, unlike a naive
183
+ // `authority.split(':')[0]`, which would truncate `[::1]:3210` to `[`.
184
+ hostname: parsed.hostname.toLowerCase(),
185
+ port: parsed.port,
186
+ };
187
+ }
188
+
189
+ /**
190
+ * Canonical `host:port` authority for a raw Host header value.
191
+ * @param {unknown} hostHeader - raw Host header.
192
+ * @returns {string | null} canonical authority, or null when unparsable.
193
+ */
194
+ export function requestAuthority(hostHeader) {
195
+ return parseRequestAuthority(hostHeader)?.authority ?? null;
196
+ }
197
+
198
+ /**
199
+ * Whether a parsed browser Origin is this server's own origin.
200
+ * @param {string} origin - raw Origin header.
201
+ * @param {{ authority: string }} host - parsed Host header facts.
202
+ * @returns {{ ok: true } | { ok: false, code: string }} verdict.
203
+ */
204
+ function originMatchesHost(origin, host, prefix) {
205
+ let parsed;
206
+ try {
207
+ parsed = new URL(origin);
208
+ } catch {
209
+ return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
210
+ }
211
+ // `Origin` is a scheme plus authority, never a path: a value carrying userinfo,
212
+ // a path, a query or a fragment is not a browser Origin at all.
213
+ if (parsed.username !== '' || parsed.password !== '') return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
214
+ if (parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '') {
215
+ return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
216
+ }
217
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
218
+ return { ok: false, code: `${prefix}_ORIGIN_INVALID` };
219
+ }
220
+ if (parsed.host.toLowerCase() !== host.authority) return { ok: false, code: `${prefix}_CROSS_ORIGIN` };
221
+ if (!isLoopbackHostname(parsed.hostname.toLowerCase())) {
222
+ return { ok: false, code: `${prefix}_ORIGIN_NOT_LOCAL` };
223
+ }
224
+ return { ok: true };
225
+ }
226
+
227
+ /**
228
+ * Peer-side fence for external-connection endpoints.
229
+ *
230
+ * A connection credential is only meaningful when the peer is provably this
231
+ * machine: the socket is loopback, the Host header names this machine, and a
232
+ * browser-marked request is same-origin. Anything else is refused before the
233
+ * credential is even examined.
234
+ * @param {{socket?: {remoteAddress?: string}, headers?: Record<string, unknown>}} request - node request-like object.
235
+ * @returns {{ ok: true } | { ok: false, code: string, status: number }} verdict.
236
+ */
237
+ export function fenceExternalConnection(request) {
238
+ const remote = request?.socket?.remoteAddress;
239
+ if (!isLoopbackAddress(remote)) {
240
+ return { ok: false, code: 'CONNECTION_NOT_LOCAL', status: 403 };
241
+ }
242
+ const host = parseRequestAuthority(request?.headers?.host);
243
+ if (host === null) return { ok: false, code: 'CONNECTION_HOST_INVALID', status: 403 };
244
+ if (!isLoopbackHostname(host.hostname)) {
245
+ return { ok: false, code: 'CONNECTION_HOST_NOT_LOCAL', status: 403 };
246
+ }
247
+ const fetchSite = String(request?.headers?.['sec-fetch-site'] ?? '').toLowerCase();
248
+ if (fetchSite !== '' && fetchSite !== 'same-origin' && fetchSite !== 'none') {
249
+ return { ok: false, code: 'CONNECTION_CROSS_ORIGIN', status: 403 };
250
+ }
251
+ const origin = request?.headers?.origin;
252
+ if (typeof origin === 'string' && origin !== '') {
253
+ const verdict = originMatchesHost(origin, host, 'CONNECTION');
254
+ if (verdict.ok !== true) return { ok: false, code: verdict.code, status: 403 };
255
+ }
256
+ return { ok: true };
257
+ }
258
+
259
+ /**
260
+ * Whether the listening posture still allows external-connection endpoints.
261
+ * A non-loopback bind destroys the only locality proof these endpoints have, so
262
+ * the plugin refuses to serve them rather than trusting a header assertion.
263
+ * @param {string} bindHost - configured webserver bind host.
264
+ * @returns {{ ok: boolean, code?: string }} verdict.
265
+ */
266
+ export function bindAllowsExternalConnections(bindHost) {
267
+ if (bindHost === '127.0.0.1') return { ok: true };
268
+ return {
269
+ ok: false,
270
+ code: 'CONNECTION_BIND_NOT_LOOPBACK',
271
+ };
272
+ }
273
+
274
+ /**
275
+ * User-plane fence for the authenticated native control surface.
276
+ *
277
+ * Two independent facts must hold: the request is a first-party same-origin
278
+ * request (no cross-site form or script can forge it), and the native browser
279
+ * session says the request speaks for the operator. This function performs the
280
+ * first check itself and delegates the second, so a caller cannot satisfy it by
281
+ * sending a header.
282
+ *
283
+ * The Origin rule is asymmetric on purpose:
284
+ *
285
+ * * a **write** (`POST` and anything else that is not `GET`/`HEAD`) must carry
286
+ * a same-origin `Origin` and a JSON content type. Browsers always send
287
+ * `Origin` on those requests, so a missing one is a non-browser caller trying
288
+ * to look like one, and a non-JSON type is a cross-site form post;
289
+ * * an authenticated **read** (`GET`/`HEAD`) may omit `Origin`, because
290
+ * same-origin `GET` navigations legitimately do not send it. It still has to
291
+ * pass the native authentication check, and a supplied `Origin` is still
292
+ * required to match this server.
293
+ *
294
+ * This helper is not wired to the live user plane: that plane is registered on
295
+ * the native `connection.fetch` carrier, which applies the harness's own fence
296
+ * and browser-session authentication before any handler runs. This function
297
+ * exists for a future plain-node user plane and for tests of the rule itself.
298
+ * @param {{method?: string, headers?: Record<string, unknown>, socket?: {remoteAddress?: string}}} request - node request-like object.
299
+ * @param {(request: object) => boolean | Promise<boolean>} isNativeAuthenticated - native authentication verdict.
300
+ * @returns {Promise<{ ok: true } | { ok: false, code: string, status: number }>} verdict.
301
+ */
302
+ export async function fenceUserPlane(request, isNativeAuthenticated) {
303
+ const remote = request?.socket?.remoteAddress;
304
+ if (!isLoopbackAddress(remote)) return { ok: false, code: 'USER_PLANE_NOT_LOCAL', status: 403 };
305
+ const host = parseRequestAuthority(request?.headers?.host);
306
+ if (host === null) return { ok: false, code: 'USER_PLANE_HOST_INVALID', status: 403 };
307
+ const method = String(request?.method ?? 'GET').toUpperCase();
308
+ const isRead = method === 'GET' || method === 'HEAD';
309
+ const origin = request?.headers?.origin;
310
+ if (typeof origin !== 'string' || origin === '') {
311
+ if (!isRead) {
312
+ // A browser write always carries Origin; a non-browser local tool must not
313
+ // reach this plane at all because it cannot prove a native session.
314
+ return { ok: false, code: 'USER_PLANE_ORIGIN_REQUIRED', status: 403 };
315
+ }
316
+ } else {
317
+ const verdict = originMatchesHost(origin, host, 'USER_PLANE');
318
+ if (verdict.ok !== true) return { ok: false, code: verdict.code, status: 403 };
319
+ }
320
+ const fetchSite = String(request?.headers?.['sec-fetch-site'] ?? '').toLowerCase();
321
+ if (fetchSite !== '' && fetchSite !== 'same-origin' && fetchSite !== 'none') {
322
+ return { ok: false, code: 'USER_PLANE_CROSS_SITE', status: 403 };
323
+ }
324
+ if (!isRead) {
325
+ const contentType = String(request?.headers?.['content-type'] ?? '').toLowerCase();
326
+ if (!contentType.startsWith('application/json')) {
327
+ return { ok: false, code: 'USER_PLANE_CONTENT_TYPE', status: 415 };
328
+ }
329
+ }
330
+ let authenticated = false;
331
+ try {
332
+ authenticated = (await isNativeAuthenticated(request)) === true;
333
+ } catch {
334
+ authenticated = false;
335
+ }
336
+ if (!authenticated) return { ok: false, code: 'USER_PLANE_UNAUTHENTICATED', status: 401 };
337
+ return { ok: true };
338
+ }
339
+
340
+ /**
341
+ * Constant-time comparison of two strings of arbitrary length.
342
+ * @param {string} a - first value.
343
+ * @param {string} b - second value.
344
+ * @returns {boolean} true when equal.
345
+ */
346
+ export function safeEqual(a, b) {
347
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
348
+ const left = Buffer.from(a, 'utf8');
349
+ const right = Buffer.from(b, 'utf8');
350
+ if (left.byteLength !== right.byteLength) return false;
351
+ return timingSafeEqual(left, right);
352
+ }
353
+
354
+ /**
355
+ * SHA-256 of a value as lowercase hex. Only hashes of secrets are retained.
356
+ * @param {string} value - value to digest.
357
+ * @returns {string} hex digest.
358
+ */
359
+ export function sha256(value) {
360
+ return createHash('sha256').update(String(value), 'utf8').digest('hex');
361
+ }