@powerhousedao/portle 6.2.3-dev.79 → 6.2.3-dev.80

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 @@
1
+ {"version":3,"file":"subgraph-6lmwvcN4.mjs","names":["dns","port"],"sources":["../src/binaries.ts","../src/gate.ts","../src/delegation.ts","../src/site/enrol.ts","../src/site/hostnames.ts","../src/site/render-caddyfile.ts","../src/site/render-frpc.ts","../src/state.ts","../src/supervisor.ts","../src/runner.ts","../src/subgraph.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Where the two executables come from, in order:\n * 1. `PORTLE_FRPC_BIN` / `PORTLE_CADDY_BIN` (an explicit path wins, and only it is tried);\n * 2. `~/.ph/portle/bin/<name>` (where the release download will put them);\n * 3. the PATH.\n * The Caddy must be Portle's own build (rfc2136 + acme-dns modules); a stock\n * Caddy on the PATH starts but cannot obtain the certificate.\n */\nexport interface BinaryLocations {\n frpc: string | null;\n caddy: string | null;\n /** Every path that was looked at, for the status report. */\n searched: string[];\n}\n\nexport interface ResolveBinariesOptions {\n env?: NodeJS.ProcessEnv;\n home?: string;\n platform?: NodeJS.Platform;\n exists?: (path: string) => boolean;\n}\n\nexport const BINARY_ENV = {\n frpc: \"PORTLE_FRPC_BIN\",\n caddy: \"PORTLE_CADDY_BIN\",\n} as const;\n\nexport function portleBinDir(\n home: string,\n platform: NodeJS.Platform = process.platform,\n): string {\n return pathFor(platform).join(home, \".ph\", \"portle\", \"bin\");\n}\n\n/** Paths are joined by the target platform's rules, so a lookup is the same whichever host runs it. */\nfunction pathFor(platform: NodeJS.Platform): typeof path.posix {\n return platform === \"win32\" ? path.win32 : path.posix;\n}\n\nexport function resolveBinaries(\n options: ResolveBinariesOptions = {},\n): BinaryLocations {\n const env = options.env ?? process.env;\n const platform = options.platform ?? process.platform;\n const exists = options.exists ?? existsSync;\n const home = options.home ?? env.HOME ?? env.USERPROFILE ?? \"\";\n const suffix = platform === \"win32\" ? \".exe\" : \"\";\n const p = pathFor(platform);\n const searched: string[] = [];\n\n const find = (name: \"frpc\" | \"caddy\"): string | null => {\n const explicit = env[BINARY_ENV[name]];\n if (explicit) {\n searched.push(explicit);\n return exists(explicit) ? explicit : null;\n }\n const candidates = [\n p.join(portleBinDir(home, platform), `${name}${suffix}`),\n ];\n for (const dir of (env.PATH ?? env.Path ?? \"\")\n .split(p.delimiter)\n .filter(Boolean)) {\n candidates.push(p.join(dir, `${name}${suffix}`));\n }\n for (const candidate of candidates) {\n searched.push(candidate);\n if (exists(candidate)) return candidate;\n }\n return null;\n };\n\n return { frpc: find(\"frpc\"), caddy: find(\"caddy\"), searched };\n}\n","/**\n * The publication gate: the host's authorization facts, judged.\n *\n * Publishing a project through Portle puts its switchboard on the internet,\n * so the plugin refuses to bring the tunnel up unless the host is locked\n * down and the person asking is one of its admins. The gate is expressed in\n * terms of the RESOLVED authorization settings, never the environment\n * variables that produced them: `DEFAULT_PROTECTION` is inert under\n * `ADMIN_ONLY`, and the env can be contradicted by the config file.\n *\n * It is an interlock, not security. The server does not become safer because\n * the studio refuses; what makes the gate mean something is that the same\n * plugin owns the tunnel, so \"published\" implies \"locked down\" for as long as\n * the plugin is the thing publishing.\n */\n\n/** The host's authorization policy, as reactor-api resolves it at boot. */\nexport type PortlePolicy = \"OPEN\" | \"ADMIN_ONLY\" | \"DOCUMENT_PERMISSIONS\";\n\n/** What the gate judges: read off the switchboard's `API` object. */\nexport interface GateFacts {\n policy: PortlePolicy;\n /** Lower-cased addresses of the host's supreme admins. */\n admins: readonly string[];\n /** Documents without a permission row count as protected. */\n defaultProtection: boolean;\n /** The bearer is verified and `ctx.user` is populated. */\n identityResolved: boolean;\n /** Anonymous callers are refused with a 401 before any resolver. */\n requireAuthenticatedCaller: boolean;\n}\n\nexport interface GateCheck {\n id: GateCheckId;\n ok: boolean;\n /** What was found. */\n detail: string;\n /** What to change when `ok` is false. */\n fix?: string;\n}\n\nexport type GateCheckId =\n | \"identity\"\n | \"floor\"\n | \"policy\"\n | \"protection\"\n | \"admins\"\n | \"caller\"\n | \"custom-subgraphs\";\n\nexport interface GateReport {\n /** Every check passed: the tunnel may come up for this caller. */\n publishable: boolean;\n checks: GateCheck[];\n /** True of every deployment; not blocking, never silent. */\n warnings: GateCheck[];\n}\n\n/** One of the host's listed admins, whatever the policy. */\nexport function isListedAdmin(\n admins: readonly string[],\n address: string | undefined,\n): boolean {\n if (!address) return false;\n const caller = address.toLowerCase();\n return admins.some((admin) => admin.toLowerCase() === caller);\n}\n\nconst POLICY_FIX =\n \"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.\";\n\nexport function evaluateGate(\n facts: GateFacts,\n caller: { address?: string } | undefined,\n): GateReport {\n const policyOk =\n facts.policy === \"ADMIN_ONLY\" ||\n (facts.policy === \"DOCUMENT_PERMISSIONS\" && facts.defaultProtection);\n\n const checks: GateCheck[] = [\n {\n id: \"identity\",\n ok: facts.identityResolved,\n detail: facts.identityResolved\n ? \"Bearer tokens are verified and the caller is known to every resolver.\"\n : \"The host never reads a bearer; no caller can be identified.\",\n fix: facts.identityResolved\n ? undefined\n : \"Set RESOLVE_CALLER_IDENTITY=true.\",\n },\n {\n id: \"floor\",\n ok: facts.requireAuthenticatedCaller,\n detail: facts.requireAuthenticatedCaller\n ? \"Anonymous callers are refused with a 401 before any resolver runs.\"\n : \"Anonymous callers reach every subgraph.\",\n fix: facts.requireAuthenticatedCaller\n ? undefined\n : \"Set REQUIRE_AUTHENTICATED_CALLER=true (needs RESOLVE_CALLER_IDENTITY=true).\",\n },\n {\n id: \"policy\",\n ok: policyOk,\n detail: describePolicy(facts),\n fix: policyOk ? undefined : POLICY_FIX,\n },\n {\n id: \"protection\",\n ok: facts.policy !== \"DOCUMENT_PERMISSIONS\" || facts.defaultProtection,\n detail:\n facts.policy === \"DOCUMENT_PERMISSIONS\"\n ? facts.defaultProtection\n ? \"Documents without a permission row are protected.\"\n : \"Documents without a permission row are readable by any caller.\"\n : \"Not consulted under this policy.\",\n fix:\n facts.policy === \"DOCUMENT_PERMISSIONS\" && !facts.defaultProtection\n ? \"Set DEFAULT_PROTECTION=true.\"\n : undefined,\n },\n {\n id: \"admins\",\n ok: facts.admins.length > 0,\n detail:\n facts.admins.length > 0\n ? `${facts.admins.length} admin address(es) listed.`\n : \"No admin address is listed; nobody could administer the published host.\",\n fix:\n facts.admins.length > 0\n ? undefined\n : \"Set ADMINS to the comma-separated addresses that may publish.\",\n },\n {\n id: \"caller\",\n ok: isListedAdmin(facts.admins, caller?.address),\n detail: caller?.address\n ? isListedAdmin(facts.admins, caller.address)\n ? \"You are one of the listed admins.\"\n : \"You are signed in, but not one of the listed admins.\"\n : \"You are not signed in.\",\n fix: isListedAdmin(facts.admins, caller?.address)\n ? undefined\n : \"Sign in with Renown as one of the ADMINS addresses.\",\n },\n ];\n\n const warnings: GateCheck[] = [\n {\n id: \"custom-subgraphs\",\n ok: false,\n detail:\n \"The project's own subgraphs enforce nothing by themselves; the policy and the floor do not reach their resolvers.\",\n fix: \"Have every custom resolver check the caller (assertCanRead or canRead on the drive it serves).\",\n },\n ];\n\n return {\n publishable: checks.every((check) => check.ok),\n checks,\n warnings,\n };\n}\n\n/**\n * The gate without the caller: what the host itself must satisfy before the\n * tunnel may come up unattended at boot. The caller check is per request.\n */\nexport function bootGatePasses(facts: GateFacts): boolean {\n return evaluateGate(facts, undefined).checks.every(\n (check) => check.ok || check.id === \"caller\",\n );\n}\n\nfunction describePolicy(facts: GateFacts): string {\n switch (facts.policy) {\n case \"OPEN\":\n return \"OPEN: everyone, anonymous included, may read and write everything.\";\n case \"ADMIN_ONLY\":\n return \"ADMIN_ONLY: only the listed admins may read or write anything.\";\n case \"DOCUMENT_PERMISSIONS\":\n return facts.defaultProtection\n ? \"DOCUMENT_PERMISSIONS with default protection: grants decide, unprotected documents do not exist.\"\n : \"DOCUMENT_PERMISSIONS without default protection: documents with no permission row are open to every caller.\";\n }\n}\n","import { promises as dns } from \"node:dns\";\n\n/**\n * Whether a customer zone is delegated to the relay's nameservers, as the\n * machine's resolver sees it. Vendored from site-relay\n * (`packages/site-agent/src/delegation.ts` at df26ab8).\n *\n * Caddy asks the CA for the wildcard the moment it starts; before the\n * delegation exists the CA's resolvers answer NXDOMAIN and cache it for the\n * parent's negative TTL, so a site started too early loses an hour per\n * attempt and burns its authorization-failure budget. NXDOMAIN and no data\n * count as \"not yet\"; a resolver that cannot answer is retried, then reported\n * as such.\n */\nexport interface Delegation {\n zone: string;\n nameservers: string[];\n}\n\nexport type ResolveNs = (zone: string) => Promise<string[]>;\n\n/** The resolver could not answer at all (timeout, refused, SERVFAIL), so\n * whether the zone is delegated is unknown, which is not \"not delegated\". */\nexport class DelegationCheckError extends Error {\n constructor(zone: string, cause: unknown) {\n super(\n `could not check whether ${zone} is delegated: the resolver failed (${errorText(cause)})`,\n { cause },\n );\n this.name = \"DelegationCheckError\";\n }\n}\n\nconst canonical = (name: string) =>\n name.trim().toLowerCase().replace(/\\.$/, \"\");\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) {\n const code = (error as { code?: unknown }).code;\n return typeof code === \"string\" && !error.message.includes(code)\n ? `${code}: ${error.message}`\n : error.message;\n }\n return String(error);\n}\n\n/** Answers that mean the zone has no NS records yet: NXDOMAIN or no data. */\nconst NOT_DELEGATED = [\"ENOTFOUND\", \"ENODATA\", \"NXDOMAIN\"];\n\nfunction isNotDelegatedAnswer(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n const text = `${typeof code === \"string\" ? code : \"\"} ${error instanceof Error ? error.message : \"\"}`;\n return NOT_DELEGATED.some((answer) => text.includes(answer));\n}\n\nexport type DelegationCheckOptions = {\n /** Resolver attempts before a failure is reported; default 4. */\n attempts?: number;\n /** First retry delay, doubled per attempt; default 1000 ms. */\n delayMs?: number;\n sleep?: (ms: number) => Promise<void>;\n};\n\n/**\n * True once the resolver lists one of the relay's nameservers; false when it\n * answers that the zone has none (NXDOMAIN, no data, other nameservers).\n * A resolver that cannot answer is retried with backoff, then reported as a\n * {@link DelegationCheckError}: a DNS blip at boot is not a missing delegation.\n */\nexport async function isDelegated(\n delegation: Delegation,\n resolveNs: ResolveNs = (zone) => dns.resolveNs(zone),\n options: DelegationCheckOptions = {},\n): Promise<boolean> {\n const expected = new Set(delegation.nameservers.map(canonical));\n const attempts = Math.max(1, options.attempts ?? 4);\n const sleep =\n options.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n let delay = options.delayMs ?? 1000;\n for (let attempt = 1; ; attempt++) {\n try {\n const found = await resolveNs(delegation.zone);\n return found.some((ns) => expected.has(canonical(ns)));\n } catch (error) {\n if (isNotDelegatedAnswer(error)) return false;\n if (attempt >= attempts) {\n throw new DelegationCheckError(delegation.zone, error);\n }\n await sleep(delay);\n delay *= 2;\n }\n }\n}\n","import type { EnrollmentResponse } from \"./types.js\";\n\n/**\n * Enrols this site with the Portle control plane: one token, one site. The\n * token is single use; the answer is the site's identity and every secret the\n * tunnel and the certificate need, and is stored once by the caller.\n */\nexport async function enrolWithControlPlane(\n controlPlaneUrl: string,\n token: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<EnrollmentResponse> {\n const url = `${controlPlaneUrl.replace(/\\/$/, \"\")}/v1/enroll`;\n const res = await fetchImpl(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n body: JSON.stringify({ token }),\n signal: AbortSignal.timeout(30_000),\n });\n const text = await res.text();\n if (res.status !== 201) {\n throw new Error(\n `enrolment failed: HTTP ${res.status} ${text.slice(0, 300)}`,\n );\n }\n const data = JSON.parse(text) as Partial<EnrollmentResponse>;\n if (\n !data.siteId ||\n !data.siteSecret ||\n !data.frp?.token ||\n !data.dns?.tsigSecret\n ) {\n throw new Error(\"enrolment response is incomplete\");\n }\n return data as EnrollmentResponse;\n}\n","/**\n * Hostname rules of a Portle site, vendored from site-relay\n * (`packages/shared/src/hostnames.ts` at df26ab8). The relay's control plane\n * enforces the same rules on the names a site may claim, so a config this\n * module refuses would be refused there too. Keep in sync.\n */\n\n/** Site IDs are opaque: 10 chars, [a-z0-9], first char a letter. */\nexport const SITE_ID_RE = /^[a-z][a-z0-9]{9}$/;\n\n/** One DNS label as we allow it: 1-63 chars of [a-z0-9-], no leading/trailing dash. */\nexport const LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n\nexport type ZoneKind = \"customer\" | \"shared\";\n\nexport function isSiteId(value: string): boolean {\n return SITE_ID_RE.test(value);\n}\n\n/** Lowercase ASCII, no trailing dot, every label well formed, at most 253 chars. */\nexport function isWellFormedHostname(value: string): boolean {\n if (value.length === 0 || value.length > 253) return false;\n if (value !== value.toLowerCase()) return false;\n return value.split(\".\").every((label) => LABEL_RE.test(label));\n}\n\n/** A site zone: well formed, at least two labels, no punycode. */\nexport function isSiteZone(value: string): boolean {\n if (!isWellFormedHostname(value)) return false;\n const labels = value.split(\".\");\n return (\n labels.length >= 2 && !labels.some((label) => label.startsWith(\"xn--\"))\n );\n}\n\n/** The wildcard name every site gets. */\nexport function siteWildcard(siteZone: string): string {\n return `*.${siteZone}`;\n}\n","import { SWITCHBOARD_PROXY_PATHS } from \"@powerhousedao/host-core\";\nimport {\n LABEL_RE,\n isSiteId,\n isSiteZone,\n isWellFormedHostname,\n siteWildcard,\n} from \"./hostnames.js\";\n\n/**\n * Renders the site's Caddyfile. Vendored from site-relay\n * (`packages/site-agent/src/render/caddyfile.ts` at df26ab8). Caddy holds\n * the private key and the wildcard certificate, obtained by DNS-01 through\n * the relay's PowerDNS (TSIG) or the acme-dns fallback on the control plane.\n */\nexport type Dns01 =\n | {\n mode: \"rfc2136\";\n keyName: string;\n keyAlg: string;\n secret: string;\n server: string;\n }\n | {\n mode: \"acmedns\";\n username: string;\n password: string;\n subdomain: string;\n serverUrl: string;\n };\n\nexport interface CaddyRenderInput {\n siteId: string;\n /** The site's zone: the wildcard block is `*.<siteZone>`. */\n siteZone: string;\n email: string;\n acmeCaUrl?: string | undefined;\n /** Path of the ACME directory's TLS root as Caddy will read it (staging CAs). */\n acmeCaRootFile?: string | undefined;\n /** Caddy's PROXY-protocol `allow`: who may send PROXY headers (frpc). */\n proxyAllowCidr: string;\n /** host:port every name in the zone proxies to unless `upstreams` names its label. */\n appUpstream: string;\n /**\n * Per-label upstreams inside the zone: `{ api: \"127.0.0.1:7540\" }` sends\n * `api.<siteZone>` there and every other name (other labels, dashed LAN\n * names, vanity domains) to `appUpstream`.\n */\n upstreams?: Record<string, string> | undefined;\n vanityDomains: string[];\n askUrl: string;\n resolvers: string[];\n dns01: Dns01;\n /** Local listen ports; 443/80 unless the machine cannot bind them. */\n listen?: { https: number; http: number } | undefined;\n /**\n * Send the upstream's own host:port as the Host header instead of the\n * public name, for dev servers that check it (Vite's allowedHosts).\n */\n rewriteHostHeader?: boolean | undefined;\n /**\n * Same-origin publication: on this label the switchboard's paths go to the\n * API upstream, so the SPA finds its backend on its own origin (no\n * cross-origin calls, no local-network prompt); its config names the\n * switchboard as `${origin}`, which the browser resolves to this label.\n * Everything else on the label goes to the label's own upstream.\n */\n appRoute?: { label: string; apiTarget: string } | undefined;\n}\n\n/**\n * The switchboard's HTTP surface as Caddy path matchers, from the one list\n * Connect's own servers proxy (`SWITCHBOARD_PROXY_PATHS`): `/x` and `/x/*`\n * for a bare prefix, `/x/*` for one that ends in a slash. `/d/*` is listed\n * apart: a browser navigation there is one of Connect's routes.\n */\nexport const SWITCHBOARD_PATHS: readonly string[] =\n SWITCHBOARD_PROXY_PATHS.filter((prefix) => prefix !== \"/d/\").flatMap(\n (prefix) =>\n prefix.endsWith(\"/\") ? [`${prefix}*`] : [prefix, `${prefix}/*`],\n );\n\nfunction port(value: number, what: string): number {\n if (!Number.isInteger(value) || value < 1 || value > 65535) {\n throw new Error(`invalid ${what}: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** Caddyfile quoted string: backslash and double quote escaped. */\nfunction q(value: string): string {\n if (/[\\r\\n]/.test(value)) throw new Error(\"newline in Caddyfile value\");\n return `\"${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction token(value: string, what: string): string {\n if (!/^[A-Za-z0-9.:/_\\-@+=]+$/.test(value)) {\n throw new Error(`invalid ${what}: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\nexport function renderCaddyfile(input: CaddyRenderInput): string {\n if (!isSiteId(input.siteId))\n throw new Error(`invalid siteId ${input.siteId}`);\n if (!isSiteZone(input.siteZone))\n throw new Error(`invalid siteZone ${input.siteZone}`);\n for (const v of input.vanityDomains) {\n if (!isWellFormedHostname(v) || v.includes(\"*\"))\n throw new Error(`invalid vanity domain ${v}`);\n }\n if (input.resolvers.length === 0)\n throw new Error(\"at least one resolver is required\");\n const wildcard = siteWildcard(input.siteZone);\n const upstream = token(input.appUpstream, \"app upstream\");\n const labelled = Object.entries(input.upstreams ?? {})\n .map(([label, target]) => {\n if (!LABEL_RE.test(label) || label !== label.toLowerCase()) {\n throw new Error(`invalid upstream label: ${JSON.stringify(label)}`);\n }\n return { label, target: token(target, `upstream for ${label}`) };\n })\n .sort((a, b) => (a.label < b.label ? -1 : 1));\n const allow = token(input.proxyAllowCidr, \"PROXY allow CIDR\");\n const resolvers = input.resolvers.map((r) => token(r, \"resolver\")).join(\" \");\n\n const dns =\n input.dns01.mode === \"rfc2136\"\n ? `\t\tdns rfc2136 {\n\t\t\tkey_name ${q(input.dns01.keyName)}\n\t\t\tkey_alg ${q(input.dns01.keyAlg)}\n\t\t\tkey ${q(input.dns01.secret)}\n\t\t\tserver ${q(input.dns01.server)}\n\t\t}`\n : `\t\tdns acmedns {\n\t\t\tusername ${q(input.dns01.username)}\n\t\t\tpassword ${q(input.dns01.password)}\n\t\t\tsubdomain ${q(input.dns01.subdomain)}\n\t\t\tserver_url ${q(input.dns01.serverUrl)}\n\t\t}`;\n\n /** One reverse_proxy directive at the given tab depth. */\n const proxy = (target: string, depth: number): string => {\n const t = \"\\t\".repeat(depth);\n return input.rewriteHostHeader\n ? `${t}reverse_proxy ${target} {\\n${t}\\theader_up Host {upstream_hostport}\\n${t}}`\n : `${t}reverse_proxy ${target}`;\n };\n\n const https = port(input.listen?.https ?? 443, \"HTTPS port\");\n const http = port(input.listen?.http ?? 80, \"HTTP port\");\n if (https === http) throw new Error(\"HTTPS and HTTP ports must differ\");\n\n const globals = [\n `\temail ${token(input.email, \"email\")}`,\n // Non-default ports: Caddy's automatic HTTPS (and its HTTP→HTTPS redirect)\n // then serves the site blocks there instead of 443/80.\n https !== 443 ? `\thttps_port ${https}` : \"\",\n http !== 80 ? `\thttp_port ${http}` : \"\",\n input.acmeCaUrl ? `\tacme_ca ${token(input.acmeCaUrl, \"ACME CA URL\")}` : \"\",\n input.acmeCaRootFile\n ? // A local path, quoted: Windows paths carry backslashes and may carry\n // spaces, and Go accepts forward slashes on every platform.\n `\tacme_ca_root ${q(input.acmeCaRootFile.replace(/\\\\/g, \"/\"))}`\n : \"\",\n `\n\t# PROXY protocol v2 from frpc only; plain LAN clients pass through unchanged\n\t# (ignore = a spoofed header from anyone else is parsed and discarded).\n\tservers :${https} {\n\t\tlistener_wrappers {\n\t\t\tproxy_protocol {\n\t\t\t\ttimeout 5s\n\t\t\t\tallow ${allow}\n\t\t\t\tfallback_policy ignore\n\t\t\t}\n\t\t\ttls\n\t\t}\n\t}`,\n input.vanityDomains.length > 0\n ? `\n\t# Vanity domains are issued on demand, only when the control plane approves the name.\n\ton_demand_tls {\n\t\task ${token(input.askUrl, \"ask URL\")}\n\t}`\n : \"\",\n `\n\tlog {\n\t\toutput stdout\n\t\tlevel INFO\n\t}`,\n ]\n .filter((l) => l !== \"\")\n .join(\"\\n\");\n\n const vanity =\n input.vanityDomains.length > 0\n ? `\n# Vanity domains (${input.vanityDomains.join(\", \")}): validated by http-01 or\n# tls-alpn-01 through the relay. No DNS config here, so those stay enabled.\nhttps:// {\n\ttls {\n\t\ton_demand\n\t}\n${proxy(upstream, 1)}\n}\n`\n : \"\";\n\n // With per-label upstreams the wildcard block routes by host: one matcher\n // per label, first match wins, and the bare `handle` takes everything else.\n const appRoute = input.appRoute;\n if (appRoute) {\n if (!labelled.some((l) => l.label === appRoute.label)) {\n throw new Error(\n `appRoute names label ${JSON.stringify(appRoute.label)}, which has no upstream`,\n );\n }\n token(appRoute.apiTarget, \"appRoute.apiTarget\");\n }\n /**\n * The label's handle body: the plain proxy, or the same-origin split (the\n * same rules as Connect's own dev and preview servers): the switchboard's\n * paths go to the API upstream, `/d/*` too unless the request is a browser\n * navigation (it accepts HTML), which is one of Connect's routes.\n */\n const labelBody = (label: string, target: string): string => {\n if (!appRoute || appRoute.label !== label) return proxy(target, 2);\n return [\n `\t\t@switchboard path ${SWITCHBOARD_PATHS.join(\" \")}\n\t\thandle @switchboard {\n${proxy(appRoute.apiTarget, 3)}\n\t\t}\n\t\t@drive {\n\t\t\tpath /d/*\n\t\t\tnot header Accept *text/html*\n\t\t}\n\t\thandle @drive {\n${proxy(appRoute.apiTarget, 3)}\n\t\t}`,\n `\t\thandle {\n${proxy(target, 3)}\n\t\t}`,\n ].join(\"\\n\");\n };\n\n const routing =\n labelled.length === 0\n ? proxy(upstream, 1)\n : [\n ...labelled.map(\n ({ label, target }) => `\t@${label} host ${label}.${input.siteZone}\n\thandle @${label} {\n${labelBody(label, target)}\n\t}`,\n ),\n `\thandle {\n${proxy(upstream, 2)}\n\t}`,\n ].join(\"\\n\");\n\n return `# Generated by @powerhousedao/portle for site ${input.siteId} (${input.siteZone}). Do not edit; the plugin rewrites it.\n{\n${globals}\n}\n\n# Wildcard only, never the zone apex: one certificate per site. DNS-01 is\n# configured only inside this block so other challenge types stay available.\n${wildcard} {\n\ttls {\n${dns}\n\t\tresolvers ${resolvers}\n\t\tpropagation_delay 2s\n\t}\n${routing}\n}\n${vanity}`;\n}\n\nexport function rfc2136Dns(\n keyName: string,\n secret: string,\n server: string,\n keyAlg = \"hmac-sha256\",\n): Dns01 {\n return { mode: \"rfc2136\", keyName, keyAlg, secret, server };\n}\n","import {\n isSiteId,\n isSiteZone,\n isWellFormedHostname,\n siteWildcard,\n} from \"./hostnames.js\";\n\n/**\n * Renders frpc.toml for one site. Vendored from site-relay\n * (`packages/site-agent/src/render/frpc.ts` at df26ab8), minus the TOML\n * parse-back self-check (no TOML dependency here; the inputs are validated\n * before they are written).\n */\nexport interface FrpcRenderInput {\n siteId: string;\n siteSecret: string;\n /** The site's zone: `*.<siteZone>` is the wildcard it claims. */\n siteZone: string;\n serverAddr: string;\n serverPort: number;\n serverName: string;\n token: string;\n /** Path of the relay CA file as frpc will read it. */\n trustedCaFile: string;\n /** Hostname/IP of the local Caddy as seen from frpc. */\n caddyHost: string;\n vanityDomains: string[];\n /** The local Caddy's ports; 443/80 by default. */\n localHttpsPort?: number | undefined;\n localHttpPort?: number | undefined;\n}\n\nfunction port(value: number, what: string): number {\n if (!Number.isInteger(value) || value < 1 || value > 65535) {\n throw new Error(`invalid ${what}: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** TOML basic strings share JSON's escaping rules for everything we emit. */\nfunction s(value: string): string {\n return JSON.stringify(value);\n}\n\nexport function renderFrpcToml(input: FrpcRenderInput): string {\n if (!isSiteId(input.siteId))\n throw new Error(`invalid siteId ${input.siteId}`);\n if (!isSiteZone(input.siteZone))\n throw new Error(`invalid siteZone ${input.siteZone}`);\n for (const v of input.vanityDomains) {\n if (!isWellFormedHostname(v) || v.includes(\"*\"))\n throw new Error(`invalid vanity domain ${v}`);\n }\n if (\n !Number.isInteger(input.serverPort) ||\n input.serverPort <= 0 ||\n input.serverPort > 65535\n ) {\n throw new Error(`invalid serverPort ${input.serverPort}`);\n }\n const domains = [siteWildcard(input.siteZone), ...input.vanityDomains];\n const list = `[${domains.map(s).join(\", \")}]`;\n const httpsPort = port(input.localHttpsPort ?? 443, \"local HTTPS port\");\n const httpPort = port(input.localHttpPort ?? 80, \"local HTTP port\");\n\n return `# Generated by @powerhousedao/portle for site ${input.siteId} (${input.siteZone}). Do not edit; the plugin rewrites it.\nserverAddr = ${s(input.serverAddr)}\nserverPort = ${input.serverPort}\nuser = ${s(input.siteId)}\nclientID = ${s(input.siteId)}\nloginFailExit = false\n\nauth.method = \"token\"\nauth.token = ${s(input.token)}\n\n# Per-site identity, validated by the control plane's frps Login plugin.\nmetadatas.site_id = ${s(input.siteId)}\nmetadatas.site_secret = ${s(input.siteSecret)}\n\n# frpc does not verify frps's certificate unless trustedCaFile is set.\ntransport.tls.enable = true\ntransport.tls.trustedCaFile = ${s(input.trustedCaFile)}\ntransport.tls.serverName = ${s(input.serverName)}\n\nwebServer.addr = \"127.0.0.1\"\nwebServer.port = 7400\n\nlog.to = \"console\"\nlog.level = \"info\"\n\n# TLS passthrough (frps routes by SNI, never decrypts); PROXY v2 carries the\n# visitor address to Caddy. PROXY protocol only here, never on the http proxy.\n[[proxies]]\nname = \"tls\"\ntype = \"https\"\nlocalIP = ${s(input.caddyHost)}\nlocalPort = ${httpsPort}\ncustomDomains = ${list}\ntransport.proxyProtocolVersion = \"v2\"\n\n# Plain HTTP: Caddy redirects to HTTPS; also carries http-01 for vanity domains.\n[[proxies]]\nname = \"web\"\ntype = \"http\"\nlocalIP = ${s(input.caddyHost)}\nlocalPort = ${httpPort}\ncustomDomains = ${list}\n`;\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { EnrollmentResponse } from \"./site/types.js\";\n\n/**\n * Everything the plugin keeps on disk lives under `<project>/.ph/portle/`:\n *\n * enrollment.json the site's identity and secrets (mode 600)\n * site.json the operator's choices: what the tunnel exposes, autostart\n * frpc.toml, Caddyfile, certs/ rendered on every start (mode 600)\n * caddy/ Caddy's data dir: the certificate, which must persist\n * logs/ frpc.log, caddy.log\n */\nexport const PORTLE_DIR = join(\".ph\", \"portle\");\nexport const ENROLLMENT_FILE = \"enrollment.json\";\nexport const SITE_FILE = \"site.json\";\n\n/** The operator's choices, kept beside the enrolment. */\nexport interface SiteSettings {\n /** The control plane the site enrolled with (needed for `ask` and acme-dns). */\n controlPlaneUrl: string;\n /** host:port every name proxies to unless `upstreams` names its label. */\n appUpstream: string;\n /** Per-label upstreams, e.g. `{ api: \"127.0.0.1:7540\", app: \"127.0.0.1:2540\" }`. */\n upstreams: Record<string, string>;\n /** rfc2136 straight to the relay's PowerDNS, or the acme-dns HTTPS fallback. */\n dns01Mode: \"rfc2136\" | \"acmedns\";\n /**\n * The local ports Caddy listens on. 443/80 is what the LAN path needs; a\n * machine that cannot bind them (another server, macOS without root)\n * can use high ports and still be reached through the relay.\n */\n listen: { https: number; http: number };\n /**\n * Send the upstream's own host:port as the Host header instead of the\n * public name. Dev servers that check the Host header (Vite's\n * `server.allowedHosts`) refuse the public name otherwise.\n */\n rewriteHostHeader?: boolean;\n /**\n * Publish Connect and the switchboard on ONE origin: the `app` label also\n * serves the switchboard's paths (proxied to the `api` upstream) and a\n * runtime config in which the switchboard's local origin is replaced by\n * the public one. Needs both the `app` and `api` labels. Default on.\n */\n sameOrigin?: boolean;\n /** Bring the tunnel up at boot when the gate passes. Set by start, cleared by stop. */\n autostart: boolean;\n}\n\n/**\n * The project root the switchboard serves: the directory of its config file\n * when the host passed one, else the working directory.\n */\nexport function projectRootOf(\n options: { configFile?: unknown } | undefined,\n): string {\n const configFile = options?.configFile;\n return typeof configFile === \"string\" && configFile.length > 0\n ? dirname(resolve(configFile))\n : process.cwd();\n}\n\nexport function stateDirOf(projectRoot: string): string {\n return join(projectRoot, PORTLE_DIR);\n}\n\n/** Writes atomically (temp file + rename) with the given mode (best effort on Windows). */\nexport function writeFileAtomic(\n path: string,\n content: string,\n mode = 0o644,\n): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, content, { encoding: \"utf8\", mode });\n try {\n chmodSync(tmp, mode);\n } catch {\n /* Windows has no POSIX modes */\n }\n renameSync(tmp, path);\n}\n\nexport function readEnrollment(stateDir: string): EnrollmentResponse | null {\n const path = join(stateDir, ENROLLMENT_FILE);\n if (!existsSync(path)) return null;\n const data = JSON.parse(\n readFileSync(path, \"utf8\"),\n ) as Partial<EnrollmentResponse>;\n if (!data.siteId || !data.siteSecret || !data.dns?.tsigSecret) {\n throw new Error(`${path} is not a valid enrolment`);\n }\n return data as EnrollmentResponse;\n}\n\nexport function writeEnrollment(\n stateDir: string,\n enrollment: EnrollmentResponse,\n): void {\n writeFileAtomic(\n join(stateDir, ENROLLMENT_FILE),\n `${JSON.stringify(enrollment, null, 2)}\\n`,\n 0o600,\n );\n}\n\nexport const DEFAULT_SITE_SETTINGS: Omit<SiteSettings, \"controlPlaneUrl\"> = {\n appUpstream: \"127.0.0.1:3000\",\n upstreams: {},\n dns01Mode: \"rfc2136\",\n listen: { https: 443, http: 80 },\n rewriteHostHeader: false,\n sameOrigin: true,\n autostart: false,\n};\n\nexport function readSiteSettings(stateDir: string): SiteSettings | null {\n const path = join(stateDir, SITE_FILE);\n if (!existsSync(path)) return null;\n const data = JSON.parse(readFileSync(path, \"utf8\")) as Partial<SiteSettings>;\n if (typeof data.controlPlaneUrl !== \"string\")\n throw new Error(`${path} names no control plane`);\n return {\n ...DEFAULT_SITE_SETTINGS,\n ...data,\n controlPlaneUrl: data.controlPlaneUrl,\n };\n}\n\nexport function writeSiteSettings(\n stateDir: string,\n settings: SiteSettings,\n): void {\n writeFileAtomic(\n join(stateDir, SITE_FILE),\n `${JSON.stringify(settings, null, 2)}\\n`,\n 0o600,\n );\n}\n","import { spawn, spawnSync, type ChildProcess } from \"node:child_process\";\nimport { closeSync, mkdirSync, openSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n/**\n * One long-running child (frpc, Caddy) kept alive by the plugin: started\n * hidden, logged to a file, restarted with backoff when it dies, and stopped\n * as a process tree. Mirrors host-core's spawn conventions (`windowsHide`,\n * SIGTERM then SIGKILL after a timeout).\n */\nexport interface SupervisedOptions {\n name: string;\n command: string;\n args: string[];\n cwd: string;\n /** Appended to; stdout and stderr of every run. */\n logFile: string;\n env?: NodeJS.ProcessEnv;\n /** Restart delay after a death: doubles from `initialMs` up to `maxMs`, resets after a healthy run. */\n backoff?: { initialMs: number; maxMs: number };\n /** A run longer than this resets the backoff. */\n healthyAfterMs?: number;\n stopTimeoutMs?: number;\n platform?: NodeJS.Platform;\n spawnImpl?: typeof spawn;\n onEvent?: (event: SupervisedEvent) => void;\n}\n\nexport type SupervisedEvent =\n | { type: \"started\"; name: string; pid: number }\n | {\n type: \"exited\";\n name: string;\n code: number | null;\n signal: string | null;\n restarting: boolean;\n delayMs: number;\n }\n | { type: \"stopped\"; name: string }\n | { type: \"spawn-failed\"; name: string; error: string };\n\nexport interface SupervisedStatus {\n name: string;\n command: string;\n running: boolean;\n pid: number | null;\n startedAt: string | null;\n restarts: number;\n lastExit: { code: number | null; signal: string | null; at: string } | null;\n}\n\nexport interface SupervisedLike {\n start(): void;\n stop(): Promise<void>;\n status(): SupervisedStatus;\n}\n\nexport class Supervised implements SupervisedLike {\n readonly #opts: Required<\n Pick<\n SupervisedOptions,\n \"backoff\" | \"healthyAfterMs\" | \"stopTimeoutMs\" | \"platform\"\n >\n > &\n SupervisedOptions;\n\n #child: ChildProcess | null = null;\n #startedAt: number | null = null;\n #restarts = 0;\n #delayMs: number;\n #lastExit: SupervisedStatus[\"lastExit\"] = null;\n #stopping = false;\n #restartTimer: NodeJS.Timeout | null = null;\n #exited: Promise<void> | null = null;\n\n constructor(options: SupervisedOptions) {\n this.#opts = {\n backoff: { initialMs: 1_000, maxMs: 30_000 },\n healthyAfterMs: 30_000,\n stopTimeoutMs: 5_000,\n platform: process.platform,\n ...options,\n };\n this.#delayMs = this.#opts.backoff.initialMs;\n }\n\n status(): SupervisedStatus {\n return {\n name: this.#opts.name,\n command: [this.#opts.command, ...this.#opts.args].join(\" \"),\n running: this.#child !== null,\n pid: this.#child?.pid ?? null,\n startedAt: this.#startedAt\n ? new Date(this.#startedAt).toISOString()\n : null,\n restarts: this.#restarts,\n lastExit: this.#lastExit,\n };\n }\n\n start(): void {\n if (this.#child) return;\n this.#stopping = false;\n this.#spawn();\n }\n\n async stop(): Promise<void> {\n this.#stopping = true;\n if (this.#restartTimer) {\n clearTimeout(this.#restartTimer);\n this.#restartTimer = null;\n }\n const child = this.#child;\n const exited = this.#exited;\n if (!child || !exited) return;\n this.#kill(child, \"SIGTERM\");\n let timer: NodeJS.Timeout | undefined;\n const timedOut = await Promise.race([\n exited.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), this.#opts.stopTimeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (timedOut) this.#kill(child, \"SIGKILL\");\n await exited;\n this.#opts.onEvent?.({ type: \"stopped\", name: this.#opts.name });\n }\n\n #spawn(): void {\n const { command, args, cwd, logFile, env, platform } = this.#opts;\n mkdirSync(dirname(logFile), { recursive: true });\n const fd = openSync(logFile, \"a\");\n let child: ChildProcess;\n try {\n child = (this.#opts.spawnImpl ?? spawn)(command, args, {\n cwd,\n env: env ?? process.env,\n stdio: [\"ignore\", fd, fd],\n windowsHide: true,\n // A process group of its own on POSIX, so stop() reaches the tree.\n detached: platform !== \"win32\",\n });\n } catch (error) {\n closeSync(fd);\n this.#opts.onEvent?.({\n type: \"spawn-failed\",\n name: this.#opts.name,\n error: String(error),\n });\n this.#scheduleRestart(null, null);\n return;\n }\n closeSync(fd);\n this.#child = child;\n this.#startedAt = Date.now();\n const startedAt = this.#startedAt;\n this.#exited = new Promise<void>((resolve) => {\n const done = (code: number | null, signal: NodeJS.Signals | null) => {\n if (this.#child !== child) return;\n this.#child = null;\n this.#lastExit = { code, signal, at: new Date().toISOString() };\n if (Date.now() - startedAt >= this.#opts.healthyAfterMs) {\n this.#delayMs = this.#opts.backoff.initialMs;\n }\n resolve();\n if (!this.#stopping) this.#scheduleRestart(code, signal);\n };\n child.once(\"exit\", done);\n child.once(\"error\", (error) => {\n this.#opts.onEvent?.({\n type: \"spawn-failed\",\n name: this.#opts.name,\n error: error.message,\n });\n if (child.pid === undefined) done(null, null);\n });\n });\n if (child.pid !== undefined) {\n this.#opts.onEvent?.({\n type: \"started\",\n name: this.#opts.name,\n pid: child.pid,\n });\n }\n }\n\n #scheduleRestart(code: number | null, signal: NodeJS.Signals | null): void {\n const delayMs = this.#delayMs;\n this.#opts.onEvent?.({\n type: \"exited\",\n name: this.#opts.name,\n code,\n signal,\n restarting: true,\n delayMs,\n });\n this.#delayMs = Math.min(this.#delayMs * 2, this.#opts.backoff.maxMs);\n this.#restartTimer = setTimeout(() => {\n this.#restartTimer = null;\n if (this.#stopping) return;\n this.#restarts += 1;\n this.#spawn();\n }, delayMs);\n this.#restartTimer.unref();\n }\n\n #kill(child: ChildProcess, signal: \"SIGTERM\" | \"SIGKILL\"): void {\n const pid = child.pid;\n if (pid === undefined) return;\n if (this.#opts.platform === \"win32\") {\n // No signals on Windows: take the whole tree down in one go.\n spawnSync(\"taskkill\", [\"/PID\", String(pid), \"/T\", \"/F\"], {\n windowsHide: true,\n stdio: \"ignore\",\n });\n return;\n }\n try {\n // The negative pid addresses the process group created by `detached`.\n process.kill(-pid, signal);\n } catch {\n try {\n process.kill(pid, signal);\n } catch {\n // already gone\n }\n }\n }\n}\n","import { existsSync, mkdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport {\n resolveBinaries,\n type BinaryLocations,\n type ResolveBinariesOptions,\n} from \"./binaries.js\";\nimport {\n DelegationCheckError,\n isDelegated,\n type DelegationCheckOptions,\n type ResolveNs,\n} from \"./delegation.js\";\nimport { enrolWithControlPlane } from \"./site/enrol.js\";\nimport { LABEL_RE } from \"./site/hostnames.js\";\nimport {\n renderCaddyfile,\n rfc2136Dns,\n type Dns01,\n} from \"./site/render-caddyfile.js\";\nimport { renderFrpcToml } from \"./site/render-frpc.js\";\nimport type { EnrollmentResponse } from \"./site/types.js\";\nimport {\n DEFAULT_SITE_SETTINGS,\n readEnrollment,\n readSiteSettings,\n writeEnrollment,\n writeFileAtomic,\n writeSiteSettings,\n type SiteSettings,\n} from \"./state.js\";\nimport {\n Supervised,\n type SupervisedLike,\n type SupervisedOptions,\n type SupervisedStatus,\n} from \"./supervisor.js\";\n\nexport type TunnelState = \"down\" | \"up\" | \"degraded\";\n\nexport interface TunnelStatus {\n stateDir: string;\n enrolled: boolean;\n siteId: string | null;\n siteZone: string | null;\n zoneKind: string | null;\n delegation: { zone: string; nameservers: string[] } | null;\n settings: SiteSettings | null;\n binaries: BinaryLocations;\n tunnel: {\n state: TunnelState;\n frpc: SupervisedStatus | null;\n caddy: SupervisedStatus | null;\n };\n /** The public names this site serves, from its labels. */\n urls: string[];\n}\n\nexport interface EnrolInput {\n controlPlaneUrl: string;\n token: string;\n}\n\nexport type SettingsPatch = Partial<\n Pick<\n SiteSettings,\n | \"appUpstream\"\n | \"upstreams\"\n | \"dns01Mode\"\n | \"listen\"\n | \"rewriteHostHeader\"\n | \"sameOrigin\"\n >\n>;\n\n/** What the subgraph and the hooks drive; the class below is the real one. */\nexport interface PortleRunnerLike {\n status(): TunnelStatus;\n /** True/false for a customer zone; null when the site needs no delegation. */\n checkDelegation(): Promise<boolean | null>;\n enrol(input: EnrolInput): Promise<TunnelStatus>;\n configure(patch: SettingsPatch): TunnelStatus;\n start(): Promise<TunnelStatus>;\n /** Stops both processes; clears `autostart` unless `keepAutostart` (a host shutdown). */\n stop(options?: StopOptions): Promise<TunnelStatus>;\n}\n\nexport interface StopOptions {\n /** The host is going down, not the operator's wish: the tunnel comes back at the next boot. */\n keepAutostart?: boolean;\n}\n\nexport interface PortleRunnerDeps extends ResolveBinariesOptions {\n stateDir: string;\n fetchImpl?: typeof fetch;\n resolveNs?: ResolveNs;\n /** Retry policy of the delegation check (tests shorten it). */\n delegationCheck?: DelegationCheckOptions;\n createSupervised?: (options: SupervisedOptions) => SupervisedLike;\n log?: (msg: string, detail?: Record<string, unknown>) => void;\n}\n\nexport class PortleRunner implements PortleRunnerLike {\n readonly #deps: PortleRunnerDeps;\n #frpc: SupervisedLike | null = null;\n #caddy: SupervisedLike | null = null;\n\n constructor(deps: PortleRunnerDeps) {\n this.#deps = { ...deps, stateDir: resolve(deps.stateDir) };\n }\n\n get stateDir(): string {\n return this.#deps.stateDir;\n }\n\n status(): TunnelStatus {\n const enrollment = this.#enrollment();\n const settings = enrollment ? readSiteSettings(this.#deps.stateDir) : null;\n const frpc = this.#frpc?.status() ?? null;\n const caddy = this.#caddy?.status() ?? null;\n const running = [frpc?.running, caddy?.running].filter(Boolean).length;\n const labels = Object.keys(settings?.upstreams ?? {});\n return {\n stateDir: this.#deps.stateDir,\n enrolled: enrollment !== null,\n siteId: enrollment?.siteId ?? null,\n siteZone: enrollment?.siteZone ?? null,\n zoneKind: enrollment?.zoneKind ?? null,\n delegation: enrollment?.delegation ?? null,\n settings,\n binaries: resolveBinaries(this.#deps),\n tunnel: {\n state: running === 2 ? \"up\" : running === 0 ? \"down\" : \"degraded\",\n frpc,\n caddy,\n },\n urls: enrollment\n ? (labels.length ? labels : [\"app\"]).map(\n (label) => `https://${label}.${enrollment.siteZone}/`,\n )\n : [],\n };\n }\n\n /** For status: a resolver that cannot answer reads as not delegated (yet). */\n async checkDelegation(): Promise<boolean | null> {\n const delegation = this.#enrollment()?.delegation;\n if (!delegation) return null;\n try {\n return await isDelegated(\n delegation,\n this.#deps.resolveNs,\n this.#deps.delegationCheck,\n );\n } catch (error) {\n if (error instanceof DelegationCheckError) return false;\n throw error;\n }\n }\n\n async enrol(input: EnrolInput): Promise<TunnelStatus> {\n if (this.#enrollment()) {\n throw new Error(\n \"this project is already enrolled; remove .ph/portle/enrollment.json to enrol again\",\n );\n }\n const controlPlaneUrl = input.controlPlaneUrl.replace(/\\/$/, \"\");\n if (!/^https?:\\/\\//.test(controlPlaneUrl))\n throw new Error(\"controlPlaneUrl must be an http(s) URL\");\n const enrollment = await enrolWithControlPlane(\n controlPlaneUrl,\n input.token,\n this.#deps.fetchImpl,\n );\n writeEnrollment(this.#deps.stateDir, enrollment);\n const existing = readSiteSettings(this.#deps.stateDir);\n writeSiteSettings(this.#deps.stateDir, {\n ...DEFAULT_SITE_SETTINGS,\n ...existing,\n controlPlaneUrl,\n autostart: false,\n });\n this.#deps.log?.(\"enrolled\", {\n siteId: enrollment.siteId,\n siteZone: enrollment.siteZone,\n zoneKind: enrollment.zoneKind,\n });\n return this.status();\n }\n\n configure(patch: SettingsPatch): TunnelStatus {\n const settings = this.#settings();\n if (patch.upstreams) {\n for (const [label, target] of Object.entries(patch.upstreams)) {\n if (!LABEL_RE.test(label))\n throw new Error(`invalid upstream label ${JSON.stringify(label)}`);\n if (!target) throw new Error(`upstream ${label} has no target`);\n }\n }\n // Over the wire the mode is a plain string; the type says otherwise.\n const mode: string | undefined = patch.dns01Mode;\n if (mode && mode !== \"rfc2136\" && mode !== \"acmedns\") {\n throw new Error(`dns01Mode must be rfc2136 or acmedns`);\n }\n if (patch.listen) {\n for (const [name, value] of Object.entries(patch.listen)) {\n if (!Number.isInteger(value) || value < 1 || value > 65535) {\n throw new Error(`listen.${name} must be a port number`);\n }\n }\n if (patch.listen.https === patch.listen.http) {\n throw new Error(\"listen.https and listen.http must differ\");\n }\n }\n writeSiteSettings(this.#deps.stateDir, { ...settings, ...patch });\n return this.status();\n }\n\n /** Writes the CA files, frpc.toml and the Caddyfile for the current enrolment and settings. */\n render(): {\n frpcConfig: string;\n caddyfile: string;\n certsDir: string;\n } {\n const enrollment = this.#requireEnrollment();\n const settings = this.#settings();\n const dir = this.#deps.stateDir;\n const certsDir = join(dir, \"certs\");\n mkdirSync(certsDir, { recursive: true });\n writeFileAtomic(\n join(certsDir, \"relay-ca.crt\"),\n enrollment.frp.caPem,\n 0o600,\n );\n const acmeRoot = enrollment.acme.caRootPem\n ? join(certsDir, \"acme-ca-root.pem\")\n : undefined;\n if (acmeRoot && enrollment.acme.caRootPem)\n writeFileAtomic(acmeRoot, enrollment.acme.caRootPem, 0o600);\n\n const frpcConfig = join(dir, \"frpc.toml\");\n writeFileAtomic(\n frpcConfig,\n renderFrpcToml({\n siteId: enrollment.siteId,\n siteSecret: enrollment.siteSecret,\n siteZone: enrollment.siteZone,\n serverAddr: enrollment.frp.serverAddr,\n serverPort: enrollment.frp.serverPort,\n serverName: enrollment.frp.serverName,\n token: enrollment.frp.token,\n trustedCaFile: join(certsDir, \"relay-ca.crt\"),\n caddyHost: \"127.0.0.1\",\n vanityDomains: [],\n localHttpsPort: settings.listen.https,\n localHttpPort: settings.listen.http,\n }),\n 0o600,\n );\n\n const dns01: Dns01 =\n settings.dns01Mode === \"acmedns\"\n ? {\n mode: \"acmedns\",\n username: enrollment.acmeDns.username,\n password: enrollment.acmeDns.password,\n subdomain: enrollment.acmeDns.subdomain,\n serverUrl: enrollment.acmeDns.baseUrl,\n }\n : rfc2136Dns(\n enrollment.dns.tsigKeyName,\n enrollment.dns.tsigSecret,\n enrollment.dns.server,\n enrollment.dns.tsigAlgorithm,\n );\n const dnsHost =\n enrollment.dns.server.split(\":\")[0] ?? enrollment.dns.server;\n const appRoute = this.#appRoute(settings);\n const caddyfile = join(dir, \"Caddyfile\");\n writeFileAtomic(\n caddyfile,\n renderCaddyfile({\n siteId: enrollment.siteId,\n siteZone: enrollment.siteZone,\n email: enrollment.acme.email,\n acmeCaUrl: enrollment.acme.caUrl,\n acmeCaRootFile: acmeRoot,\n // frpc runs on this machine and is the only PROXY-header sender.\n proxyAllowCidr: \"127.0.0.1/32\",\n appUpstream: settings.appUpstream,\n upstreams: settings.upstreams,\n vanityDomains: [],\n askUrl: `${settings.controlPlaneUrl}/v1/tls/ask`,\n resolvers: enrollment.dns.resolvers.length\n ? enrollment.dns.resolvers\n : [dnsHost],\n dns01,\n listen: settings.listen,\n rewriteHostHeader: settings.rewriteHostHeader ?? false,\n appRoute,\n }),\n 0o600,\n );\n return { frpcConfig, caddyfile, certsDir };\n }\n\n /**\n * Brings the tunnel up. A customer zone must be delegated first: Caddy\n * would otherwise ask the CA for a name the CA cannot resolve, and the\n * negative answer is cached for an hour.\n */\n async start(): Promise<TunnelStatus> {\n const delegation = this.#requireEnrollment().delegation;\n let delegated = true;\n if (delegation) {\n try {\n delegated = await isDelegated(\n delegation,\n this.#deps.resolveNs,\n this.#deps.delegationCheck,\n );\n } catch (error) {\n if (error instanceof DelegationCheckError) {\n throw new Error(\n `cannot start: ${error.message}. This is a DNS lookup failure, not a missing delegation: start again once DNS answers.`,\n { cause: error },\n );\n }\n throw error;\n }\n }\n if (delegation && !delegated) {\n throw new Error(\n `cannot start: ${delegation.zone} is not delegated yet. Create at your DNS provider: ${delegation.nameservers\n .map((ns) => `${delegation.zone} NS ${ns}`)\n .join(\"; \")} — then start again.`,\n );\n }\n const binaries = resolveBinaries(this.#deps);\n const missing = ([\"frpc\", \"caddy\"] as const).filter(\n (name) => !binaries[name],\n );\n if (missing.length > 0) {\n throw new Error(\n `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(\", \")}`,\n );\n }\n const { frpcConfig, caddyfile } = this.render();\n return this.#startNow(\n { frpc: binaries.frpc!, caddy: binaries.caddy! },\n { frpcConfig, caddyfile },\n );\n }\n\n #startNow(\n binaries: { frpc: string; caddy: string },\n { frpcConfig, caddyfile }: { frpcConfig: string; caddyfile: string },\n ): TunnelStatus {\n const dir = this.#deps.stateDir;\n const logs = join(dir, \"logs\");\n const create =\n this.#deps.createSupervised ??\n ((options: SupervisedOptions) => new Supervised(options));\n const log = this.#deps.log;\n const onEvent = (event: unknown) =>\n log?.(\"tunnel\", event as Record<string, unknown>);\n\n if (!this.#caddy) {\n const caddyHome = join(dir, \"caddy\");\n mkdirSync(caddyHome, { recursive: true });\n this.#caddy = create({\n name: \"caddy\",\n command: binaries.caddy!,\n args: [\"run\", \"--config\", caddyfile, \"--adapter\", \"caddyfile\"],\n cwd: dir,\n logFile: join(logs, \"caddy.log\"),\n // Caddy keeps the certificate under its data dir; pin it beside the site.\n env: {\n ...(this.#deps.env ?? process.env),\n XDG_DATA_HOME: caddyHome,\n XDG_CONFIG_HOME: join(caddyHome, \"config\"),\n },\n onEvent,\n });\n }\n if (!this.#frpc) {\n this.#frpc = create({\n name: \"frpc\",\n command: binaries.frpc!,\n args: [\"-c\", frpcConfig],\n cwd: dir,\n logFile: join(logs, \"frpc.log\"),\n env: this.#deps.env ?? process.env,\n onEvent,\n });\n }\n this.#caddy.start();\n this.#frpc.start();\n writeSiteSettings(dir, { ...this.#settings(), autostart: true });\n log?.(\"tunnel started\", { siteZone: this.#requireEnrollment().siteZone });\n return this.status();\n }\n\n async stop(options: StopOptions = {}): Promise<TunnelStatus> {\n await this.#frpc?.stop();\n await this.#caddy?.stop();\n this.#frpc = null;\n this.#caddy = null;\n if (\n !options.keepAutostart &&\n this.#enrollment() &&\n readSiteSettings(this.#deps.stateDir)\n ) {\n writeSiteSettings(this.#deps.stateDir, {\n ...this.#settings(),\n autostart: false,\n });\n }\n this.#deps.log?.(\"tunnel stopped\", {\n autostart: this.wantsAutostart(),\n });\n return this.status();\n }\n\n /** Whether the operator asked for the tunnel to come up at boot. */\n wantsAutostart(): boolean {\n return (\n this.#enrollment() !== null &&\n readSiteSettings(this.#deps.stateDir)?.autostart === true\n );\n }\n\n /**\n * Same-origin publication for the `app` label: its handle also proxies the\n * switchboard's paths to the `api` upstream, the same split Connect's own\n * dev and preview servers make (the connect runner's `runner.proxy`), so\n * the SPA calls its own origin for everything and its served config, which\n * names the switchboard as `${origin}`, resolves to this label in the\n * browser. No cross-origin requests, no browser prompt for a local\n * address, and nothing rendered or fetched from the app at start.\n */\n #appRoute(\n settings: SiteSettings,\n ): { label: string; apiTarget: string } | undefined {\n if (settings.sameOrigin === false) return undefined;\n const app = settings.upstreams.app;\n const api = settings.upstreams.api;\n if (!app || !api) return undefined;\n return { label: \"app\", apiTarget: api };\n }\n\n #enrollment(): EnrollmentResponse | null {\n return existsSync(this.#deps.stateDir)\n ? readEnrollment(this.#deps.stateDir)\n : null;\n }\n\n #requireEnrollment(): EnrollmentResponse {\n const enrollment = this.#enrollment();\n if (!enrollment)\n throw new Error(\"this project is not enrolled with Portle yet\");\n return enrollment;\n }\n\n #settings(): SiteSettings {\n const settings = readSiteSettings(this.#deps.stateDir);\n if (!settings)\n throw new Error(\"this project is not enrolled with Portle yet\");\n return settings;\n }\n}\n","import type { API, Context, ISubgraph } from \"@powerhousedao/reactor-api\";\nimport { GraphQLError, parse } from \"graphql\";\nimport {\n evaluateGate,\n isListedAdmin,\n type GateFacts,\n type GateReport,\n type PortlePolicy,\n} from \"./gate.js\";\nimport type { PortleRunnerLike, TunnelStatus } from \"./runner.js\";\n\n/** The slice of the switchboard's API object the subgraph reads. */\nexport type PortleApi = Pick<\n API,\n \"authorizationService\" | \"requireAuthenticatedCaller\" | \"relationalDb\"\n> & {\n /** Present exactly when the host resolves caller identity. */\n authService: unknown;\n};\n\nexport const PORTLE_SUBGRAPH_NAME = \"portle\";\n\nexport const portleTypeDefs = parse(/* GraphQL */ `\n type PortleCheck {\n id: String!\n ok: Boolean!\n detail: String!\n fix: String\n }\n\n type PortleCaller {\n address: String\n isAdmin: Boolean!\n }\n\n type PortleReadiness {\n publishable: Boolean!\n checks: [PortleCheck!]!\n warnings: [PortleCheck!]!\n me: PortleCaller!\n }\n\n type PortleSupervised {\n name: String!\n command: String!\n running: Boolean!\n pid: Int\n startedAt: String\n restarts: Int!\n lastExitCode: Int\n lastExitSignal: String\n lastExitAt: String\n }\n\n type PortleTunnel {\n \"\"\"\n down, degraded (one of the two processes), or up\n \"\"\"\n state: String!\n frpc: PortleSupervised\n caddy: PortleSupervised\n }\n\n type PortleDelegation {\n zone: String!\n nameservers: [String!]!\n \"\"\"\n Whether the zone's NS records already point at the relay, as this\n machine's resolver sees it. Known on portleStatus; null elsewhere.\n \"\"\"\n delegated: Boolean\n }\n\n type PortleListen {\n https: Int!\n http: Int!\n }\n\n type PortleUpstream {\n label: String!\n target: String!\n }\n\n type PortleSettings {\n controlPlaneUrl: String!\n appUpstream: String!\n upstreams: [PortleUpstream!]!\n dns01Mode: String!\n listen: PortleListen!\n rewriteHostHeader: Boolean!\n sameOrigin: Boolean!\n autostart: Boolean!\n }\n\n type PortleBinaries {\n frpc: String\n caddy: String\n searched: [String!]!\n }\n\n type PortleStatus {\n stateDir: String!\n enrolled: Boolean!\n siteId: String\n siteZone: String\n zoneKind: String\n delegation: PortleDelegation\n settings: PortleSettings\n binaries: PortleBinaries!\n tunnel: PortleTunnel!\n urls: [String!]!\n }\n\n input PortleUpstreamInput {\n label: String!\n target: String!\n }\n\n type Query {\n \"\"\"\n Whether this host may be published through Portle, check by check.\n Under an OPEN policy it answers everyone, since there is no admin to\n distinguish; under any other policy only a listed admin may ask.\n \"\"\"\n portleReadiness: PortleReadiness!\n \"\"\"\n The site's enrolment, settings, binaries and tunnel. Admins only.\n \"\"\"\n portleStatus: PortleStatus!\n }\n\n type Mutation {\n \"\"\"\n Enrol this project with a Portle control plane using a one-time token.\n \"\"\"\n portleEnrol(controlPlaneUrl: String!, token: String!): PortleStatus!\n \"\"\"\n What the tunnel exposes: the default upstream and per-label upstreams.\n \"\"\"\n portleConfigure(\n appUpstream: String\n upstreams: [PortleUpstreamInput!]\n dns01Mode: String\n listenHttps: Int\n listenHttp: Int\n \"\"\"\n Send the upstream's host:port as the Host header (for dev servers that\n check it, such as Vite's allowedHosts).\n \"\"\"\n rewriteHostHeader: Boolean\n \"\"\"\n Serve Connect and the switchboard on the app label's origin, with a\n runtime config that points the SPA at that origin (default on).\n \"\"\"\n sameOrigin: Boolean\n ): PortleStatus!\n \"\"\"\n Bring the tunnel up. Refused unless every readiness check passes for the caller.\n \"\"\"\n portleStart: PortleStatus!\n portleStop: PortleStatus!\n }\n`);\n\n/** The host's authorization facts, read off the API object. */\nexport function gateFactsOf(api: PortleApi): GateFacts {\n const config = api.authorizationService.config;\n return {\n policy: config.policy as PortlePolicy,\n admins: config.admins,\n defaultProtection: config.defaultProtection,\n identityResolved: api.authService !== undefined,\n requireAuthenticatedCaller: api.requireAuthenticatedCaller,\n };\n}\n\nexport type PortleReadiness = GateReport & {\n me: { address: string | null; isAdmin: boolean };\n};\n\nfunction forbidden(message: string): GraphQLError {\n return new GraphQLError(message, { extensions: { code: \"FORBIDDEN\" } });\n}\n\nexport function readiness(api: PortleApi, ctx: Context): PortleReadiness {\n const facts = gateFactsOf(api);\n const address = ctx.user?.address;\n const isAdmin = isListedAdmin(facts.admins, address);\n if (facts.policy !== \"OPEN\" && !isAdmin) {\n throw forbidden(\"Portle readiness is for the host's admins.\");\n }\n return {\n ...evaluateGate(facts, ctx.user),\n me: { address: address ?? null, isAdmin },\n };\n}\n\n/** Every other field: a listed admin on a host that is not OPEN. */\nexport function requireAdmin(api: PortleApi, ctx: Context): GateFacts {\n const facts = gateFactsOf(api);\n if (facts.policy === \"OPEN\") {\n throw forbidden(\n \"Portle is disabled while the host's authorization policy is OPEN; lock the host down first (see portleReadiness).\",\n );\n }\n if (!isListedAdmin(facts.admins, ctx.user?.address)) {\n throw forbidden(\"Portle is for the host's admins.\");\n }\n return facts;\n}\n\ntype WireUpstream = { label: string; target: string };\n\n/** The GraphQL shape of a status: maps become lists, exits flatten. */\nexport function toWireStatus(\n status: TunnelStatus,\n delegated: boolean | null = null,\n) {\n const supervised = (s: TunnelStatus[\"tunnel\"][\"frpc\"]) =>\n s && {\n name: s.name,\n command: s.command,\n running: s.running,\n pid: s.pid,\n startedAt: s.startedAt,\n restarts: s.restarts,\n lastExitCode: s.lastExit?.code ?? null,\n lastExitSignal: s.lastExit?.signal ?? null,\n lastExitAt: s.lastExit?.at ?? null,\n };\n return {\n ...status,\n delegation: status.delegation && { ...status.delegation, delegated },\n settings: status.settings && {\n ...status.settings,\n rewriteHostHeader: status.settings.rewriteHostHeader ?? false,\n sameOrigin: status.settings.sameOrigin ?? true,\n upstreams: Object.entries(status.settings.upstreams).map(\n ([label, target]): WireUpstream => ({ label, target }),\n ),\n },\n tunnel: {\n state: status.tunnel.state,\n frpc: supervised(status.tunnel.frpc),\n caddy: supervised(status.tunnel.caddy),\n },\n };\n}\n\nexport interface PortleSubgraphDeps {\n api: PortleApi;\n runner: PortleRunnerLike;\n}\n\n/**\n * The `portle` subgraph as a plain `ISubgraph`: no reactor reads, no setup,\n * so it needs none of `BaseSubgraph` and keeps the plugin free of runtime\n * imports from reactor-api.\n */\nexport function createPortleSubgraph({\n api,\n runner,\n}: PortleSubgraphDeps): ISubgraph {\n const guarded =\n <A, R>(run: (args: A, ctx: Context, facts: GateFacts) => R) =>\n (_parent: unknown, args: A, ctx: Context): R =>\n run(args, ctx, requireAdmin(api, ctx));\n\n return {\n name: PORTLE_SUBGRAPH_NAME,\n typeDefs: portleTypeDefs,\n relationalDb: api.relationalDb,\n hasSubscriptions: false,\n resolvers: {\n Query: {\n portleReadiness: (_parent: unknown, _args: unknown, ctx: Context) =>\n readiness(api, ctx),\n portleStatus: guarded(async () =>\n toWireStatus(runner.status(), await runner.checkDelegation()),\n ),\n },\n Mutation: {\n portleEnrol: guarded(\n async (args: { controlPlaneUrl: string; token: string }) =>\n toWireStatus(\n await runner.enrol({\n controlPlaneUrl: args.controlPlaneUrl,\n token: args.token,\n }),\n ),\n ),\n portleConfigure: guarded(\n (args: {\n appUpstream?: string | null;\n upstreams?: WireUpstream[] | null;\n dns01Mode?: string | null;\n listenHttps?: number | null;\n listenHttp?: number | null;\n rewriteHostHeader?: boolean | null;\n sameOrigin?: boolean | null;\n }) =>\n toWireStatus(\n runner.configure({\n ...(args.appUpstream ? { appUpstream: args.appUpstream } : {}),\n ...(args.upstreams\n ? {\n upstreams: Object.fromEntries(\n args.upstreams.map((u) => [\n u.label.toLowerCase(),\n u.target,\n ]),\n ),\n }\n : {}),\n ...(args.dns01Mode\n ? { dns01Mode: args.dns01Mode as \"rfc2136\" | \"acmedns\" }\n : {}),\n ...(args.listenHttps != null || args.listenHttp != null\n ? {\n listen: {\n https: args.listenHttps ?? 443,\n http: args.listenHttp ?? 80,\n },\n }\n : {}),\n ...(args.rewriteHostHeader != null\n ? { rewriteHostHeader: args.rewriteHostHeader }\n : {}),\n ...(args.sameOrigin != null\n ? { sameOrigin: args.sameOrigin }\n : {}),\n }),\n ),\n ),\n portleStart: guarded(\n async (_args: unknown, ctx: Context, facts: GateFacts) => {\n const report = evaluateGate(facts, ctx.user);\n if (!report.publishable) {\n const failing = report.checks\n .filter((c) => !c.ok)\n .map((c) => c.id);\n throw forbidden(\n `The publication gate is not met (${failing.join(\", \")}); see portleReadiness.`,\n );\n }\n return toWireStatus(await runner.start());\n },\n ),\n portleStop: guarded(async () => toWireStatus(await runner.stop())),\n },\n },\n };\n}\n"],"mappings":";;;;;;;AAyBA,MAAa,aAAa;CACxB,MAAM;CACN,OAAO;AACT;AAEA,SAAgB,aACd,MACA,WAA4B,QAAQ,UAC5B;CACR,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK,MAAM,OAAO,UAAU,KAAK;AAC5D;;AAGA,SAAS,QAAQ,UAA8C;CAC7D,OAAO,aAAa,UAAU,KAAK,QAAQ,KAAK;AAClD;AAEA,SAAgB,gBACd,UAAkC,CAAC,GAClB;CACjB,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,MAAM,WAAW,QAAQ,YAAY,QAAQ;CAC7C,MAAM,SAAS,QAAQ,UAAU;CACjC,MAAM,OAAO,QAAQ,QAAQ,IAAI,QAAQ,IAAI,eAAe;CAC5D,MAAM,SAAS,aAAa,UAAU,SAAS;CAC/C,MAAM,IAAI,QAAQ,QAAQ;CAC1B,MAAM,WAAqB,CAAC;CAE5B,MAAM,QAAQ,SAA0C;EACtD,MAAM,WAAW,IAAI,WAAW;EAChC,IAAI,UAAU;GACZ,SAAS,KAAK,QAAQ;GACtB,OAAO,OAAO,QAAQ,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KACxD,MAAM,SAAS,aAAa,OAAO,IAAI,IAAI;KAC3C,IAAI,CAAC,OAAO,aAIV,MAAM,UACJ,oCAJc,OAAO,OACpB,QAAQ,MAAM,CAAC,EAAE,EAAE,CAAC,CACpB,KAAK,MAAM,EAAE,EAE4B,CAAC,CAAC,KAAK,IAAI,EAAE,wBACzD;KAEF,OAAO,aAAa,MAAM,OAAO,MAAM,CAAC;IAC1C,CACF;IACA,YAAY,QAAQ,YAAY,aAAa,MAAM,OAAO,KAAK,CAAC,CAAC;GACnE;EACF;CACF;AACF"}
@@ -1,3 +1,4 @@
1
+ import { i as PortleRunnerLike } from "./runner-DjoiJrWX.mjs";
1
2
  import { HostPlugin } from "@powerhousedao/host-core";
