@tnunamak/dalan 0.6.2 → 0.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 (74) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +2 -0
  4. package/README.md +81 -84
  5. package/bin/dalan.mjs +9 -0
  6. package/bin/dot-worker.mjs +29 -4
  7. package/contracts/adapter-qualification.schema.json +170 -0
  8. package/docs/chatgpt-worker-onboarding.md +10 -14
  9. package/docs/claude-worker-onboarding.md +9 -8
  10. package/docs/codex-to-muse.md +21 -35
  11. package/docs/connect-chatgpt.md +10 -16
  12. package/docs/dalan-upgrade.md +4 -2
  13. package/docs/local-agent-mcp.md +24 -4
  14. package/docs/local-agent-requester.md +46 -0
  15. package/docs/manual-setup.md +2 -2
  16. package/docs/operations.md +12 -13
  17. package/docs/pull-workers.md +1 -2
  18. package/docs/service-setup.md +110 -163
  19. package/docs/setup-reference.md +6 -6
  20. package/docs/t3-question-relationship.md +43 -0
  21. package/docs/t3-reverse-control.md +12 -8
  22. package/docs/t3-wake-fence-r4.md +42 -0
  23. package/docs/test-suite-isolation.md +204 -0
  24. package/docs/worker-clients.md +6 -4
  25. package/package.json +5 -3
  26. package/qualification/README.md +13 -0
  27. package/qualification/mcp.json +121 -0
  28. package/qualification/protocol-v0.json +127 -0
  29. package/scripts/dalan-try-selfcheck.mjs +8 -7
  30. package/scripts/worker-bridge-setup.mjs +91 -81
  31. package/src/admin-socket.mjs +2 -1
  32. package/src/answer-journal.mjs +200 -0
  33. package/src/as-store.mjs +5 -3
  34. package/src/as.mjs +35 -26
  35. package/src/auth-check.mjs +59 -0
  36. package/src/cli-help.mjs +16 -16
  37. package/src/client-approval.mjs +57 -0
  38. package/src/client-convenience.mjs +166 -0
  39. package/src/client-conveniences.json +106 -0
  40. package/src/client-conveniences.schema.json +97 -0
  41. package/src/connect-cli.mjs +5 -5
  42. package/src/default-home.mjs +36 -0
  43. package/src/destinations/index.mjs +6 -0
  44. package/src/destinations/none.mjs +3 -0
  45. package/src/destinations/t3.mjs +63 -6
  46. package/src/execution.mjs +20 -2
  47. package/src/follow-current.mjs +27 -0
  48. package/src/gozar-routes.mjs +315 -0
  49. package/src/host-budget.mjs +17 -11
  50. package/src/host-execution-policy.mjs +2 -2
  51. package/src/host-stop-reverify.mjs +6 -4
  52. package/src/integrator.mjs +3 -1
  53. package/src/redirect-policy.mjs +61 -0
  54. package/src/route-setting.mjs +71 -12
  55. package/src/server.mjs +64 -12
  56. package/src/service-auto-update.mjs +8 -1
  57. package/src/service-launchd.mjs +186 -0
  58. package/src/service-migrate-workers.mjs +12 -2
  59. package/src/service-update-runtime.mjs +40 -6
  60. package/src/service-update.mjs +20 -14
  61. package/src/service.mjs +211 -63
  62. package/src/setup.mjs +55 -44
  63. package/src/store.mjs +77 -14
  64. package/src/submission-policy.mjs +8 -4
  65. package/src/t3.mjs +21 -2
  66. package/src/tool-registry.mjs +54 -8
  67. package/src/try-exposure.mjs +7 -657
  68. package/src/try-hosted.mjs +71 -101
  69. package/src/try-selfcheck.mjs +15 -8
  70. package/src/try.mjs +9 -13
  71. package/src/workers.mjs +4 -3
  72. package/src/workspace.mjs +94 -15
  73. package/scripts/lib/expose-tailscale.mjs +0 -408
  74. package/src/try-hosted-clients.mjs +0 -46
