@tnunamak/dalan 0.0.0-stage → 0.5.2

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 (182) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +339 -0
  5. package/README.md +348 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +38 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +755 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/connect-chatgpt.md +78 -0
  17. package/docs/connection-longevity.md +37 -0
  18. package/docs/dalan-upgrade.md +242 -0
  19. package/docs/deadman.md +59 -0
  20. package/docs/dot-pr-reviewer.config.example.json +9 -0
  21. package/docs/durability-audit.md +27 -0
  22. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  23. package/docs/keycloak-oauth-setup.md +30 -0
  24. package/docs/local-agent-mcp.md +39 -0
  25. package/docs/manual-setup.md +135 -0
  26. package/docs/mirror-fetch.md +98 -0
  27. package/docs/operations.md +751 -0
  28. package/docs/operator-duties.md +68 -0
  29. package/docs/owner-integrator.md +27 -0
  30. package/docs/portable-auth-profile.md +109 -0
  31. package/docs/pr-head-reviewer.md +54 -0
  32. package/docs/pr-preflight.md +26 -0
  33. package/docs/pull-workers.md +97 -0
  34. package/docs/redaction.md +27 -0
  35. package/docs/service-setup.md +166 -0
  36. package/docs/setup-reference.md +80 -0
  37. package/docs/t3-connector-icon.png +0 -0
  38. package/docs/t3-integration.md +49 -0
  39. package/docs/t3-result-retry-delivery.md +41 -0
  40. package/docs/t3-reverse-control.md +107 -0
  41. package/docs/usage.md +439 -0
  42. package/docs/worker-clients.md +285 -0
  43. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  44. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  45. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  46. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  47. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  48. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  49. package/package.json +65 -4
  50. package/packages/job-core/README.md +18 -0
  51. package/packages/job-core/index.mjs +2 -0
  52. package/packages/job-core/package.json +8 -0
  53. package/packages/job-core/protocol/canonical.mjs +11 -0
  54. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  55. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  56. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  57. package/packages/job-core/transitions.mjs +25 -0
  58. package/scripts/daily-selfcheck.mjs +135 -0
  59. package/scripts/lib/expose-tailscale.mjs +408 -0
  60. package/scripts/live-trial/common.mjs +272 -0
  61. package/scripts/monitor-targets.mjs +44 -0
  62. package/scripts/upgrade-drain.mjs +39 -0
  63. package/scripts/worker-bridge-setup.mjs +925 -0
  64. package/src/ack-ledger.mjs +37 -0
  65. package/src/acp-bridge.mjs +412 -0
  66. package/src/acp-context.mjs +138 -0
  67. package/src/admin-socket.mjs +14 -0
  68. package/src/alerts.mjs +147 -0
  69. package/src/artifact-journal.mjs +75 -0
  70. package/src/as-files.mjs +347 -0
  71. package/src/as-store.mjs +456 -0
  72. package/src/as.mjs +497 -0
  73. package/src/auth.mjs +166 -0
  74. package/src/builtin-http.mjs +22 -0
  75. package/src/check-coverage.mjs +38 -0
  76. package/src/check-lint.mjs +88 -0
  77. package/src/check-readiness.mjs +112 -0
  78. package/src/check-response.mjs +19 -0
  79. package/src/claim-command-ledger.mjs +51 -0
  80. package/src/cli-help.mjs +172 -0
  81. package/src/cli-name.mjs +16 -0
  82. package/src/connect-cli.mjs +126 -0
  83. package/src/consumers.mjs +61 -0
  84. package/src/deadman.mjs +329 -0
  85. package/src/delivery.mjs +19 -0
  86. package/src/demo-worker.mjs +150 -0
  87. package/src/destinations/index.mjs +23 -0
  88. package/src/destinations/none.mjs +15 -0
  89. package/src/destinations/t3.mjs +109 -0
  90. package/src/diagnostic.mjs +78 -0
  91. package/src/docs-url.mjs +9 -0
  92. package/src/drain-runner.mjs +9 -0
  93. package/src/drained-slot.mjs +53 -0
  94. package/src/drained.mjs +40 -0
  95. package/src/durable-waiters.mjs +236 -0
  96. package/src/env.mjs +19 -0
  97. package/src/execution.mjs +112 -0
  98. package/src/failure-type.mjs +28 -0
  99. package/src/get-summary.mjs +32 -0
  100. package/src/git-env.mjs +15 -0
  101. package/src/host-budget-receipts.mjs +154 -0
  102. package/src/host-budget-seccomp.py +33 -0
  103. package/src/host-budget-service.mjs +54 -0
  104. package/src/host-budget-stop.mjs +26 -0
  105. package/src/host-budget-storage.py +259 -0
  106. package/src/host-budget.mjs +149 -0
  107. package/src/host-cgroup.mjs +23 -0
  108. package/src/host-check-allowlist.mjs +42 -0
  109. package/src/host-execution-policy.mjs +38 -0
  110. package/src/host-health.mjs +34 -0
  111. package/src/host-stop-reverify.mjs +44 -0
  112. package/src/inbox.mjs +55 -0
  113. package/src/integrator.mjs +322 -0
  114. package/src/job-retention.mjs +69 -0
  115. package/src/legacy-names.mjs +8 -0
  116. package/src/lifecycle.mjs +291 -0
  117. package/src/limits.mjs +31 -0
  118. package/src/loopback.mjs +9 -0
  119. package/src/mcp-outcome.mjs +70 -0
  120. package/src/mcp-stdio.mjs +191 -0
  121. package/src/mirror-fetch-lock.py +164 -0
  122. package/src/mirror-fetch.mjs +174 -0
  123. package/src/notify-ledger.mjs +82 -0
  124. package/src/objectives.mjs +129 -0
  125. package/src/owner-report-artifact.mjs +66 -0
  126. package/src/patch-apply.mjs +84 -0
  127. package/src/path-syntax.mjs +16 -0
  128. package/src/paths.mjs +67 -0
  129. package/src/pr-head-reviewer.mjs +596 -0
  130. package/src/pr-preflight.mjs +51 -0
  131. package/src/prepared-node-modules.mjs +129 -0
  132. package/src/projects.mjs +480 -0
  133. package/src/protocol-artifact-commands.mjs +52 -0
  134. package/src/protocol-delivery-driver.mjs +167 -0
  135. package/src/protocol-finish.mjs +100 -0
  136. package/src/protocol-owner-command.mjs +35 -0
  137. package/src/protocol-owner-mutations.mjs +22 -0
  138. package/src/protocol-owner-waiters.mjs +67 -0
  139. package/src/protocol-retention.mjs +52 -0
  140. package/src/protocol-services.mjs +61 -0
  141. package/src/protocol-stop-observer.mjs +131 -0
  142. package/src/publish-plan.mjs +245 -0
  143. package/src/redaction.mjs +763 -0
  144. package/src/rejections.mjs +18 -0
  145. package/src/request-log.mjs +102 -0
  146. package/src/restore-check.mjs +90 -0
  147. package/src/result-binding.mjs +65 -0
  148. package/src/runtime-check.mjs +13 -0
  149. package/src/sandbox-supervisor.mjs +105 -0
  150. package/src/schema-subset.mjs +186 -0
  151. package/src/scopes.mjs +15 -0
  152. package/src/server.mjs +1340 -0
  153. package/src/shutdown-signal.mjs +12 -0
  154. package/src/signal-sandbox-processes.py +56 -0
  155. package/src/signal.mjs +119 -0
  156. package/src/status-evidence.mjs +47 -0
  157. package/src/status-summary.mjs +54 -0
  158. package/src/store.mjs +3057 -0
  159. package/src/submission-policy.mjs +623 -0
  160. package/src/subscription-storage.mjs +64 -0
  161. package/src/t3-audit.mjs +120 -0
  162. package/src/t3-control.mjs +102 -0
  163. package/src/t3-transport.mjs +158 -0
  164. package/src/t3.mjs +209 -0
  165. package/src/terminal-safe.mjs +19 -0
  166. package/src/tool-registry.mjs +451 -0
  167. package/src/try-command.mjs +11 -0
  168. package/src/try.mjs +589 -0
  169. package/src/webhooks.mjs +86 -0
  170. package/src/work-order.mjs +265 -0
  171. package/src/worker-instructions.mjs +26 -0
  172. package/src/worker-prompt.mjs +4 -0
  173. package/src/workers.mjs +622 -0
  174. package/src/workspace.mjs +1058 -0
  175. package/systemd/dot-bridge-heartbeat.service +18 -0
  176. package/systemd/dot-bridge-heartbeat.timer +10 -0
  177. package/systemd/dot-bridge-selfcheck.service +12 -0
  178. package/systemd/dot-bridge-selfcheck.timer +11 -0
  179. package/systemd/dot-bridge.service +17 -0
  180. package/systemd/dot-deadman.service +30 -0
  181. package/systemd/dot-pr-reviewer.service +11 -0
  182. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,408 @@