2
3
  //#region src/switchboard.d.ts
3
4
  /**
@@ -5,27 +6,41 @@ import { HostPlugin } from "@powerhousedao/host-core";
5
6
  * through the Portle relay. Listed in the project's switchboard host file
6
7
  * (`runner.plugins`); presence is activation, and it takes no config.
7
8
  *
8
- * Today it mounts the `portle` subgraph, whose `portleReadiness` query reports
9
- * the publication gate check by check (see `gate.ts`). The tunnel itself
10
- * (enrolment, frpc and Caddy under supervision) follows in later work and
11
- * hangs off the same plugin, so the gate and the thing it guards share one
12
- * owner.
9
+ * It mounts the `portle` subgraph (readiness, status, enrol, configure,
10
+ * start, stop) and owns the tunnel: frpc and Caddy run as its supervised
11
+ * children, come up at boot only when the operator asked for it AND the
12
+ * publication gate passes, and go down with the switchboard. The gate and
13
+ * the thing it guards share one owner, so "published" implies "locked down".
13
14
  */
14
15
  /**
15
16
  * The slice of the switchboard's plugin context this plugin reads. The
16
17
  * switchboard does not export its context type; these are the fields it
17
- * documents as set by the time `onSubgraphsRegistering` fires.
18
+ * documents as set by the time the hooks fire.
18
19
  */