@@ -0,0 +1,27 @@
1
+ // The `dalan` on PATH is whichever package npm installed first. After the updater installs newer versions side by side under the service home,
2
+ // the CLI must run the version the service runs, or the two drift. This runs the service's `current` package instead of this one.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { spawn } from 'node:child_process';
6
+ import { readDefaultHome } from './default-home.mjs';
7
+
8
+ const real = file => { try { return fs.realpathSync(file); } catch { return null; } };
9
+
10
+ // The entry script to hand over to, or null to stay in this package. `ownBin` is this package's bin/dalan.mjs; `argv` is the
11
+ // command line after the script. An explicit --home names a home other than the default one, so this package runs it.
12
+ export function followTarget({ ownBin, env = process.env, argv = [] }) {
13
+ if (env.DALAN_NO_FOLLOW === '1' || env.DALAN_FOLLOWED === '1') return null;
14
+ if (argv.some(arg => arg === '--home' || arg.startsWith('--home='))) return null;
15
+ const home = env.DALAN_HOME ? path.resolve(env.DALAN_HOME) : readDefaultHome(env);
16
+ if (!home) return null;
17
+ const target = real(path.join(home, 'current', 'bin', 'dalan.mjs')), own = real(ownBin);
18
+ return target && own && target !== own ? target : null;
19
+ }
20
+
21
+ // Runs the other package with the same arguments and exits with its status. Never returns.
22
+ export function handOver(target, { argv = process.argv.slice(2), env = process.env } = {}) {
23
+ const child = spawn(process.execPath, [target, ...argv], { stdio: 'inherit', env: { ...env, DALAN_FOLLOWED: '1' } });
24
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => child.kill(signal));
25
+ child.on('error', error => { process.stderr.write(`dalan: could not run the service's current version (${error.message}); set DALAN_NO_FOLLOW=1 to use this copy\n`); process.exit(1); });
26
+ child.on('exit', (code, signal) => { if (signal) { process.removeAllListeners(signal); process.kill(process.pid, signal); } else process.exit(code ?? 1); });
27
+ }
@@ -0,0 +1,315 @@
1
+ // The one place where Dalan reaches the network. Dalan asks Gozar for a route through its frozen consumer exports and branches only on
2
+ // the shapes and the 21 error codes of that contract (tnunamak/gozar, contract/route-contract-c0 @ 91b41a1; the pinned fixture is
3
+ // src/test-support/gozar-contract.json). Dalan never names a provider, never validates or translates a route name, and never builds a
4
+ // command for a provider: a name from `--route` goes to Gozar as written.
5
+ //
6
+ // Every function takes the Gozar module as `gozar`, so tests inject a fake that is checked against the same fixture.
7
+ import { createRequire } from 'node:module';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { safeDiagnostic } from './diagnostic.mjs';
12
+ import { readJournal, removeJournal, writeJournal, readRouteSetting, writeRouteSetting } from './route-setting.mjs';
13
+
14
+ export const OWNER = 'dalan';
15
+ export const SCHEMA_VERSION = 1;
16
+ export const FROZEN_CODES = Object.freeze(['invalid_input', 'requirements_unsatisfied', 'setup_required', 'consent_required', 'consent_unknown', 'consent_expired',
17
+ 'consent_mismatch', 'candidate_stale', 'preference_conflict', 'route_not_found', 'route_conflict', 'address_changed', 'stopped_by_user', 'handing_back',
18
+ 'verification_failed', 'provider_unavailable', 'cleanup_debt', 'unsupported', 'ambiguous_route', 'busy', 'internal_error']);
19
+ // The exports Dalan calls. A Gozar that lacks one is older than the contract: that is `runtime_missing`, not a route error.
20
+ export const REQUIRED_EXPORTS = Object.freeze(['catalogRoutes', 'ensureRoute', 'adoptRoute', 'expose', 'routeStatus', 'closeRoute', 'watchRoutes', 'inspectLegacyRoute', 'runSetupAction', 'addService']);
21
+
22
+ export class RouteError extends Error {
23
+ constructor(code, message, { nextAction = null, cause } = {}) { super(message, cause ? { cause } : undefined); this.name = 'RouteError'; this.code = code; this.nextAction = nextAction; }
24
+ }
25
+
26
+ // ---- finding Gozar ---------------------------------------------------------------------------------------------------------------------
27
+ const require = createRequire(import.meta.url);
28
+ // The bundled package, resolved from Dalan's own install tree (not the working directory). An install without the contract's exports
29
+ // is reported as `runtime_missing` with the next step; nothing falls back to another executable.
30
+ export async function resolveGozar({ importer = () => import('@tnunamak/gozar'), resolvePackage = () => require.resolve('@tnunamak/gozar/package.json') } = {}) {
31
+ let module;
32
+ try { module = await importer(); } catch (error) {
33
+ if (error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'MODULE_NOT_FOUND') throw new RouteError('runtime_missing', 'Gozar is not installed with this Dalan. Reinstall @tnunamak/dalan with its dependencies, then run this again.', { cause: error });
34
+ throw error;
35
+ }
36
+ const missing = REQUIRED_EXPORTS.filter(name => typeof module?.[name] !== 'function');
37
+ if (missing.length) {
38
+ let version = 'unknown';
39
+ try { version = JSON.parse(fs.readFileSync(resolvePackage(), 'utf8')).version ?? version; } catch { /* reported as unknown */ }
40
+ throw new RouteError('runtime_missing', `The installed Gozar (${version}) does not provide the route contract (missing ${missing.join(', ')}). Update @tnunamak/dalan to a release that bundles it.`);
41
+ }
42
+ return module;
43
+ }
44
+
45
+ // Gozar's profile home for the real OS user. An explicit GOZAR_HOME selects a separate profile.
46
+ export const gozarHomeFor = (env = process.env) => path.resolve(env.GOZAR_HOME ?? path.join(env.HOME ?? os.homedir(), '.local', 'state', 'gozar'));
47
+
48
+ // ---- requests --------------------------------------------------------------------------------------------------------------------------
49
+ export const dalanRequirements = ({ address = 'any' } = {}) => ({ reach: 'internet', transport: 'https', payloadAccess: 'allow-provider', address, setup: 'allow', protocols: ['sse', 'streamable-http', 'oauth-dcr'] });
50
+
51
+ // `route` is the owner's name for a Gozar route, passed through exactly. An empty or non-string value is refused only because it is no name at all.
52
+ export function buildQuery({ home, target, usage, route, origin, intent, migrationRef, address = 'any', requirements }) {
53
+ if (route !== undefined && (typeof route !== 'string' || route.length === 0)) throw new RouteError('invalid_input', '--route needs a name');
54
+ const query = { schemaVersion: SCHEMA_VERSION, owner: OWNER, target, usage, requirements: requirements ?? dalanRequirements({ address }), home };
55
+ if (route !== undefined) query.route = route;
56
+ if (origin !== undefined) query.origin = origin;
57
+ if (intent !== undefined) query.intent = intent;
58
+ if (migrationRef !== undefined) query.migrationRef = migrationRef;
59
+ return query;
60
+ }
61
+ export const targetFor = port => `127.0.0.1:${port}`;
62
+
63
+ // ---- choosing and showing candidates (data only) ---------------------------------------------------------------------------------------
64
+ export const readyCandidates = catalog => [...catalog.candidates].filter(c => c.eligible && c.setup.state === 'ready' && typeof c.candidateToken === 'string').sort((a, b) => a.rank - b.rank);
65
+ export const pickCandidate = catalog => readyCandidates(catalog)[0] ?? null;
66
+ // `--route WORD` is Gozar's own name for a route when Gozar has one. Otherwise it is a word in the label of a route Gozar offers, so an owner can
67
+ // type what the label says. The word is matched only against labels Gozar returned; no provider is named here. Returns the query to send and how to
68
+ // pick the candidate: an unnamed query lets Gozar offer every route, and `pick` chooses the matching one.
69
+ export async function resolveRouteWord({ gozar, query }) {
70
+ if (query.route === undefined) return { query, pick: pickCandidate };
71
+ try { await gozar.catalogRoutes(query); return { query, pick: pickCandidate }; } catch (error) { if (error?.code !== 'route_not_found') throw error; }
72
+ const { route: word, ...bare } = query, needle = String(word).toLowerCase();
73
+ const catalog = await gozar.catalogRoutes(bare);
74
+ const matches = catalog.candidates.filter(c => `${c.display?.label ?? ''}`.toLowerCase().includes(needle));
75
+ const pick = cat => readyCandidates(cat).find(c => matches.some(m => m.name === c.name)) ?? null;
76
+ if (!matches.length) throw new RouteError('route_not_found', `No route named ${JSON.stringify(word)}, and none offered is labelled with it. Offered: ${catalog.candidates.map(c => c.display?.label).filter(Boolean).join('; ') || 'none'}.`);
77
+ return { query: bare, pick };
78
+ }
79
+ export const approvalFor = candidate => ({ candidateToken: candidate.candidateToken, disclosureRevision: candidate.disclosure.revision });
80
+
81
+ const yesNo = value => value === true ? 'yes' : value === false ? 'no' : 'unknown';
82
+ // One block of lines per candidate, built only from what Gozar returned. Labels name a provider only as returned display data.
83
+ export function describeCandidate(candidate, index) {
84
+ const p = candidate.properties;
85
+ const readers = p.traffic.readers.length ? p.traffic.readers.join(', ') : 'none listed';
86
+ const lines = [`${index === undefined ? '' : `${index + 1}. `}${candidate.display.label}${candidate.eligible ? '' : ' (not usable for this)'}`, ` ${candidate.display.description}`,
87
+ ` reach: ${p.reach}; address: ${p.address.stability} (${p.address.scope}${p.address.conditions.length ? `; ${p.address.conditions.join('; ')}` : ''})`,
88
+ ` traffic readers: ${readers}; provider can read payload: ${yesNo(p.traffic.providerCanReadPayload)}; ends TLS at: ${p.traffic.tlsTermination}`,
89
+ ` cost: ${p.cost.summary}; account needed: ${yesNo(p.needsAccount)}; lifetimes: ${p.lifetimes.join(', ')}`];
90
+ if (!candidate.eligible) lines.push(` not met: ${candidate.unmet.map(u => `${u.requirement} (${u.reasonCode})`).join(', ')}`);
91
+ if (candidate.setup.state !== 'ready') lines.push(` setup: ${candidate.setup.state}${candidate.setup.actions.length ? `; actions: ${candidate.setup.actions.map(a => a.label).join('; ')}` : ''}`);
92
+ return lines;
93
+ }
94
+ export function describeDisclosure(candidate) {
95
+ const d = candidate.disclosure;
96
+ return [d.text, ...d.links.map(l => `${l.label}: ${l.href}`)];
97
+ }
98
+
99
+ // Frozen code -> one line and the owner's next step. Provider diagnostics stay inside Gozar; Dalan prints only its own text, the
100
+ // message Gozar chose to expose, and the action Gozar names.
101
+ const EXPLAIN = {
102
+ invalid_input: 'Dalan sent Gozar a request it refused as invalid.', requirements_unsatisfied: 'No route satisfies what Dalan needs (an HTTPS address reachable from the internet).',
103
+ setup_required: 'A route needs one setup step first.', consent_required: 'This route needs your approval first.', consent_unknown: 'The approval was already used or is unknown. Ask for the choices again.',
104
+ consent_expired: 'The approval expired. Ask for the choices again.', consent_mismatch: 'The approval was for a different request. Ask for the choices again.', candidate_stale: 'The route choice changed while you decided. Ask again.',
105
+ preference_conflict: 'Your route preferences changed meanwhile. Try again.', route_not_found: 'Gozar has no route with that name.', route_conflict: 'Another owner or a newer route replaced this one; it was left untouched.',
106
+ address_changed: 'The public address changed.', stopped_by_user: 'This route was stopped by you; approve it again to start it.', handing_back: 'The route is being handed back to its previous owner.',
107
+ verification_failed: 'The route did not pass Gozar\'s check.', provider_unavailable: 'The route provider is unavailable right now.', cleanup_debt: 'A route could not be fully removed.',
108
+ unsupported: 'This computer or request is not supported by any route.', ambiguous_route: 'Gozar cannot tell which existing route this is, so it changed nothing.',
109
+ busy: 'Gozar is busy. Wait a moment and try again.', internal_error: 'Gozar had an unexpected fault.', runtime_missing: 'Gozar is not available.',
110
+ };
111
+ export function explainRouteError(error) {
112
+ const code = typeof error?.code === 'string' && (FROZEN_CODES.includes(error.code) || error.code === 'runtime_missing') ? error.code : null;
113
+ // Gozar's next step is shown as text for every code, including one Dalan does not know yet; Dalan never acts on it.
114
+ const action = error?.nextAction ?? null;
115
+ const fix = action ? [action.label, action.instructions, action.href].filter(value => typeof value === 'string' && value.length > 0).map(value => safeDiagnostic(value, 240)).join(' - ') || null : null;
116
+ if (!code) return { code: null, line: safeDiagnostic(String(error?.message ?? error), 240), fix };
117
+ const detail = code === 'runtime_missing' ? error.message : `${EXPLAIN[code]}${error.message && !EXPLAIN[code].includes(error.message) ? ` (${safeDiagnostic(error.message, 160)})` : ''}`;
118
+ return { code, line: detail, fix };
119
+ }
120
+
121
+ // ---- a session route (`dalan try --public`) --------------------------------------------------------------------------------------------
122
+ // `consent(candidate)` shows the disclosure and resolves true only on an explicit yes. The route lasts for the trial and is closed with it.
123
+ const abortError = signal => signal.reason ?? Object.assign(new Error('stopped'), { name: 'AbortError', code: 'ABORT_ERR' });
124
+
125
+ // `wait: 'allocated'` is for a trial whose bridge needs the address before it can answer Gozar's check: Dalan then runs its own readiness check.
126
+ export async function startSessionRoute({ gozar, query, consent, signal, wait = 'verified', pick = pickCandidate }) {
127
+ signal?.throwIfAborted();
128
+ const catalog = await gozar.catalogRoutes(query);
129
+ signal?.throwIfAborted();
130
+ const candidate = pick(catalog);
131
+ if (!candidate) throw noCandidateError(catalog);
132
+ if (!await consent(candidate, catalog)) throw Object.assign(new RouteError('consent_required', 'No public route was started because consent was not given.'), { tryKind: 'consent' });
133
+ let view;
134
+ try { view = await gozar.expose({ ...query, approval: approvalFor(candidate), wait }); } catch (error) { throw error; }
135
+ const handle = view?.handle;
136
+ const closeNow = () => gozar.closeRoute({ home: query.home, handle, mode: 'remove' }).catch(() => null);
137
+ let url; try { url = new URL(view.origin); } catch { /* rejected below */ }
138
+ if (!handle || !url || url.protocol !== 'https:' || url.origin !== view.origin || (wait === 'verified' && (view.state !== 'usable' || view.verification?.status !== 'verified'))) {
139
+ if (handle) await closeNow();
140
+ throw new RouteError('verification_failed', 'Gozar did not return a verified HTTPS origin for this route.');
141
+ }
142
+ // Ctrl-C while Gozar was starting: the route exists now, so it is closed before the abort is reported.
143
+ if (signal?.aborted) { await closeNow(); throw abortError(signal); }
144
+ return sessionRoute({ gozar, home: query.home, view, candidate });
145
+ }
146
+
147
+ function sessionRoute({ gozar, home, view, candidate }) {
148
+ const { handle, origin } = view;
149
+ const watch = new AbortController();
150
+ let reason = null, resolveEnded;
151
+ const exited = new Promise(resolve => { resolveEnded = resolve; });
152
+ const end = why => { if (reason === null) reason = why; resolveEnded(reason); };
153
+ const watcher = (async () => {
154
+ try {
155
+ for await (const event of gozar.watchRoutes({ home, handle, signal: watch.signal })) {
156
+ const route = event.route;
157
+ // A route Gozar has not verified yet (the bridge was still starting when it looked) is pending, not lost. Dalan's own public
158
+ // identity check covers a route that never works; only a lost or moved route ends the trial here.
159
+ if (route.state === 'unverified' && !route.published) continue;
160
+ if (event.type === 'snapshot' && route.state === 'usable' && route.published === origin) continue;
161
+ if (route.state === 'usable' && route.published === origin) continue;
162
+ if (route.state === 'address_changed' || (route.published && route.published !== origin)) end('rotated');
163
+ else end('lost');
164
+ return;
165
+ }
166
+ if (!watch.signal.aborted) end('lost');
167
+ } catch (error) { if (!watch.signal.aborted) end('lost'); }
168
+ })();
169
+ let stopped = null;
170
+ return {
171
+ origin, handle, view, candidate, exited, endedBecause: () => reason,
172
+ stop() { // idempotent; ends the watch first, then asks Gozar to remove exactly this handle
173
+ stopped ??= (async () => {
174
+ watch.abort(); await watcher.catch(() => {});
175
+ try {
176
+ const closed = await gozar.closeRoute({ home, handle, mode: 'remove' });
177
+ if (closed.cleanup?.state === 'debt') return { removed: false, detail: `Gozar reports cleanup debt for this route: ${safeDiagnostic(closed.cleanup.message ?? 'no detail', 200)}. Run \`dalan setup\` to review it.` };
178
+ return closed.state === 'released' ? { removed: true } : { removed: false, detail: `Gozar reports the route is ${closed.state}; its removal could not be confirmed.` };
179
+ } catch (error) {
180
+ if (error?.code === 'route_not_found') return { removed: true };
181
+ if (error?.code === 'route_conflict') return { removed: false, detail: 'Gozar reports a newer route replaced this one, so cleanup of this trial could not be confirmed. The replacement was left untouched.' };
182
+ return { removed: false, detail: `Gozar could not confirm the route removal (${explainRouteError(error).line}).` };
183
+ }
184
+ })();
185
+ return stopped;
186
+ },
187
+ };
188
+ }
189
+
190
+ function noCandidateError(catalog) {
191
+ const needsSetup = catalog.candidates.find(c => c.setup.state === 'action-required');
192
+ if (needsSetup) return new RouteError('setup_required', 'A route needs one setup step before it can start.', { nextAction: needsSetup.setup.actions[0] ?? null });
193
+ if (catalog.candidates.length && catalog.candidates.every(c => c.setup.state === 'unsupported')) return new RouteError('unsupported', 'No route is supported on this computer yet.');
194
+ return new RouteError('requirements_unsatisfied', 'No route satisfies what Dalan needs.');
195
+ }
196
+
197
+ // ---- durable routes and external services ----------------------------------------------------------------------------------------------
198
+ // A durable route is never closed by an app exit. The first allocation asks once (the pin keeps the consent); a later call reuses it.
199
+ export async function ensureDurableRoute({ gozar, query, consent, reconsent = false, pick = pickCandidate }) {
200
+ try { return await gozar.ensureRoute({ ...query, ...(reconsent ? { reconsent: true } : {}) }); }
201
+ catch (error) { if (error?.code !== 'consent_required') throw error; }
202
+ const catalog = await gozar.catalogRoutes(query);
203
+ const candidate = pick(catalog);
204
+ if (!candidate) throw noCandidateError(catalog);
205
+ if (!await consent(candidate, catalog)) throw Object.assign(new RouteError('consent_required', 'The route was not started because consent was not given.'), { tryKind: 'consent' });
206
+ return gozar.ensureRoute({ ...query, approval: approvalFor(candidate), ...(reconsent ? { reconsent: true } : {}) });
207
+ }
208
+
209
+ // Registers the owner's own origin (a route the owner runs) and reads it back through the same view as any other route.
210
+ export async function registerExternalService({ gozar, home, origin, target, verifyCmd }) {
211
+ const reply = await gozar.addService({ origin, target, home, ...(verifyCmd ? { verifyCmd } : {}) });
212
+ const route = reply?.route;
213
+ if (reply?.schemaVersion !== SCHEMA_VERSION || route?.origin !== origin || route?.target !== target) throw new RouteError('verification_failed', 'Gozar returned a service route that does not match the requested origin and target.');
214
+ const view = await gozar.routeStatus({ home, handle: { kind: 'external', id: origin, generation: 1 } });
215
+ return { route, view };
216
+ }
217
+
218
+ // ---- the Host a bridge accepts -----------------------------------------------------------------------------------------------------------
219
+ // A route may forward with the default port written out (`name:443`). The configured origin names no port, so both forms are the same
220
+ // authority. Nothing else changes: another host, another port or a prefix/suffix of the name stays refused.
221
+ export function canonicalHost(hostHeader, origin) {
222
+ const url = new URL(origin);
223
+ const host = String(hostHeader ?? '').toLowerCase();
224
+ if (url.protocol === 'https:' && url.port === '' && host === `${url.hostname.toLowerCase()}:443`) return url.host;
225
+ return hostHeader;
226
+ }
227
+ export function normalizeRequestHost(req, origin) {
228
+ const canonical = canonicalHost(req.headers.host, origin);
229
+ if (canonical !== req.headers.host) req.headers.host = canonical;
230
+ }
231
+
232
+ // ---- moving a 0.6 route to Gozar ----------------------------------------------------------------------------------------------------------
233
+ // Fence the old exposure code -> adopt while Dalan serves the proof -> restart -> commit v2 settings. Every step is journaled and
234
+ // fsynced. Anything uncertain stops with the old ingress and the old sign-in state untouched; there is no release-and-recreate fallback.
235
+ export const CRASH_POINTS = Object.freeze(['after-prepared', 'after-fence', 'after-fence-journal', 'after-adopt', 'after-adopt-journal', 'after-restart', 'after-commit-setting']);
236
+
237
+ export async function migrateLegacyRoute({
238
+ gozar, env = process.env, gozarHome, routeName, routeId, origin, target, bridgeHome, stateFiles,
239
+ fence, unfence, restart, authenticatedCheck, consent, crash = () => {}, generation,
240
+ }) {
241
+ const hand = { from: `${OWNER}-legacy`, generation };
242
+ const q = (extra = {}) => buildQuery({ home: gozarHome, target, usage: { kind: 'durable', routeId }, route: routeName, origin, address: 'stable', ...extra });
243
+ const journal = phase => writeJournal({ phase, generation, origin, routeId }, env);
244
+ // A halt lifts the fence (a no-op when nothing moved) and leaves the old ingress and the old sign-in state exactly as found.
245
+ const halt = async (reason, extra = {}) => { await unfence().catch(() => {}); removeJournal(env); return { migrated: false, reason, ...extra }; };
246
+
247
+ const existing = readJournal(env);
248
+ if (existing?.phase === 'dalan-committed') { removeJournal(env); return { migrated: true, resumed: true }; }
249
+ journal('prepared'); crash('after-prepared');
250
+
251
+ // Already adopted by an earlier, interrupted run? An ensure without approval returns an existing pin and can never create one.
252
+ let adopted = null;
253
+ if (existing) {
254
+ try { const view = await gozar.ensureRoute(q()); if (view.origin === origin) adopted = view; }
255
+ catch (error) { if (error?.code !== 'consent_required' && error?.code !== 'route_not_found') throw error; }
256
+ }
257
+ if (!adopted) {
258
+ // Gozar reads the old state where it was written: lift an earlier fence, inspect, then fence again.
259
+ await unfence();
260
+ const inspected = await gozar.inspectLegacyRoute({ home: gozarHome, owner: OWNER, source: { stateFiles: stateFiles() }, origin, target });
261
+ if (inspected.state !== 'adoptable') return halt(inspected.reasonCode ?? inspected.state, { nextAction: inspected.nextAction ?? null });
262
+ try { await fence(); } catch (error) { return halt(`the old exposure could not be fenced (${safeDiagnostic(error.message, 160)})`); }
263
+ crash('after-fence'); journal('old-owner-fenced'); crash('after-fence-journal');
264
+ const intent = q({ intent: 'adopt', migrationRef: inspected.migrationRef });
265
+ const catalog = await gozar.catalogRoutes(intent);
266
+ const candidate = pickCandidate(catalog);
267
+ if (!candidate) return halt('Gozar offered no route to adopt this origin');
268
+ if (!await consent(candidate, catalog)) return halt('adoption was not approved');
269
+ try { adopted = await gozar.adoptRoute({ ...intent, origin, approval: approvalFor(candidate), handover: hand }); }
270
+ catch (error) { return halt(`Gozar did not adopt the route (${explainRouteError(error).line}); the old route is unchanged`); }
271
+ crash('after-adopt');
272
+ }
273
+ journal('gozar-adopted'); crash('after-adopt-journal');
274
+
275
+ // Restart on the same home and prove the existing credentials still work through the same origin before committing.
276
+ let ok = false;
277
+ try { await restart(); crash('after-restart'); ok = await authenticatedCheck(); } catch (error) { if (error?.simulatedCrash) throw error; ok = false; }
278
+ if (!ok) {
279
+ // Two-phase hand-back: persist Gozar's opaque transfer, let the previous owner take over, then confirm. Never two mutators.
280
+ const back = await gozar.releaseRoute({ routeId, mode: 'hand-back', home: gozarHome });
281
+ writeJournal({ phase: 'gozar-adopted', generation, origin, routeId, transfer: back.transfer }, env);
282
+ await unfence();
283
+ await gozar.confirmHandBack({ routeId, transfer: back.transfer, home: gozarHome });
284
+ removeJournal(env);
285
+ return { migrated: false, reason: 'the existing sign-in did not work through the new route; the old route was handed back' };
286
+ }
287
+ writeRouteSetting({ version: 2, requirements: dalanRequirements({ address: 'stable' }), gozarHome, routeName: routeName ?? null, routeId, origin, bridgeHome: bridgeHome ?? null }, env);
288
+ crash('after-commit-setting');
289
+ journal('dalan-committed'); removeJournal(env);
290
+ return { migrated: true, origin, routeId, view: adopted };
291
+ }
292
+
293
+ // The fence for the files a 0.6 install wrote: each `dot-bridge-<worker>.exposure.json` record is moved aside, so older code that reads
294
+ // the record can no longer act on the rule. Unfence moves it back. Both are repeatable, and neither touches the rule itself.
295
+ export const FENCE_SUFFIX = '.gozar-fence';
296
+ export function legacyRecordFiles(dir) {
297
+ let names = []; try { names = fs.readdirSync(dir); } catch { return []; }
298
+ return names.filter(name => /^dot-bridge-.+\.exposure\.json(\.gozar-fence)?$/.test(name)).map(name => path.join(dir, name));
299
+ }
300
+ export function fenceLegacyRecords(dir) {
301
+ const moved = [];
302
+ for (const file of legacyRecordFiles(dir)) {
303
+ if (file.endsWith(FENCE_SUFFIX)) { moved.push(file); continue; }
304
+ const stat = fs.lstatSync(file);
305
+ if (!stat.isFile() || (typeof process.getuid === 'function' && stat.uid !== process.getuid())) throw new Error(`${file} is not a regular file you own; ownership is unclear`);
306
+ fs.renameSync(file, `${file}${FENCE_SUFFIX}`); moved.push(`${file}${FENCE_SUFFIX}`);
307
+ }
308
+ if (!moved.length) throw new Error('no old exposure record to fence; ownership is unclear');
309
+ return moved;
310
+ }
311
+ export function unfenceLegacyRecords(dir) {
312
+ for (const file of legacyRecordFiles(dir)) if (file.endsWith(FENCE_SUFFIX) && !fs.existsSync(file.slice(0, -FENCE_SUFFIX.length))) fs.renameSync(file, file.slice(0, -FENCE_SUFFIX.length));
313
+ }
314
+
315
+ export { readRouteSetting };
@@ -6,9 +6,7 @@ import {prepareHostReceipts,assertHostReceiptIsolation,readVerifiedHostStop} fro
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { spawn } from 'node:child_process';
8
8
 
