@tnunamak/dalan 0.6.1 → 0.7.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/CHANGELOG.md +32 -0
- package/README.md +25 -64
- package/bin/dalan.mjs +9 -0
- package/bin/dot-worker.mjs +16 -2
- package/docs/chatgpt-worker-onboarding.md +10 -14
- package/docs/claude-worker-onboarding.md +9 -8
- package/docs/codex-to-muse.md +21 -35
- package/docs/connect-chatgpt.md +10 -16
- package/docs/dalan-upgrade.md +4 -2
- package/docs/local-agent-mcp.md +24 -4
- package/docs/manual-setup.md +2 -2
- package/docs/operations.md +10 -11
- package/docs/pull-workers.md +1 -2
- package/docs/service-setup.md +99 -145
- package/docs/setup-reference.md +5 -5
- package/docs/worker-clients.md +4 -4
- package/package.json +2 -3
- package/scripts/dalan-try-selfcheck.mjs +8 -7
- package/scripts/worker-bridge-setup.mjs +91 -81
- package/src/as-store.mjs +5 -3
- package/src/as.mjs +35 -26
- package/src/auth-check.mjs +53 -0
- package/src/cli-help.mjs +20 -15
- package/src/client-approval.mjs +57 -0
- package/src/client-convenience.mjs +166 -0
- package/src/client-conveniences.json +106 -0
- package/src/client-conveniences.schema.json +97 -0
- package/src/connect-cli.mjs +5 -5
- package/src/default-home.mjs +36 -0
- package/src/follow-current.mjs +25 -0
- package/src/gozar-routes.mjs +314 -0
- package/src/redirect-policy.mjs +61 -0
- package/src/route-setting.mjs +71 -12
- package/src/server.mjs +38 -2
- package/src/service-auto-update.mjs +68 -0
- package/src/service-launchd.mjs +166 -0
- package/src/service-update-gate.mjs +20 -0
- package/src/service-update-lock.mjs +22 -0
- package/src/service-update-runtime.mjs +290 -0
- package/src/service-update.mjs +399 -0
- package/src/service.mjs +241 -58
- package/src/setup.mjs +55 -44
- package/src/try-exposure.mjs +7 -657
- package/src/try-hosted.mjs +71 -101
- package/src/try-selfcheck.mjs +15 -8
- package/src/try.mjs +9 -13
- package/scripts/lib/expose-tailscale.mjs +0 -408
- package/src/try-hosted-clients.mjs +0 -46
|
@@ -0,0 +1,314 @@
|
|
|
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
|
+
if (!code) return { code: null, line: safeDiagnostic(String(error?.message ?? error), 240), fix: null };
|
|
114
|
+
const action = error.nextAction ?? null;
|
|
115
|
+
const fix = action ? [action.label, action.instructions, action.href].filter(Boolean).join(' - ') : null;
|
|
116
|
+
const detail = code === 'runtime_missing' ? error.message : `${EXPLAIN[code]}${error.message && !EXPLAIN[code].includes(error.message) ? ` (${safeDiagnostic(error.message, 160)})` : ''}`;
|
|
117
|
+
return { code, line: detail, fix };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---- a session route (`dalan try --public`) --------------------------------------------------------------------------------------------
|
|
121
|
+
// `consent(candidate)` shows the disclosure and resolves true only on an explicit yes. The route lasts for the trial and is closed with it.
|
|
122
|
+
const abortError = signal => signal.reason ?? Object.assign(new Error('stopped'), { name: 'AbortError', code: 'ABORT_ERR' });
|
|
123
|
+
|
|
124
|
+
// `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.
|
|
125
|
+
export async function startSessionRoute({ gozar, query, consent, signal, wait = 'verified', pick = pickCandidate }) {
|
|
126
|
+
signal?.throwIfAborted();
|
|
127
|
+
const catalog = await gozar.catalogRoutes(query);
|
|
128
|
+
signal?.throwIfAborted();
|
|
129
|
+
const candidate = pick(catalog);
|
|
130
|
+
if (!candidate) throw noCandidateError(catalog);
|
|
131
|
+
if (!await consent(candidate, catalog)) throw Object.assign(new RouteError('consent_required', 'No public route was started because consent was not given.'), { tryKind: 'consent' });
|
|
132
|
+
let view;
|
|
133
|
+
try { view = await gozar.expose({ ...query, approval: approvalFor(candidate), wait }); } catch (error) { throw error; }
|
|
134
|
+
const handle = view?.handle;
|
|
135
|
+
const closeNow = () => gozar.closeRoute({ home: query.home, handle, mode: 'remove' }).catch(() => null);
|
|
136
|
+
let url; try { url = new URL(view.origin); } catch { /* rejected below */ }
|
|
137
|
+
if (!handle || !url || url.protocol !== 'https:' || url.origin !== view.origin || (wait === 'verified' && (view.state !== 'usable' || view.verification?.status !== 'verified'))) {
|
|
138
|
+
if (handle) await closeNow();
|
|
139
|
+
throw new RouteError('verification_failed', 'Gozar did not return a verified HTTPS origin for this route.');
|
|
140
|
+
}
|
|
141
|
+
// Ctrl-C while Gozar was starting: the route exists now, so it is closed before the abort is reported.
|
|
142
|
+
if (signal?.aborted) { await closeNow(); throw abortError(signal); }
|
|
143
|
+
return sessionRoute({ gozar, home: query.home, view, candidate });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function sessionRoute({ gozar, home, view, candidate }) {
|
|
147
|
+
const { handle, origin } = view;
|
|
148
|
+
const watch = new AbortController();
|
|
149
|
+
let reason = null, resolveEnded;
|
|
150
|
+
const exited = new Promise(resolve => { resolveEnded = resolve; });
|
|
151
|
+
const end = why => { if (reason === null) reason = why; resolveEnded(reason); };
|
|
152
|
+
const watcher = (async () => {
|
|
153
|
+
try {
|
|
154
|
+
for await (const event of gozar.watchRoutes({ home, handle, signal: watch.signal })) {
|
|
155
|
+
const route = event.route;
|
|
156
|
+
// A route Gozar has not verified yet (the bridge was still starting when it looked) is pending, not lost. Dalan's own public
|
|
157
|
+
// identity check covers a route that never works; only a lost or moved route ends the trial here.
|
|
158
|
+
if (route.state === 'unverified' && !route.published) continue;
|
|
159
|
+
if (event.type === 'snapshot' && route.state === 'usable' && route.published === origin) continue;
|
|
160
|
+
if (route.state === 'usable' && route.published === origin) continue;
|
|
161
|
+
if (route.state === 'address_changed' || (route.published && route.published !== origin)) end('rotated');
|
|
162
|
+
else end('lost');
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (!watch.signal.aborted) end('lost');
|
|
166
|
+
} catch (error) { if (!watch.signal.aborted) end('lost'); }
|
|
167
|
+
})();
|
|
168
|
+
let stopped = null;
|
|
169
|
+
return {
|
|
170
|
+
origin, handle, view, candidate, exited, endedBecause: () => reason,
|
|
171
|
+
stop() { // idempotent; ends the watch first, then asks Gozar to remove exactly this handle
|
|
172
|
+
stopped ??= (async () => {
|
|
173
|
+
watch.abort(); await watcher.catch(() => {});
|
|
174
|
+
try {
|
|
175
|
+
const closed = await gozar.closeRoute({ home, handle, mode: 'remove' });
|
|
176
|
+
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.` };
|
|
177
|
+
return closed.state === 'released' ? { removed: true } : { removed: false, detail: `Gozar reports the route is ${closed.state}; its removal could not be confirmed.` };
|
|
178
|
+
} catch (error) {
|
|
179
|
+
if (error?.code === 'route_not_found') return { removed: true };
|
|
180
|
+
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.' };
|
|
181
|
+
return { removed: false, detail: `Gozar could not confirm the route removal (${explainRouteError(error).line}).` };
|
|
182
|
+
}
|
|
183
|
+
})();
|
|
184
|
+
return stopped;
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function noCandidateError(catalog) {
|
|
190
|
+
const needsSetup = catalog.candidates.find(c => c.setup.state === 'action-required');
|
|
191
|
+
if (needsSetup) return new RouteError('setup_required', 'A route needs one setup step before it can start.', { nextAction: needsSetup.setup.actions[0] ?? null });
|
|
192
|
+
if (catalog.candidates.length && catalog.candidates.every(c => c.setup.state === 'unsupported')) return new RouteError('unsupported', 'No route is supported on this computer yet.');
|
|
193
|
+
return new RouteError('requirements_unsatisfied', 'No route satisfies what Dalan needs.');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---- durable routes and external services ----------------------------------------------------------------------------------------------
|
|
197
|
+
// 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.
|
|
198
|
+
export async function ensureDurableRoute({ gozar, query, consent, reconsent = false, pick = pickCandidate }) {
|
|
199
|
+
try { return await gozar.ensureRoute({ ...query, ...(reconsent ? { reconsent: true } : {}) }); }
|
|
200
|
+
catch (error) { if (error?.code !== 'consent_required') throw error; }
|
|
201
|
+
const catalog = await gozar.catalogRoutes(query);
|
|
202
|
+
const candidate = pick(catalog);
|
|
203
|
+
if (!candidate) throw noCandidateError(catalog);
|
|
204
|
+
if (!await consent(candidate, catalog)) throw Object.assign(new RouteError('consent_required', 'The route was not started because consent was not given.'), { tryKind: 'consent' });
|
|
205
|
+
return gozar.ensureRoute({ ...query, approval: approvalFor(candidate), ...(reconsent ? { reconsent: true } : {}) });
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Registers the owner's own origin (a route the owner runs) and reads it back through the same view as any other route.
|
|
209
|
+
export async function registerExternalService({ gozar, home, origin, target, verifyCmd }) {
|
|
210
|
+
const reply = await gozar.addService({ origin, target, home, ...(verifyCmd ? { verifyCmd } : {}) });
|
|
211
|
+
const route = reply?.route;
|
|
212
|
+
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.');
|
|
213
|
+
const view = await gozar.routeStatus({ home, handle: { kind: 'external', id: origin, generation: 1 } });
|
|
214
|
+
return { route, view };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ---- the Host a bridge accepts -----------------------------------------------------------------------------------------------------------
|
|
218
|
+
// A route may forward with the default port written out (`name:443`). The configured origin names no port, so both forms are the same
|
|
219
|
+
// authority. Nothing else changes: another host, another port or a prefix/suffix of the name stays refused.
|
|
220
|
+
export function canonicalHost(hostHeader, origin) {
|
|
221
|
+
const url = new URL(origin);
|
|
222
|
+
const host = String(hostHeader ?? '').toLowerCase();
|
|
223
|
+
if (url.protocol === 'https:' && url.port === '' && host === `${url.hostname.toLowerCase()}:443`) return url.host;
|
|
224
|
+
return hostHeader;
|
|
225
|
+
}
|
|
226
|
+
export function normalizeRequestHost(req, origin) {
|
|
227
|
+
const canonical = canonicalHost(req.headers.host, origin);
|
|
228
|
+
if (canonical !== req.headers.host) req.headers.host = canonical;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ---- moving a 0.6 route to Gozar ----------------------------------------------------------------------------------------------------------
|
|
232
|
+
// Fence the old exposure code -> adopt while Dalan serves the proof -> restart -> commit v2 settings. Every step is journaled and
|
|
233
|
+
// fsynced. Anything uncertain stops with the old ingress and the old sign-in state untouched; there is no release-and-recreate fallback.
|
|
234
|
+
export const CRASH_POINTS = Object.freeze(['after-prepared', 'after-fence', 'after-fence-journal', 'after-adopt', 'after-adopt-journal', 'after-restart', 'after-commit-setting']);
|
|
235
|
+
|
|
236
|
+
export async function migrateLegacyRoute({
|
|
237
|
+
gozar, env = process.env, gozarHome, routeName, routeId, origin, target, bridgeHome, stateFiles,
|
|
238
|
+
fence, unfence, restart, authenticatedCheck, consent, crash = () => {}, generation,
|
|
239
|
+
}) {
|
|
240
|
+
const hand = { from: `${OWNER}-legacy`, generation };
|
|
241
|
+
const q = (extra = {}) => buildQuery({ home: gozarHome, target, usage: { kind: 'durable', routeId }, route: routeName, origin, address: 'stable', ...extra });
|
|
242
|
+
const journal = phase => writeJournal({ phase, generation, origin, routeId }, env);
|
|
243
|
+
// 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.
|
|
244
|
+
const halt = async (reason, extra = {}) => { await unfence().catch(() => {}); removeJournal(env); return { migrated: false, reason, ...extra }; };
|
|
245
|
+
|
|
246
|
+
const existing = readJournal(env);
|
|
247
|
+
if (existing?.phase === 'dalan-committed') { removeJournal(env); return { migrated: true, resumed: true }; }
|
|
248
|
+
journal('prepared'); crash('after-prepared');
|
|
249
|
+
|
|
250
|
+
// Already adopted by an earlier, interrupted run? An ensure without approval returns an existing pin and can never create one.
|
|
251
|
+
let adopted = null;
|
|
252
|
+
if (existing) {
|
|
253
|
+
try { const view = await gozar.ensureRoute(q()); if (view.origin === origin) adopted = view; }
|
|
254
|
+
catch (error) { if (error?.code !== 'consent_required' && error?.code !== 'route_not_found') throw error; }
|
|
255
|
+
}
|
|
256
|
+
if (!adopted) {
|
|
257
|
+
// Gozar reads the old state where it was written: lift an earlier fence, inspect, then fence again.
|
|
258
|
+
await unfence();
|
|
259
|
+
const inspected = await gozar.inspectLegacyRoute({ home: gozarHome, owner: OWNER, source: { stateFiles: stateFiles() }, origin, target });
|
|
260
|
+
if (inspected.state !== 'adoptable') return halt(inspected.reasonCode ?? inspected.state, { nextAction: inspected.nextAction ?? null });
|
|
261
|
+
try { await fence(); } catch (error) { return halt(`the old exposure could not be fenced (${safeDiagnostic(error.message, 160)})`); }
|
|
262
|
+
crash('after-fence'); journal('old-owner-fenced'); crash('after-fence-journal');
|
|
263
|
+
const intent = q({ intent: 'adopt', migrationRef: inspected.migrationRef });
|
|
264
|
+
const catalog = await gozar.catalogRoutes(intent);
|
|
265
|
+
const candidate = pickCandidate(catalog);
|
|
266
|
+
if (!candidate) return halt('Gozar offered no route to adopt this origin');
|
|
267
|
+
if (!await consent(candidate, catalog)) return halt('adoption was not approved');
|
|
268
|
+
try { adopted = await gozar.adoptRoute({ ...intent, origin, approval: approvalFor(candidate), handover: hand }); }
|
|
269
|
+
catch (error) { return halt(`Gozar did not adopt the route (${explainRouteError(error).line}); the old route is unchanged`); }
|
|
270
|
+
crash('after-adopt');
|
|
271
|
+
}
|
|
272
|
+
journal('gozar-adopted'); crash('after-adopt-journal');
|
|
273
|
+
|
|
274
|
+
// Restart on the same home and prove the existing credentials still work through the same origin before committing.
|
|
275
|
+
let ok = false;
|
|
276
|
+
try { await restart(); crash('after-restart'); ok = await authenticatedCheck(); } catch (error) { if (error?.simulatedCrash) throw error; ok = false; }
|
|
277
|
+
if (!ok) {
|
|
278
|
+
// Two-phase hand-back: persist Gozar's opaque transfer, let the previous owner take over, then confirm. Never two mutators.
|
|
279
|
+
const back = await gozar.releaseRoute({ routeId, mode: 'hand-back', home: gozarHome });
|
|
280
|
+
writeJournal({ phase: 'gozar-adopted', generation, origin, routeId, transfer: back.transfer }, env);
|
|
281
|
+
await unfence();
|
|
282
|
+
await gozar.confirmHandBack({ routeId, transfer: back.transfer, home: gozarHome });
|
|
283
|
+
removeJournal(env);
|
|
284
|
+
return { migrated: false, reason: 'the existing sign-in did not work through the new route; the old route was handed back' };
|
|
285
|
+
}
|
|
286
|
+
writeRouteSetting({ version: 2, requirements: dalanRequirements({ address: 'stable' }), gozarHome, routeName: routeName ?? null, routeId, origin, bridgeHome: bridgeHome ?? null }, env);
|
|
287
|
+
crash('after-commit-setting');
|
|
288
|
+
journal('dalan-committed'); removeJournal(env);
|
|
289
|
+
return { migrated: true, origin, routeId, view: adopted };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// 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
|
|
293
|
+
// the record can no longer act on the rule. Unfence moves it back. Both are repeatable, and neither touches the rule itself.
|
|
294
|
+
export const FENCE_SUFFIX = '.gozar-fence';
|
|
295
|
+
export function legacyRecordFiles(dir) {
|
|
296
|
+
let names = []; try { names = fs.readdirSync(dir); } catch { return []; }
|
|
297
|
+
return names.filter(name => /^dot-bridge-.+\.exposure\.json(\.gozar-fence)?$/.test(name)).map(name => path.join(dir, name));
|
|
298
|
+
}
|
|
299
|
+
export function fenceLegacyRecords(dir) {
|
|
300
|
+
const moved = [];
|
|
301
|
+
for (const file of legacyRecordFiles(dir)) {
|
|
302
|
+
if (file.endsWith(FENCE_SUFFIX)) { moved.push(file); continue; }
|
|
303
|
+
const stat = fs.lstatSync(file);
|
|
304
|
+
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`);
|
|
305
|
+
fs.renameSync(file, `${file}${FENCE_SUFFIX}`); moved.push(`${file}${FENCE_SUFFIX}`);
|
|
306
|
+
}
|
|
307
|
+
if (!moved.length) throw new Error('no old exposure record to fence; ownership is unclear');
|
|
308
|
+
return moved;
|
|
309
|
+
}
|
|
310
|
+
export function unfenceLegacyRecords(dir) {
|
|
311
|
+
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));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export { readRouteSetting };
|
|
@@ -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
|
+
}
|
package/src/route-setting.mjs
CHANGED
|
@@ -1,24 +1,83 @@
|
|
|
1
|
-
// The owner's saved
|
|
2
|
-
// trial home, so a trial
|
|
3
|
-
//
|
|
1
|
+
// The owner's saved public-route choice, written by `dalan setup`. One small file in the user's config directory, outside every
|
|
2
|
+
// trial home, so a deleted trial never loses it and a trial never writes it.
|
|
3
|
+
//
|
|
4
|
+
// Version 2 stores only what Dalan owns: the requirements it asked for, the Gozar state home, the Gozar route name (an opaque
|
|
5
|
+
// string that Dalan never interprets), the durable route id, the pinned origin and the bridge home. Everything about how a route is
|
|
6
|
+
// provided belongs to Gozar. A file of any other version fails closed: it is reported, never guessed at or rewritten.
|
|
4
7
|
import fs from 'node:fs';
|
|
5
8
|
import os from 'node:os';
|
|
6
9
|
import path from 'node:path';
|
|
10
|
+
import { randomBytes } from 'node:crypto';
|
|
7
11
|
|
|
8
|
-
export const
|
|
12
|
+
export const SETTING_VERSION = 2;
|
|
13
|
+
const KEYS = ['version', 'requirements', 'gozarHome', 'routeName', 'routeId', 'origin', 'bridgeHome'];
|
|
9
14
|
export const routeSettingPath = (env = process.env) => path.join(env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config'), 'dalan', 'route.json');
|
|
15
|
+
export const migrationJournalPath = (env = process.env) => path.join(path.dirname(routeSettingPath(env)), 'route-migration.json');
|
|
16
|
+
|
|
17
|
+
const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
18
|
+
const nullableString = value => value === null || (typeof value === 'string' && value.length > 0);
|
|
19
|
+
|
|
20
|
+
// Throws a message when a setting is not exactly the version-2 shape.
|
|
21
|
+
export function validateSetting(value) {
|
|
22
|
+
if (!isRecord(value)) throw new Error('the saved route setting is not an object');
|
|
23
|
+
if (value.version !== SETTING_VERSION) throw new Error(`the saved route setting has version ${JSON.stringify(value.version)}; this Dalan reads version ${SETTING_VERSION}`);
|
|
24
|
+
const extra = Object.keys(value).filter(key => !KEYS.includes(key));
|
|
25
|
+
if (extra.length) throw new Error(`the saved route setting has unknown fields (${extra.join(', ')})`);
|
|
26
|
+
if (!isRecord(value.requirements)) throw new Error('the saved route setting has no requirements');
|
|
27
|
+
for (const key of ['gozarHome']) if (typeof value[key] !== 'string' || !path.isAbsolute(value[key])) throw new Error(`the saved route setting needs an absolute ${key}`);
|
|
28
|
+
for (const key of ['routeName', 'routeId', 'origin', 'bridgeHome']) if (!nullableString(value[key])) throw new Error(`the saved route setting has an invalid ${key}`);
|
|
29
|
+
if (value.origin !== null) {
|
|
30
|
+
let url; try { url = new URL(value.origin); } catch { /* checked below */ }
|
|
31
|
+
if (!url || url.protocol !== 'https:' || url.origin !== value.origin) throw new Error('the saved route setting origin is not an https origin');
|
|
32
|
+
}
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// What the file holds: { state: 'none' } (no file), { state: 'current', setting } (version 2) or { state: 'legacy' | 'unreadable' }.
|
|
37
|
+
// A legacy file is any file that is not version 2 (the 0.6 shape had no version). It is never edited in place.
|
|
38
|
+
export function inspectRouteSetting(env = process.env) {
|
|
39
|
+
let text;
|
|
40
|
+
try { text = fs.readFileSync(routeSettingPath(env), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return { state: 'none' }; return { state: 'unreadable', reason: error.code ?? error.message }; }
|
|
41
|
+
let value;
|
|
42
|
+
try { value = JSON.parse(text); } catch { return { state: 'unreadable', reason: 'not JSON' }; }
|
|
43
|
+
if (isRecord(value) && !('version' in value)) return { state: 'legacy', value };
|
|
44
|
+
try { return { state: 'current', setting: validateSetting(value) }; } catch (error) { return { state: 'unreadable', reason: error.message }; }
|
|
45
|
+
}
|
|
10
46
|
|
|
11
47
|
export function readRouteSetting(env = process.env) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return ROUTE_CHOICES.includes(route) ? route : null;
|
|
15
|
-
} catch { return null; }
|
|
48
|
+
const found = inspectRouteSetting(env);
|
|
49
|
+
return found.state === 'current' ? found.setting : null;
|
|
16
50
|
}
|
|
17
51
|
|
|
18
|
-
|
|
19
|
-
if (!ROUTE_CHOICES.includes(route)) throw new Error(`unknown route ${JSON.stringify(route)}`);
|
|
20
|
-
const file = routeSettingPath(env);
|
|
52
|
+
function writePrivateAtomic(file, text) {
|
|
21
53
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
22
|
-
|
|
54
|
+
const temporary = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
|
55
|
+
const fd = fs.openSync(temporary, 'wx', 0o600);
|
|
56
|
+
try { fs.writeSync(fd, text); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
57
|
+
fs.renameSync(temporary, file);
|
|
58
|
+
const dirFd = fs.openSync(path.dirname(file), 'r');
|
|
59
|
+
try { fs.fsyncSync(dirFd); } finally { fs.closeSync(dirFd); }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function writeRouteSetting(setting, env = process.env) {
|
|
63
|
+
validateSetting(setting);
|
|
64
|
+
const file = routeSettingPath(env);
|
|
65
|
+
writePrivateAtomic(file, `${JSON.stringify(Object.fromEntries(KEYS.map(key => [key, setting[key]])))}\n`);
|
|
23
66
|
return file;
|
|
24
67
|
}
|
|
68
|
+
|
|
69
|
+
// ---- the migration journal ---------------------------------------------------------------------------------------------------------
|
|
70
|
+
// One fsynced record per step of a move from a 0.6 route: prepared, old-owner-fenced, gozar-adopted, dalan-committed. `transfer` is
|
|
71
|
+
// Gozar's opaque hand-back data, written before the old owner takes over again.
|
|
72
|
+
export const JOURNAL_PHASES = ['prepared', 'old-owner-fenced', 'gozar-adopted', 'dalan-committed'];
|
|
73
|
+
export function writeJournal(journal, env = process.env) {
|
|
74
|
+
if (!JOURNAL_PHASES.includes(journal.phase)) throw new Error(`unknown migration phase ${journal.phase}`);
|
|
75
|
+
writePrivateAtomic(migrationJournalPath(env), `${JSON.stringify({ version: 1, ...journal })}\n`);
|
|
76
|
+
}
|
|
77
|
+
export function readJournal(env = process.env) {
|
|
78
|
+
let value;
|
|
79
|
+
try { value = JSON.parse(fs.readFileSync(migrationJournalPath(env), 'utf8')); } catch (error) { if (error.code === 'ENOENT') return null; throw new Error(`the route migration journal is unreadable (${error.code ?? 'not JSON'}); leaving the old route untouched`); }
|
|
80
|
+
if (!isRecord(value) || value.version !== 1 || !JOURNAL_PHASES.includes(value.phase)) throw new Error('the route migration journal has an unknown version or phase; leaving the old route untouched');
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
export function removeJournal(env = process.env) { fs.rmSync(migrationJournalPath(env), { force: true }); }
|
package/src/server.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { updateWindowOpen, refuseDuringUpdate } from './service-update-gate.mjs';
|
|
1
2
|
import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
2
3
|
import {inspect} from 'node:util';
|
|
3
4
|
import { loopbackRequestAllowed } from './loopback.mjs';
|
|
5
|
+
import { normalizeRequestHost } from './gozar-routes.mjs';
|
|
4
6
|
import { defaultPath,workspaceRoot,rootWarnings } from './paths.mjs';
|
|
5
7
|
import { readEnv } from './env.mjs';
|
|
6
8
|
import http from 'node:http';
|
|
@@ -211,7 +213,8 @@ const protocolServices=catalogProfile==='protocol-v0'?createProtocolServices(sto
|
|
|
211
213
|
const iconBytes=fs.readFileSync(new URL('../docs/t3-connector-icon.png',import.meta.url));
|
|
212
214
|
const iconSource=`data:image/png;base64,${iconBytes.toString('base64')}`;
|
|
213
215
|
if(Buffer.byteLength(iconSource)>10000) throw new Error('server icon exceeds 10 KB');
|
|
214
|
-
const
|
|
216
|
+
const packageVersion=JSON.parse(fs.readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
217
|
+
const serverInfo={name:catalogProfile==='legacy-v46'?'dot-bridge':'dalan',version:catalogProfile==='legacy-v46'?'0.2.0':packageVersion,icons:[{src:iconSource,mimeType:'image/png',sizes:['128x128']}]};
|
|
215
218
|
// A quiet-delivery job in profile mode has no T3 thread; its response must not carry the T3 fields. Legacy profile keeps them.
|
|
216
219
|
const withoutT3=response=>{ if(legacyProfile||response.delivery_mode!=='none') return response; const {t3_muted,thread_id,...rest}=response; return rest; };
|
|
217
220
|
function mayPrepareCheckMetadata(response,worker,subject=null) {
|
|
@@ -422,6 +425,17 @@ const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'da
|
|
|
422
425
|
// Same name mapping as the protected-resource metadata and the 401 challenge, so all three surfaces agree.
|
|
423
426
|
const advertisedScope=name=>wireScope(scopeFor(name),legacyScopeNames(oauth));
|
|
424
427
|
if(oauth) for(const item of tools) item.securitySchemes=[{type:'oauth2',scopes:[advertisedScope(item.name)]}];
|
|
428
|
+
// During an update, refuse a changed catalog before either listener can expose it.
|
|
429
|
+
const catalogGuardFile=path.join(configDir,'service-catalog.json');
|
|
430
|
+
if(fs.existsSync(catalogGuardFile)) {
|
|
431
|
+
const info=fs.lstatSync(catalogGuardFile);
|
|
432
|
+
if(!info.isFile()||info.isSymbolicLink()||(info.mode&0o777)!==0o600)throw new Error('service catalog guard mismatch');
|
|
433
|
+
const guard=JSON.parse(fs.readFileSync(catalogGuardFile,'utf8'));
|
|
434
|
+
const normalize=value=>Array.isArray(value)?value.map(normalize):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,normalize(value[key])])):value;
|
|
435
|
+
const ordered=catalogs=>Object.fromEntries(Object.keys(catalogs).sort().map(worker=>[worker,[...catalogs[worker]].sort((a,b)=>a.name.localeCompare(b.name))]));
|
|
436
|
+
const actual=Object.fromEntries([...workers.workers.keys()].map(worker=>[worker,catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,worker,'t3')):tools]));
|
|
437
|
+
if(guard.version!==packageVersion||JSON.stringify(normalize(ordered(guard.catalogs??{})))!==JSON.stringify(normalize(ordered(actual))))throw new Error('service catalog guard mismatch');
|
|
438
|
+
}
|
|
425
439
|
// A refusal that must stay tells the worker the next call and what to change; workers often do not retry a bare "invalid X".
|
|
426
440
|
const argumentFixes={
|
|
427
441
|
finish:{
|
|
@@ -950,8 +964,11 @@ const verifyService=builtinMode&&readEnv('DALAN_GOZAR_SERVICE')==='1'?createServ
|
|
|
950
964
|
const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)=>{
|
|
951
965
|
const outcome=req.url===publicPath?beginMcpOutcome(req,res,log,toolNames,!!oauth):null;
|
|
952
966
|
try {
|
|
967
|
+
// Updater window: no entry may acknowledge a write the rollback snapshot would erase. Clients retry after the commit.
|
|
968
|
+
if(updateWindowOpen()) return refuseDuringUpdate(res);
|
|
953
969
|
if(loopback && !loopbackRequestAllowed(req, `http://127.0.0.1:${port}`)) { log({kind:'mcp_inbound',status:403,route:'loopback',ua:uaToken(req)}); res.writeHead(403); res.end(); return; }
|
|
954
970
|
// Both authentication modes serve only the configured public Host, including discovery and verifier routes.
|
|
971
|
+
if(as||oauth) normalizeRequestHost(req,new URL(as?as.publicUrl:oauth.OAUTH_AUDIENCE).origin); // a route may send the default port written out (name:443)
|
|
955
972
|
if(as ? !as.hostOk(req) : oauth&&req.headers.host!==new URL(oauth.OAUTH_AUDIENCE).host) { log({kind:'mcp_inbound',status:421,route:'host',ua:uaToken(req)}); res.writeHead(421); res.end(); return; }
|
|
956
973
|
if(verifyService?.(req,res)) return;
|
|
957
974
|
if(!as && req.url==='/.well-known/oauth-protected-resource' && oauthMetadata && req.method==='GET') return json(res,200,protectedResource(oauthMetadata));
|
|
@@ -991,10 +1008,23 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
991
1008
|
let rejected=null, dryRequested=false;
|
|
992
1009
|
try {
|
|
993
1010
|
const raw=req.method==='POST'?await readBody(req):'',body=raw?JSON.parse(raw):{},url=new URL(req.url,'http://localhost');
|
|
1011
|
+
if(updateWindowOpen()&&!(req.method==='GET'&&url.pathname==='/service-check')) return refuseDuringUpdate(res);
|
|
994
1012
|
if(url.pathname.startsWith('/protocol/service/')) {
|
|
995
1013
|
if(!protocolServices||req.method!=='POST')return json(res,404,{error:'not found'});
|
|
996
1014
|
return json(res,200,await protocolServices.invoke(url.pathname.slice('/protocol/service/'.length),req.headers['x-protocol-service-capability'],body));
|
|
997
1015
|
}
|
|
1016
|
+
if(url.pathname==='/service-check'&&req.method==='GET') {
|
|
1017
|
+
adminOperator(req);
|
|
1018
|
+
const catalogs={};
|
|
1019
|
+
for(const worker of workers.workers.keys()) {
|
|
1020
|
+
const principal={worker,subject:'service-self-check',local:true};
|
|
1021
|
+
const initialized=await dispatch({method:'initialize',params:{protocolVersion:'2025-11-25'}},principal);
|
|
1022
|
+
if(!initialized.capabilities?.tools)throw new Error('service self-check: initialize failed');
|
|
1023
|
+
await dispatch({method:'ping'},principal);
|
|
1024
|
+
catalogs[worker]=(await dispatch({method:'tools/list'},principal)).tools;
|
|
1025
|
+
}
|
|
1026
|
+
return json(res,200,{version:packageVersion,catalogs,port:publicServer.address()?.port,self_check:true,update_protocol:1});
|
|
1027
|
+
}
|
|
998
1028
|
dryRequested=url.pathname==='/submit-preview';
|
|
999
1029
|
log({kind:'admin_call',route:url.pathname,method:req.method});
|
|
1000
1030
|
if(url.pathname==='/submit'&&(url.searchParams.get('dry_run')==='1'||body.dry_run===true)) throw new Error('dry run requires POST /submit-preview; /submit always submits');
|
|
@@ -1430,12 +1460,15 @@ function maintain() {
|
|
|
1430
1460
|
} catch(error) { log({kind:'maintenance_error',reason:error.message}); }
|
|
1431
1461
|
}
|
|
1432
1462
|
const runDrain=createDrainRunner(drain,log);
|
|
1433
|
-
store.recoverSends();
|
|
1434
1463
|
try { fs.unlinkSync(socket); } catch(e) { if(e.code!=='ENOENT') throw e; }
|
|
1435
1464
|
const adminListening=new Promise(resolve=>adminServer.listen(socket,()=>{fs.chmodSync(socket,0o600);console.log(`admin socket ${socket}`);resolve();}));
|
|
1436
1465
|
// Built-in mode sits behind a tunnel on this computer: only loopback may reach the listener.
|
|
1437
1466
|
const bindHost=readEnv('DALAN_BIND_HOST')||(as||loopbackOnly||loopback?'127.0.0.1':'0.0.0.0');
|
|
1438
1467
|
const publicListening=new Promise(resolve=>publicServer.listen(port,bindHost,()=>{console.log(`MCP listening on ${bindHost}:${publicServer.address().port}`);resolve();}));
|
|
1468
|
+
// Every background writer starts only when no update window is open, so a candidate restarted inside the window changes no state
|
|
1469
|
+
// the rollback snapshot would discard. Outside a window this runs at once, in the same order as before.
|
|
1470
|
+
function startBackground() {
|
|
1471
|
+
store.recoverSends();
|
|
1439
1472
|
// Cleanup removes worktrees and dependency caches; it starts only after both servers listen, and
|
|
1440
1473
|
// cleanupExpired is async and single-flight, so neither startup nor the hourly tick blocks requests.
|
|
1441
1474
|
if(workspace) {
|
|
@@ -1453,6 +1486,9 @@ const staleDays=(d=>Number.isFinite(d)&&d>0?d:7)(Number(readEnv('DALAN_DECISION_
|
|
|
1453
1486
|
const sweepStale=()=>{try{const ids=store.sweepStaleDecisions(staleDays);if(ids.length)log({kind:'decisions_stale',count:ids.length,request_ids:ids.slice(0,20)});}catch(error){log({kind:'decisions_stale_error',reason:error.message});}};
|
|
1454
1487
|
sweepStale(); setInterval(sweepStale,3600000).unref();
|
|
1455
1488
|
setInterval(()=>checkAlerts(store,log).catch(e=>log({kind:'alert_error',reason:e.message})),60000).unref();
|
|
1489
|
+
}
|
|
1490
|
+
const startWhenWindowCloses=()=>{ if(updateWindowOpen()) setTimeout(startWhenWindowCloses,250).unref(); else startBackground(); };
|
|
1491
|
+
startWhenWindowCloses();
|
|
1456
1492
|
|
|
1457
1493
|
}
|
|
1458
1494
|
|