19
20
  export interface PortleHostContext {
21
+ options?: Record<string, unknown>;
22
+ logger?: unknown;
20
23
  api?: unknown;
21
24
  graphqlManager?: unknown;
22
25
  /** Late subgraph registrations drain before the readiness router update. */
23
26
  lateSubgraphs?: Promise<unknown>[];
27
+ /** Set by this plugin at onSubgraphsRegistering. */
28
+ portle?: {
29
+ runner: PortleRunnerLike;
30
+ };
31
+ }
32
+ interface LoggerLike {
33
+ info(message: string, ...args: unknown[]): void;
34
+ warn(message: string, ...args: unknown[]): void;
24
35
  }
25
36
  export interface PortleHooks {
26
37
  onSubgraphsRegistering: (ctx: PortleHostContext) => Promise<void>;
38
+ onDrivesReady: (ctx: PortleHostContext) => Promise<void>;
39
+ onShutdown: (ctx: PortleHostContext) => Promise<void>;
27
40
  }
28
41
  export declare const PORTLE_PLUGIN_NAME = "portle";
42
+ /** Injected by tests; the real plugin builds a PortleRunner on the project's state dir. */
43
+ export declare function createPortlePlugin(makeRunner?: (stateDir: string, log: LoggerLike) => PortleRunnerLike): HostPlugin<PortleHooks>;
29
44
  export declare const portleSwitchboardPlugin: HostPlugin<PortleHooks>;