9
- // One active envelope per Unix user, shared by every bridge process. The systemd
10
- // unit name is an atomic reservation; it disappears only after its tree stops.
11
- export const HOST_UNIT = 'dot-bridge-host-check.service';
9
+ // The fixed production unit reserves one active envelope per Unix user.
12
10
  export const HOST_BUDGET_CEILINGS = Object.freeze({ cpu_ms: 120000, wall_ms: 180000, memory_bytes: 1024 ** 3, processes: 128, disk_write_bytes: 256 * 1024 ** 2, output_bytes: 1024 ** 2 });
13
11
  const minima = { cpu_ms: 50, wall_ms: 100, memory_bytes: 128 * 1024 ** 2, processes: 16, disk_write_bytes: 1024 ** 2, output_bytes: 1024 };
14
12
  const service = fileURLToPath(new URL('./host-budget-service.mjs', import.meta.url));
@@ -77,12 +75,16 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
77
75
  'LimitCORE=0', 'UMask=0077',
78
76
  `ExecStopPost=${[process.execPath, stopRecorder,...(receipts?['--check-run-id',receipts.checkRunId,'--receipt-dir',receipts.receiptDir]:[])].map(propertyArg).join(' ')}`,
79
77
  ];
80
- const args = ['--user', '--quiet', '--wait', '--pipe', '--collect', `--unit=${HOST_UNIT}`, ...properties.map(p => `--property=${p}`), '--', process.execPath, service];
78
+ // Test suites isolate their reservation without changing the production default.
79
+ const suffix = process.env.NODE_ENV === 'production' ? undefined : process.env.DALAN_HOST_CHECK_UNIT_SUFFIX;
80
+ if (suffix && !/^[a-zA-Z0-9-]{1,80}$/.test(suffix)) throw new Error('invalid DALAN_HOST_CHECK_UNIT_SUFFIX');
81
+ const unit = `dot-bridge-host-check${suffix ? '-' + suffix : ''}.service`;
82
+ const args = ['--user', '--quiet', '--wait', '--pipe', '--collect', `--unit=${unit}`, ...properties.map(p => `--property=${p}`), '--', process.execPath, service];
81
83
  const started=performance.now();