1
+ // Public exposure for a worker bridge: Tailscale Funnel (preflight, port choice, the funnel rule, public verification,
2
+ // removal) and the ngrok fallback (config file and printed commands only; this code never runs ngrok).
3
+ // Used by scripts/worker-bridge-setup.mjs --expose tailscale|ngrok. Nothing here changes a serve or funnel rule that already
4
+ // exists. The only Tailscale mutation is our own rule on our own port.
5
+ import fs from 'node:fs';
6
+ import https from 'node:https';
7
+ import path from 'node:path';
8
+ import { randomBytes } from 'node:crypto';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { Resolver } from 'node:dns/promises';
11
+
12
+ // Public ports Tailscale Funnel accepts, in the order we prefer them.
13
+ // Source: https://tailscale.com/kb/1223/funnel ("443, 8443, and 10000").
14
+ export const FUNNEL_PORTS = [443, 8443, 10000];
15
+ // Admin pages. Host verified this session: https://tailscale.com/kb/1223/funnel and https://tailscale.com/kb/1153/enabling-https
16
+ // both name console.tailscale.com. Brief: "use whichever host the docs currently give".
17
+ export const ADMIN_DNS_URL = 'https://console.tailscale.com/admin/dns';
18
+ export const ADMIN_ACL_URL = 'https://console.tailscale.com/admin/acls';
19
+ export const INSTALL_URL = 'https://tailscale.com/download';
20
+ export const HTTPS_DOC_URL = 'https://tailscale.com/kb/1153/enabling-https';
21
+ export const FUNNEL_DOC_URL = 'https://tailscale.com/kb/1223/funnel';
22
+ export const MACOS_VARIANTS_DOC_URL = 'https://tailscale.com/docs/concepts/macos-variants';
23
+ const DEFAULT_TIMEOUT_MS = 20_000;
24
+ const refuseOverwrite = message => { throw Object.assign(new Error(message), { name: 'SetupRefusal', code: 'SETUP_REFUSED' }); };
25
+
26
+ // Public DNS: up to 10 minutes is normal (first Funnel certificate). Progress every 30 s.
27
+ export const DNS_WAIT_MS = 600_000;
28
+ export const DNS_PROGRESS_MS = 30_000;
29
+
30
+ // ngrok: free-plan limits from https://ngrok.com/docs/pricing-limits/free-plan-limits (20,000 HTTP requests/month, 1 GB egress/month).
31
+ export const NGROK_FREE_PLAN_URL = 'https://ngrok.com/docs/pricing-limits/free-plan-limits';
32
+ export const NGROK_QUOTA_WARNING = `ngrok free plan quota (${NGROK_FREE_PLAN_URL}): 20,000 HTTP requests per month and 1 GB egress per month. `
33
+ + 'A 60 s wake hook alone makes about 43,000 requests per month. Set the hook poll interval to 300 s or more with ngrok. '
34
+ + 'Rejecting fast polls on the bridge would still count them against the quota, so the interval has to be set in the hook.';
35
+ export const WAKE_POLL_SECONDS = 60;
36
+ export const WAKE_POLL_SECONDS_NGROK = 300;
37
+
38
+ const MACOS_APP = '/Applications/Tailscale.app';
39
+
40
+ // The wake-hook poll interval for this home: 300 s when any recorded exposure is ngrok, else 60 s.
41
+ export function pollIntervalSeconds(records) {
42
+ return records.some(r => r.mode === 'ngrok') ? WAKE_POLL_SECONDS_NGROK : WAKE_POLL_SECONDS;
43
+ }
44
+
45
+ // Reads every dot-bridge-<worker>.exposure.json in a bridge home. Missing home or no records gives [].
46
+ export function readExposureRecords(home, { readdir = fs.readdirSync, read = fs.readFileSync } = {}) {
47
+ let names;
48
+ try { names = readdir(home); } catch { return []; }
49
+ return names.filter(n => /^dot-bridge-.+\.exposure\.json$/.test(n))
50
+ .map(n => JSON.parse(read(path.join(home, n), 'utf8')));
51
+ }
52
+
53
+ export function enableMagicDnsMessage() {
54
+ return `MagicDNS is off for this tailnet. Turn it on at ${ADMIN_DNS_URL} (the DNS page, MagicDNS), then retry. Doc: ${HTTPS_DOC_URL} (step 2).`;
55
+ }
56
+
57
+ // The doc says enabling HTTPS publishes machine names and the tailnet DNS name on a public ledger. Say so before the owner clicks.
58
+ export function enableHttpsMessage() {
59
+ return `HTTPS certificates are off for this tailnet. Turn them on at ${ADMIN_DNS_URL} (HTTPS Certificates: Enable HTTPS). `
60
+ + `Tailscale publishes your machine names and tailnet DNS name on a public ledger when you do; accept that or do not enable Funnel. Then retry. Doc: ${HTTPS_DOC_URL}.`;
61
+ }
62
+
63
+ export function enableFunnelMessage() {
64
+ return `Funnel is not allowed for this tailnet. Add the funnel node attribute at ${ADMIN_ACL_URL} (Access controls, Funnel section, "Add Funnel to policy"), then retry. Doc: ${FUNNEL_DOC_URL}.`;
65
+ }
66
+
67
+ export function macConflictMessage(label) {
68
+ return `macOS: the Tailscale ${label} is installed and its CLI is the \`tailscale\` on PATH. Funnel is not supported by the App Store app or the Standalone app; only the open-source tailscaled supports it (${MACOS_VARIANTS_DOC_URL}). The app and the open-source daemon conflict. Nothing was changed.\n`
69
+ + 'Either:\n'
70
+ + ' 1. Quit Tailscale from the menu bar, then uninstall the app (Standalone: move /Applications/Tailscale.app to the Trash; App Store: delete it from Launchpad). Then run:\n'
71
+ + ' brew install tailscale && sudo brew services start tailscale && sudo tailscale up\n'
72
+ + ' and retry this command.\n'
73
+ + ' 2. Or use the ngrok fallback instead: --expose ngrok --ngrok-domain <assigned-domain>';
74
+ }
75
+
76
+ const notInstalled = () => new Error(`Tailscale is not installed. Install it from ${INSTALL_URL}, then run \`tailscale up\` and retry.`);
77
+ const notRunning = () => new Error('Tailscale is not running or not logged in. Run `tailscale up` and retry.');
78
+
79
+ // Injected by tests through PATH only; the real binary is never named here except as the PATH lookup.
80
+ export function defaultTailscale(args) {
81
+ return spawnSync('tailscale', args, { encoding: 'utf8', timeout: DEFAULT_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
82
+ }
83
+
84
+ // First executable named `name` on PATH, or null.
85
+ export function whichOnPath(name, env = process.env) {
86
+ for (const dir of (env.PATH ?? '').split(path.delimiter)) {
87
+ if (!dir) continue;
88
+ const candidate = path.join(dir, name);
89
+ try { fs.accessSync(candidate, fs.constants.X_OK); return candidate; } catch { /* keep looking */ }
90
+ }
91
+ return null;
92
+ }
93
+
94
+ // macOS variant check (darwin only). Detects the App Store or Standalone app at /Applications/Tailscale.app.
95
+ // It is in use when the `tailscale` on PATH resolves into that bundle. The open-source tailscaled (Homebrew) on PATH is fine.
96
+ // Everything is injected so tests can use fake paths. Returns null off macOS or when the app is not installed.
97
+ // The App Store label relies on the _MASReceipt directory (the usual App Store receipt location). Assumed, not doc-verified.
98
+ export function macVariantCheck({
99
+ platform = process.platform, exists = fs.existsSync, realpath = fs.realpathSync, which = name => whichOnPath(name),
100
+ } = {}) {
101
+ if (platform !== 'darwin' || !exists(MACOS_APP)) return null;
102
+ const label = exists(path.join(MACOS_APP, 'Contents/_MASReceipt/receipt')) ? 'App Store app' : 'Standalone app';
103
+ const cli = which('tailscale');
104
+ let real = null;
105
+ if (cli) { try { real = realpath(cli); } catch { real = cli; } }
106
+ if (real && real.startsWith(`${MACOS_APP}/`)) return { label, inUse: true, cli: real };
107
+ return { label, inUse: false, cli: real, warning: `the Tailscale ${label} is installed, but the \`tailscale\` on PATH is not its CLI (${real ?? 'not found'}); continuing with that one. If the app's daemon is also running, the two will conflict: ${MACOS_VARIANTS_DOC_URL}` };
108
+ }
109
+
110
+ function parseJsonOutput(result, label) {
111
+ const text = (result.stdout ?? '').trim();
112
+ if (!text.startsWith('{')) {
113
+ if (result.status === 0 && text === '') return {};
114
+ throw new Error(`could not read \`${label}\` output as JSON`);
115
+ }
116
+ try { return JSON.parse(text); }
117
+ catch { throw new Error(`could not parse \`${label}\` output as JSON`); }
118
+ }
119
+
120
+ function runOrThrow(tailscale, args, label) {
121
+ const r = tailscale(args);
122
+ if (r.error?.code === 'ENOENT') throw notInstalled();
123
+ if (r.error) throw new Error(`\`tailscale ${label}\` failed to start (${r.error.code ?? r.error.message})`);
124
+ if (r.status !== 0) throw new Error(`\`tailscale ${label}\` exited ${r.status ?? r.signal}: ${String(r.stderr ?? '').trim().split('\n').at(-1) ?? ''}`.trimEnd());
125
+ return r;
126
+ }
127
+
128
+ // Ports the cap allows: the query of https://tailscale.com/cap/funnel-ports?ports=443,8443,10000 in Self.CapMap.
129
+ export function allowedFunnelPorts(capMap = {}) {
130
+ const ports = new Set();
131
+ for (const key of Object.keys(capMap)) {
132
+ if (!key.startsWith('https://tailscale.com/cap/funnel-ports')) continue;
133
+ for (const p of new URL(key).searchParams.get('ports')?.split(',') ?? []) {
134
+ const n = Number(p);
135
+ if (Number.isInteger(n)) ports.add(n);
136
+ }
137
+ }
138
+ return [...ports].sort((a, b) => a - b);
139
+ }
140
+
141
+ // Ports that serve status already uses: TCP listeners and Web handlers keyed by "name:port".
142
+ export function occupiedPorts(serve) {
143
+ const occupied = new Map();
144
+ for (const k of Object.keys(serve.TCP ?? {})) occupied.set(Number(k), `TCP listener on ${k}`);
145
+ for (const k of Object.keys(serve.Web ?? {})) occupied.set(Number(k.split(':').at(-1)), `web rule ${k}`);
146
+ return occupied;
147
+ }
148
+
149
+ // Read-only. Throws with the exact next step for each refusal, in this order: macOS variant, status, MagicDNS, HTTPS, funnel.
150
+ // MagicDNS is CurrentTailnet.MagicDNSEnabled (field name observed in `tailscale status --json` on this host).
151
+ // HTTPS is the `https` key in Self.CapMap (observed on this host; the HTTPS doc names no field, so this is assumed to track it).
152
+ // Funnel is the `funnel` key in Self.CapMap plus the funnel-ports cap (observed on this host).
153
+ export function preflight({ tailscale = defaultTailscale, platform = process.platform, mac = {} } = {}) {
154
+ const variant = macVariantCheck({ platform, ...mac });
155
+ if (variant?.inUse) throw new Error(macConflictMessage(variant.label));
156
+ const status = runOrThrow(tailscale, ['status', '--json'], 'status --json');
157
+ const s = parseJsonOutput(status, 'tailscale status --json');
158
+ if (s.BackendState !== 'Running') throw notRunning();
159
+ const dnsName = String(s.Self?.DNSName ?? '').replace(/\.$/, '');
160
+ if (!dnsName) throw new Error('`tailscale status --json` has no Self.DNSName; the node is not fully set up');
161
+ if (s.CurrentTailnet?.MagicDNSEnabled !== true) throw new Error(enableMagicDnsMessage());
162
+ const capMap = s.Self?.CapMap ?? {};
163
+ if (!('https' in capMap)) throw new Error(enableHttpsMessage());
164
+ const allowed = allowedFunnelPorts(capMap);
165
+ if (!('funnel' in capMap) || allowed.length === 0) throw new Error(enableFunnelMessage());
166
+ const serve = parseJsonOutput(runOrThrow(tailscale, ['serve', 'status', '--json'], 'serve status --json'), 'tailscale serve status --json');
167
+ return { dnsName, allowed, occupied: occupiedPorts(serve), warnings: variant?.warning ? [variant.warning] : [] };
168
+ }
169
+
170
+ // --funnel-port must be allowed and free. Without it, the first free allowed port of 443, 8443, 10000.
171
+ export function choosePort({ requested, allowed, occupied }) {
172
+ if (requested !== undefined) {
173
+ if (!allowed.includes(requested)) throw new Error(`--funnel-port ${requested} is not allowed for this tailnet (allowed: ${allowed.join(', ')})`);
174
+ if (occupied.has(requested)) throw new Error(`--funnel-port ${requested} is already used (${occupied.get(requested)}). Pick another port; existing rules are never replaced.`);
175
+ return requested;
176
+ }
177
+ const free = FUNNEL_PORTS.find(p => allowed.includes(p) && !occupied.has(p));
178
+ if (free !== undefined) return free;
179
+ const lines = FUNNEL_PORTS.map(p => {
180
+ if (!allowed.includes(p)) return ` ${p}: not allowed by this tailnet`;
181
+ return ` ${p}: ${occupied.get(p) ?? 'free'}`;
182
+ });
183
+ throw new Error(`no free Funnel port (443, 8443, 10000). What occupies each port:\n${lines.join('\n')}\nRemove one of those rules yourself, or pass --funnel-port with a free allowed port.`);
184
+ }
185
+
186
+ export function publicUrl(dnsName, port) {
187
+ return `https://${dnsName}${port === 443 ? '' : `:${port}`}`;
188
+ }
189
+
190
+ export const funnelOnArgs = (port, localPort) => ['funnel', '--bg', `--https=${port}`, `http://127.0.0.1:${localPort}`];
191
+ export const funnelOffArgs = port => ['funnel', `--https=${port}`, 'off'];
192
+ export const funnelStatusArgs = () => ['funnel', 'status', '--json'];
193
+
194
+ // True when the funnel status maps exactly our port to our local bridge port, and nothing else on that port.
195
+ export function funnelRuleMatches(status, dnsName, port, localPort) {
196
+ const key = `${dnsName}:${port}`;
197
+ const handlers = status.Web?.[key]?.Handlers ?? {};
198
+ return Object.keys(handlers).join(',') === '/'
199
+ && handlers['/'].Proxy === `http://127.0.0.1:${localPort}`
200
+ && status.AllowFunnel?.[key] === true;
201
+ }
202
+
203
+ export function funnelRulePresent(status, dnsName, port) {
204
+ return Object.hasOwn(status.Web ?? {}, `${dnsName}:${port}`);
205
+ }
206
+
207
+ // Public DNS through three resolvers in parallel (one resolver can keep a negative-cached NXDOMAIN for a new name for >10 min).
208
+ // Returns the first IPv4 found as { address, server }, or null when none of them has an answer.
209
+ export const PUBLIC_DNS_SERVERS = ['1.1.1.1', '8.8.8.8', '9.9.9.9'];
210
+
211
+ export function makePublicResolver(resolvers = defaultResolvers()) {
212
+ return name => new Promise(resolve => {
213
+ let pending = resolvers.length;
214
+ const settle = () => { if (--pending === 0) resolve(null); };
215
+ for (const { server, resolver } of resolvers) {
216
+ resolver.resolve4(name).then(
217
+ addresses => (addresses[0] ? resolve({ address: addresses[0], server }) : settle()),
218
+ settle,
219
+ );
220
+ }
221
+ });
222
+ }
223
+
224
+ function defaultResolvers() {
225
+ return PUBLIC_DNS_SERVERS.map(server => {
226
+ const resolver = new Resolver({ timeout: 3000, tries: 1 });
227
+ resolver.setServers([server]);
228
+ return { server, resolver };
229
+ });
230
+ }
231
+
232
+ // GET /admin pinned to the address that DNS returned. Expects 404 from the bridge (its unauthenticated path).
233
+ export function fetchPinned(url, address, { timeoutMs = 15_000 } = {}) {
234
+ const u = new URL(url);
235
+ return new Promise((resolve, reject) => {
236
+ const req = https.request({
237
+ hostname: u.hostname, port: u.port || 443, path: '/admin', method: 'GET', timeout: timeoutMs,
238
+ // Keep the hostname for SNI and the Host header; only the address is pinned.
239
+ lookup: (_host, options, cb) => (options?.all ? cb(null, [{ address, family: 4 }]) : cb(null, address, 4)),
240
+ }, res => { res.resume(); resolve(res.statusCode); });
241
+ req.on('timeout', () => req.destroy(new Error('timeout')));
242
+ req.on('error', reject);
243
+ req.end();
244
+ });
245
+ }
246
+
247
+ // Retries DNS for up to timeoutMs (10 minutes is normal), logging progress every progressMs, then retries GET /admin for up to 120 s until it returns 404.
248
+ const HTTPS_WAIT_MS = 120_000;
249
+
250
+ export async function verifyPublic({
251
+ url, dnsName, resolve4, request = fetchPinned, sleep = ms => new Promise(r => setTimeout(r, ms)), now = Date.now,
252
+ timeoutMs = DNS_WAIT_MS, intervalMs = 5_000, progressMs = DNS_PROGRESS_MS, log = console.log,
253
+ }) {
254
+ const secs = ms => Math.round(ms / 1000);
255
+ const start = now();
256
+ const end = start + timeoutMs;
257
+ let nextProgress = progressMs;
258
+ let found = null;
259
+ while (!found) {
260
+ found = await resolve4(dnsName);
261
+ if (found) break;
262
+ const elapsed = now() - start;
263
+ if (elapsed >= nextProgress && elapsed < timeoutMs) {
264
+ log(`waiting for public DNS of ${dnsName} … ${secs(elapsed)} s / ${secs(timeoutMs)} s`);
265
+ nextProgress += progressMs;
266
+ }
267
+ if (now() >= end) break;
268
+ await sleep(intervalMs);
269
+ }
270
+ if (!found) {
271
+ log(`FAIL public DNS: no A record for ${dnsName} from 1.1.1.1, 8.8.8.8 or 9.9.9.9 after ${secs(timeoutMs)} s. Likely cause: the Funnel rule or its certificate is not ready, or the name is not published yet. Next: run \`dig @8.8.8.8 ${dnsName} A\` (also try @1.1.1.1 and @9.9.9.9) and \`tailscale funnel status\`, then retry.`);
272
+ return false;
273
+ }
274
+ const { address, server } = found;
275
+ log(`PASS public DNS: ${dnsName} -> ${address} (via ${server})`);
276
+ // Funnel needs a while after the rule exists: the first requests can fail the TLS handshake or hit a 5xx.
277
+ // Retry every non-404 outcome until the window ends, then fail with the last error or status.
278
+ const httpsEnd = now() + HTTPS_WAIT_MS;
279
+ let nextHttpsProgress = now() + progressMs;
280
+ let last;
281
+ for (;;) {
282
+ try {
283
+ const code = await request(url, address);
284
+ if (code === 404) break;
285
+ last = `GET /admin returned ${code}, expected 404 from the bridge`;
286
+ } catch (e) { last = e.message; }
287
+ if (now() >= httpsEnd) {
288
+ log(`FAIL public HTTPS: ${last} (still failing after ${secs(HTTPS_WAIT_MS)} s). Likely cause: the Funnel certificate is still being issued, the rule is not active, or a different service answers on this port. Next: \`tailscale funnel status\` and check the local port, then retry.`);
289
+ return false;
290
+ }
291
+ if (now() >= nextHttpsProgress) {
292
+ log(`waiting for public HTTPS of ${dnsName} … last result: ${last}`);
293
+ nextHttpsProgress += progressMs;
294
+ }
295
+ await sleep(intervalMs);
296
+ }
297
+ log('PASS public HTTPS: GET /admin returned 404 from the bridge');
298
+ return true;
299
+ }
300
+
301
+ export function recordPath(unitDir, worker) {
302
+ return path.join(unitDir, `dot-bridge-${worker}.exposure.json`);
303
+ }
304
+
305
+ function writeRecord(file, value) {
306
+ try { fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' }); }
307
+ catch (error) {
308
+ if (error.code === 'EEXIST') refuseOverwrite(`${file} already exists; refusing to overwrite an exposure record`);
309
+ throw error;
310
+ }
311
+ fs.chmodSync(file, 0o600);
312
+ }
313
+
314
+ function readOwnedRecord(file) {
315
+ const stat = fs.lstatSync(file);
316
+ if (!stat.isFile() || stat.isSymbolicLink() || (typeof process.getuid === 'function' && stat.uid !== process.getuid())) {
317
+ throw new Error(`exposure record ${file} is not a regular file owned by the current user; refusing to use it`);
318
+ }
319
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
320
+ }
321
+
322
+ // Step 3 of the brief: run our funnel rule, then prove it maps exactly our port.
323
+ export function applyFunnel({ tailscale = defaultTailscale, dnsName, port, localPort }) {
324
+ runOrThrow(tailscale, funnelOnArgs(port, localPort), `funnel --bg --https=${port}`);
325
+ const status = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
326
+ if (!funnelRuleMatches(status, dnsName, port, localPort)) {
327
+ throw new Error(`funnel status does not show ${dnsName}:${port} mapped to http://127.0.0.1:${localPort}. Run \`tailscale funnel status\` and fix it by hand; nothing else was changed.`);
328
+ }
329
+ }
330
+
331
+ export const ngrokStopCommands = worker => [
332
+ `ngrok service stop`,
333
+ `ngrok service uninstall`,
334
+ ].map(c => ` ${c} # worker ${worker}`);
335
+
336
+ // --remove: a tailscale record turns off exactly its rule and verifies it is gone; an ngrok record only drops the record
337
+ // and prints the ngrok commands (ngrok is never run here). Units and home are left alone.
338
+ export function removeExposure({ tailscale = defaultTailscale, file, log = console.log }) {
339
+ if (!fs.existsSync(file)) throw new Error(`no exposure record at ${file}; nothing to remove`);
340
+ const rec = readOwnedRecord(file);
341
+ if (rec.mode === 'ngrok') {
342
+ if (!rec.domain || !rec.ngrok_config) throw new Error(`exposure record ${file} is not a valid ngrok record`);
343
+ fs.rmSync(file);
344
+ log(`Removed the ngrok exposure record for ${rec.domain} (was -> http://127.0.0.1:${rec.local_port}). ngrok itself was NOT stopped by this script. To stop it and remove its service, run:`);
345
+ for (const line of ngrokStopCommands(rec.worker)) log(line);
346
+ log(`The ngrok config ${rec.ngrok_config} is left in place; delete it yourself if you do not need it.`);
347
+ return;
348
+ }
349
+ if (rec.mode !== 'tailscale' || !Number.isInteger(rec.public_port) || !rec.dns_name) throw new Error(`exposure record ${file} is not a tailscale record`);
350
+ const before = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
351
+ if (funnelRulePresent(before, rec.dns_name, rec.public_port)) {
352
+ if (!funnelRuleMatches(before, rec.dns_name, rec.public_port, rec.local_port)) {
353
+ throw new Error(`funnel rule ${rec.dns_name}:${rec.public_port} no longer matches this setup; refusing to change it. Inspect tailscale funnel status and remove the owned rule by hand if appropriate.`);
354
+ }
355
+ runOrThrow(tailscale, funnelOffArgs(rec.public_port), `funnel --https=${rec.public_port} off`);
356
+ const after = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
357
+ if (funnelRulePresent(after, rec.dns_name, rec.public_port)) throw new Error(`funnel rule ${rec.dns_name}:${rec.public_port} is still present after off`);
358
+ }
359
+ fs.rmSync(file);
360
+ log(`Removed Funnel rule ${rec.dns_name}:${rec.public_port} (was -> http://127.0.0.1:${rec.local_port}) and its record`);
361
+ }
362
+
363
+ // Publish intent before changing Funnel so --remove can recover an interrupted mutation.
364
+ export function writeExposureRecord({ file, worker, dnsName, port, localPort, url, state = 'pending' }) {
365
+ writeRecord(file, { mode: 'tailscale', state, worker, dns_name: dnsName, public_url: url, public_port: port, local_port: localPort, created_at: new Date().toISOString() });
366
+ }
367
+
368
+ export function updateExposureState(file, state) {
369
+ const info = fs.lstatSync(file);
370
+ if (!info.isFile() || info.isSymbolicLink() || (typeof process.getuid === 'function' && info.uid !== process.getuid())) {
371
+ throw new Error('exposure record is not a regular file owned by the current user; refusing to update it');
372
+ }
373
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
374
+ const temporary = `${file}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
375
+ fs.writeFileSync(temporary, `${JSON.stringify({ ...value, state }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
376
+ fs.renameSync(temporary, file);
377
+ }
378
+
379
+ // ngrok v3 agent config (https://ngrok.com/docs/agent/config/v3: version 3, endpoints[].name, url, upstream.url).
380
+ // The authtoken is deliberately absent: `ngrok config add-authtoken` keeps it in ngrok's own config.
381
+ export function ngrokConfigText({ worker, domain, localPort }) {
382
+ return `version: 3\n\nendpoints:\n - name: dot-bridge-${worker}\n url: ${domain}\n upstream:\n url: http://127.0.0.1:${localPort}\n`;
383
+ }
384
+
385
+ export function ngrokConfigPath(home, worker) {
386
+ return path.join(home, `ngrok-${worker}.yml`);
387
+ }
388
+
389
+ // Writes the config (0600, never overwritten) and the record (0600). The record is what signal-token and --remove read.
390
+ export function writeNgrokExposure({ home, worker, domain, localPort, file }) {
391
+ const configFile = ngrokConfigPath(home, worker);
392
+ try { fs.writeFileSync(configFile, ngrokConfigText({ worker, domain, localPort }), { mode: 0o600, flag: 'wx' }); }
393
+ catch (error) {
394
+ if (error.code === 'EEXIST') refuseOverwrite(`${configFile} already exists; refusing to overwrite the ngrok config`);
395
+ throw error;
396
+ }
397
+ fs.chmodSync(configFile, 0o600);
398
+ writeRecord(file, { mode: 'ngrok', state: 'unverified', worker, domain, public_url: `https://${domain}`, public_port: null, local_port: localPort, ngrok_config: configFile, created_at: new Date().toISOString() });
399
+ return configFile;
400
+ }
401
+
402
+ export function ngrokCommands(configFile) {
403
+ return [
404
+ 'ngrok config add-authtoken <TOKEN> # placeholder: paste your token from the ngrok dashboard; this script never stores it',
405
+ `ngrok service install --config ${configFile}`,
406
+ 'ngrok service start',
407
+ ];
408
+ }