30
45
  //#endregion
31
46
  export { portleSwitchboardPlugin as default };
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard.d.mts","names":[],"sources":["../src/switchboard.ts"],"mappings":";;;;;;;;;;;;;;;;;;iBAqBiB;EACf;EACA;;EAEA,gBAAgB;;iBAWD;EACf,yBAAyB,KAAK,sBAAsB;;qBAGzC;qBAEA,yBAAyB,WAAW"}
1
+ {"version":3,"file":"switchboard.d.mts","names":[],"sources":["../src/switchboard.ts"],"mappings":";;;;;;;;;;;;;;;;;;;iBA4BiB;EACf,UAAU;EACV;EACA;EACA;;EAEA,gBAAgB;;EAEhB;IAAW,QAAQ;;;UAWX;EACR,KAAK,oBAAoB;EACzB,KAAK,oBAAoB;;iBAkBV;EACf,yBAAyB,KAAK,sBAAsB;EACpD,gBAAgB,KAAK,sBAAsB;EAC3C,aAAa,KAAK,sBAAsB;;qBAG7B;;wBAGG,mBACd,cAAa,kBAAkB,KAAK,eAAe,mBASlD,WAAW;qBAqED,yBAAyB,WAAW"}
@@ -1,19 +1,72 @@
1
- import { n as createPortleSubgraph } from "./subgraph-D7PtSa_n.mjs";
1
+ import { _ as stateDirOf, b as bootGatePasses, c as PortleRunner, m as projectRootOf, n as createPortleSubgraph, r as gateFactsOf } from "./subgraph-6lmwvcN4.mjs";
2
2
  //#region src/switchboard.ts