82
84
  const child = spawn('/usr/bin/systemd-run', args, { stdio: ['pipe', 'pipe', 'pipe'] });
83
85
  onSpawned();
84
86
  child.stdin.write(serialized+'\n');
85
- let buffer = '', message = null, stopped = null, pid = null, diagnostic = '', callbackError = null, cancellationSent = false;
87
+ let buffer = '', message = null, stopped = null, pid = null, diagnostic = '', callbackError = null, cancellationSent = false, cpuExceeded = false;
86
88
  const launched = [];
87
89
  const partial = new Map();
88
90
  let partialUsage = null;
@@ -106,16 +108,20 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
106
108
  if (event.event === 'pid') pid = event.pid;
107
109
  if (event.event === 'started' && phases.some(p => p.name === event.phase)) {
108
110
  launched.push(event.phase);
109
- if (onStarted) Promise.resolve(onStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
111
+ if (onStarted) Promise.resolve(onStarted({ pid, unit, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
110
112
  }
111
- if (event.event === 'output_started' && onOutputStarted) Promise.resolve(onOutputStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
113
+ if (event.event === 'output_started' && onOutputStarted) Promise.resolve(onOutputStarted({ pid, unit, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
112
114
  if (event.event === 'partial' && launched.includes(event.phase)) {
113
115
  const chunks = partial.get(event.phase) ?? [];
114
116
  chunks.push(Buffer.from(event.output, 'base64'));
115
117
  partial.set(event.phase, chunks);
116
118
  partialUsage = event.usage;
117
119
  }
118
- if (event.event === 'result') message = event.result;
120
+ if (event.event === 'result') {
121
+ // Both supervisors report here; EOF cleanup cannot undo an observed limit.
122
+ cpuExceeded ||= event.result?.error === 'budget exceeded: cpu';
123
+ message = event.result;
124
+ }
119
125
  if (event.event === 'stopped') stopped = event.stop;
120
126
  } catch { diagnostic = 'invalid supervisor response'; }
121
127
  }
@@ -129,10 +135,10 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
129
135
  if (callbackError) throw callbackError;
130
136
  // ExecStopPost runs after systemd has killed/reaped every process in the unit,
131
137
  // even on OOM, RuntimeMaxSec, or loss of the main supervisor. No PID sweep or
132
- // application TTL can release a still-running reservation.
138
+ // application TTL can certify a still-running tree as stopped.
133
139
  const stopEvidence=resolveHostStopEvidence(receipts,stopped);
134
140
  const stop = { verified: stopEvidence?.verified === true, reason: stopEvidence?.verified ? 'systemd_control_group_stopped' : 'service_stop_not_observed', service_result: stopped?.result ?? null, invocation_id: stopEvidence?.invocationId ?? stopped?.invocation_id ?? null, remaining_pids: stopEvidence?.remaining_pids ?? stopped?.remaining_pids ?? null, oom_kill: stopped?.oom_kill ?? null };
135
- let error = message?.error ?? null;
141
+ let error = cpuExceeded ? 'budget exceeded: cpu' : message?.error ?? null;
136
142
  if (stopped?.oom_kill > 0 || stopped?.result === 'oom-kill') error = 'budget exceeded: memory';
137
143
  else if (stopped?.result === 'timeout') error = 'budget exceeded: wall';
138
144
  else if (stopped && !message) error = stopped.result === 'signal' ? 'supervisor interrupted' : `host preparation failed: ${diagnostic.trim() || stopped.exit_status || 'supervisor exited without a receipt'}`;
@@ -145,5 +151,5 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
145
151
  const bytes = Buffer.concat(phaseResults.map(p => p.bytes)).subarray(0, budgets.output_bytes);
146
152
  const notStarted=provesHostNotStarted({spawnError:exit.error,pid,stopped}); // stderr is not trusted for this decision.
147
153
  const usage = message?.usage ? { ...partialUsage, ...message.usage } : partialUsage;
148
- return { dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
154
+ return { unit, dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
149
155
  }
@@ -20,10 +20,10 @@ export function hostCheckAuthorization(repo, checkId, expectedSpec = null) {
20
20
  return { spec };
21
21
  }
22
22
 
23
- export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null) {
23
+ export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null,excludedPathsAbsent=false) {
24
24
  const scope=assignment.scope_paths;
25
25
  const narrow=Array.isArray(scope)&&scope.length&&!scope.some(p=>p.replace(/^\.\//,'').replace(/\/$/,'')==='.');
26
- if(narrow||assignment.scope_excluded?.length) {
26
+ if(narrow||(assignment.scope_excluded?.length&&!excludedPathsAbsent)) {
27
27
  return 'scope_paths_read_isolation_unavailable: this executor exposes the whole checkout; a check needs an owner-approved repository-wide read grant';
28
28
  }
29
29
  if(sensitivePolicyPaths().error) return 'sensitive_policy_unavailable: restore a valid mode-0600 submission policy before running host checks';
@@ -2,12 +2,11 @@ import fs from 'node:fs';
2
2
  import {spawnSync} from 'node:child_process';
3
3
  import {readHostStart,writeHostReverify,readVerifiedHostStop,validBootId} from './host-budget-receipts.mjs';
4
4
  import {readCgroupProcesses} from './host-cgroup.mjs';
5
- import {HOST_UNIT} from './host-budget.mjs';
6
5
 
7
6
  const currentBootId=()=>fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim();
8
7
  // Only "inactive" or "failed" shows the unit is gone. Any other answer, error or timeout counts as still active.
9
- function hostUnitInactive() {
10
- const r=spawnSync('/usr/bin/systemctl',['--user','is-active',HOST_UNIT],{encoding:'utf8',timeout:5000});
8
+ function hostUnitInactive(unit) {
9
+ const r=spawnSync('/usr/bin/systemctl',['--user','is-active',unit],{encoding:'utf8',timeout:5000});
11
10
  return !r.error&&['inactive','failed'].includes((r.stdout??'').trim());
12
11
  }
13
12
  // A missing cgroup directory means no process remains. Any other read error propagates and keeps the stop unverified.
@@ -32,7 +31,10 @@ export function reverifyHostStop({receiptDir,checkRunId},{bootId=currentBootId,u
32
31
  if(!validBootId(now)) return null;
33
32
  let basis;
34
33
  if(now!==start.boot_id) basis='boot_changed';
35
- else if(typeof start.cgroup==='string'&&unitInactive()===true) {
34
+ else if(typeof start.cgroup==='string') {
35
+ // The trusted start receipt records the exact unit, including legacy names.
36
+ const unit=start.cgroup.split('/').at(-1);
37
+ if(!/^dot-bridge-host-check(?:-[a-zA-Z0-9-]+)?\.service$/.test(unit)||unitInactive(unit)!==true) return null;
36
38
  const remaining=scan('/sys/fs/cgroup'+start.cgroup);
37
39
  if(Array.isArray(remaining)&&remaining.length===0) basis='cgroup_empty';
38
40
  }
@@ -129,8 +129,10 @@ function runIsolatedCheck(check,checkoutDir,runnerRoot,repoName) {
129
129
  fs.mkdirSync(sourceCopyDir,{mode:0o700});
130
130
  const masked=sensitiveMasks(checkoutDir,repoName,sourceCopyDir);
131
131
  const request={checkout_dir:checkoutDir,runner_root:root,argv:check.argv,github_repo:repoName,maskPaths:masked.paths,sourceExemptions:masked.sourceExemptions};
132
- const env={PATH:'/usr/bin:/bin',HOME:path.join(root,'home'),TMPDIR:path.join(root,'tmp'),LANG:'C.UTF-8',LC_ALL:'C.UTF-8',TZ:'UTC',NODE_ENV:'production',DALAN_WORKSPACE_ROOT:path.join(root,'workspace'),DALAN_INTEGRATOR_SCRATCH_ROOT:buildScratch};
132
+ const testSuffix=process.env.NODE_ENV!=='production'&&process.env.DALAN_HOST_CHECK_UNIT_SUFFIX;
133
+ const env={PATH:'/usr/bin:/bin',HOME:path.join(root,'home'),TMPDIR:path.join(root,'tmp'),LANG:'C.UTF-8',LC_ALL:'C.UTF-8',TZ:'UTC',NODE_ENV:testSuffix?'test':'production',DALAN_WORKSPACE_ROOT:path.join(root,'workspace'),DALAN_INTEGRATOR_SCRATCH_ROOT:buildScratch};
133
134
  if(readEnv('DALAN_HOST_CHECKS')==='1') env.DALAN_HOST_CHECKS='1';
135
+ if(testSuffix) env.DALAN_HOST_CHECK_UNIT_SUFFIX=testSuffix;
134
136
  if(process.env.XDG_RUNTIME_DIR) env.XDG_RUNTIME_DIR=process.env.XDG_RUNTIME_DIR;
135
137
  if(process.env.DBUS_SESSION_BUS_ADDRESS) env.DBUS_SESSION_BUS_ADDRESS=process.env.DBUS_SESSION_BUS_ADDRESS;
136
138
  fs.mkdirSync(env.HOME,{recursive:true,mode:0o700});
@@ -0,0 +1,61 @@
1
+ // The redirect-URI policy of the built-in authorization server. It is a pure function of the URI's own properties:
2
+ // no I/O, no client name, no brand, no list of vendors. Who may connect is decided by the owner's approval of one pairing
3
+ // code and the redirect shown with it, not by this file. This file only refuses URIs that could not be a safe browser target.
4
+ //
5
+ // Accepted:
6
+ // - HTTPS, a dotted DNS host in lower-case ASCII (punycode for IDN) that is not an IP address, no userinfo, no fragment,
7
+ // canonical spelling, a fixed query kept byte for byte.
8
+ // - Native loopback (RFC 8252): http://127.0.0.1, http://[::1] or exactly http://localhost, any port, a canonical path, no query.
9
+ // Everything else (other schemes, remote HTTP, wildcards, IP-literal HTTPS, aliases of loopback) is refused.
10
+
11
+ const MAX_LENGTH = 512;
12
+ const UNSAFE = /[\p{C}\p{Z}\\]/u; // controls, format and separator characters (bidi marks, spaces, NUL) and backslash
13
+ const HTTPS_HOST = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
14
+ const LOOPBACK = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(?::([0-9]+))?(\/[A-Za-z0-9._~\-/]*)$/;
15
+
16
+ const refuse = reason => ({ ok: false, reason });
17
+
18
+ export function validateRedirectUri(uri) {
19
+ if (typeof uri !== 'string' || !uri) return refuse('redirect URI must be a non-empty string');
20
+ if (uri.length > MAX_LENGTH) return refuse(`redirect URI is longer than ${MAX_LENGTH} characters`);
21
+ if (UNSAFE.test(uri)) return refuse('redirect URI has control, space, separator or backslash characters');
22
+ if (uri.includes('#')) return refuse('redirect URI must not have a fragment');
23
+ if (uri.includes('*')) return refuse('redirect URI must not contain a wildcard');
24
+ let url;
25
+ try { url = new URL(uri); } catch { return refuse('redirect URI is not a valid URL'); }
26
+ // The registered string is the one the client will send back. It must already be in canonical form: the parser may not
27
+ // rewrite case, default ports, "." and ".." segments, escapes or numeric host spellings behind our back.
28
+ if (url.href !== uri) return refuse('redirect URI is not in canonical spelling');
29
+ if (url.username || url.password) return refuse('redirect URI must not carry credentials');
30
+ if (url.protocol === 'https:') {
31
+ const host = url.hostname;
32
+ if (!HTTPS_HOST.test(host)) return refuse('HTTPS redirect needs a dotted lower-case ASCII host name');
33
+ if (/^[0-9]+$/.test(host.slice(host.lastIndexOf('.') + 1))) return refuse('HTTPS redirect must use a host name, not an IP address');
34
+ if (host === 'localhost' || host.endsWith('.localhost')) return refuse('HTTPS redirect must not name localhost');
35
+ return { ok: true, kind: 'https', origin: url.origin, host, uri, punycode: host.split('.').some(label => label.startsWith('xn--')) };
36
+ }
37
+ if (url.protocol === 'http:') {
38
+ const match = LOOPBACK.exec(uri);
39
+ if (!match) return refuse('HTTP is only allowed for http://127.0.0.1, http://[::1] or http://localhost');
40
+ const [, host, port, pathname] = match;
41
+ if (port !== undefined && (String(Number(port)) !== port || Number(port) < 1 || Number(port) > 65535)) return refuse('loopback port must be from 1 to 65535');
42
+ const segments = pathname.split('/').slice(1);
43
+ if (pathname !== '/' && segments.some(s => !s || s === '.' || s === '..')) return refuse('loopback path must have exact canonical segments');
44
+ return { ok: true, kind: 'loopback', origin: `http://${host}`, host, uri, punycode: false };
45
+ }
46
+ return refuse('redirect URI must use https, or http on loopback');
47
+ }
48
+
49
+ // The origin that groups review and revocation. It never grants anything on its own. Null when the URI is not valid.
50
+ export const redirectOrigin = uri => { const r = validateRedirectUri(uri); return r.ok ? r.origin : null; };
51
+
52
+ // Does a requested redirect match one the client registered? Exact string, or native loopback where only the port differs.
53
+ export function matchRegisteredRedirect(registered, requested) {
54
+ if (!Array.isArray(registered) || typeof requested !== 'string') return false;
55
+ return registered.some(uri => {
56
+ if (uri === requested) return true;
57
+ const a = validateRedirectUri(uri), b = validateRedirectUri(requested);
58
+ if (!a.ok || !b.ok || a.kind !== 'loopback' || b.kind !== 'loopback') return false;
59
+ return a.host === b.host && new URL(uri).pathname === new URL(requested).pathname;
60
+ });
61
+ }