@powerhousedao/portle 0.0.0-stage → 6.2.3-dev.101

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.
@@ -0,0 +1,1219 @@
1
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import path, { dirname, join, resolve } from "node:path";
3
+ import { promises } from "node:dns";
4
+ import { SWITCHBOARD_PROXY_PATHS } from "@powerhousedao/host-core";
5
+ import { spawn, spawnSync } from "node:child_process";
6
+ import { GraphQLError, parse } from "graphql";
7
+ //#region src/binaries.ts
8
+ const BINARY_ENV = {
9
+ frpc: "PORTLE_FRPC_BIN",
10
+ caddy: "PORTLE_CADDY_BIN"
11
+ };
12
+ function portleBinDir(home, platform = process.platform) {
13
+ return pathFor(platform).join(home, ".ph", "portle", "bin");
14
+ }
15
+ /** Paths are joined by the target platform's rules, so a lookup is the same whichever host runs it. */
16
+ function pathFor(platform) {
17
+ return platform === "win32" ? path.win32 : path.posix;
18
+ }
19
+ function resolveBinaries(options = {}) {
20
+ const env = options.env ?? process.env;
21
+ const platform = options.platform ?? process.platform;
22
+ const exists = options.exists ?? existsSync;
23
+ const home = options.home ?? env.HOME ?? env.USERPROFILE ?? "";
24
+ const suffix = platform === "win32" ? ".exe" : "";
25
+ const p = pathFor(platform);
26
+ const searched = [];
27
+ const find = (name) => {
28
+ const explicit = env[BINARY_ENV[name]];
29
+ if (explicit) {
30
+ searched.push(explicit);
31
+ return exists(explicit) ? explicit : null;
32
+ }
33
+ const candidates = [p.join(portleBinDir(home, platform), `${name}${suffix}`)];
34
+ for (const dir of (env.PATH ?? env.Path ?? "").split(p.delimiter).filter(Boolean)) candidates.push(p.join(dir, `${name}${suffix}`));
35
+ for (const candidate of candidates) {
36
+ searched.push(candidate);
37
+ if (exists(candidate)) return candidate;
38
+ }
39
+ return null;
40
+ };
41
+ return {
42
+ frpc: find("frpc"),
43
+ caddy: find("caddy"),
44
+ searched
45
+ };
46
+ }
47
+ //#endregion
48
+ //#region src/gate.ts
49
+ /** One of the host's listed admins, whatever the policy. */
50
+ function isListedAdmin(admins, address) {
51
+ if (!address) return false;
52
+ const caller = address.toLowerCase();
53
+ return admins.some((admin) => admin.toLowerCase() === caller);
54
+ }
55
+ const POLICY_FIX = "Set AUTH_ENABLED=true (or auth.enabled in powerhouse.config.json). ADMIN_ONLY is enough; DOCUMENT_PERMISSIONS_ENABLED=true with DEFAULT_PROTECTION=true also passes.";
56
+ function evaluateGate(facts, caller) {
57
+ const policyOk = facts.policy === "ADMIN_ONLY" || facts.policy === "DOCUMENT_PERMISSIONS" && facts.defaultProtection;
58
+ const checks = [
59
+ {
60
+ id: "identity",
61
+ ok: facts.identityResolved,
62
+ detail: facts.identityResolved ? "Bearer tokens are verified and the caller is known to every resolver." : "The host never reads a bearer; no caller can be identified.",
63
+ fix: facts.identityResolved ? void 0 : "Set RESOLVE_CALLER_IDENTITY=true."
64
+ },
65
+ {
66
+ id: "floor",
67
+ ok: facts.requireAuthenticatedCaller,
68
+ detail: facts.requireAuthenticatedCaller ? "Anonymous callers are refused with a 401 before any resolver runs." : "Anonymous callers reach every subgraph.",
69
+ fix: facts.requireAuthenticatedCaller ? void 0 : "Set REQUIRE_AUTHENTICATED_CALLER=true (needs RESOLVE_CALLER_IDENTITY=true)."
70
+ },
71
+ {
72
+ id: "policy",
73
+ ok: policyOk,
74
+ detail: describePolicy(facts),
75
+ fix: policyOk ? void 0 : POLICY_FIX
76
+ },
77
+ {
78
+ id: "protection",
79
+ ok: facts.policy !== "DOCUMENT_PERMISSIONS" || facts.defaultProtection,
80
+ detail: facts.policy === "DOCUMENT_PERMISSIONS" ? facts.defaultProtection ? "Documents without a permission row are protected." : "Documents without a permission row are readable by any caller." : "Not consulted under this policy.",
81
+ fix: facts.policy === "DOCUMENT_PERMISSIONS" && !facts.defaultProtection ? "Set DEFAULT_PROTECTION=true." : void 0
82
+ },
83
+ {
84
+ id: "admins",
85
+ ok: facts.admins.length > 0,
86
+ detail: facts.admins.length > 0 ? `${facts.admins.length} admin address(es) listed.` : "No admin address is listed; nobody could administer the published host.",
87
+ fix: facts.admins.length > 0 ? void 0 : "Set ADMINS to the comma-separated addresses that may publish."
88
+ },
89
+ {
90
+ id: "caller",
91
+ ok: isListedAdmin(facts.admins, caller?.address),
92
+ detail: caller?.address ? isListedAdmin(facts.admins, caller.address) ? "You are one of the listed admins." : "You are signed in, but not one of the listed admins." : "You are not signed in.",
93
+ fix: isListedAdmin(facts.admins, caller?.address) ? void 0 : "Sign in with Renown as one of the ADMINS addresses."
94
+ }
95
+ ];
96
+ return {
97
+ publishable: checks.every((check) => check.ok),
98
+ checks,
99
+ warnings: [{
100
+ id: "custom-subgraphs",
101
+ ok: false,
102
+ detail: "The project's own subgraphs enforce nothing by themselves; the policy and the floor do not reach their resolvers.",
103
+ fix: "Have every custom resolver check the caller (assertCanRead or canRead on the drive it serves)."
104
+ }]
105
+ };
106
+ }
107
+ /**
108
+ * The gate without the caller: what the host itself must satisfy before the
109
+ * tunnel may come up unattended at boot. The caller check is per request.
110
+ */
111
+ function bootGatePasses(facts) {
112
+ return evaluateGate(facts, void 0).checks.every((check) => check.ok || check.id === "caller");
113
+ }
114
+ function describePolicy(facts) {
115
+ switch (facts.policy) {
116
+ case "OPEN": return "OPEN: everyone, anonymous included, may read and write everything.";
117
+ case "ADMIN_ONLY": return "ADMIN_ONLY: only the listed admins may read or write anything.";
118
+ case "DOCUMENT_PERMISSIONS": return facts.defaultProtection ? "DOCUMENT_PERMISSIONS with default protection: grants decide, unprotected documents do not exist." : "DOCUMENT_PERMISSIONS without default protection: documents with no permission row are open to every caller.";
119
+ }
120
+ }
121
+ //#endregion
122
+ //#region src/delegation.ts
123
+ /** The resolver could not answer at all (timeout, refused, SERVFAIL), so
124
+ * whether the zone is delegated is unknown, which is not "not delegated". */
125
+ var DelegationCheckError = class extends Error {
126
+ constructor(zone, cause) {
127
+ super(`could not check whether ${zone} is delegated: the resolver failed (${errorText(cause)})`, { cause });
128
+ this.name = "DelegationCheckError";
129
+ }
130
+ };
131
+ const canonical = (name) => name.trim().toLowerCase().replace(/\.$/, "");
132
+ function errorText(error) {
133
+ if (error instanceof Error) {
134
+ const code = error.code;
135
+ return typeof code === "string" && !error.message.includes(code) ? `${code}: ${error.message}` : error.message;
136
+ }
137
+ return String(error);
138
+ }
139
+ /** Answers that mean the zone has no NS records yet: NXDOMAIN or no data. */
140
+ const NOT_DELEGATED = [
141
+ "ENOTFOUND",
142
+ "ENODATA",
143
+ "NXDOMAIN"
144
+ ];
145
+ function isNotDelegatedAnswer(error) {
146
+ const code = error?.code;
147
+ const text = `${typeof code === "string" ? code : ""} ${error instanceof Error ? error.message : ""}`;
148
+ return NOT_DELEGATED.some((answer) => text.includes(answer));
149
+ }
150
+ /**
151
+ * True once the resolver lists one of the relay's nameservers; false when it
152
+ * answers that the zone has none (NXDOMAIN, no data, other nameservers).
153
+ * A resolver that cannot answer is retried with backoff, then reported as a
154
+ * {@link DelegationCheckError}: a DNS blip at boot is not a missing delegation.
155
+ */
156
+ async function isDelegated(delegation, resolveNs = (zone) => promises.resolveNs(zone), options = {}) {
157
+ const expected = new Set(delegation.nameservers.map(canonical));
158
+ const attempts = Math.max(1, options.attempts ?? 4);
159
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
160
+ let delay = options.delayMs ?? 1e3;
161
+ for (let attempt = 1;; attempt++) try {
162
+ return (await resolveNs(delegation.zone)).some((ns) => expected.has(canonical(ns)));
163
+ } catch (error) {
164
+ if (isNotDelegatedAnswer(error)) return false;
165
+ if (attempt >= attempts) throw new DelegationCheckError(delegation.zone, error);
166
+ await sleep(delay);
167
+ delay *= 2;
168
+ }
169
+ }
170
+ //#endregion
171
+ //#region src/site/enrol.ts
172
+ /**
173
+ * Enrols this site with the Portle control plane: one token, one site. The
174
+ * token is single use; the answer is the site's identity and every secret the
175
+ * tunnel and the certificate need, and is stored once by the caller.
176
+ */
177
+ async function enrolWithControlPlane(controlPlaneUrl, token, fetchImpl = fetch) {
178
+ const res = await fetchImpl(`${controlPlaneUrl.replace(/\/$/, "")}/v1/enroll`, {
179
+ method: "POST",
180
+ headers: {
181
+ "Content-Type": "application/json",
182
+ Accept: "application/json"
183
+ },
184
+ body: JSON.stringify({ token }),
185
+ signal: AbortSignal.timeout(3e4)
186
+ });
187
+ const text = await res.text();
188
+ if (res.status !== 201) throw new Error(`enrolment failed: HTTP ${res.status} ${text.slice(0, 300)}`);
189
+ const data = JSON.parse(text);
190
+ if (!data.siteId || !data.siteSecret || !data.frp?.token || !data.dns?.tsigSecret) throw new Error("enrolment response is incomplete");
191
+ return data;
192
+ }
193
+ //#endregion
194
+ //#region src/site/hostnames.ts
195
+ /**
196
+ * Hostname rules of a Portle site, vendored from site-relay
197
+ * (`packages/shared/src/hostnames.ts` at df26ab8). The relay's control plane
198
+ * enforces the same rules on the names a site may claim, so a config this
199
+ * module refuses would be refused there too. Keep in sync.
200
+ */
201
+ /** Site IDs are opaque: 10 chars, [a-z0-9], first char a letter. */
202
+ const SITE_ID_RE = /^[a-z][a-z0-9]{9}$/;
203
+ /** One DNS label as we allow it: 1-63 chars of [a-z0-9-], no leading/trailing dash. */
204
+ const LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
205
+ function isSiteId(value) {
206
+ return SITE_ID_RE.test(value);
207
+ }
208
+ /** Lowercase ASCII, no trailing dot, every label well formed, at most 253 chars. */
209
+ function isWellFormedHostname(value) {
210
+ if (value.length === 0 || value.length > 253) return false;
211
+ if (value !== value.toLowerCase()) return false;
212
+ return value.split(".").every((label) => LABEL_RE.test(label));
213
+ }
214
+ /** A site zone: well formed, at least two labels, no punycode. */
215
+ function isSiteZone(value) {
216
+ if (!isWellFormedHostname(value)) return false;
217
+ const labels = value.split(".");
218
+ return labels.length >= 2 && !labels.some((label) => label.startsWith("xn--"));
219
+ }
220
+ /** The wildcard name every site gets. */
221
+ function siteWildcard(siteZone) {
222
+ return `*.${siteZone}`;
223
+ }
224
+ //#endregion
225
+ //#region src/site/render-caddyfile.ts
226
+ /**
227
+ * The switchboard's HTTP surface as Caddy path matchers, from the one list
228
+ * Connect's own servers proxy (`SWITCHBOARD_PROXY_PATHS`): `/x` and `/x/*`
229
+ * for a bare prefix, `/x/*` for one that ends in a slash. `/d/*` is listed
230
+ * apart: a browser navigation there is one of Connect's routes.
231
+ */
232
+ const SWITCHBOARD_PATHS = SWITCHBOARD_PROXY_PATHS.filter((prefix) => prefix !== "/d/").flatMap((prefix) => prefix.endsWith("/") ? [`${prefix}*`] : [prefix, `${prefix}/*`]);
233
+ function port$1(value, what) {
234
+ if (!Number.isInteger(value) || value < 1 || value > 65535) throw new Error(`invalid ${what}: ${JSON.stringify(value)}`);
235
+ return value;
236
+ }
237
+ /** Caddyfile quoted string: backslash and double quote escaped. */
238
+ function q(value) {
239
+ if (/[\r\n]/.test(value)) throw new Error("newline in Caddyfile value");
240
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
241
+ }
242
+ function token(value, what) {
243
+ if (!/^[A-Za-z0-9.:/_\-@+=]+$/.test(value)) throw new Error(`invalid ${what}: ${JSON.stringify(value)}`);
244
+ return value;
245
+ }
246
+ function renderCaddyfile(input) {
247
+ if (!isSiteId(input.siteId)) throw new Error(`invalid siteId ${input.siteId}`);
248
+ if (!isSiteZone(input.siteZone)) throw new Error(`invalid siteZone ${input.siteZone}`);
249
+ for (const v of input.vanityDomains) if (!isWellFormedHostname(v) || v.includes("*")) throw new Error(`invalid vanity domain ${v}`);
250
+ if (input.resolvers.length === 0) throw new Error("at least one resolver is required");
251
+ const wildcard = siteWildcard(input.siteZone);
252
+ const upstream = token(input.appUpstream, "app upstream");
253
+ const labelled = Object.entries(input.upstreams ?? {}).map(([label, target]) => {
254
+ if (!LABEL_RE.test(label) || label !== label.toLowerCase()) throw new Error(`invalid upstream label: ${JSON.stringify(label)}`);
255
+ return {
256
+ label,
257
+ target: token(target, `upstream for ${label}`)
258
+ };
259
+ }).sort((a, b) => a.label < b.label ? -1 : 1);
260
+ const allow = token(input.proxyAllowCidr, "PROXY allow CIDR");
261
+ const resolvers = input.resolvers.map((r) => token(r, "resolver")).join(" ");
262
+ const dns = input.dns01.mode === "rfc2136" ? ` dns rfc2136 {
263
+ key_name ${q(input.dns01.keyName)}
264
+ key_alg ${q(input.dns01.keyAlg)}
265
+ key ${q(input.dns01.secret)}
266
+ server ${q(input.dns01.server)}
267
+ }` : ` dns acmedns {
268
+ username ${q(input.dns01.username)}
269
+ password ${q(input.dns01.password)}
270
+ subdomain ${q(input.dns01.subdomain)}
271
+ server_url ${q(input.dns01.serverUrl)}
272
+ }`;
273
+ /** One reverse_proxy directive at the given tab depth. */
274
+ const proxy = (target, depth) => {
275
+ const t = " ".repeat(depth);
276
+ return input.rewriteHostHeader ? `${t}reverse_proxy ${target} {\n${t}\theader_up Host {upstream_hostport}\n${t}}` : `${t}reverse_proxy ${target}`;
277
+ };
278
+ const https = port$1(input.listen?.https ?? 443, "HTTPS port");
279
+ const http = port$1(input.listen?.http ?? 80, "HTTP port");
280
+ if (https === http) throw new Error("HTTPS and HTTP ports must differ");
281
+ const globals = [
282
+ ` email ${token(input.email, "email")}`,
283
+ https !== 443 ? ` https_port ${https}` : "",
284
+ http !== 80 ? ` http_port ${http}` : "",
285
+ input.acmeCaUrl ? ` acme_ca ${token(input.acmeCaUrl, "ACME CA URL")}` : "",
286
+ input.acmeCaRootFile ? ` acme_ca_root ${q(input.acmeCaRootFile.replace(/\\/g, "/"))}` : "",
287
+ `
288
+ # PROXY protocol v2 from frpc only; plain LAN clients pass through unchanged
289
+ # (ignore = a spoofed header from anyone else is parsed and discarded).
290
+ servers :${https} {
291
+ listener_wrappers {
292
+ proxy_protocol {
293
+ timeout 5s
294
+ allow ${allow}
295
+ fallback_policy ignore
296
+ }
297
+ tls
298
+ }
299
+ }`,
300
+ input.vanityDomains.length > 0 ? `
301
+ # Vanity domains are issued on demand, only when the control plane approves the name.
302
+ on_demand_tls {
303
+ ask ${token(input.askUrl, "ask URL")}
304
+ }` : "",
305
+ `
306
+ log {
307
+ output stdout
308
+ level INFO
309
+ }`
310
+ ].filter((l) => l !== "").join("\n");
311
+ const vanity = input.vanityDomains.length > 0 ? `
312
+ # Vanity domains (${input.vanityDomains.join(", ")}): validated by http-01 or
313
+ # tls-alpn-01 through the relay. No DNS config here, so those stay enabled.
314
+ https:// {
315
+ tls {
316
+ on_demand
317
+ }
318
+ ${proxy(upstream, 1)}
319
+ }
320
+ ` : "";
321
+ const appRoute = input.appRoute;
322
+ if (appRoute) {
323
+ if (!labelled.some((l) => l.label === appRoute.label)) throw new Error(`appRoute names label ${JSON.stringify(appRoute.label)}, which has no upstream`);
324
+ token(appRoute.apiTarget, "appRoute.apiTarget");
325
+ }
326
+ /**
327
+ * The label's handle body: the plain proxy, or the same-origin split (the
328
+ * same rules as Connect's own dev and preview servers): the switchboard's
329
+ * paths go to the API upstream, `/d/*` too unless the request is a browser
330
+ * navigation (it accepts HTML), which is one of Connect's routes.
331
+ */
332
+ const labelBody = (label, target) => {
333
+ if (!appRoute || appRoute.label !== label) return proxy(target, 2);
334
+ return [` @switchboard path ${SWITCHBOARD_PATHS.join(" ")}
335
+ handle @switchboard {
336
+ ${proxy(appRoute.apiTarget, 3)}
337
+ }
338
+ @drive {
339
+ path /d/*
340
+ not header Accept *text/html*
341
+ }
342
+ handle @drive {
343
+ ${proxy(appRoute.apiTarget, 3)}
344
+ }`, ` handle {
345
+ ${proxy(target, 3)}
346
+ }`].join("\n");
347
+ };
348
+ const routing = labelled.length === 0 ? proxy(upstream, 1) : [...labelled.map(({ label, target }) => ` @${label} host ${label}.${input.siteZone}
349
+ handle @${label} {
350
+ ${labelBody(label, target)}
351
+ }`), ` handle {
352
+ ${proxy(upstream, 2)}
353
+ }`].join("\n");
354
+ return `# Generated by @powerhousedao/portle for site ${input.siteId} (${input.siteZone}). Do not edit; the plugin rewrites it.
355
+ {
356
+ ${globals}
357
+ }
358
+
359
+ # Wildcard only, never the zone apex: one certificate per site. DNS-01 is
360
+ # configured only inside this block so other challenge types stay available.
361
+ ${wildcard} {
362
+ tls {
363
+ ${dns}
364
+ resolvers ${resolvers}
365
+ propagation_delay 2s
366
+ }
367
+ ${routing}
368
+ }
369
+ ${vanity}`;
370
+ }
371
+ function rfc2136Dns(keyName, secret, server, keyAlg = "hmac-sha256") {
372
+ return {
373
+ mode: "rfc2136",
374
+ keyName,
375
+ keyAlg,
376
+ secret,
377
+ server
378
+ };
379
+ }
380
+ //#endregion
381
+ //#region src/site/render-frpc.ts
382
+ function port(value, what) {
383
+ if (!Number.isInteger(value) || value < 1 || value > 65535) throw new Error(`invalid ${what}: ${JSON.stringify(value)}`);
384
+ return value;
385
+ }
386
+ /** TOML basic strings share JSON's escaping rules for everything we emit. */
387
+ function s(value) {
388
+ return JSON.stringify(value);
389
+ }
390
+ function renderFrpcToml(input) {
391
+ if (!isSiteId(input.siteId)) throw new Error(`invalid siteId ${input.siteId}`);
392
+ if (!isSiteZone(input.siteZone)) throw new Error(`invalid siteZone ${input.siteZone}`);
393
+ for (const v of input.vanityDomains) if (!isWellFormedHostname(v) || v.includes("*")) throw new Error(`invalid vanity domain ${v}`);
394
+ if (!Number.isInteger(input.serverPort) || input.serverPort <= 0 || input.serverPort > 65535) throw new Error(`invalid serverPort ${input.serverPort}`);
395
+ const list = `[${[siteWildcard(input.siteZone), ...input.vanityDomains].map(s).join(", ")}]`;
396
+ const httpsPort = port(input.localHttpsPort ?? 443, "local HTTPS port");
397
+ const httpPort = port(input.localHttpPort ?? 80, "local HTTP port");
398
+ return `# Generated by @powerhousedao/portle for site ${input.siteId} (${input.siteZone}). Do not edit; the plugin rewrites it.
399
+ serverAddr = ${s(input.serverAddr)}
400
+ serverPort = ${input.serverPort}
401
+ user = ${s(input.siteId)}
402
+ clientID = ${s(input.siteId)}
403
+ loginFailExit = false
404
+
405
+ auth.method = "token"
406
+ auth.token = ${s(input.token)}
407
+
408
+ # Per-site identity, validated by the control plane's frps Login plugin.
409
+ metadatas.site_id = ${s(input.siteId)}
410
+ metadatas.site_secret = ${s(input.siteSecret)}
411
+
412
+ # frpc does not verify frps's certificate unless trustedCaFile is set.
413
+ transport.tls.enable = true
414
+ transport.tls.trustedCaFile = ${s(input.trustedCaFile)}
415
+ transport.tls.serverName = ${s(input.serverName)}
416
+
417
+ webServer.addr = "127.0.0.1"
418
+ webServer.port = 7400
419
+
420
+ log.to = "console"
421
+ log.level = "info"
422
+
423
+ # TLS passthrough (frps routes by SNI, never decrypts); PROXY v2 carries the
424
+ # visitor address to Caddy. PROXY protocol only here, never on the http proxy.
425
+ [[proxies]]
426
+ name = "tls"
427
+ type = "https"
428
+ localIP = ${s(input.caddyHost)}
429
+ localPort = ${httpsPort}
430
+ customDomains = ${list}
431
+ transport.proxyProtocolVersion = "v2"
432
+
433
+ # Plain HTTP: Caddy redirects to HTTPS; also carries http-01 for vanity domains.
434
+ [[proxies]]
435
+ name = "web"
436
+ type = "http"
437
+ localIP = ${s(input.caddyHost)}
438
+ localPort = ${httpPort}
439
+ customDomains = ${list}
440
+ `;
441
+ }
442
+ //#endregion
443
+ //#region src/state.ts
444
+ /**
445
+ * Everything the plugin keeps on disk lives under `<project>/.ph/portle/`:
446
+ *
447
+ * enrollment.json the site's identity and secrets (mode 600)
448
+ * site.json the operator's choices: what the tunnel exposes, autostart
449
+ * frpc.toml, Caddyfile, certs/ rendered on every start (mode 600)
450
+ * caddy/ Caddy's data dir: the certificate, which must persist
451
+ * logs/ frpc.log, caddy.log
452
+ */
453
+ const PORTLE_DIR = join(".ph", "portle");
454
+ const ENROLLMENT_FILE = "enrollment.json";
455
+ const SITE_FILE = "site.json";
456
+ /**
457
+ * The project root the switchboard serves: the directory of its config file
458
+ * when the host passed one, else the working directory.
459
+ */
460
+ function projectRootOf(options) {
461
+ const configFile = options?.configFile;
462
+ return typeof configFile === "string" && configFile.length > 0 ? dirname(resolve(configFile)) : process.cwd();
463
+ }
464
+ function stateDirOf(projectRoot) {
465
+ return join(projectRoot, PORTLE_DIR);
466
+ }
467
+ /**
468
+ * Where this host keeps its Portle state: with the rest of its `.ph`. A desktop
469
+ * app points `PH_USER_DATA_DIR` at the identity that signed in, so each identity
470
+ * has its own site, and a run with its own data can't pick up this project's
471
+ * enrolment and bring up its tunnel.
472
+ */
473
+ function hostStateDir(options, env = process.env) {
474
+ return stateDirOf(env.PH_USER_DATA_DIR || projectRootOf(options));
475
+ }
476
+ /** Writes atomically (temp file + rename) with the given mode (best effort on Windows). */
477
+ function writeFileAtomic(path, content, mode = 420) {
478
+ mkdirSync(dirname(path), { recursive: true });
479
+ const tmp = `${path}.tmp`;
480
+ writeFileSync(tmp, content, {
481
+ encoding: "utf8",
482
+ mode
483
+ });
484
+ try {
485
+ chmodSync(tmp, mode);
486
+ } catch {}
487
+ renameSync(tmp, path);
488
+ }
489
+ function readEnrollment(stateDir) {
490
+ const path = join(stateDir, ENROLLMENT_FILE);
491
+ if (!existsSync(path)) return null;
492
+ const data = JSON.parse(readFileSync(path, "utf8"));
493
+ if (!data.siteId || !data.siteSecret || !data.dns?.tsigSecret) throw new Error(`${path} is not a valid enrolment`);
494
+ return data;
495
+ }
496
+ function writeEnrollment(stateDir, enrollment) {
497
+ writeFileAtomic(join(stateDir, ENROLLMENT_FILE), `${JSON.stringify(enrollment, null, 2)}\n`, 384);
498
+ }
499
+ const DEFAULT_SITE_SETTINGS = {
500
+ appUpstream: "127.0.0.1:3000",
501
+ upstreams: {},
502
+ dns01Mode: "rfc2136",
503
+ listen: {
504
+ https: 443,
505
+ http: 80
506
+ },
507
+ rewriteHostHeader: false,
508
+ sameOrigin: true,
509
+ autostart: false
510
+ };
511
+ function readSiteSettings(stateDir) {
512
+ const path = join(stateDir, SITE_FILE);
513
+ if (!existsSync(path)) return null;
514
+ const data = JSON.parse(readFileSync(path, "utf8"));
515
+ if (typeof data.controlPlaneUrl !== "string") throw new Error(`${path} names no control plane`);
516
+ return {
517
+ ...DEFAULT_SITE_SETTINGS,
518
+ ...data,
519
+ controlPlaneUrl: data.controlPlaneUrl
520
+ };
521
+ }
522
+ function writeSiteSettings(stateDir, settings) {
523
+ writeFileAtomic(join(stateDir, SITE_FILE), `${JSON.stringify(settings, null, 2)}\n`, 384);
524
+ }
525
+ //#endregion
526
+ //#region src/supervisor.ts
527
+ var Supervised = class {
528
+ #opts;
529
+ #child = null;
530
+ #startedAt = null;
531
+ #restarts = 0;
532
+ #delayMs;
533
+ #lastExit = null;
534
+ #stopping = false;
535
+ #restartTimer = null;
536
+ #exited = null;
537
+ constructor(options) {
538
+ this.#opts = {
539
+ backoff: {
540
+ initialMs: 1e3,
541
+ maxMs: 3e4
542
+ },
543
+ healthyAfterMs: 3e4,
544
+ stopTimeoutMs: 5e3,
545
+ platform: process.platform,
546
+ ...options
547
+ };
548
+ this.#delayMs = this.#opts.backoff.initialMs;
549
+ }
550
+ status() {
551
+ return {
552
+ name: this.#opts.name,
553
+ command: [this.#opts.command, ...this.#opts.args].join(" "),
554
+ running: this.#child !== null,
555
+ pid: this.#child?.pid ?? null,
556
+ startedAt: this.#startedAt ? new Date(this.#startedAt).toISOString() : null,
557
+ restarts: this.#restarts,
558
+ lastExit: this.#lastExit
559
+ };
560
+ }
561
+ start() {
562
+ if (this.#child) return;
563
+ this.#stopping = false;
564
+ this.#spawn();
565
+ }
566
+ async stop() {
567
+ this.#stopping = true;
568
+ if (this.#restartTimer) {
569
+ clearTimeout(this.#restartTimer);
570
+ this.#restartTimer = null;
571
+ }
572
+ const child = this.#child;
573
+ const exited = this.#exited;
574
+ if (!child || !exited) return;
575
+ this.#kill(child, "SIGTERM");
576
+ let timer;
577
+ const timedOut = await Promise.race([exited.then(() => false), new Promise((resolve) => {
578
+ timer = setTimeout(() => resolve(true), this.#opts.stopTimeoutMs);
579
+ })]);
580
+ clearTimeout(timer);
581
+ if (timedOut) this.#kill(child, "SIGKILL");
582
+ await exited;
583
+ this.#opts.onEvent?.({
584
+ type: "stopped",
585
+ name: this.#opts.name
586
+ });
587
+ }
588
+ #spawn() {
589
+ const { command, args, cwd, logFile, env, platform } = this.#opts;
590
+ mkdirSync(dirname(logFile), { recursive: true });
591
+ const fd = openSync(logFile, "a");
592
+ let child;
593
+ try {
594
+ child = (this.#opts.spawnImpl ?? spawn)(command, args, {
595
+ cwd,
596
+ env: env ?? process.env,
597
+ stdio: [
598
+ "ignore",
599
+ fd,
600
+ fd
601
+ ],
602
+ windowsHide: true,
603
+ detached: platform !== "win32"
604
+ });
605
+ } catch (error) {
606
+ closeSync(fd);
607
+ this.#opts.onEvent?.({
608
+ type: "spawn-failed",
609
+ name: this.#opts.name,
610
+ error: String(error)
611
+ });
612
+ this.#scheduleRestart(null, null);
613
+ return;
614
+ }
615
+ closeSync(fd);
616
+ this.#child = child;
617
+ this.#startedAt = Date.now();
618
+ const startedAt = this.#startedAt;
619
+ this.#exited = new Promise((resolve) => {
620
+ const done = (code, signal) => {
621
+ if (this.#child !== child) return;
622
+ this.#child = null;
623
+ this.#lastExit = {
624
+ code,
625
+ signal,
626
+ at: (/* @__PURE__ */ new Date()).toISOString()
627
+ };
628
+ if (Date.now() - startedAt >= this.#opts.healthyAfterMs) this.#delayMs = this.#opts.backoff.initialMs;
629
+ resolve();
630
+ if (!this.#stopping) this.#scheduleRestart(code, signal);
631
+ };
632
+ child.once("exit", done);
633
+ child.once("error", (error) => {
634
+ this.#opts.onEvent?.({
635
+ type: "spawn-failed",
636
+ name: this.#opts.name,
637
+ error: error.message
638
+ });
639
+ if (child.pid === void 0) done(null, null);
640
+ });
641
+ });
642
+ if (child.pid !== void 0) this.#opts.onEvent?.({
643
+ type: "started",
644
+ name: this.#opts.name,
645
+ pid: child.pid
646
+ });
647
+ }
648
+ #scheduleRestart(code, signal) {
649
+ const delayMs = this.#delayMs;
650
+ this.#opts.onEvent?.({
651
+ type: "exited",
652
+ name: this.#opts.name,
653
+ code,
654
+ signal,
655
+ restarting: true,
656
+ delayMs
657
+ });
658
+ this.#delayMs = Math.min(this.#delayMs * 2, this.#opts.backoff.maxMs);
659
+ this.#restartTimer = setTimeout(() => {
660
+ this.#restartTimer = null;
661
+ if (this.#stopping) return;
662
+ this.#restarts += 1;
663
+ this.#spawn();
664
+ }, delayMs);
665
+ this.#restartTimer.unref();
666
+ }
667
+ #kill(child, signal) {
668
+ const pid = child.pid;
669
+ if (pid === void 0) return;
670
+ if (this.#opts.platform === "win32") {
671
+ spawnSync("taskkill", [
672
+ "/PID",
673
+ String(pid),
674
+ "/T",
675
+ "/F"
676
+ ], {
677
+ windowsHide: true,
678
+ stdio: "ignore"
679
+ });
680
+ return;
681
+ }
682
+ try {
683
+ process.kill(-pid, signal);
684
+ } catch {
685
+ try {
686
+ process.kill(pid, signal);
687
+ } catch {}
688
+ }
689
+ }
690
+ };
691
+ //#endregion
692
+ //#region src/runner.ts
693
+ var PortleRunner = class {
694
+ #deps;
695
+ #frpc = null;
696
+ #caddy = null;
697
+ constructor(deps) {
698
+ this.#deps = {
699
+ ...deps,
700
+ stateDir: resolve(deps.stateDir)
701
+ };
702
+ }
703
+ get stateDir() {
704
+ return this.#deps.stateDir;
705
+ }
706
+ status() {
707
+ const enrollment = this.#enrollment();
708
+ const settings = enrollment ? readSiteSettings(this.#deps.stateDir) : null;
709
+ const frpc = this.#frpc?.status() ?? null;
710
+ const caddy = this.#caddy?.status() ?? null;
711
+ const running = [frpc?.running, caddy?.running].filter(Boolean).length;
712
+ const labels = Object.keys(settings?.upstreams ?? {});
713
+ return {
714
+ stateDir: this.#deps.stateDir,
715
+ enrolled: enrollment !== null,
716
+ siteId: enrollment?.siteId ?? null,
717
+ siteZone: enrollment?.siteZone ?? null,
718
+ zoneKind: enrollment?.zoneKind ?? null,
719
+ delegation: enrollment?.delegation ?? null,
720
+ settings,
721
+ binaries: resolveBinaries(this.#deps),
722
+ tunnel: {
723
+ state: running === 2 ? "up" : running === 0 ? "down" : "degraded",
724
+ frpc,
725
+ caddy
726
+ },
727
+ urls: enrollment ? (labels.length ? labels : ["app"]).map((label) => `https://${label}.${enrollment.siteZone}/`) : []
728
+ };
729
+ }
730
+ /** For status: a resolver that cannot answer reads as not delegated (yet). */
731
+ async checkDelegation() {
732
+ const delegation = this.#enrollment()?.delegation;
733
+ if (!delegation) return null;
734
+ try {
735
+ return await isDelegated(delegation, this.#deps.resolveNs, this.#deps.delegationCheck);
736
+ } catch (error) {
737
+ if (error instanceof DelegationCheckError) return false;
738
+ throw error;
739
+ }
740
+ }
741
+ async enrol(input) {
742
+ if (this.#enrollment()) throw new Error("this project is already enrolled; remove .ph/portle/enrollment.json to enrol again");
743
+ const controlPlaneUrl = input.controlPlaneUrl.replace(/\/$/, "");
744
+ if (!/^https?:\/\//.test(controlPlaneUrl)) throw new Error("controlPlaneUrl must be an http(s) URL");
745
+ const enrollment = await enrolWithControlPlane(controlPlaneUrl, input.token, this.#deps.fetchImpl);
746
+ writeEnrollment(this.#deps.stateDir, enrollment);
747
+ const existing = readSiteSettings(this.#deps.stateDir);
748
+ writeSiteSettings(this.#deps.stateDir, {
749
+ ...DEFAULT_SITE_SETTINGS,
750
+ ...existing,
751
+ controlPlaneUrl,
752
+ autostart: false
753
+ });
754
+ this.#deps.log?.("enrolled", {
755
+ siteId: enrollment.siteId,
756
+ siteZone: enrollment.siteZone,
757
+ zoneKind: enrollment.zoneKind
758
+ });
759
+ return this.status();
760
+ }
761
+ configure(patch) {
762
+ const settings = this.#settings();
763
+ if (patch.upstreams) for (const [label, target] of Object.entries(patch.upstreams)) {
764
+ if (!LABEL_RE.test(label)) throw new Error(`invalid upstream label ${JSON.stringify(label)}`);
765
+ if (!target) throw new Error(`upstream ${label} has no target`);
766
+ }
767
+ const mode = patch.dns01Mode;
768
+ if (mode && mode !== "rfc2136" && mode !== "acmedns") throw new Error(`dns01Mode must be rfc2136 or acmedns`);
769
+ if (patch.listen) {
770
+ for (const [name, value] of Object.entries(patch.listen)) if (!Number.isInteger(value) || value < 1 || value > 65535) throw new Error(`listen.${name} must be a port number`);
771
+ if (patch.listen.https === patch.listen.http) throw new Error("listen.https and listen.http must differ");
772
+ }
773
+ writeSiteSettings(this.#deps.stateDir, {
774
+ ...settings,
775
+ ...patch
776
+ });
777
+ return this.status();
778
+ }
779
+ /** Writes the CA files, frpc.toml and the Caddyfile for the current enrolment and settings. */
780
+ render() {
781
+ const enrollment = this.#requireEnrollment();
782
+ const settings = this.#settings();
783
+ const dir = this.#deps.stateDir;
784
+ const certsDir = join(dir, "certs");
785
+ mkdirSync(certsDir, { recursive: true });
786
+ writeFileAtomic(join(certsDir, "relay-ca.crt"), enrollment.frp.caPem, 384);
787
+ const acmeRoot = enrollment.acme.caRootPem ? join(certsDir, "acme-ca-root.pem") : void 0;
788
+ if (acmeRoot && enrollment.acme.caRootPem) writeFileAtomic(acmeRoot, enrollment.acme.caRootPem, 384);
789
+ const frpcConfig = join(dir, "frpc.toml");
790
+ writeFileAtomic(frpcConfig, renderFrpcToml({
791
+ siteId: enrollment.siteId,
792
+ siteSecret: enrollment.siteSecret,
793
+ siteZone: enrollment.siteZone,
794
+ serverAddr: enrollment.frp.serverAddr,
795
+ serverPort: enrollment.frp.serverPort,
796
+ serverName: enrollment.frp.serverName,
797
+ token: enrollment.frp.token,
798
+ trustedCaFile: join(certsDir, "relay-ca.crt"),
799
+ caddyHost: "127.0.0.1",
800
+ vanityDomains: [],
801
+ localHttpsPort: settings.listen.https,
802
+ localHttpPort: settings.listen.http
803
+ }), 384);
804
+ const dns01 = settings.dns01Mode === "acmedns" ? {
805
+ mode: "acmedns",
806
+ username: enrollment.acmeDns.username,
807
+ password: enrollment.acmeDns.password,
808
+ subdomain: enrollment.acmeDns.subdomain,
809
+ serverUrl: enrollment.acmeDns.baseUrl
810
+ } : rfc2136Dns(enrollment.dns.tsigKeyName, enrollment.dns.tsigSecret, enrollment.dns.server, enrollment.dns.tsigAlgorithm);
811
+ const dnsHost = enrollment.dns.server.split(":")[0] ?? enrollment.dns.server;
812
+ const appRoute = this.#appRoute(settings);
813
+ const caddyfile = join(dir, "Caddyfile");
814
+ writeFileAtomic(caddyfile, renderCaddyfile({
815
+ siteId: enrollment.siteId,
816
+ siteZone: enrollment.siteZone,
817
+ email: enrollment.acme.email,
818
+ acmeCaUrl: enrollment.acme.caUrl,
819
+ acmeCaRootFile: acmeRoot,
820
+ proxyAllowCidr: "127.0.0.1/32",
821
+ appUpstream: settings.appUpstream,
822
+ upstreams: settings.upstreams,
823
+ vanityDomains: [],
824
+ askUrl: `${settings.controlPlaneUrl}/v1/tls/ask`,
825
+ resolvers: enrollment.dns.resolvers.length ? enrollment.dns.resolvers : [dnsHost],
826
+ dns01,
827
+ listen: settings.listen,
828
+ rewriteHostHeader: settings.rewriteHostHeader ?? false,
829
+ appRoute
830
+ }), 384);
831
+ return {
832
+ frpcConfig,
833
+ caddyfile,
834
+ certsDir
835
+ };
836
+ }
837
+ /**
838
+ * Brings the tunnel up. A customer zone must be delegated first: Caddy
839
+ * would otherwise ask the CA for a name the CA cannot resolve, and the
840
+ * negative answer is cached for an hour.
841
+ */
842
+ async start() {
843
+ const delegation = this.#requireEnrollment().delegation;
844
+ let delegated = true;
845
+ if (delegation) try {
846
+ delegated = await isDelegated(delegation, this.#deps.resolveNs, this.#deps.delegationCheck);
847
+ } catch (error) {
848
+ if (error instanceof DelegationCheckError) throw new Error(`cannot start: ${error.message}. This is a DNS lookup failure, not a missing delegation: start again once DNS answers.`, { cause: error });
849
+ throw error;
850
+ }
851
+ if (delegation && !delegated) throw new Error(`cannot start: ${delegation.zone} is not delegated yet. Create at your DNS provider: ${delegation.nameservers.map((ns) => `${delegation.zone} NS ${ns}`).join("; ")} — then start again.`);
852
+ const binaries = resolveBinaries(this.#deps);
853
+ const missing = ["frpc", "caddy"].filter((name) => !binaries[name]);
854
+ if (missing.length > 0) throw new Error(`cannot start: ${missing.join(" and ")} not found (set ${missing.map((n) => n === "frpc" ? "PORTLE_FRPC_BIN" : "PORTLE_CADDY_BIN").join(", ")} or install into ~/.ph/portle/bin). Looked at: ${binaries.searched.join(", ")}`);
855
+ const { frpcConfig, caddyfile } = this.render();
856
+ return this.#startNow({
857
+ frpc: binaries.frpc,
858
+ caddy: binaries.caddy
859
+ }, {
860
+ frpcConfig,
861
+ caddyfile
862
+ });
863
+ }
864
+ #startNow(binaries, { frpcConfig, caddyfile }) {
865
+ const dir = this.#deps.stateDir;
866
+ const logs = join(dir, "logs");
867
+ const create = this.#deps.createSupervised ?? ((options) => new Supervised(options));
868
+ const log = this.#deps.log;
869
+ const onEvent = (event) => log?.("tunnel", event);
870
+ if (!this.#caddy) {
871
+ const caddyHome = join(dir, "caddy");
872
+ mkdirSync(caddyHome, { recursive: true });
873
+ this.#caddy = create({
874
+ name: "caddy",
875
+ command: binaries.caddy,
876
+ args: [
877
+ "run",
878
+ "--config",
879
+ caddyfile,
880
+ "--adapter",
881
+ "caddyfile"
882
+ ],
883
+ cwd: dir,
884
+ logFile: join(logs, "caddy.log"),
885
+ env: {
886
+ ...this.#deps.env ?? process.env,
887
+ XDG_DATA_HOME: caddyHome,
888
+ XDG_CONFIG_HOME: join(caddyHome, "config")
889
+ },
890
+ onEvent
891
+ });
892
+ }
893
+ if (!this.#frpc) this.#frpc = create({
894
+ name: "frpc",
895
+ command: binaries.frpc,
896
+ args: ["-c", frpcConfig],
897
+ cwd: dir,
898
+ logFile: join(logs, "frpc.log"),
899
+ env: this.#deps.env ?? process.env,
900
+ onEvent
901
+ });
902
+ this.#caddy.start();
903
+ this.#frpc.start();
904
+ writeSiteSettings(dir, {
905
+ ...this.#settings(),
906
+ autostart: true
907
+ });
908
+ log?.("tunnel started", { siteZone: this.#requireEnrollment().siteZone });
909
+ return this.status();
910
+ }
911
+ async stop(options = {}) {
912
+ await this.#frpc?.stop();
913
+ await this.#caddy?.stop();
914
+ this.#frpc = null;
915
+ this.#caddy = null;
916
+ if (!options.keepAutostart && this.#enrollment() && readSiteSettings(this.#deps.stateDir)) writeSiteSettings(this.#deps.stateDir, {
917
+ ...this.#settings(),
918
+ autostart: false
919
+ });
920
+ this.#deps.log?.("tunnel stopped", { autostart: this.wantsAutostart() });
921
+ return this.status();
922
+ }
923
+ /** Whether the operator asked for the tunnel to come up at boot. */
924
+ wantsAutostart() {
925
+ return this.#enrollment() !== null && readSiteSettings(this.#deps.stateDir)?.autostart === true;
926
+ }
927
+ /**
928
+ * Same-origin publication for the `app` label: its handle also proxies the
929
+ * switchboard's paths to the `api` upstream, the same split Connect's own
930
+ * dev and preview servers make (the connect runner's `runner.proxy`), so
931
+ * the SPA calls its own origin for everything and its served config, which
932
+ * names the switchboard as `${origin}`, resolves to this label in the
933
+ * browser. No cross-origin requests, no browser prompt for a local
934
+ * address, and nothing rendered or fetched from the app at start.
935
+ */
936
+ #appRoute(settings) {
937
+ if (settings.sameOrigin === false) return void 0;
938
+ const app = settings.upstreams.app;
939
+ const api = settings.upstreams.api;
940
+ if (!app || !api) return void 0;
941
+ return {
942
+ label: "app",
943
+ apiTarget: api
944
+ };
945
+ }
946
+ #enrollment() {
947
+ return existsSync(this.#deps.stateDir) ? readEnrollment(this.#deps.stateDir) : null;
948
+ }
949
+ #requireEnrollment() {
950
+ const enrollment = this.#enrollment();
951
+ if (!enrollment) throw new Error("this project is not enrolled with Portle yet");
952
+ return enrollment;
953
+ }
954
+ #settings() {
955
+ const settings = readSiteSettings(this.#deps.stateDir);
956
+ if (!settings) throw new Error("this project is not enrolled with Portle yet");
957
+ return settings;
958
+ }
959
+ };
960
+ //#endregion
961
+ //#region src/subgraph.ts
962
+ const PORTLE_SUBGRAPH_NAME = "portle";
963
+ const portleTypeDefs = parse(`
964
+ type PortleCheck {
965
+ id: String!
966
+ ok: Boolean!
967
+ detail: String!
968
+ fix: String
969
+ }
970
+
971
+ type PortleCaller {
972
+ address: String
973
+ isAdmin: Boolean!
974
+ }
975
+
976
+ type PortleReadiness {
977
+ publishable: Boolean!
978
+ checks: [PortleCheck!]!
979
+ warnings: [PortleCheck!]!
980
+ me: PortleCaller!
981
+ }
982
+
983
+ type PortleSupervised {
984
+ name: String!
985
+ command: String!
986
+ running: Boolean!
987
+ pid: Int
988
+ startedAt: String
989
+ restarts: Int!
990
+ lastExitCode: Int
991
+ lastExitSignal: String
992
+ lastExitAt: String
993
+ }
994
+
995
+ type PortleTunnel {
996
+ """
997
+ down, degraded (one of the two processes), or up
998
+ """
999
+ state: String!
1000
+ frpc: PortleSupervised
1001
+ caddy: PortleSupervised
1002
+ }
1003
+
1004
+ type PortleDelegation {
1005
+ zone: String!
1006
+ nameservers: [String!]!
1007
+ """
1008
+ Whether the zone's NS records already point at the relay, as this
1009
+ machine's resolver sees it. Known on portleStatus; null elsewhere.
1010
+ """
1011
+ delegated: Boolean
1012
+ }
1013
+
1014
+ type PortleListen {
1015
+ https: Int!
1016
+ http: Int!
1017
+ }
1018
+
1019
+ type PortleUpstream {
1020
+ label: String!
1021
+ target: String!
1022
+ }
1023
+
1024
+ type PortleSettings {
1025
+ controlPlaneUrl: String!
1026
+ appUpstream: String!
1027
+ upstreams: [PortleUpstream!]!
1028
+ dns01Mode: String!
1029
+ listen: PortleListen!
1030
+ rewriteHostHeader: Boolean!
1031
+ sameOrigin: Boolean!
1032
+ autostart: Boolean!
1033
+ }
1034
+
1035
+ type PortleBinaries {
1036
+ frpc: String
1037
+ caddy: String
1038
+ searched: [String!]!
1039
+ }
1040
+
1041
+ type PortleStatus {
1042
+ stateDir: String!
1043
+ enrolled: Boolean!
1044
+ siteId: String
1045
+ siteZone: String
1046
+ zoneKind: String
1047
+ delegation: PortleDelegation
1048
+ settings: PortleSettings
1049
+ binaries: PortleBinaries!
1050
+ tunnel: PortleTunnel!
1051
+ urls: [String!]!
1052
+ }
1053
+
1054
+ input PortleUpstreamInput {
1055
+ label: String!
1056
+ target: String!
1057
+ }
1058
+
1059
+ type Query {
1060
+ """
1061
+ Whether this host may be published through Portle, check by check.
1062
+ Under an OPEN policy it answers everyone, since there is no admin to
1063
+ distinguish; under any other policy only a listed admin may ask.
1064
+ """
1065
+ portleReadiness: PortleReadiness!
1066
+ """
1067
+ The site's enrolment, settings, binaries and tunnel. Admins only.
1068
+ """
1069
+ portleStatus: PortleStatus!
1070
+ }
1071
+
1072
+ type Mutation {
1073
+ """
1074
+ Enrol this project with a Portle control plane using a one-time token.
1075
+ """
1076
+ portleEnrol(controlPlaneUrl: String!, token: String!): PortleStatus!
1077
+ """
1078
+ What the tunnel exposes: the default upstream and per-label upstreams.
1079
+ """
1080
+ portleConfigure(
1081
+ appUpstream: String
1082
+ upstreams: [PortleUpstreamInput!]
1083
+ dns01Mode: String
1084
+ listenHttps: Int
1085
+ listenHttp: Int
1086
+ """
1087
+ Send the upstream's host:port as the Host header (for dev servers that
1088
+ check it, such as Vite's allowedHosts).
1089
+ """
1090
+ rewriteHostHeader: Boolean
1091
+ """
1092
+ Serve Connect and the switchboard on the app label's origin, with a
1093
+ runtime config that points the SPA at that origin (default on).
1094
+ """
1095
+ sameOrigin: Boolean
1096
+ ): PortleStatus!
1097
+ """
1098
+ Bring the tunnel up. Refused unless every readiness check passes for the caller.
1099
+ """
1100
+ portleStart: PortleStatus!
1101
+ portleStop: PortleStatus!
1102
+ }
1103
+ `);
1104
+ /** The host's authorization facts, read off the API object. */
1105
+ function gateFactsOf(api) {
1106
+ const config = api.authorizationService.config;
1107
+ return {
1108
+ policy: config.policy,
1109
+ admins: config.admins,
1110
+ defaultProtection: config.defaultProtection,
1111
+ identityResolved: api.authService !== void 0,
1112
+ requireAuthenticatedCaller: api.requireAuthenticatedCaller
1113
+ };
1114
+ }
1115
+ function forbidden(message) {
1116
+ return new GraphQLError(message, { extensions: { code: "FORBIDDEN" } });
1117
+ }
1118
+ function readiness(api, ctx) {
1119
+ const facts = gateFactsOf(api);
1120
+ const address = ctx.user?.address;
1121
+ const isAdmin = isListedAdmin(facts.admins, address);
1122
+ if (facts.policy !== "OPEN" && !isAdmin) throw forbidden("Portle readiness is for the host's admins.");
1123
+ return {
1124
+ ...evaluateGate(facts, ctx.user),
1125
+ me: {
1126
+ address: address ?? null,
1127
+ isAdmin
1128
+ }
1129
+ };
1130
+ }
1131
+ /** Every other field: a listed admin on a host that is not OPEN. */
1132
+ function requireAdmin(api, ctx) {
1133
+ const facts = gateFactsOf(api);
1134
+ if (facts.policy === "OPEN") throw forbidden("Portle is disabled while the host's authorization policy is OPEN; lock the host down first (see portleReadiness).");
1135
+ if (!isListedAdmin(facts.admins, ctx.user?.address)) throw forbidden("Portle is for the host's admins.");
1136
+ return facts;
1137
+ }
1138
+ /** The GraphQL shape of a status: maps become lists, exits flatten. */
1139
+ function toWireStatus(status, delegated = null) {
1140
+ const supervised = (s) => s && {
1141
+ name: s.name,
1142
+ command: s.command,
1143
+ running: s.running,
1144
+ pid: s.pid,
1145
+ startedAt: s.startedAt,
1146
+ restarts: s.restarts,
1147
+ lastExitCode: s.lastExit?.code ?? null,
1148
+ lastExitSignal: s.lastExit?.signal ?? null,
1149
+ lastExitAt: s.lastExit?.at ?? null
1150
+ };
1151
+ return {
1152
+ ...status,
1153
+ delegation: status.delegation && {
1154
+ ...status.delegation,
1155
+ delegated
1156
+ },
1157
+ settings: status.settings && {
1158
+ ...status.settings,
1159
+ rewriteHostHeader: status.settings.rewriteHostHeader ?? false,
1160
+ sameOrigin: status.settings.sameOrigin ?? true,
1161
+ upstreams: Object.entries(status.settings.upstreams).map(([label, target]) => ({
1162
+ label,
1163
+ target
1164
+ }))
1165
+ },
1166
+ tunnel: {
1167
+ state: status.tunnel.state,
1168
+ frpc: supervised(status.tunnel.frpc),
1169
+ caddy: supervised(status.tunnel.caddy)
1170
+ }
1171
+ };
1172
+ }
1173
+ /**
1174
+ * The `portle` subgraph as a plain `ISubgraph`: no reactor reads, no setup,
1175
+ * so it needs none of `BaseSubgraph` and keeps the plugin free of runtime
1176
+ * imports from reactor-api.
1177
+ */
1178
+ function createPortleSubgraph({ api, runner }) {
1179
+ const guarded = (run) => (_parent, args, ctx) => run(args, ctx, requireAdmin(api, ctx));
1180
+ return {
1181
+ name: PORTLE_SUBGRAPH_NAME,
1182
+ typeDefs: portleTypeDefs,
1183
+ relationalDb: api.relationalDb,
1184
+ hasSubscriptions: false,
1185
+ resolvers: {
1186
+ Query: {
1187
+ portleReadiness: (_parent, _args, ctx) => readiness(api, ctx),
1188
+ portleStatus: guarded(async () => toWireStatus(runner.status(), await runner.checkDelegation()))
1189
+ },
1190
+ Mutation: {
1191
+ portleEnrol: guarded(async (args) => toWireStatus(await runner.enrol({
1192
+ controlPlaneUrl: args.controlPlaneUrl,
1193
+ token: args.token
1194
+ }))),
1195
+ portleConfigure: guarded((args) => toWireStatus(runner.configure({
1196
+ ...args.appUpstream ? { appUpstream: args.appUpstream } : {},
1197
+ ...args.upstreams ? { upstreams: Object.fromEntries(args.upstreams.map((u) => [u.label.toLowerCase(), u.target])) } : {},
1198
+ ...args.dns01Mode ? { dns01Mode: args.dns01Mode } : {},
1199
+ ...args.listenHttps != null || args.listenHttp != null ? { listen: {
1200
+ https: args.listenHttps ?? 443,
1201
+ http: args.listenHttp ?? 80
1202
+ } } : {},
1203
+ ...args.rewriteHostHeader != null ? { rewriteHostHeader: args.rewriteHostHeader } : {},
1204
+ ...args.sameOrigin != null ? { sameOrigin: args.sameOrigin } : {}
1205
+ }))),
1206
+ portleStart: guarded(async (_args, ctx, facts) => {
1207
+ const report = evaluateGate(facts, ctx.user);
1208
+ if (!report.publishable) throw forbidden(`The publication gate is not met (${report.checks.filter((c) => !c.ok).map((c) => c.id).join(", ")}); see portleReadiness.`);
1209
+ return toWireStatus(await runner.start());
1210
+ }),
1211
+ portleStop: guarded(async () => toWireStatus(await runner.stop()))
1212
+ }
1213
+ }
1214
+ };
1215
+ }
1216
+ //#endregion
1217
+ export { isListedAdmin as C, resolveBinaries as E, evaluateGate as S, portleBinDir as T, readSiteSettings as _, readiness as a, writeSiteSettings as b, PortleRunner as c, ENROLLMENT_FILE as d, PORTLE_DIR as f, readEnrollment as g, projectRootOf as h, portleTypeDefs as i, Supervised as l, hostStateDir as m, createPortleSubgraph as n, requireAdmin as o, SITE_FILE as p, gateFactsOf as r, toWireStatus as s, PORTLE_SUBGRAPH_NAME as t, DEFAULT_SITE_SETTINGS as u, stateDirOf as v, BINARY_ENV as w, bootGatePasses as x, writeEnrollment as y };
1218
+
1219
+ //# sourceMappingURL=subgraph-UKA_XDW0.mjs.map