3
+ function loggerOf(ctx) {
4
+ const logger = ctx.logger;
5
+ if (logger && typeof logger.info === "function" && typeof logger.warn === "function") return logger;
6
+ return {
7
+ info: (m, ...a) => console.log(`[portle] ${m}`, ...a),
8
+ warn: (m, ...a) => console.warn(`[portle] ${m}`, ...a)
9
+ };
10
+ }
3
11
  const PORTLE_PLUGIN_NAME = "portle";
4
- const portleSwitchboardPlugin = {
5
- name: PORTLE_PLUGIN_NAME,
6
- appliesTo: "switchboard",
7
- hooks: { onSubgraphsRegistering: async (ctx) => {
8
- const api = ctx.api;
9
- const registry = ctx.graphqlManager;
10
- if (!api || !registry) throw new Error("The portle plugin needs the switchboard's API and GraphQL manager at onSubgraphsRegistering; the host handed neither.");
11
- const registration = registry.registerSubgraphInstance(createPortleSubgraph(api), "graphql", false);
12
- (ctx.lateSubgraphs ??= []).push(registration);
13
- await Promise.resolve();
14
- } }
15
- };
12
+ /** Injected by tests; the real plugin builds a PortleRunner on the project's state dir. */
13
+ function createPortlePlugin(makeRunner = (stateDir, log) => new PortleRunner({
14
+ stateDir,
15
+ log: (msg, detail) => log.info(`[portle] ${msg} ${detail ? JSON.stringify(detail) : ""}`)
16
+ })) {
17
+ /** One runner per host, built by whichever hook the host reaches first. */
18
+ const ensureRunner = (ctx) => {
19
+ if (ctx.portle) return ctx.portle.runner;
20
+ const runner = makeRunner(stateDirOf(projectRootOf(ctx.options)), loggerOf(ctx));
21
+ ctx.portle = { runner };
22
+ return runner;
23
+ };
24
+ return {
25
+ name: PORTLE_PLUGIN_NAME,
26
+ appliesTo: "switchboard",
27
+ hooks: {
28
+ onSubgraphsRegistering: async (ctx) => {
29
+ const api = ctx.api;
30
+ const registry = ctx.graphqlManager;
31
+ if (!api || !registry) throw new Error("The portle plugin needs the switchboard's API and GraphQL manager at onSubgraphsRegistering; the host handed neither.");
32
+ const runner = ensureRunner(ctx);
33
+ const registration = registry.registerSubgraphInstance(createPortleSubgraph({
34
+ api,
35
+ runner
36
+ }), "graphql", false);
37
+ (ctx.lateSubgraphs ??= []).push(registration);
38
+ await Promise.resolve();
39
+ },
40
+ onDrivesReady: async (ctx) => {
41
+ const runner = ctx.portle?.runner;
42
+ const api = ctx.api;
43
+ if (!runner || !api) return;
44
+ const log = loggerOf(ctx);
45
+ const status = runner.status();
46
+ if (!status.enrolled || !status.settings?.autostart) return;
47
+ const facts = gateFactsOf(api);
48
+ if (!bootGatePasses(facts)) {
49
+ log.warn("[portle] the tunnel stays down: this host no longer passes the publication gate (see portleReadiness). Lock it down again or stop publishing.");
50
+ return;
51
+ }
52
+ try {
53
+ await runner.start();
54
+ log.info(`[portle] tunnel up for ${status.siteZone}`);
55
+ } catch (error) {
56
+ log.warn(`[portle] the tunnel could not start: ${error instanceof Error ? error.message : String(error)}`);
57
+ }
58
+ },
59
+ onShutdown: async (ctx) => {
60
+ const runner = ctx.portle?.runner;
61
+ if (!runner) return;
62
+ if (runner.status().tunnel.state === "down") return;
63
+ await runner.stop({ keepAutostart: true });
64
+ }
65
+ }
66
+ };
67
+ }
68
+ const portleSwitchboardPlugin = createPortlePlugin();
16
69
  //#endregion
17
- export { PORTLE_PLUGIN_NAME, portleSwitchboardPlugin as default, portleSwitchboardPlugin };
70
+ export { PORTLE_PLUGIN_NAME, createPortlePlugin, portleSwitchboardPlugin as default, portleSwitchboardPlugin };
18
71
 
19
72
  //# sourceMappingURL=switchboard.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard.mjs","names":[],"sources":["../src/switchboard.ts"],"sourcesContent":["import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport type { ISubgraph } from \"@powerhousedao/reactor-api\";\nimport { createPortleSubgraph, type PortleApi } from \"./subgraph.js\";\n\n/**\n * Portle, server side: the host plugin that lets a project publish itself\n * through the Portle relay. Listed in the project's switchboard host file\n * (`runner.plugins`); presence is activation, and it takes no config.\n *\n * Today it mounts the `portle` subgraph, whose `portleReadiness` query reports\n * the publication gate check by check (see `gate.ts`). The tunnel itself\n * (enrolment, frpc and Caddy under supervision) follows in later work and\n * hangs off the same plugin, so the gate and the thing it guards share one\n * owner.\n */\n\n/**\n * The slice of the switchboard's plugin context this plugin reads. The\n * switchboard does not export its context type; these are the fields it\n * documents as set by the time `onSubgraphsRegistering` fires.\n */\nexport interface PortleHostContext {\n api?: unknown;\n graphqlManager?: unknown;\n /** Late subgraph registrations drain before the readiness router update. */\n lateSubgraphs?: Promise<unknown>[];\n}\n\ninterface SubgraphRegistry {\n registerSubgraphInstance(\n subgraph: ISubgraph,\n supergraph?: string,\n core?: boolean,\n ): Promise<unknown>;\n}\n\nexport interface PortleHooks {\n onSubgraphsRegistering: (ctx: PortleHostContext) => Promise<void>;\n}\n\nexport const PORTLE_PLUGIN_NAME = \"portle\";\n\nexport const portleSwitchboardPlugin: HostPlugin<PortleHooks> = {\n name: PORTLE_PLUGIN_NAME,\n appliesTo: \"switchboard\",\n hooks: {\n onSubgraphsRegistering: async (ctx) => {\n const api = ctx.api as PortleApi | undefined;\n const registry = ctx.graphqlManager as SubgraphRegistry | undefined;\n if (!api || !registry) {\n throw new Error(\n \"The portle plugin needs the switchboard's API and GraphQL manager at onSubgraphsRegistering; the host handed neither.\",\n );\n }\n const registration = registry.registerSubgraphInstance(\n createPortleSubgraph(api),\n \"graphql\",\n false,\n );\n (ctx.lateSubgraphs ??= []).push(registration);\n await Promise.resolve();\n },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default portleSwitchboardPlugin;\n"],"mappings":";;AAwCA,MAAa,qBAAqB;AAElC,MAAa,0BAAmD;CAC9D,MAAM;CACN,WAAW;CACX,OAAO,EACL,wBAAwB,OAAO,QAAQ;EACrC,MAAM,MAAM,IAAI;EAChB,MAAM,WAAW,IAAI;EACrB,IAAI,CAAC,OAAO,CAAC,UACX,MAAM,IAAI,MACR,uHACF;EAEF,MAAM,eAAe,SAAS,yBAC5B,qBAAqB,GAAG,GACxB,WACA,KACF;EACA,CAAC,IAAI,kBAAkB,CAAC,EAAA,CAAG,KAAK,YAAY;EAC5C,MAAM,QAAQ,QAAQ;CACxB,EACF;AACF"}
1
+ {"version":3,"file":"switchboard.mjs","names":[],"sources":["../src/switchboard.ts"],"sourcesContent":["import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport type { ISubgraph } from \"@powerhousedao/reactor-api\";\nimport { bootGatePasses } from \"./gate.js\";\nimport { PortleRunner, type PortleRunnerLike } from \"./runner.js\";\nimport { projectRootOf, stateDirOf } from \"./state.js\";\nimport {\n createPortleSubgraph,\n gateFactsOf,\n type PortleApi,\n} from \"./subgraph.js\";\n\n/**\n * Portle, server side: the host plugin that lets a project publish itself\n * through the Portle relay. Listed in the project's switchboard host file\n * (`runner.plugins`); presence is activation, and it takes no config.\n *\n * It mounts the `portle` subgraph (readiness, status, enrol, configure,\n * start, stop) and owns the tunnel: frpc and Caddy run as its supervised\n * children, come up at boot only when the operator asked for it AND the\n * publication gate passes, and go down with the switchboard. The gate and\n * the thing it guards share one owner, so \"published\" implies \"locked down\".\n */\n\n/**\n * The slice of the switchboard's plugin context this plugin reads. The\n * switchboard does not export its context type; these are the fields it\n * documents as set by the time the hooks fire.\n */\nexport interface PortleHostContext {\n options?: Record<string, unknown>;\n logger?: unknown;\n api?: unknown;\n graphqlManager?: unknown;\n /** Late subgraph registrations drain before the readiness router update. */\n lateSubgraphs?: Promise<unknown>[];\n /** Set by this plugin at onSubgraphsRegistering. */\n portle?: { runner: PortleRunnerLike };\n}\n\ninterface SubgraphRegistry {\n registerSubgraphInstance(\n subgraph: ISubgraph,\n supergraph?: string,\n core?: boolean,\n ): Promise<unknown>;\n}\n\ninterface LoggerLike {\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n}\n\nfunction loggerOf(ctx: PortleHostContext): LoggerLike {\n const logger = ctx.logger as Partial<LoggerLike> | undefined;\n if (\n logger &&\n typeof logger.info === \"function\" &&\n typeof logger.warn === \"function\"\n ) {\n return logger as LoggerLike;\n }\n return {\n info: (m, ...a) => console.log(`[portle] ${m}`, ...a),\n warn: (m, ...a) => console.warn(`[portle] ${m}`, ...a),\n };\n}\n\nexport interface PortleHooks {\n onSubgraphsRegistering: (ctx: PortleHostContext) => Promise<void>;\n onDrivesReady: (ctx: PortleHostContext) => Promise<void>;\n onShutdown: (ctx: PortleHostContext) => Promise<void>;\n}\n\nexport const PORTLE_PLUGIN_NAME = \"portle\";\n\n/** Injected by tests; the real plugin builds a PortleRunner on the project's state dir. */\nexport function createPortlePlugin(\n makeRunner: (stateDir: string, log: LoggerLike) => PortleRunnerLike = (\n stateDir,\n log,\n ) =>\n new PortleRunner({\n stateDir,\n log: (msg, detail) =>\n log.info(`[portle] ${msg} ${detail ? JSON.stringify(detail) : \"\"}`),\n }),\n): HostPlugin<PortleHooks> {\n /** One runner per host, built by whichever hook the host reaches first. */\n const ensureRunner = (ctx: PortleHostContext): PortleRunnerLike => {\n if (ctx.portle) return ctx.portle.runner;\n const runner = makeRunner(\n stateDirOf(projectRootOf(ctx.options)),\n loggerOf(ctx),\n );\n ctx.portle = { runner };\n return runner;\n };\n return {\n name: PORTLE_PLUGIN_NAME,\n appliesTo: \"switchboard\",\n hooks: {\n onSubgraphsRegistering: async (ctx) => {\n const api = ctx.api as PortleApi | undefined;\n const registry = ctx.graphqlManager as SubgraphRegistry | undefined;\n if (!api || !registry) {\n throw new Error(\n \"The portle plugin needs the switchboard's API and GraphQL manager at onSubgraphsRegistering; the host handed neither.\",\n );\n }\n const runner = ensureRunner(ctx);\n const registration = registry.registerSubgraphInstance(\n createPortleSubgraph({ api, runner }),\n \"graphql\",\n false,\n );\n (ctx.lateSubgraphs ??= []).push(registration);\n await Promise.resolve();\n },\n // The last boot hook: the subgraph is mounted and the drives are seeded.\n onDrivesReady: async (ctx) => {\n const runner = ctx.portle?.runner;\n const api = ctx.api as PortleApi | undefined;\n if (!runner || !api) return;\n const log = loggerOf(ctx);\n const status = runner.status();\n if (!status.enrolled || !status.settings?.autostart) return;\n const facts = gateFactsOf(api);\n if (!bootGatePasses(facts)) {\n log.warn(\n \"[portle] the tunnel stays down: this host no longer passes the publication gate (see portleReadiness). Lock it down again or stop publishing.\",\n );\n return;\n }\n try {\n await runner.start();\n log.info(`[portle] tunnel up for ${status.siteZone}`);\n } catch (error) {\n log.warn(\n `[portle] the tunnel could not start: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n onShutdown: async (ctx) => {\n const runner = ctx.portle?.runner;\n if (!runner) return;\n const status = runner.status();\n if (status.tunnel.state === \"down\") return;\n // The host is going down, not the operator's wish: the processes stop,\n // `autostart` stays, so the tunnel returns with the next boot.\n await runner.stop({ keepAutostart: true });\n },\n },\n };\n}\n\nexport const portleSwitchboardPlugin: HostPlugin<PortleHooks> =\n createPortlePlugin();\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default portleSwitchboardPlugin;\n"],"mappings":";;AAoDA,SAAS,SAAS,KAAoC;CACpD,MAAM,SAAS,IAAI;CACnB,IACE,UACA,OAAO,OAAO,SAAS,cACvB,OAAO,OAAO,SAAS,YAEvB,OAAO;CAET,OAAO;EACL,OAAO,GAAG,GAAG,MAAM,QAAQ,IAAI,YAAY,KAAK,GAAG,CAAC;EACpD,OAAO,GAAG,GAAG,MAAM,QAAQ,KAAK,YAAY,KAAK,GAAG,CAAC;CACvD;AACF;AAQA,MAAa,qBAAqB;;AAGlC,SAAgB,mBACd,cACE,UACA,QAEA,IAAI,aAAa;CACf;CACA,MAAM,KAAK,WACT,IAAI,KAAK,YAAY,IAAI,GAAG,SAAS,KAAK,UAAU,MAAM,IAAI,IAAI;AACtE,CAAC,GACsB;;CAEzB,MAAM,gBAAgB,QAA6C;EACjE,IAAI,IAAI,QAAQ,OAAO,IAAI,OAAO;EAClC,MAAM,SAAS,WACb,WAAW,cAAc,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6 @@
1
1
  {
2
2
  "name": "@powerhousedao/portle",
3
- "version": "6.2.3-dev.79",
3
+ "version": "6.2.3-dev.80",
4
4
  "description": "Publish a Powerhouse project through Portle: a switchboard host plugin that checks the host's authorization gate and, later, runs the site tunnel. EXPERIMENTAL.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "repository": {
@@ -35,12 +35,12 @@
35
35
  "graphql": "^16"
36
36
  },
37
37
  "peerDependencies": {
38
- "@powerhousedao/host-core": "6.2.3-dev.79",
39
- "@powerhousedao/reactor-api": "6.2.3-dev.79"
38
+ "@powerhousedao/host-core": "6.2.3-dev.80",
39
+ "@powerhousedao/reactor-api": "6.2.3-dev.80"
40
40
  },
41
41
  "devDependencies": {
42
- "@powerhousedao/host-core": "6.2.3-dev.79",
43
- "@powerhousedao/reactor-api": "6.2.3-dev.79",
42
+ "@powerhousedao/host-core": "6.2.3-dev.80",
43
+ "@powerhousedao/reactor-api": "6.2.3-dev.80",
44
44
  "tsdown": "0.23.0",
45
45
  "typescript": "7.0.2",
46
46
  "vitest": "5.0.3"
@@ -1,141 +0,0 @@
1
- import { GraphQLError, parse } from "graphql";
2
- //#region src/gate.ts
3
- /** One of the host's listed admins, whatever the policy. */
4
- function isListedAdmin(admins, address) {
5
- if (!address) return false;
6
- const caller = address.toLowerCase();
7
- return admins.some((admin) => admin.toLowerCase() === caller);
8
- }
9
- 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.";
10
- function evaluateGate(facts, caller) {
11
- const policyOk = facts.policy === "ADMIN_ONLY" || facts.policy === "DOCUMENT_PERMISSIONS" && facts.defaultProtection;
12
- const checks = [
13
- {
14
- id: "identity",
15
- ok: facts.identityResolved,
16
- 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.",
17
- fix: facts.identityResolved ? void 0 : "Set RESOLVE_CALLER_IDENTITY=true."
18
- },
19
- {
20
- id: "floor",
21
- ok: facts.requireAuthenticatedCaller,
22
- detail: facts.requireAuthenticatedCaller ? "Anonymous callers are refused with a 401 before any resolver runs." : "Anonymous callers reach every subgraph.",
23
- fix: facts.requireAuthenticatedCaller ? void 0 : "Set REQUIRE_AUTHENTICATED_CALLER=true (needs RESOLVE_CALLER_IDENTITY=true)."
24
- },
25
- {
26
- id: "policy",
27
- ok: policyOk,
28
- detail: describePolicy(facts),
29
- fix: policyOk ? void 0 : POLICY_FIX
30
- },
31
- {
32
- id: "protection",
33
- ok: facts.policy !== "DOCUMENT_PERMISSIONS" || facts.defaultProtection,
34
- 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.",
35
- fix: facts.policy === "DOCUMENT_PERMISSIONS" && !facts.defaultProtection ? "Set DEFAULT_PROTECTION=true." : void 0
36
- },
37
- {
38
- id: "admins",
39
- ok: facts.admins.length > 0,
40
- detail: facts.admins.length > 0 ? `${facts.admins.length} admin address(es) listed.` : "No admin address is listed; nobody could administer the published host.",
41
- fix: facts.admins.length > 0 ? void 0 : "Set ADMINS to the comma-separated addresses that may publish."
42
- },
43
- {
44
- id: "caller",
45
- ok: isListedAdmin(facts.admins, caller?.address),
46
- 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.",
47
- fix: isListedAdmin(facts.admins, caller?.address) ? void 0 : "Sign in with Renown as one of the ADMINS addresses."
48
- }
49
- ];
50
- return {
51
- publishable: checks.every((check) => check.ok),
52
- checks,
53
- warnings: [{
54
- id: "custom-subgraphs",
55
- ok: false,
56
- detail: "The project's own subgraphs enforce nothing by themselves; the policy and the floor do not reach their resolvers.",
57
- fix: "Have every custom resolver check the caller (assertCanRead or canRead on the drive it serves)."
58
- }]
59
- };
60
- }
61
- function describePolicy(facts) {
62
- switch (facts.policy) {
63
- case "OPEN": return "OPEN: everyone, anonymous included, may read and write everything.";
64
- case "ADMIN_ONLY": return "ADMIN_ONLY: only the listed admins may read or write anything.";
65
- 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.";
66
- }
67
- }
68
- //#endregion
69
- //#region src/subgraph.ts
70
- const PORTLE_SUBGRAPH_NAME = "portle";
71
- const portleTypeDefs = parse(`
72
- type PortleCheck {
73
- id: String!
74
- ok: Boolean!
75
- detail: String!
76
- fix: String
77
- }
78
-
79
- type PortleCaller {
80
- address: String
81
- isAdmin: Boolean!
82
- }
83
-
84
- type PortleReadiness {
85
- publishable: Boolean!
86
- checks: [PortleCheck!]!
87
- warnings: [PortleCheck!]!
88
- me: PortleCaller!
89
- }
90
-
91
- type Query {
92
- """
93
- Whether this host may be published through Portle, check by check.
94
- Under an OPEN policy it answers everyone, since there is no admin to
95
- distinguish; under any other policy only a listed admin may ask.
96
- """
97
- portleReadiness: PortleReadiness!
98
- }
99
- `);
100
- /** The host's authorization facts, read off the API object. */
101
- function gateFactsOf(api) {
102
- const config = api.authorizationService.config;
103
- return {
104
- policy: config.policy,
105
- admins: config.admins,
106
- defaultProtection: config.defaultProtection,
107
- identityResolved: api.authService !== void 0,
108
- requireAuthenticatedCaller: api.requireAuthenticatedCaller
109
- };
110
- }
111
- function readiness(api, ctx) {
112
- const facts = gateFactsOf(api);
113
- const address = ctx.user?.address;
114
- const isAdmin = isListedAdmin(facts.admins, address);
115
- if (facts.policy !== "OPEN" && !isAdmin) throw new GraphQLError("Portle readiness is for the host's admins.", { extensions: { code: "FORBIDDEN" } });
116
- return {
117
- ...evaluateGate(facts, ctx.user),
118
- me: {
119
- address: address ?? null,
120
- isAdmin
121
- }
122
- };
123
- }
124
- /**
125
- * The `portle` subgraph as a plain `ISubgraph`: no reactor reads, no setup,
126
- * so it needs none of `BaseSubgraph` and keeps the plugin free of runtime
127
- * imports from reactor-api.
128
- */
129
- function createPortleSubgraph(api) {
130
- return {
131
- name: PORTLE_SUBGRAPH_NAME,
132
- typeDefs: portleTypeDefs,
133
- relationalDb: api.relationalDb,
134
- hasSubscriptions: false,
135
- resolvers: { Query: { portleReadiness: (_parent, _args, ctx) => readiness(api, ctx) } }
136
- };
137
- }
138
- //#endregion
139
- export { readiness as a, portleTypeDefs as i, createPortleSubgraph as n, evaluateGate as o, gateFactsOf as r, isListedAdmin as s, PORTLE_SUBGRAPH_NAME as t };
140
-
141
- //# sourceMappingURL=subgraph-D7PtSa_n.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"subgraph-D7PtSa_n.mjs","names":[],"sources":["../src/gate.ts","../src/subgraph.ts"],"sourcesContent":["/**\n * The publication gate: the host's authorization facts, judged.\n *\n * Publishing a project through Portle puts its switchboard on the internet,\n * so the plugin refuses to bring the tunnel up unless the host is locked\n * down and the person asking is one of its admins. The gate is expressed in\n * terms of the RESOLVED authorization settings, never the environment\n * variables that produced them: `DEFAULT_PROTECTION` is inert under\n * `ADMIN_ONLY`, and the env can be contradicted by the config file.\n *\n * It is an interlock, not security. The server does not become safer because\n * the studio refuses; what makes the gate mean something is that the same\n * plugin owns the tunnel, so \"published\" implies \"locked down\" for as long as\n * the plugin is the thing publishing.\n */\n\n/** The host's authorization policy, as reactor-api resolves it at boot. */\nexport type PortlePolicy = \"OPEN\" | \"ADMIN_ONLY\" | \"DOCUMENT_PERMISSIONS\";\n\n/** What the gate judges: read off the switchboard's `API` object. */\nexport interface GateFacts {\n policy: PortlePolicy;\n /** Lower-cased addresses of the host's supreme admins. */\n admins: readonly string[];\n /** Documents without a permission row count as protected. */\n defaultProtection: boolean;\n /** The bearer is verified and `ctx.user` is populated. */\n identityResolved: boolean;\n /** Anonymous callers are refused with a 401 before any resolver. */\n requireAuthenticatedCaller: boolean;\n}\n\nexport interface GateCheck {\n id: GateCheckId;\n ok: boolean;\n /** What was found. */\n detail: string;\n /** What to change when `ok` is false. */\n fix?: string;\n}\n\nexport type GateCheckId =\n | \"identity\"\n | \"floor\"\n | \"policy\"\n | \"protection\"\n | \"admins\"\n | \"caller\"\n | \"custom-subgraphs\";\n\nexport interface GateReport {\n /** Every check passed: the tunnel may come up for this caller. */\n publishable: boolean;\n checks: GateCheck[];\n /** True of every deployment; not blocking, never silent. */\n warnings: GateCheck[];\n}\n\n/** One of the host's listed admins, whatever the policy. */\nexport function isListedAdmin(\n admins: readonly string[],\n address: string | undefined,\n): boolean {\n if (!address) return false;\n const caller = address.toLowerCase();\n return admins.some((admin) => admin.toLowerCase() === caller);\n}\n\nconst POLICY_FIX =\n \"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.\";\n\nexport function evaluateGate(\n facts: GateFacts,\n caller: { address?: string } | undefined,\n): GateReport {\n const policyOk =\n facts.policy === \"ADMIN_ONLY\" ||\n (facts.policy === \"DOCUMENT_PERMISSIONS\" && facts.defaultProtection);\n\n const checks: GateCheck[] = [\n {\n id: \"identity\",\n ok: facts.identityResolved,\n detail: facts.identityResolved\n ? \"Bearer tokens are verified and the caller is known to every resolver.\"\n : \"The host never reads a bearer; no caller can be identified.\",\n fix: facts.identityResolved\n ? undefined\n : \"Set RESOLVE_CALLER_IDENTITY=true.\",\n },\n {\n id: \"floor\",\n ok: facts.requireAuthenticatedCaller,\n detail: facts.requireAuthenticatedCaller\n ? \"Anonymous callers are refused with a 401 before any resolver runs.\"\n : \"Anonymous callers reach every subgraph.\",\n fix: facts.requireAuthenticatedCaller\n ? undefined\n : \"Set REQUIRE_AUTHENTICATED_CALLER=true (needs RESOLVE_CALLER_IDENTITY=true).\",\n },\n {\n id: \"policy\",\n ok: policyOk,\n detail: describePolicy(facts),\n fix: policyOk ? undefined : POLICY_FIX,\n },\n {\n id: \"protection\",\n ok: facts.policy !== \"DOCUMENT_PERMISSIONS\" || facts.defaultProtection,\n detail:\n facts.policy === \"DOCUMENT_PERMISSIONS\"\n ? facts.defaultProtection\n ? \"Documents without a permission row are protected.\"\n : \"Documents without a permission row are readable by any caller.\"\n : \"Not consulted under this policy.\",\n fix:\n facts.policy === \"DOCUMENT_PERMISSIONS\" && !facts.defaultProtection\n ? \"Set DEFAULT_PROTECTION=true.\"\n : undefined,\n },\n {\n id: \"admins\",\n ok: facts.admins.length > 0,\n detail:\n facts.admins.length > 0\n ? `${facts.admins.length} admin address(es) listed.`\n : \"No admin address is listed; nobody could administer the published host.\",\n fix:\n facts.admins.length > 0\n ? undefined\n : \"Set ADMINS to the comma-separated addresses that may publish.\",\n },\n {\n id: \"caller\",\n ok: isListedAdmin(facts.admins, caller?.address),\n detail: caller?.address\n ? isListedAdmin(facts.admins, caller.address)\n ? \"You are one of the listed admins.\"\n : \"You are signed in, but not one of the listed admins.\"\n : \"You are not signed in.\",\n fix: isListedAdmin(facts.admins, caller?.address)\n ? undefined\n : \"Sign in with Renown as one of the ADMINS addresses.\",\n },\n ];\n\n const warnings: GateCheck[] = [\n {\n id: \"custom-subgraphs\",\n ok: false,\n detail:\n \"The project's own subgraphs enforce nothing by themselves; the policy and the floor do not reach their resolvers.\",\n fix: \"Have every custom resolver check the caller (assertCanRead or canRead on the drive it serves).\",\n },\n ];\n\n return {\n publishable: checks.every((check) => check.ok),\n checks,\n warnings,\n };\n}\n\nfunction describePolicy(facts: GateFacts): string {\n switch (facts.policy) {\n case \"OPEN\":\n return \"OPEN: everyone, anonymous included, may read and write everything.\";\n case \"ADMIN_ONLY\":\n return \"ADMIN_ONLY: only the listed admins may read or write anything.\";\n case \"DOCUMENT_PERMISSIONS\":\n return facts.defaultProtection\n ? \"DOCUMENT_PERMISSIONS with default protection: grants decide, unprotected documents do not exist.\"\n : \"DOCUMENT_PERMISSIONS without default protection: documents with no permission row are open to every caller.\";\n }\n}\n","import type { API, Context, ISubgraph } from \"@powerhousedao/reactor-api\";\nimport { GraphQLError, parse } from \"graphql\";\nimport {\n evaluateGate,\n isListedAdmin,\n type GateFacts,\n type GateReport,\n type PortlePolicy,\n} from \"./gate.js\";\n\n/** The slice of the switchboard's API object the subgraph reads. */\nexport type PortleApi = Pick<\n API,\n \"authorizationService\" | \"requireAuthenticatedCaller\" | \"relationalDb\"\n> & {\n /** Present exactly when the host resolves caller identity. */\n authService: unknown;\n};\n\nexport const PORTLE_SUBGRAPH_NAME = \"portle\";\n\nexport const portleTypeDefs = parse(/* GraphQL */ `\n type PortleCheck {\n id: String!\n ok: Boolean!\n detail: String!\n fix: String\n }\n\n type PortleCaller {\n address: String\n isAdmin: Boolean!\n }\n\n type PortleReadiness {\n publishable: Boolean!\n checks: [PortleCheck!]!\n warnings: [PortleCheck!]!\n me: PortleCaller!\n }\n\n type Query {\n \"\"\"\n Whether this host may be published through Portle, check by check.\n Under an OPEN policy it answers everyone, since there is no admin to\n distinguish; under any other policy only a listed admin may ask.\n \"\"\"\n portleReadiness: PortleReadiness!\n }\n`);\n\n/** The host's authorization facts, read off the API object. */\nexport function gateFactsOf(api: PortleApi): GateFacts {\n const config = api.authorizationService.config;\n return {\n policy: config.policy as PortlePolicy,\n admins: config.admins,\n defaultProtection: config.defaultProtection,\n identityResolved: api.authService !== undefined,\n requireAuthenticatedCaller: api.requireAuthenticatedCaller,\n };\n}\n\nexport type PortleReadiness = GateReport & {\n me: { address: string | null; isAdmin: boolean };\n};\n\nexport function readiness(api: PortleApi, ctx: Context): PortleReadiness {\n const facts = gateFactsOf(api);\n const address = ctx.user?.address;\n const isAdmin = isListedAdmin(facts.admins, address);\n if (facts.policy !== \"OPEN\" && !isAdmin) {\n throw new GraphQLError(\"Portle readiness is for the host's admins.\", {\n extensions: { code: \"FORBIDDEN\" },\n });\n }\n return {\n ...evaluateGate(facts, ctx.user),\n me: { address: address ?? null, isAdmin },\n };\n}\n\n/**\n * The `portle` subgraph as a plain `ISubgraph`: no reactor reads, no setup,\n * so it needs none of `BaseSubgraph` and keeps the plugin free of runtime\n * imports from reactor-api.\n */\nexport function createPortleSubgraph(api: PortleApi): ISubgraph {\n return {\n name: PORTLE_SUBGRAPH_NAME,\n typeDefs: portleTypeDefs,\n relationalDb: api.relationalDb,\n hasSubscriptions: false,\n resolvers: {\n Query: {\n portleReadiness: (_parent: unknown, _args: unknown, ctx: Context) =>\n readiness(api, ctx),\n },\n },\n };\n}\n"],"mappings":";;;AA2DA,SAAgB,cACd,QACA,SACS;CACT,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,SAAS,QAAQ,YAAY;CACnC,OAAO,OAAO,MAAM,UAAU,MAAM,YAAY,MAAM,MAAM;AAC9D;AAEA,MAAM,aACJ;AAEF,SAAgB,aACd,OACA,QACY;CACZ,MAAM,WACJ,MAAM,WAAW,gBAChB,MAAM,WAAW,0BAA0B,MAAM;CAEpD,MAAM,SAAsB;EAC1B;GACE,IAAI;GACJ,IAAI,MAAM;GACV,QAAQ,MAAM,mBACV,0EACA;GACJ,KAAK,MAAM,mBACP,KAAA,IACA;EACN;EACA;GACE,IAAI;GACJ,IAAI,MAAM;GACV,QAAQ,MAAM,6BACV,uEACA;GACJ,KAAK,MAAM,6BACP,KAAA,IACA;EACN;EACA;GACE,IAAI;GACJ,IAAI;GACJ,QAAQ,eAAe,KAAK;GAC5B,KAAK,WAAW,KAAA,IAAY;EAC9B;EACA;GACE,IAAI;GACJ,IAAI,MAAM,WAAW,0BAA0B,MAAM;GACrD,QACE,MAAM,WAAW,yBACb,MAAM,oBACJ,sDACA,mEACF;GACN,KACE,MAAM,WAAW,0BAA0B,CAAC,MAAM,oBAC9C,iCACA,KAAA;EACR;EACA;GACE,IAAI;GACJ,IAAI,MAAM,OAAO,SAAS;GAC1B,QACE,MAAM,OAAO,SAAS,IAClB,GAAG,MAAM,OAAO,OAAO,8BACvB;GACN,KACE,MAAM,OAAO,SAAS,IAClB,KAAA,IACA;EACR;EACA;GACE,IAAI;GACJ,IAAI,cAAc,MAAM,QAAQ,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