@tafrahq/wt-tunnel-server 0.0.0-stage → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +111 -2
  3. package/dist/auth.js +121 -0
  4. package/dist/auth.js.map +1 -0
  5. package/dist/bin.js +26 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/binaries.js +51 -0
  8. package/dist/binaries.js.map +1 -0
  9. package/dist/brand.js +10 -0
  10. package/dist/brand.js.map +1 -0
  11. package/dist/ca-page.js +112 -0
  12. package/dist/ca-page.js.map +1 -0
  13. package/dist/children.js +72 -0
  14. package/dist/children.js.map +1 -0
  15. package/dist/cli.js +111 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/config.js +55 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/context.js +5 -0
  20. package/dist/context.js.map +1 -0
  21. package/dist/daemon.js +176 -0
  22. package/dist/daemon.js.map +1 -0
  23. package/dist/dev-host.js +71 -0
  24. package/dist/dev-host.js.map +1 -0
  25. package/dist/errors.js +8 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/hosts.js +32 -0
  28. package/dist/hosts.js.map +1 -0
  29. package/dist/internal.js +62 -0
  30. package/dist/internal.js.map +1 -0
  31. package/dist/listen.js +31 -0
  32. package/dist/listen.js.map +1 -0
  33. package/dist/packages/binaries/src/caddy.js +24 -0
  34. package/dist/packages/binaries/src/caddy.js.map +1 -0
  35. package/dist/packages/binaries/src/frp.js +45 -0
  36. package/dist/packages/binaries/src/frp.js.map +1 -0
  37. package/dist/packages/binaries/src/install.js +110 -0
  38. package/dist/packages/binaries/src/install.js.map +1 -0
  39. package/dist/packages/contract/src/bin.js +20 -0
  40. package/dist/packages/contract/src/bin.js.map +1 -0
  41. package/dist/packages/contract/src/index.js +12 -0
  42. package/dist/packages/contract/src/index.js.map +1 -0
  43. package/dist/packages/contract/src/root-ca.js +61 -0
  44. package/dist/packages/contract/src/root-ca.js.map +1 -0
  45. package/dist/packages/contract/src/server-config.js +99 -0
  46. package/dist/packages/contract/src/server-config.js.map +1 -0
  47. package/dist/packages/contract/src/temp-dir.js +12 -0
  48. package/dist/packages/contract/src/temp-dir.js.map +1 -0
  49. package/dist/ready.js +36 -0
  50. package/dist/ready.js.map +1 -0
  51. package/dist/render.js +101 -0
  52. package/dist/render.js.map +1 -0
  53. package/dist/reply.js +46 -0
  54. package/dist/reply.js.map +1 -0
  55. package/dist/root-ca.js +85 -0
  56. package/dist/root-ca.js.map +1 -0
  57. package/dist/runtime.js +49 -0
  58. package/dist/runtime.js.map +1 -0
  59. package/dist/service.js +59 -0
  60. package/dist/service.js.map +1 -0
  61. package/dist/session.js +67 -0
  62. package/dist/session.js.map +1 -0
  63. package/dist/sign-in.js +103 -0
  64. package/dist/sign-in.js.map +1 -0
  65. package/dist/supervise.js +33 -0
  66. package/dist/supervise.js.map +1 -0
  67. package/package.json +66 -3
  68. package/src/auth.ts +153 -0
  69. package/src/bin.ts +26 -0
  70. package/src/binaries.ts +82 -0
  71. package/src/brand.ts +10 -0
  72. package/src/ca-page.ts +166 -0
  73. package/src/children.ts +98 -0
  74. package/src/cli.ts +208 -0
  75. package/src/config.ts +92 -0
  76. package/src/context.ts +23 -0
  77. package/src/daemon.ts +254 -0
  78. package/src/dev-host.ts +101 -0
  79. package/src/errors.ts +14 -0
  80. package/src/hosts.ts +49 -0
  81. package/src/internal.ts +89 -0
  82. package/src/listen.ts +43 -0
  83. package/src/ready.ts +50 -0
  84. package/src/render.ts +121 -0
  85. package/src/reply.ts +60 -0
  86. package/src/root-ca.ts +116 -0
  87. package/src/runtime.ts +49 -0
  88. package/src/service.ts +90 -0
  89. package/src/session.ts +130 -0
  90. package/src/sign-in.ts +147 -0
  91. package/src/supervise.ts +51 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tafra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # wt-tunnel-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The server half of [server mode](../../docs/server-mode.md). `wt-tunnel-server start` runs three things under one supervisor process:
4
+
5
+ - **Caddy** on 443 (and 80, which redirects to https). Dev hosts get certificates on demand from the deployment's own root CA.
6
+ - **frps** on 7000. Tunnel clients connect here with the tunnel token over TLS. Its HTTP vhost listens on 127.0.0.1:8080 only.
7
+ - **The auth service** on 127.0.0.1:4000, inside the supervisor. It runs the sign-in (Google, GitHub, Microsoft or Cloudflare Access) through Better Auth, with no database, and strips the session cookie before a request reaches an app.
8
+
9
+ The supervisor writes the Caddyfile and frps.toml from the config into a private temporary directory, starts Caddy and frps, and prefixes their output with `[caddy]` or `[frps]`. Once every port accepts connections it prints `ready`. If Caddy or frps exits, the supervisor stops the other and exits with code 1, so a platform restarts it. SIGTERM or SIGINT stops both and exits 0.
10
+
11
+ The same CLI runs directly on a host and in the published Docker image, which installs the same package that is published to npm.
12
+
13
+ ## Run the image
14
+
15
+ Each release publishes the image to GitHub Container Registry as `ghcr.io/tafrahq/wt-tunnel-server:<version>`, for linux/amd64. The image is public, so pulling it needs no token. It runs on any host that gives it raw TCP on ports 443, 80 and 7000:
16
+
17
+ ```sh
18
+ docker run --rm -p 443:443 -p 80:80 -p 7000:7000 \
19
+ -v "$PWD/.server:/etc/wt-tunnel-server:ro" ghcr.io/tafrahq/wt-tunnel-server:<version> \
20
+ --config /etc/wt-tunnel-server
21
+ ```
22
+
23
+ The image runs `wt-tunnel-server start` with the Caddy and frps it ships, so arguments after the image name go to `start`. Everything in the container runs as the unprivileged `node` user, uid 1000, so it must be able to read the mounted files: `ca.key` and the config are 0600, so the host user that owns them needs uid 1000, or the files a mode that lets the container read them. The Caddy binary carries `cap_net_bind_service`, so it can bind 443 and 80 without root.
24
+
25
+ The host also needs these DNS records:
26
+
27
+ - `*.<domain>` for each dev domain, the tunnel host that clients connect to, and the sign-in host (`authHost`), all pointing at the host directly. Caddy and frps end TLS themselves, so no proxy may sit in front of them.
28
+
29
+ Caddy gets the sign-in host a public certificate from Let's Encrypt at each start, so ports 80 and 443 must be reachable from the internet. Let's Encrypt issues at most five certificates for one name a week; past that, and on a host the internet cannot reach, Caddy falls back to its internal CA, which browsers do not trust. Caddy keeps its certificates in a temporary directory that each start creates anew.
30
+
31
+ For the recommended setup on Fly.io, use [`wt-tunnel`](../cli/README.md). It creates the server folder, then the app, its IPs, a secret per file in the folder, the Machine and the records.
32
+
33
+ ## Run without Docker
34
+
35
+ The CLI is published to npm. Install it, or build it from a checkout as the [root README](../../README.md#install) shows:
36
+
37
+ ```sh
38
+ npm install --global @tafrahq/wt-tunnel-server
39
+ cd my-wt-tunnel/.server
40
+ wt-tunnel-server check
41
+ wt-tunnel-server start --detach
42
+ ```
43
+
44
+ It needs Node.js 26 or later, on Linux or macOS.
45
+
46
+ ### Commands
47
+
48
+ | Command | What it does | Exit code |
49
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
50
+ | `start` | Runs the server in the foreground, with its output on stdout, until Caddy or frps exits or it gets SIGTERM or SIGINT. | 0 after SIGTERM or SIGINT, 1 if Caddy or frps exited or start failed |
51
+ | `start --detach` | Checks the config and finds the binaries, then starts the server in the background. It returns once Caddy, frps and the auth service listen, and prints where the log is. If the server exits during startup, it prints the log's last lines instead. It refuses to start while a server from the same state directory runs. | 0 when the server is up, 1 otherwise |
52
+ | `stop` | Sends SIGTERM to the detached server and waits until it, Caddy and frps have exited. Anything still running after 15 seconds gets SIGKILL. | 0, also when nothing was running |
53
+ | `status` | Prints `running: pid <pid>, since <time>, log <path>` or `stopped`. | 0 when running, 3 when stopped |
54
+ | `check` | Checks the config without starting anything. | 0 when valid, 1 otherwise |
55
+
56
+ `start` and `check` read the config from `--config <file>`, or `--config <dir>` for `<dir>/wt-tunnel-server.json`. Without it, they read the JSON in `WT_TUNNEL_SERVER_CONFIG`, and without that, `wt-tunnel-server.json` in the current directory, the file `wt-tunnel deploy` writes into the server folder.
57
+
58
+ A detached server keeps `server.pid` and `server.log` in its state directory: `--state-dir <dir>`, else `WT_TUNNEL_SERVER_STATE_DIR`, else `$XDG_STATE_HOME/wt-tunnel-server`, else `~/.local/state/wt-tunnel-server`. Pass the same `--state-dir` to `start`, `stop` and `status`. The log grows across runs; each start appends a header line.
59
+
60
+ ### Caddy and frps
61
+
62
+ `start` uses binaries you installed yourself when you pass them:
63
+
64
+ ```sh
65
+ wt-tunnel-server start --config .server --caddy /usr/local/bin/caddy --frps /usr/local/bin/frps
66
+ ```
67
+
68
+ Without `--caddy` or `--frps`, it uses `caddy` or `frps` from `PATH`. If there is none, it downloads the release it pins (Caddy 2.11.7, frp 0.71.1) for linux or darwin on amd64 or arm64, checks the tarball's SHA-256 against the pinned value, and keeps the binary under `~/.cache/wt-tunnel-server` (`~/Library/Caches/wt-tunnel-server` on macOS, or `$XDG_CACHE_HOME/wt-tunnel-server`). A tarball that does not match is never unpacked.
69
+
70
+ ### Ports
71
+
72
+ Caddy binds 443 and 80. Outside Docker, only root may bind ports below 1024 by default, so as a normal user Caddy exits, and `start` names your options:
73
+
74
+ - Let the Caddy binary bind them, on Linux: `sudo setcap cap_net_bind_service=+ep <path to caddy>`. `start` prints the path it used. A downloaded Caddy keeps the capability until a new version replaces it.
75
+ - Run `wt-tunnel-server` as root.
76
+ - Move the ports with `--https-port` and `--http-port`, for example behind a load balancer that forwards 443 to 8443.
77
+
78
+ `--tunnel-port` moves frps from 7000. Clients then need the same port as `server.port` in their `wt-tunnel.json`. The internal ports (4000 for the auth service, 8080 for the frps vhost, both on 127.0.0.1) are fixed and must be free.
79
+
80
+ ## Configure
81
+
82
+ [docs/server-mode.md](../../docs/server-mode.md#server-config) lists the config's fields. `ca.cert` and `ca.key` name the root CA's PEM files, relative to the config file's directory. With the config in `WT_TUNNEL_SERVER_CONFIG`, they are relative to the current directory. `wt-tunnel deploy` writes all three files into one folder, `.server/`.
83
+
84
+ `wt-tunnel ca create` creates a root: an EC P-256 root, valid for 10 years and name-constrained to the server config's domains, or the deploy file's for a new folder, and every name under them. Keep `ca.key` secret.
85
+
86
+ Each device that opens dev URLs must trust the root once. The sign-in service serves it on the sign-in host, the one name with a publicly trusted certificate:
87
+
88
+ | Path | What it serves |
89
+ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
90
+ | `https://<authHost>/ca` | A page with the root's subject, validity, SHA-256 fingerprint and permitted names, a download button, and trust steps for macOS, iPhone and iPad, Android, Windows, Linux and Firefox. The visitor's platform, read from the User-Agent, comes first. |
91
+ | `https://<authHost>/ca.crt` | The root certificate as PEM, `application/x-x509-ca-cert`, downloaded as `wt-tunnel-ca-<label>.crt`. The label is the one in the root's name, `wt-tunnel root (<label>)`, which `wt-tunnel` sets to the tunnel host. A root named otherwise gives the first domain. |
92
+ | `https://<authHost>/ca.mobileconfig` | An unsigned Apple configuration profile, `application/x-apple-aspen-config`, with one root certificate payload. Its UUIDs come from the root's fingerprint, so a second download is the same profile. |
93
+
94
+ The three paths need no sign-in, and responses may be cached for five minutes. They serve the certificate parsed from `ca.cert` and re-encoded, so nothing else in that field, and never `ca.key`, reaches a browser. On dev hosts, `/ca` is an ordinary path behind sign-in; only `/_wt/*` is reserved there. `check` and `start` refuse a `ca.cert` that holds no readable certificate.
95
+
96
+ Each sign-in provider's redirect URI is `https://<authHost>/api/auth/callback/<provider>`, such as `.../callback/github`. [docs/server-mode.md](../../docs/server-mode.md#server-config) lists the providers and how to set each up.
97
+
98
+ ## Build the image
99
+
100
+ The image ([`docker/Dockerfile`](../../docker/Dockerfile)) installs a packed `@tafrahq/wt-tunnel-server` from its build context with `npm install --global`; its dependencies come from the public npm registry. Caddy comes from the official `caddy:2.11.7` image and frps from the checksum-verified frp release. From the repository root:
101
+
102
+ ```sh
103
+ pnpm install
104
+ pnpm --dir apps/server pack --out "$PWD/docker/wt-tunnel-server.tgz"
105
+ docker build --platform linux/amd64 -f docker/Dockerfile -t wt-tunnel-server docker
106
+ ```
107
+
108
+ The release workflow builds the published image the same way, from the very tarball it stages on npm.
109
+
110
+ ## Develop
111
+
112
+ `nub run check:quality` and `nub run test` at the repository root format, lint, type-check and test this package with the rest of the monorepo. `nubx turbo run build --filter @tafrahq/wt-tunnel-server` builds `apps/server/dist`. tsdown compiles the workspace-only packages into it: `@tafrahq/wt-tunnel-contract`, which holds the config schema that this server and `wt-tunnel` both decode, and `@tafrahq/wt-tunnel-binaries`, which pins and installs Caddy and frps. The published package depends on neither.
package/dist/auth.js ADDED
@@ -0,0 +1,121 @@
1
+ import { sessionSeconds } from "./session.js";
2
+ import { Option, Redacted, Schema } from "effect";
3
+ import { betterAuth } from "better-auth/minimal";
4
+ import { fromNodeHeaders, toNodeHandler } from "better-auth/node";
5
+ import { genericOAuth } from "better-auth/plugins/generic-oauth";
6
+ // src/auth.ts
7
+ const SignInStarted = Schema.Struct({ url: Schema.String });
8
+ const headersOf = (request) => fromNodeHeaders(request.headers);
9
+ const client = (provider) => ({
10
+ clientId: provider.clientId,
11
+ clientSecret: Redacted.value(provider.clientSecret)
12
+ });
13
+ /**
14
+ * Better Auth's built-in providers. Each reports whether the provider verified the email: Google
15
+ * from its ID token, GitHub from the account's email list, and Microsoft from the
16
+ * `verified_primary_email` or `email_verified` claim, which the app registration must add.
17
+ */
18
+ const socialProviders = ({ github, google, microsoft }) => ({
19
+ ...github === void 0 ? {} : { github: client(github) },
20
+ ...google === void 0 ? {} : { google: {
21
+ ...client(google),
22
+ prompt: "select_account"
23
+ } },
24
+ ...microsoft === void 0 ? {} : { microsoft: {
25
+ ...client(microsoft),
26
+ prompt: "select_account",
27
+ tenantId: microsoft.tenantId ?? "common"
28
+ } }
29
+ });
30
+ /**
31
+ * A Cloudflare Access OIDC app, as a generic OIDC provider that Better Auth lists with the social
32
+ * ones. Its endpoints follow from the team domain and client ID, so the server fetches no discovery
33
+ * document. The email comes from the userinfo endpoint, over TLS with the access token. Access
34
+ * signs people in through the identity providers the team set up and sends no `email_verified`
35
+ * claim, so the email counts as verified.
36
+ */
37
+ const cloudflareAccess = (cloudflare) => {
38
+ if (cloudflare === void 0) return [];
39
+ const base = `https://${cloudflare.teamDomain}/cdn-cgi/access/sso/oidc/${cloudflare.clientId}`;
40
+ return [genericOAuth({ config: [{
41
+ ...client(cloudflare),
42
+ authorizationUrl: `${base}/authorization`,
43
+ mapProfileToUser: () => ({ emailVerified: true }),
44
+ pkce: true,
45
+ providerId: "cloudflare",
46
+ scopes: [
47
+ "openid",
48
+ "email",
49
+ "profile"
50
+ ],
51
+ tokenUrl: `${base}/token`,
52
+ userInfoUrl: `${base}/userinfo`
53
+ }] })];
54
+ };
55
+ /**
56
+ * Better Auth with no database. These are the defaults Better Auth picks when `database` is absent,
57
+ * spelled out because the server's statelessness depends on them: the session lives in a JWE cookie
58
+ * that Better Auth re-issues before it expires, and OAuth state and the provider account live in
59
+ * cookies. Users land in Better Auth's in-memory adapter, which nothing reads back after sign-in,
60
+ * so a restart loses nothing that matters.
61
+ */
62
+ const createBetterAuth = (config) => betterAuth({
63
+ account: {
64
+ storeAccountCookie: true,
65
+ storeStateStrategy: "cookie"
66
+ },
67
+ baseURL: `https://${config.authHost}`,
68
+ plugins: cloudflareAccess(config.providers.cloudflare),
69
+ secret: Redacted.value(config.authSecret),
70
+ session: {
71
+ cookieCache: {
72
+ enabled: true,
73
+ maxAge: sessionSeconds,
74
+ refreshCache: true,
75
+ strategy: "jwe"
76
+ },
77
+ expiresIn: sessionSeconds
78
+ },
79
+ socialProviders: socialProviders(config.providers),
80
+ telemetry: { enabled: false }
81
+ });
82
+ const createSignIn = (config) => {
83
+ const auth = createBetterAuth(config);
84
+ return {
85
+ handler: toNodeHandler(auth),
86
+ session: async (request) => {
87
+ const { headers, response } = await auth.api.getSession({
88
+ headers: headersOf(request),
89
+ returnHeaders: true
90
+ });
91
+ return {
92
+ setCookie: headers.getSetCookie(),
93
+ value: response?.user ?? void 0
94
+ };
95
+ },
96
+ signOut: async (request) => {
97
+ return (await auth.api.signOut({
98
+ asResponse: true,
99
+ headers: headersOf(request)
100
+ })).headers.getSetCookie();
101
+ },
102
+ start: async (request, { callbackURL, provider }) => {
103
+ const response = await auth.api.signInSocial({
104
+ asResponse: true,
105
+ body: {
106
+ callbackURL,
107
+ provider
108
+ },
109
+ headers: headersOf(request)
110
+ });
111
+ const started = Schema.decodeUnknownOption(SignInStarted)(await response.json());
112
+ return {
113
+ setCookie: response.headers.getSetCookie(),
114
+ value: started.pipe(Option.map(({ url }) => url), Option.getOrUndefined)
115
+ };
116
+ }
117
+ };
118
+ };
119
+ export { createSignIn };
120
+
121
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport type { ProviderId, ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { betterAuth } from 'better-auth/minimal';\nimport { fromNodeHeaders, toNodeHandler } from 'better-auth/node';\nimport { genericOAuth } from 'better-auth/plugins/generic-oauth';\nimport { Option, Redacted, Schema } from 'effect';\n\nimport { sessionSeconds } from './session.ts';\n\ninterface SignedInUser {\n readonly email: string;\n readonly emailVerified: boolean;\n}\n\n/** Cookies Better Auth wants set, whatever the answer. */\ninterface WithCookies<Value> {\n readonly setCookie: readonly string[];\n readonly value: Value;\n}\n\n/** The slice of Better Auth the sign-in host uses. */\ninterface SignIn {\n /** Serves `/api/auth/*`, including each provider's redirect back to the sign-in host. */\n readonly handler: (request: IncomingMessage, response: ServerResponse) => Promise<void>;\n readonly session: (request: IncomingMessage) => Promise<WithCookies<SignedInUser | undefined>>;\n readonly signOut: (request: IncomingMessage) => Promise<readonly string[]>;\n /** The provider's authorization URL; Better Auth returns to `callbackURL` once signed in. */\n readonly start: (\n request: IncomingMessage,\n sign: { readonly callbackURL: string; readonly provider: ProviderId },\n ) => Promise<WithCookies<string | undefined>>;\n}\n\nconst SignInStarted = Schema.Struct({ url: Schema.String });\n\nconst headersOf = (request: IncomingMessage) => fromNodeHeaders(request.headers);\n\nconst client = (provider: {\n readonly clientId: string;\n readonly clientSecret: Redacted.Redacted;\n}) => ({\n clientId: provider.clientId,\n clientSecret: Redacted.value(provider.clientSecret),\n});\n\n/**\n * Better Auth's built-in providers. Each reports whether the provider verified the email: Google\n * from its ID token, GitHub from the account's email list, and Microsoft from the\n * `verified_primary_email` or `email_verified` claim, which the app registration must add.\n */\nconst socialProviders = ({ github, google, microsoft }: ServerConfig['providers']) => ({\n ...(github === undefined ? {} : { github: client(github) }),\n ...(google === undefined\n ? {}\n : { google: { ...client(google), prompt: 'select_account' as const } }),\n ...(microsoft === undefined\n ? {}\n : {\n microsoft: {\n ...client(microsoft),\n prompt: 'select_account' as const,\n tenantId: microsoft.tenantId ?? 'common',\n },\n }),\n});\n\n/**\n * A Cloudflare Access OIDC app, as a generic OIDC provider that Better Auth lists with the social\n * ones. Its endpoints follow from the team domain and client ID, so the server fetches no discovery\n * document. The email comes from the userinfo endpoint, over TLS with the access token. Access\n * signs people in through the identity providers the team set up and sends no `email_verified`\n * claim, so the email counts as verified.\n */\nconst cloudflareAccess = (cloudflare: ServerConfig['providers']['cloudflare']) => {\n if (cloudflare === undefined) {\n return [];\n }\n const base = `https://${cloudflare.teamDomain}/cdn-cgi/access/sso/oidc/${cloudflare.clientId}`;\n return [\n genericOAuth({\n config: [\n {\n ...client(cloudflare),\n authorizationUrl: `${base}/authorization`,\n mapProfileToUser: () => ({ emailVerified: true }),\n pkce: true,\n providerId: 'cloudflare',\n scopes: ['openid', 'email', 'profile'],\n tokenUrl: `${base}/token`,\n userInfoUrl: `${base}/userinfo`,\n },\n ],\n }),\n ];\n};\n\n/**\n * Better Auth with no database. These are the defaults Better Auth picks when `database` is absent,\n * spelled out because the server's statelessness depends on them: the session lives in a JWE cookie\n * that Better Auth re-issues before it expires, and OAuth state and the provider account live in\n * cookies. Users land in Better Auth's in-memory adapter, which nothing reads back after sign-in,\n * so a restart loses nothing that matters.\n */\nconst createBetterAuth = (config: ServerConfig) =>\n betterAuth({\n account: { storeAccountCookie: true, storeStateStrategy: 'cookie' },\n baseURL: `https://${config.authHost}`,\n plugins: cloudflareAccess(config.providers.cloudflare),\n secret: Redacted.value(config.authSecret),\n session: {\n cookieCache: { enabled: true, maxAge: sessionSeconds, refreshCache: true, strategy: 'jwe' },\n expiresIn: sessionSeconds,\n },\n socialProviders: socialProviders(config.providers),\n telemetry: { enabled: false },\n });\n\nconst createSignIn = (config: ServerConfig): SignIn => {\n const auth = createBetterAuth(config);\n return {\n handler: toNodeHandler(auth),\n session: async (request) => {\n const { headers, response } = await auth.api.getSession({\n headers: headersOf(request),\n returnHeaders: true,\n });\n return { setCookie: headers.getSetCookie(), value: response?.user ?? undefined };\n },\n signOut: async (request) => {\n const response = await auth.api.signOut({ asResponse: true, headers: headersOf(request) });\n return response.headers.getSetCookie();\n },\n start: async (request, { callbackURL, provider }) => {\n const response = await auth.api.signInSocial({\n asResponse: true,\n body: { callbackURL, provider },\n headers: headersOf(request),\n });\n const started = Schema.decodeUnknownOption(SignInStarted)(await response.json());\n return {\n setCookie: response.headers.getSetCookie(),\n value: started.pipe(\n Option.map(({ url }) => url),\n Option.getOrUndefined,\n ),\n };\n },\n };\n};\n\nexport { createSignIn };\nexport type { SignIn };\n"],"mappings":";;;;;;AAkCA,MAAM,gBAAgB,OAAO,OAAO,EAAE,KAAK,OAAO,OAAO,CAAC;AAE1D,MAAM,aAAa,YAA6B,gBAAgB,QAAQ,OAAO;AAE/E,MAAM,UAAU,cAGT;CACL,UAAU,SAAS;CACnB,cAAc,SAAS,MAAM,SAAS,YAAY;AACpD;;;;;;AAOA,MAAM,mBAAmB,EAAE,QAAQ,QAAQ,iBAA4C;CACrF,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,OAAO,MAAM,EAAE;CACzD,GAAI,WAAW,KAAA,IACX,CAAC,IACD,EAAE,QAAQ;EAAE,GAAG,OAAO,MAAM;EAAG,QAAQ;CAA0B,EAAE;CACvE,GAAI,cAAc,KAAA,IACd,CAAC,IACD,EACE,WAAW;EACT,GAAG,OAAO,SAAS;EACnB,QAAQ;EACR,UAAU,UAAU,YAAY;CAClC,EACF;AACN;;;;;;;;AASA,MAAM,oBAAoB,eAAwD;CAChF,IAAI,eAAe,KAAA,GACjB,OAAO,CAAC;CAEV,MAAM,OAAO,WAAW,WAAW,WAAW,2BAA2B,WAAW;CACpF,OAAO,CACL,aAAa,EACX,QAAQ,CACN;EACE,GAAG,OAAO,UAAU;EACpB,kBAAkB,GAAG,KAAK;EAC1B,yBAAyB,EAAE,eAAe,KAAK;EAC/C,MAAM;EACN,YAAY;EACZ,QAAQ;GAAC;GAAU;GAAS;EAAS;EACrC,UAAU,GAAG,KAAK;EAClB,aAAa,GAAG,KAAK;CACvB,CACF,EACF,CAAC,CACH;AACF;;;;;;;;AASA,MAAM,oBAAoB,WACxB,WAAW;CACT,SAAS;EAAE,oBAAoB;EAAM,oBAAoB;CAAS;CAClE,SAAS,WAAW,OAAO;CAC3B,SAAS,iBAAiB,OAAO,UAAU,UAAU;CACrD,QAAQ,SAAS,MAAM,OAAO,UAAU;CACxC,SAAS;EACP,aAAa;GAAE,SAAS;GAAM,QAAQ;GAAgB,cAAc;GAAM,UAAU;EAAM;EAC1F,WAAW;CACb;CACA,iBAAiB,gBAAgB,OAAO,SAAS;CACjD,WAAW,EAAE,SAAS,MAAM;AAC9B,CAAC;AAEH,MAAM,gBAAgB,WAAiC;CACrD,MAAM,OAAO,iBAAiB,MAAM;CACpC,OAAO;EACL,SAAS,cAAc,IAAI;EAC3B,SAAS,OAAO,YAAY;GAC1B,MAAM,EAAE,SAAS,aAAa,MAAM,KAAK,IAAI,WAAW;IACtD,SAAS,UAAU,OAAO;IAC1B,eAAe;GACjB,CAAC;GACD,OAAO;IAAE,WAAW,QAAQ,aAAa;IAAG,OAAO,UAAU,QAAQ,KAAA;GAAU;EACjF;EACA,SAAS,OAAO,YAAY;GAE1B,QAAO,MADgB,KAAK,IAAI,QAAQ;IAAE,YAAY;IAAM,SAAS,UAAU,OAAO;GAAE,CAAC,EAAA,CACzE,QAAQ,aAAa;EACvC;EACA,OAAO,OAAO,SAAS,EAAE,aAAa,eAAe;GACnD,MAAM,WAAW,MAAM,KAAK,IAAI,aAAa;IAC3C,YAAY;IACZ,MAAM;KAAE;KAAa;IAAS;IAC9B,SAAS,UAAU,OAAO;GAC5B,CAAC;GACD,MAAM,UAAU,OAAO,oBAAoB,aAAa,CAAC,CAAC,MAAM,SAAS,KAAK,CAAC;GAC/E,OAAO;IACL,WAAW,SAAS,QAAQ,aAAa;IACzC,OAAO,QAAQ,KACb,OAAO,KAAK,EAAE,UAAU,GAAG,GAC3B,OAAO,cACT;GACF;EACF;CACF;AACF"}
package/dist/bin.js ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import { binProgram } from "./packages/contract/src/bin.js";
3
+ import { run } from "./cli.js";
4
+ import { NodeRuntime, NodeServices } from "@effect/platform-node";
5
+ import { Cause, Effect, Exit, Runtime } from "effect";
6
+ // src/bin.ts
7
+ const program = binProgram({
8
+ expected: "ServerError",
9
+ name: "wt-tunnel-server",
10
+ url: import.meta.url
11
+ }, run);
12
+ /**
13
+ * SIGTERM and SIGINT interrupt the program, which stops Caddy and frps. That is a clean stop, so it
14
+ * exits 0 rather than 130, unless a child had already died.
15
+ */
16
+ const teardown = (exit, onExit) => {
17
+ if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {
18
+ onExit(Number(process.exitCode ?? 0));
19
+ return;
20
+ }
21
+ Runtime.defaultTeardown(exit, onExit);
22
+ };
23
+ NodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)), { teardown });
24
+ export {};
25
+
26
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\n// fallow-ignore-file coverage-gaps -- it runs the CLI on import, so cli.test.ts runs it as a subprocess, which fallow cannot follow; 'exits 0 when SIGTERM stops it' tests the teardown\nimport { NodeRuntime, NodeServices } from '@effect/platform-node';\nimport { binProgram } from '@tafrahq/wt-tunnel-contract/bin';\nimport { Cause, Effect, Exit, Runtime } from 'effect';\n\nimport { run } from './cli.ts';\n\nconst program = binProgram(\n { expected: 'ServerError', name: 'wt-tunnel-server', url: import.meta.url },\n run,\n);\n\n/**\n * SIGTERM and SIGINT interrupt the program, which stops Caddy and frps. That is a clean stop, so it\n * exits 0 rather than 130, unless a child had already died.\n */\nconst teardown: Runtime.Teardown = (exit, onExit) => {\n if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {\n onExit(Number(process.exitCode ?? 0));\n return;\n }\n Runtime.defaultTeardown(exit, onExit);\n};\n\nNodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)), { teardown });\n"],"mappings":";;;;;;AAQA,MAAM,UAAU,WACd;CAAE,UAAU;CAAe,MAAM;CAAoB,KAAK,YAAY;AAAI,GAC1E,GACF;;;;;AAMA,MAAM,YAA8B,MAAM,WAAW;CACnD,IAAI,KAAK,UAAU,IAAI,KAAK,MAAM,kBAAkB,KAAK,KAAK,GAAG;EAC/D,OAAO,OAAO,QAAQ,YAAY,CAAC,CAAC;EACpC;CACF;CACA,QAAQ,gBAAgB,MAAM,MAAM;AACtC;AAEA,YAAY,QAAQ,QAAQ,KAAK,OAAO,QAAQ,aAAa,KAAK,CAAC,GAAG,EAAE,SAAS,CAAC"}
@@ -0,0 +1,51 @@
1
+ import { cacheHome, pinnedBinary } from "./packages/binaries/src/install.js";
2
+ import { caddyPin } from "./packages/binaries/src/caddy.js";
3
+ import { frpPin } from "./packages/binaries/src/frp.js";
4
+ import { ServerError } from "./errors.js";
5
+ import { Effect } from "effect";
6
+ import { delimiter, join, resolve } from "node:path";
7
+ import { constants } from "node:fs";
8
+ import { access, stat } from "node:fs/promises";
9
+ // src/binaries.ts
10
+ const pins = {
11
+ caddy: caddyPin,
12
+ frps: frpPin("frps")
13
+ };
14
+ const isExecutableFile = (file) => Effect.promise(async () => {
15
+ try {
16
+ await access(file, constants.X_OK);
17
+ return (await stat(file)).isFile();
18
+ } catch {
19
+ return false;
20
+ }
21
+ });
22
+ const firstOnPath = (name, path) => Effect.gen(function* searchPath() {
23
+ const candidates = path.split(delimiter).filter(Boolean).map((dir) => join(dir, name));
24
+ const executable = yield* Effect.all(candidates.map((file) => isExecutableFile(file)));
25
+ return candidates.find((_file, index) => executable[index] === true);
26
+ });
27
+ /** The flag's path, else the first on PATH, else the pinned release in the cache. */
28
+ const resolveBinary = (name, flag, search) => Effect.gen(function* flagPathOrDownload() {
29
+ if (flag !== void 0) {
30
+ const file = resolve(flag);
31
+ if (!(yield* isExecutableFile(file))) return yield* new ServerError({ message: `--${name} ${flag} is not an executable file` });
32
+ return file;
33
+ }
34
+ const found = yield* firstOnPath(name, search.path);
35
+ if (found !== void 0) return found;
36
+ const pin = pins[name];
37
+ return yield* pinnedBinary(pin, join(search.cacheDir, name, pin.version, name)).pipe(Effect.mapError(({ message }) => new ServerError({ message: `${message} Pass --${name} <path> to use one you installed.` })));
38
+ });
39
+ const resolveBinaries = (flags) => {
40
+ const search = {
41
+ cacheDir: join(cacheHome(), "wt-tunnel-server"),
42
+ path: process.env.PATH ?? ""
43
+ };
44
+ return Effect.all({
45
+ caddy: resolveBinary("caddy", flags.caddy, search),
46
+ frps: resolveBinary("frps", flags.frps, search)
47
+ });
48
+ };
49
+ export { resolveBinaries, resolveBinary };
50
+
51
+ //# sourceMappingURL=binaries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binaries.js","names":[],"sources":["../src/binaries.ts"],"sourcesContent":["import { constants } from 'node:fs';\nimport { access, stat } from 'node:fs/promises';\nimport { delimiter, join, resolve } from 'node:path';\n\nimport { cacheHome, pinnedBinary } from '@tafrahq/wt-tunnel-binaries';\nimport { caddyPin } from '@tafrahq/wt-tunnel-binaries/caddy';\nimport { frpPin } from '@tafrahq/wt-tunnel-binaries/frp';\nimport { Effect } from 'effect';\n\nimport { ServerError } from './errors.ts';\n\nconst pins = { caddy: caddyPin, frps: frpPin('frps') } as const;\n\ntype BinaryName = keyof typeof pins;\n\n/** The Caddy and frps executables the server runs. */\ntype Binaries = Readonly<Record<BinaryName, string>>;\n\n/** Where to look for a binary that no flag names. */\ninterface Search {\n /** The cache directory pinned downloads go under. */\n readonly cacheDir: string;\n /** A PATH-style list of directories. */\n readonly path: string;\n}\n\nconst isExecutableFile = (file: string) =>\n Effect.promise(async () => {\n try {\n await access(file, constants.X_OK);\n const stats = await stat(file);\n return stats.isFile();\n } catch {\n return false;\n }\n });\n\nconst firstOnPath = (name: string, path: string) =>\n Effect.gen(function* searchPath() {\n const candidates = path\n .split(delimiter)\n .filter(Boolean)\n .map((dir) => join(dir, name));\n const executable = yield* Effect.all(candidates.map((file) => isExecutableFile(file)));\n return candidates.find((_file, index) => executable[index] === true);\n });\n\n/** The flag's path, else the first on PATH, else the pinned release in the cache. */\nconst resolveBinary = (name: BinaryName, flag: string | undefined, search: Search) =>\n Effect.gen(function* flagPathOrDownload() {\n if (flag !== undefined) {\n const file = resolve(flag);\n if (!(yield* isExecutableFile(file))) {\n return yield* new ServerError({ message: `--${name} ${flag} is not an executable file` });\n }\n return file;\n }\n const found = yield* firstOnPath(name, search.path);\n if (found !== undefined) {\n return found;\n }\n const pin = pins[name];\n return yield* pinnedBinary(pin, join(search.cacheDir, name, pin.version, name)).pipe(\n Effect.mapError(\n ({ message }: { readonly message: string }) =>\n new ServerError({\n message: `${message} Pass --${name} <path> to use one you installed.`,\n }),\n ),\n );\n });\n\nconst resolveBinaries = (flags: Readonly<Record<BinaryName, string | undefined>>) => {\n const search = { cacheDir: join(cacheHome(), 'wt-tunnel-server'), path: process.env.PATH ?? '' };\n return Effect.all({\n caddy: resolveBinary('caddy', flags.caddy, search),\n frps: resolveBinary('frps', flags.frps, search),\n });\n};\n\nexport { resolveBinaries, resolveBinary };\nexport type { Binaries };\n"],"mappings":";;;;;;;;;AAWA,MAAM,OAAO;CAAE,OAAO;CAAU,MAAM,OAAO,MAAM;AAAE;AAerD,MAAM,oBAAoB,SACxB,OAAO,QAAQ,YAAY;CACzB,IAAI;EACF,MAAM,OAAO,MAAM,UAAU,IAAI;EAEjC,QAAO,MADa,KAAK,IAAI,EAAA,CAChB,OAAO;CACtB,QAAQ;EACN,OAAO;CACT;AACF,CAAC;AAEH,MAAM,eAAe,MAAc,SACjC,OAAO,IAAI,UAAU,aAAa;CAChC,MAAM,aAAa,KAChB,MAAM,SAAS,CAAC,CAChB,OAAO,OAAO,CAAC,CACf,KAAK,QAAQ,KAAK,KAAK,IAAI,CAAC;CAC/B,MAAM,aAAa,OAAO,OAAO,IAAI,WAAW,KAAK,SAAS,iBAAiB,IAAI,CAAC,CAAC;CACrF,OAAO,WAAW,MAAM,OAAO,UAAU,WAAW,WAAW,IAAI;AACrE,CAAC;;AAGH,MAAM,iBAAiB,MAAkB,MAA0B,WACjE,OAAO,IAAI,UAAU,qBAAqB;CACxC,IAAI,SAAS,KAAA,GAAW;EACtB,MAAM,OAAO,QAAQ,IAAI;EACzB,IAAI,EAAE,OAAO,iBAAiB,IAAI,IAChC,OAAO,OAAO,IAAI,YAAY,EAAE,SAAS,KAAK,KAAK,GAAG,KAAK,4BAA4B,CAAC;EAE1F,OAAO;CACT;CACA,MAAM,QAAQ,OAAO,YAAY,MAAM,OAAO,IAAI;CAClD,IAAI,UAAU,KAAA,GACZ,OAAO;CAET,MAAM,MAAM,KAAK;CACjB,OAAO,OAAO,aAAa,KAAK,KAAK,OAAO,UAAU,MAAM,IAAI,SAAS,IAAI,CAAC,CAAC,CAAC,KAC9E,OAAO,UACJ,EAAE,cACD,IAAI,YAAY,EACd,SAAS,GAAG,QAAQ,UAAU,KAAK,mCACrC,CAAC,CACL,CACF;AACF,CAAC;AAEH,MAAM,mBAAmB,UAA4D;CACnF,MAAM,SAAS;EAAE,UAAU,KAAK,UAAU,GAAG,kBAAkB;EAAG,MAAM,QAAQ,IAAI,QAAQ;CAAG;CAC/F,OAAO,OAAO,IAAI;EAChB,OAAO,cAAc,SAAS,MAAM,OAAO,MAAM;EACjD,MAAM,cAAc,QAAQ,MAAM,MAAM,MAAM;CAChD,CAAC;AACH"}
package/dist/brand.js ADDED
@@ -0,0 +1,10 @@
1
+ // src/brand.ts
2
+ /**
3
+ * The small wt-tunnel mark, assets/brand/wt-tunnel-small.svg, as the pages' favicon. It is inlined
4
+ * as a data URI, so the pages load nothing from elsewhere; a test keeps it equal to the file.
5
+ */
6
+ const markSvg = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\"><title>wt-tunnel</title><defs><linearGradient id=\"wt-tunnel-bg\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"#1d4ed8\"/><stop offset=\"1\" stop-color=\"#172554\"/></linearGradient></defs><rect width=\"64\" height=\"64\" rx=\"14\" fill=\"url(#wt-tunnel-bg)\"/><path d=\"M12 56V32a20 20 0 0 1 40 0v24\" fill=\"none\" stroke=\"#5eead4\" stroke-width=\"8\" stroke-linecap=\"round\"/><path d=\"M32 56V36\" fill=\"none\" stroke=\"#fff\" stroke-width=\"6\" stroke-linecap=\"round\"/><circle cx=\"32\" cy=\"31\" r=\"7\" fill=\"#fff\"/></svg>";
7
+ const faviconLink = `<link rel="icon" href="data:image/svg+xml,${encodeURIComponent(markSvg)}">`;
8
+ export { faviconLink, markSvg };
9
+
10
+ //# sourceMappingURL=brand.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"brand.js","names":[],"sources":["../src/brand.ts"],"sourcesContent":["/**\n * The small wt-tunnel mark, assets/brand/wt-tunnel-small.svg, as the pages' favicon. It is inlined\n * as a data URI, so the pages load nothing from elsewhere; a test keeps it equal to the file.\n */\nconst markSvg =\n '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\"><title>wt-tunnel</title><defs><linearGradient id=\"wt-tunnel-bg\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"#1d4ed8\"/><stop offset=\"1\" stop-color=\"#172554\"/></linearGradient></defs><rect width=\"64\" height=\"64\" rx=\"14\" fill=\"url(#wt-tunnel-bg)\"/><path d=\"M12 56V32a20 20 0 0 1 40 0v24\" fill=\"none\" stroke=\"#5eead4\" stroke-width=\"8\" stroke-linecap=\"round\"/><path d=\"M32 56V36\" fill=\"none\" stroke=\"#fff\" stroke-width=\"6\" stroke-linecap=\"round\"/><circle cx=\"32\" cy=\"31\" r=\"7\" fill=\"#fff\"/></svg>';\n\nconst faviconLink = `<link rel=\"icon\" href=\"data:image/svg+xml,${encodeURIComponent(markSvg)}\">`;\n\nexport { faviconLink, markSvg };\n"],"mappings":";;;;;AAIA,MAAM,UACJ;AAEF,MAAM,cAAc,6CAA6C,mBAAmB,OAAO,EAAE"}
@@ -0,0 +1,112 @@
1
+ import { mobileconfig } from "./root-ca.js";
2
+ import { faviconLink } from "./brand.js";
3
+ import { escapeHtml, header, status } from "./reply.js";
4
+ /** Five minutes: long enough to spare the service, short enough to pick up a new root soon. */
5
+ const cacheControl = "public, max-age=300";
6
+ const code = (text) => `<pre><code>${escapeHtml(text)}</code></pre>`;
7
+ const steps = (items) => `<ol>${items.map((item) => `<li>${item}</li>`).join("")}</ol>`;
8
+ /** One section per platform, in the order shown after the visitor's own. */
9
+ const guides = [
10
+ {
11
+ html: (file) => `<p>In Terminal, from the folder you downloaded it to:</p>${code(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${file}`)}<p>Or with Keychain Access:</p>${steps([
12
+ "Double-click the downloaded file. Keychain Access adds it to a keychain.",
13
+ "Find the certificate in Keychain Access and open it.",
14
+ "Expand <b>Trust</b> and set <b>When using this certificate</b> to <b>Always Trust</b>.",
15
+ "Close the window and enter your password."
16
+ ])}`,
17
+ platform: "macos",
18
+ title: "macOS"
19
+ },
20
+ {
21
+ html: () => steps([
22
+ "In Safari, open <a href=\"/ca.mobileconfig\">the configuration profile</a> and allow the download.",
23
+ "Open <b>Settings</b> and tap <b>Profile Downloaded</b>, then <b>Install</b>.",
24
+ "Go to <b>Settings</b> &gt; <b>General</b> &gt; <b>About</b> &gt; <b>Certificate Trust Settings</b> and turn on full trust for the wt-tunnel root."
25
+ ]),
26
+ platform: "ios",
27
+ title: "iPhone and iPad"
28
+ },
29
+ {
30
+ html: () => steps([
31
+ "Download <a href=\"/ca.crt\">the certificate</a>.",
32
+ "Open <b>Settings</b> &gt; <b>Security</b> (on some phones <b>Security and privacy</b> &gt; <b>More security settings</b>) &gt; <b>Encryption &amp; credentials</b> &gt; <b>Install a certificate</b> &gt; <b>CA certificate</b>.",
33
+ "Accept the warning and pick the downloaded file."
34
+ ]),
35
+ platform: "android",
36
+ title: "Android"
37
+ },
38
+ {
39
+ html: (file) => `<p>In an administrator Command Prompt, from the download folder:</p>${code(`certutil -addstore -f Root ${file}`)}<p>Without administrator rights, <code>certutil -user -addstore Root ${escapeHtml(file)}</code> trusts it for your account only. Or open the file, select <b>Install Certificate</b>, and place it in <b>Trusted Root Certification Authorities</b>.</p>`,
40
+ platform: "windows",
41
+ title: "Windows"
42
+ },
43
+ {
44
+ html: (file) => `<p>Debian and Ubuntu:</p>${code(`sudo cp ${file} /usr/local/share/ca-certificates/\nsudo update-ca-certificates`)}<p>Fedora and RHEL:</p>${code(`sudo cp ${file} /etc/pki/ca-trust/source/anchors/\nsudo update-ca-trust`)}<p>Chrome and Chromium on Linux read their own store. With <code>certutil</code> from libnss3-tools or nss-tools:</p>${code(`certutil -d sql:$HOME/.pki/nssdb -A -t C,, -n wt-tunnel -i ${file}`)}`,
45
+ platform: "linux",
46
+ title: "Linux"
47
+ },
48
+ {
49
+ html: () => `<p>Firefox keeps its own store. On Windows and macOS it also trusts the system's roots by default; on Linux, import the file:</p>${steps([
50
+ "Open <b>Settings</b> &gt; <b>Privacy &amp; Security</b> &gt; <b>Certificates</b> &gt; <b>View Certificates</b>.",
51
+ "On <b>Authorities</b>, select <b>Import</b> and pick the downloaded file.",
52
+ "Tick <b>Trust this CA to identify websites</b>."
53
+ ])}`,
54
+ platform: "firefox",
55
+ title: "Firefox"
56
+ }
57
+ ];
58
+ /** IPads asking for desktop sites say Macintosh; they find their section second. */
59
+ const platformOf = (userAgent) => {
60
+ if (/iPhone|iPad|iPod/u.test(userAgent)) return "ios";
61
+ if (/Android/u.test(userAgent)) return "android";
62
+ if (/Windows/u.test(userAgent)) return "windows";
63
+ if (/Macintosh|Mac OS X/u.test(userAgent)) return "macos";
64
+ return /Linux|X11|CrOS/u.test(userAgent) ? "linux" : void 0;
65
+ };
66
+ /** The visitor's platform first, then Firefox if they use it on a desktop, then the rest. */
67
+ const guideOrder = (userAgent) => {
68
+ const platform = platformOf(userAgent);
69
+ const desktopFirefox = /Firefox\//u.test(userAgent) && platform !== "ios" && platform !== "android";
70
+ const rank = (guide) => {
71
+ if (guide.platform === platform) return 0;
72
+ return guide.platform === "firefox" && desktopFirefox ? 1 : guides.indexOf(guide) + guides.length;
73
+ };
74
+ return guides.toSorted((left, right) => rank(left) - rank(right));
75
+ };
76
+ const style = "body{font:16px/1.5 system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem}pre{background:#f3f3f3;padding:.6rem;overflow-x:auto;white-space:pre-wrap;word-break:break-all}dt{font-weight:600}dd{margin:0 0 .6rem}.button{display:inline-block;padding:.6rem 1rem;background:#1f6feb;color:#fff;border-radius:6px;text-decoration:none;margin:0 .5rem .5rem 0}";
77
+ const constraintsHtml = (root) => root.permitted.length === 0 ? "<dd>None. This root could vouch for any name; do not trust it.</dd>" : `<dd>${root.permitted.map((name) => `<code>${escapeHtml(name)}</code>`).join(", ")}</dd><dd>This root can only vouch for names under these domains. Trusting it does not let anyone impersonate any other site.</dd>`;
78
+ const caPage = (root, userAgent) => {
79
+ const file = `${root.fileName}.crt`;
80
+ const sections = guideOrder(userAgent).map((guide) => `<section id="${guide.platform}"><h3>${guide.title}</h3>${guide.html(file)}</section>`).join("");
81
+ return `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">${faviconLink}<title>Trust this deployment's certificate</title><style>${style}</style><h1>Trust this deployment's certificate</h1><p>Dev URLs under ${root.domains.map((domain) => `<code>${escapeHtml(domain)}</code>`).join(", ")} use certificates from this deployment's own root, so that no worktree name shows up in public Certificate Transparency logs. Install the root once on each device that opens them.</p><p><a class="button" href="/ca.crt" download="${escapeHtml(file)}">Download ${escapeHtml(file)}</a><a class="button" href="/ca.mobileconfig">iPhone and iPad profile</a></p><h2>The root</h2><dl><dt>Subject</dt><dd>${escapeHtml(root.subject)}</dd><dt>Valid</dt><dd>${root.validFrom} to ${root.validTo}</dd><dt>SHA-256 fingerprint</dt><dd><code>${root.fingerprint}</code></dd><dt>Permitted names</dt>${constraintsHtml(root)}</dl><p>Check that the fingerprint your device shows matches the one above before you trust it.</p><h2>Install it</h2>${sections}<h2>Then restart the browser</h2><p>Quit and reopen the browser so it reads the new root.</p>\n`;
82
+ };
83
+ const download = (body, contentType, fileName) => ({
84
+ body,
85
+ headers: {
86
+ "cache-control": cacheControl,
87
+ "content-disposition": `attachment; filename="${fileName}"`,
88
+ "content-type": contentType,
89
+ "x-content-type-options": "nosniff"
90
+ },
91
+ status: status.ok
92
+ });
93
+ /** The public trust routes on the sign-in host, or undefined for any other path. */
94
+ const caRoute = (request, path, root) => {
95
+ switch (path) {
96
+ case "/ca": return {
97
+ body: caPage(root, header(request, "user-agent") ?? ""),
98
+ headers: {
99
+ "cache-control": cacheControl,
100
+ "content-type": "text/html; charset=utf-8",
101
+ vary: "User-Agent"
102
+ },
103
+ status: status.ok
104
+ };
105
+ case "/ca.crt": return download(root.pem, "application/x-x509-ca-cert", `${root.fileName}.crt`);
106
+ case "/ca.mobileconfig": return download(mobileconfig(root), "application/x-apple-aspen-config", `${root.fileName}.mobileconfig`);
107
+ default: return;
108
+ }
109
+ };
110
+ export { caRoute };
111
+
112
+ //# sourceMappingURL=ca-page.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ca-page.js","names":[],"sources":["../src/ca-page.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\n\nimport { faviconLink } from './brand.ts';\nimport { escapeHtml, header, status } from './reply.ts';\nimport type { Reply } from './reply.ts';\nimport { mobileconfig } from './root-ca.ts';\nimport type { RootCa } from './root-ca.ts';\n\nconst caPath = '/ca';\n/** Five minutes: long enough to spare the service, short enough to pick up a new root soon. */\nconst cacheControl = 'public, max-age=300';\n\ntype Platform = 'android' | 'firefox' | 'ios' | 'linux' | 'macos' | 'windows';\n\ninterface Guide {\n readonly html: (file: string) => string;\n readonly platform: Platform;\n readonly title: string;\n}\n\nconst code = (text: string) => `<pre><code>${escapeHtml(text)}</code></pre>`;\nconst steps = (items: readonly string[]) =>\n `<ol>${items.map((item) => `<li>${item}</li>`).join('')}</ol>`;\n\n/** One section per platform, in the order shown after the visitor's own. */\nconst guides: readonly Guide[] = [\n {\n html: (file) =>\n `<p>In Terminal, from the folder you downloaded it to:</p>${code(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${file}`)}<p>Or with Keychain Access:</p>${steps(['Double-click the downloaded file. Keychain Access adds it to a keychain.', 'Find the certificate in Keychain Access and open it.', 'Expand <b>Trust</b> and set <b>When using this certificate</b> to <b>Always Trust</b>.', 'Close the window and enter your password.'])}`,\n platform: 'macos',\n title: 'macOS',\n },\n {\n html: () =>\n steps([\n 'In Safari, open <a href=\"/ca.mobileconfig\">the configuration profile</a> and allow the download.',\n 'Open <b>Settings</b> and tap <b>Profile Downloaded</b>, then <b>Install</b>.',\n 'Go to <b>Settings</b> &gt; <b>General</b> &gt; <b>About</b> &gt; <b>Certificate Trust Settings</b> and turn on full trust for the wt-tunnel root.',\n ]),\n platform: 'ios',\n title: 'iPhone and iPad',\n },\n {\n html: () =>\n steps([\n 'Download <a href=\"/ca.crt\">the certificate</a>.',\n 'Open <b>Settings</b> &gt; <b>Security</b> (on some phones <b>Security and privacy</b> &gt; <b>More security settings</b>) &gt; <b>Encryption &amp; credentials</b> &gt; <b>Install a certificate</b> &gt; <b>CA certificate</b>.',\n 'Accept the warning and pick the downloaded file.',\n ]),\n platform: 'android',\n title: 'Android',\n },\n {\n html: (file) =>\n `<p>In an administrator Command Prompt, from the download folder:</p>${code(`certutil -addstore -f Root ${file}`)}<p>Without administrator rights, <code>certutil -user -addstore Root ${escapeHtml(file)}</code> trusts it for your account only. Or open the file, select <b>Install Certificate</b>, and place it in <b>Trusted Root Certification Authorities</b>.</p>`,\n platform: 'windows',\n title: 'Windows',\n },\n {\n html: (file) =>\n `<p>Debian and Ubuntu:</p>${code(`sudo cp ${file} /usr/local/share/ca-certificates/\\nsudo update-ca-certificates`)}<p>Fedora and RHEL:</p>${code(`sudo cp ${file} /etc/pki/ca-trust/source/anchors/\\nsudo update-ca-trust`)}<p>Chrome and Chromium on Linux read their own store. With <code>certutil</code> from libnss3-tools or nss-tools:</p>${code(`certutil -d sql:$HOME/.pki/nssdb -A -t C,, -n wt-tunnel -i ${file}`)}`,\n platform: 'linux',\n title: 'Linux',\n },\n {\n html: () =>\n `<p>Firefox keeps its own store. On Windows and macOS it also trusts the system's roots by default; on Linux, import the file:</p>${steps(['Open <b>Settings</b> &gt; <b>Privacy &amp; Security</b> &gt; <b>Certificates</b> &gt; <b>View Certificates</b>.', 'On <b>Authorities</b>, select <b>Import</b> and pick the downloaded file.', 'Tick <b>Trust this CA to identify websites</b>.'])}`,\n platform: 'firefox',\n title: 'Firefox',\n },\n];\n\n/** IPads asking for desktop sites say Macintosh; they find their section second. */\nconst platformOf = (userAgent: string): Platform | undefined => {\n if (/iPhone|iPad|iPod/u.test(userAgent)) {\n return 'ios';\n }\n if (/Android/u.test(userAgent)) {\n return 'android';\n }\n if (/Windows/u.test(userAgent)) {\n return 'windows';\n }\n if (/Macintosh|Mac OS X/u.test(userAgent)) {\n return 'macos';\n }\n return /Linux|X11|CrOS/u.test(userAgent) ? 'linux' : undefined;\n};\n\n/** The visitor's platform first, then Firefox if they use it on a desktop, then the rest. */\nconst guideOrder = (userAgent: string): readonly Guide[] => {\n const platform = platformOf(userAgent);\n const desktopFirefox =\n /Firefox\\//u.test(userAgent) && platform !== 'ios' && platform !== 'android';\n const rank = (guide: Guide) => {\n if (guide.platform === platform) {\n return 0;\n }\n return guide.platform === 'firefox' && desktopFirefox\n ? 1\n : guides.indexOf(guide) + guides.length;\n };\n return guides.toSorted((left, right) => rank(left) - rank(right));\n};\n\nconst style =\n 'body{font:16px/1.5 system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem}pre{background:#f3f3f3;padding:.6rem;overflow-x:auto;white-space:pre-wrap;word-break:break-all}dt{font-weight:600}dd{margin:0 0 .6rem}.button{display:inline-block;padding:.6rem 1rem;background:#1f6feb;color:#fff;border-radius:6px;text-decoration:none;margin:0 .5rem .5rem 0}';\n\nconst constraintsHtml = (root: RootCa) =>\n root.permitted.length === 0\n ? '<dd>None. This root could vouch for any name; do not trust it.</dd>'\n : `<dd>${root.permitted.map((name) => `<code>${escapeHtml(name)}</code>`).join(', ')}</dd><dd>This root can only vouch for names under these domains. Trusting it does not let anyone impersonate any other site.</dd>`;\n\nconst caPage = (root: RootCa, userAgent: string) => {\n const file = `${root.fileName}.crt`;\n const sections = guideOrder(userAgent)\n .map(\n (guide) =>\n `<section id=\"${guide.platform}\"><h3>${guide.title}</h3>${guide.html(file)}</section>`,\n )\n .join('');\n return `<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\">${faviconLink}<title>Trust this deployment's certificate</title><style>${style}</style><h1>Trust this deployment's certificate</h1><p>Dev URLs under ${root.domains.map((domain) => `<code>${escapeHtml(domain)}</code>`).join(', ')} use certificates from this deployment's own root, so that no worktree name shows up in public Certificate Transparency logs. Install the root once on each device that opens them.</p><p><a class=\"button\" href=\"/ca.crt\" download=\"${escapeHtml(file)}\">Download ${escapeHtml(file)}</a><a class=\"button\" href=\"/ca.mobileconfig\">iPhone and iPad profile</a></p><h2>The root</h2><dl><dt>Subject</dt><dd>${escapeHtml(root.subject)}</dd><dt>Valid</dt><dd>${root.validFrom} to ${root.validTo}</dd><dt>SHA-256 fingerprint</dt><dd><code>${root.fingerprint}</code></dd><dt>Permitted names</dt>${constraintsHtml(root)}</dl><p>Check that the fingerprint your device shows matches the one above before you trust it.</p><h2>Install it</h2>${sections}<h2>Then restart the browser</h2><p>Quit and reopen the browser so it reads the new root.</p>\\n`;\n};\n\nconst download = (body: string, contentType: string, fileName: string): Reply => ({\n body,\n headers: {\n 'cache-control': cacheControl,\n 'content-disposition': `attachment; filename=\"${fileName}\"`,\n 'content-type': contentType,\n 'x-content-type-options': 'nosniff',\n },\n status: status.ok,\n});\n\n/** The public trust routes on the sign-in host, or undefined for any other path. */\nconst caRoute = (request: IncomingMessage, path: string, root: RootCa): Reply | undefined => {\n switch (path) {\n case caPath: {\n return {\n body: caPage(root, header(request, 'user-agent') ?? ''),\n headers: {\n 'cache-control': cacheControl,\n 'content-type': 'text/html; charset=utf-8',\n vary: 'User-Agent',\n },\n status: status.ok,\n };\n }\n case '/ca.crt': {\n return download(root.pem, 'application/x-x509-ca-cert', `${root.fileName}.crt`);\n }\n case '/ca.mobileconfig': {\n return download(\n mobileconfig(root),\n 'application/x-apple-aspen-config',\n `${root.fileName}.mobileconfig`,\n );\n }\n default: {\n return undefined;\n }\n }\n};\n\nexport { caPath, caRoute };\n"],"mappings":";;;;AAUA,MAAM,eAAe;AAUrB,MAAM,QAAQ,SAAiB,cAAc,WAAW,IAAI,EAAE;AAC9D,MAAM,SAAS,UACb,OAAO,MAAM,KAAK,SAAS,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;;AAG1D,MAAM,SAA2B;CAC/B;EACE,OAAO,SACL,4DAA4D,KAAK,wFAAwF,MAAM,EAAE,iCAAiC,MAAM;GAAC;GAA4E;GAAwD;GAA0F;EAA2C,CAAC;EACrd,UAAU;EACV,OAAO;CACT;CACA;EACE,YACE,MAAM;GACJ;GACA;GACA;EACF,CAAC;EACH,UAAU;EACV,OAAO;CACT;CACA;EACE,YACE,MAAM;GACJ;GACA;GACA;EACF,CAAC;EACH,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO,SACL,uEAAuE,KAAK,8BAA8B,MAAM,EAAE,uEAAuE,WAAW,IAAI,EAAE;EAC5M,UAAU;EACV,OAAO;CACT;CACA;EACE,OAAO,SACL,4BAA4B,KAAK,WAAW,KAAK,gEAAgE,EAAE,yBAAyB,KAAK,WAAW,KAAK,yDAAyD,EAAE,uHAAuH,KAAK,8DAA8D,MAAM;EAC9Z,UAAU;EACV,OAAO;CACT;CACA;EACE,YACE,oIAAoI,MAAM;GAAC;GAAmH;GAA6E;EAAiD,CAAC;EAC/X,UAAU;EACV,OAAO;CACT;AACF;;AAGA,MAAM,cAAc,cAA4C;CAC9D,IAAI,oBAAoB,KAAK,SAAS,GACpC,OAAO;CAET,IAAI,WAAW,KAAK,SAAS,GAC3B,OAAO;CAET,IAAI,WAAW,KAAK,SAAS,GAC3B,OAAO;CAET,IAAI,sBAAsB,KAAK,SAAS,GACtC,OAAO;CAET,OAAO,kBAAkB,KAAK,SAAS,IAAI,UAAU,KAAA;AACvD;;AAGA,MAAM,cAAc,cAAwC;CAC1D,MAAM,WAAW,WAAW,SAAS;CACrC,MAAM,iBACJ,aAAa,KAAK,SAAS,KAAK,aAAa,SAAS,aAAa;CACrE,MAAM,QAAQ,UAAiB;EAC7B,IAAI,MAAM,aAAa,UACrB,OAAO;EAET,OAAO,MAAM,aAAa,aAAa,iBACnC,IACA,OAAO,QAAQ,KAAK,IAAI,OAAO;CACrC;CACA,OAAO,OAAO,UAAU,MAAM,UAAU,KAAK,IAAI,IAAI,KAAK,KAAK,CAAC;AAClE;AAEA,MAAM,QACJ;AAEF,MAAM,mBAAmB,SACvB,KAAK,UAAU,WAAW,IACtB,wEACA,OAAO,KAAK,UAAU,KAAK,SAAS,SAAS,WAAW,IAAI,EAAE,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE;AAEzF,MAAM,UAAU,MAAc,cAAsB;CAClD,MAAM,OAAO,GAAG,KAAK,SAAS;CAC9B,MAAM,WAAW,WAAW,SAAS,CAAC,CACnC,KACE,UACC,gBAAgB,MAAM,SAAS,QAAQ,MAAM,MAAM,OAAO,MAAM,KAAK,IAAI,EAAE,WAC/E,CAAC,CACA,KAAK,EAAE;CACV,OAAO,2FAA2F,YAAY,2DAA2D,MAAM,wEAAwE,KAAK,QAAQ,KAAK,WAAW,SAAS,WAAW,MAAM,EAAE,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,uOAAuO,WAAW,IAAI,EAAE,aAAa,WAAW,IAAI,EAAE,wHAAwH,WAAW,KAAK,OAAO,EAAE,yBAAyB,KAAK,UAAU,MAAM,KAAK,QAAQ,6CAA6C,KAAK,YAAY,sCAAsC,gBAAgB,IAAI,EAAE,wHAAwH,SAAS;AACpiC;AAEA,MAAM,YAAY,MAAc,aAAqB,cAA6B;CAChF;CACA,SAAS;EACP,iBAAiB;EACjB,uBAAuB,yBAAyB,SAAS;EACzD,gBAAgB;EAChB,0BAA0B;CAC5B;CACA,QAAQ,OAAO;AACjB;;AAGA,MAAM,WAAW,SAA0B,MAAc,SAAoC;CAC3F,QAAQ,MAAR;EACE,KAAA,OACE,OAAO;GACL,MAAM,OAAO,MAAM,OAAO,SAAS,YAAY,KAAK,EAAE;GACtD,SAAS;IACP,iBAAiB;IACjB,gBAAgB;IAChB,MAAM;GACR;GACA,QAAQ,OAAO;EACjB;EAEF,KAAK,WACH,OAAO,SAAS,KAAK,KAAK,8BAA8B,GAAG,KAAK,SAAS,KAAK;EAEhF,KAAK,oBACH,OAAO,SACL,aAAa,IAAI,GACjB,oCACA,GAAG,KAAK,SAAS,cACnB;EAEF,SACE;CAEJ;AACF"}
@@ -0,0 +1,72 @@
1
+ import { Effect } from "effect";
2
+ import { spawn } from "node:child_process";
3
+ import { once } from "node:events";
4
+ import { createInterface } from "node:readline";
5
+ // src/children.ts
6
+ const stopGraceMillis = 1e4;
7
+ /** How many of a child's last output lines to keep for explaining why it exited. */
8
+ const keptLines = 20;
9
+ const eachLine = (stream, onLine) => {
10
+ if (stream !== null) createInterface({ input: stream }).on("line", onLine);
11
+ };
12
+ const startChild = (spec) => {
13
+ const output = [];
14
+ const child = spawn(spec.command, [...spec.args], {
15
+ env: {
16
+ ...process.env,
17
+ ...spec.env
18
+ },
19
+ stdio: [
20
+ "ignore",
21
+ "pipe",
22
+ "pipe"
23
+ ]
24
+ });
25
+ const onLine = (line) => {
26
+ console.log(`[${spec.name}] ${line}`);
27
+ output.push(line);
28
+ output.splice(0, output.length - keptLines);
29
+ };
30
+ eachLine(child.stdout, onLine);
31
+ eachLine(child.stderr, onLine);
32
+ return {
33
+ name: spec.name,
34
+ output,
35
+ process: child
36
+ };
37
+ };
38
+ const running = (child) => child.process.exitCode === null && child.process.signalCode === null;
39
+ /** SIGTERM to every child still running, then SIGKILL to any left after the grace period. */
40
+ const stopChildren = (children) => Effect.promise(async () => {
41
+ const alive = children.filter((child) => running(child));
42
+ const exits = alive.map((child) => once(child.process, "exit"));
43
+ for (const child of alive) child.process.kill("SIGTERM");
44
+ const timer = setTimeout(() => {
45
+ for (const child of alive.filter((candidate) => running(candidate))) child.process.kill("SIGKILL");
46
+ }, stopGraceMillis);
47
+ await Promise.all(exits);
48
+ clearTimeout(timer);
49
+ });
50
+ /** Starts the children for the scope; closing the scope stops them. */
51
+ const startChildren = (specs) => Effect.acquireRelease(Effect.sync(() => specs.map((spec) => startChild(spec))), (children) => stopChildren(children));
52
+ const childExit = ({ name, output, process: child }) => Effect.callback((resume) => {
53
+ child.once("error", (error) => {
54
+ resume(Effect.succeed({
55
+ name,
56
+ output,
57
+ reason: error.message
58
+ }));
59
+ });
60
+ child.once("close", (code, signal) => {
61
+ resume(Effect.succeed({
62
+ name,
63
+ output,
64
+ reason: `code ${code} signal ${signal}`
65
+ }));
66
+ });
67
+ });
68
+ /** Completes with the first child to exit or fail to spawn. */
69
+ const firstExit = (children) => Effect.raceAll(children.map((child) => childExit(child)));
70
+ export { firstExit, startChildren };
71
+
72
+ //# sourceMappingURL=children.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"children.js","names":[],"sources":["../src/children.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport type { ChildProcess } from 'node:child_process';\nimport { once } from 'node:events';\nimport { createInterface } from 'node:readline';\nimport type { Readable } from 'node:stream';\n\nimport { Effect } from 'effect';\n\nconst stopGraceMillis = 10_000;\n/** How many of a child's last output lines to keep for explaining why it exited. */\nconst keptLines = 20;\n\ninterface ChildSpec {\n readonly args: readonly string[];\n readonly command: string;\n readonly env: Readonly<Record<string, string>>;\n readonly name: string;\n}\n\ninterface Child {\n readonly name: string;\n /** The child's last output lines, oldest first. */\n readonly output: readonly string[];\n readonly process: ChildProcess;\n}\n\ninterface Exited {\n readonly name: string;\n readonly output: readonly string[];\n readonly reason: string;\n}\n\nconst eachLine = (stream: Readable | null, onLine: (line: string) => void) => {\n if (stream !== null) {\n createInterface({ input: stream }).on('line', onLine);\n }\n};\n\nconst startChild = (spec: ChildSpec): Child => {\n const output: string[] = [];\n const child = spawn(spec.command, [...spec.args], {\n env: { ...process.env, ...spec.env },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const onLine = (line: string) => {\n console.log(`[${spec.name}] ${line}`);\n output.push(line);\n output.splice(0, output.length - keptLines);\n };\n eachLine(child.stdout, onLine);\n eachLine(child.stderr, onLine);\n return { name: spec.name, output, process: child };\n};\n\nconst running = (child: Child) =>\n child.process.exitCode === null && child.process.signalCode === null;\n\n/** SIGTERM to every child still running, then SIGKILL to any left after the grace period. */\nconst stopChildren = (children: readonly Child[]) =>\n Effect.promise(async () => {\n const alive = children.filter((child) => running(child));\n const exits = alive.map((child) => once(child.process, 'exit'));\n for (const child of alive) {\n child.process.kill('SIGTERM');\n }\n const timer = setTimeout(() => {\n for (const child of alive.filter((candidate) => running(candidate))) {\n child.process.kill('SIGKILL');\n }\n }, stopGraceMillis);\n await Promise.all(exits);\n clearTimeout(timer);\n });\n\n/** Starts the children for the scope; closing the scope stops them. */\nconst startChildren = (specs: readonly ChildSpec[]) =>\n Effect.acquireRelease(\n Effect.sync(() => specs.map((spec) => startChild(spec))),\n (children: readonly Child[]) => stopChildren(children),\n );\n\nconst childExit = ({ name, output, process: child }: Child) =>\n Effect.callback<Exited>((resume) => {\n child.once('error', (error: Readonly<Error>) => {\n resume(Effect.succeed({ name, output, reason: error.message }));\n });\n // 'close' waits for the output streams to end, so `output` holds the last lines.\n child.once('close', (code, signal) => {\n resume(Effect.succeed({ name, output, reason: `code ${code} signal ${signal}` }));\n });\n });\n\n/** Completes with the first child to exit or fail to spawn. */\nconst firstExit = (children: readonly Child[]) =>\n Effect.raceAll(children.map((child) => childExit(child)));\n\nexport { firstExit, startChildren };\nexport type { Exited };\n"],"mappings":";;;;;AAQA,MAAM,kBAAkB;;AAExB,MAAM,YAAY;AAsBlB,MAAM,YAAY,QAAyB,WAAmC;CAC5E,IAAI,WAAW,MACb,gBAAgB,EAAE,OAAO,OAAO,CAAC,CAAC,CAAC,GAAG,QAAQ,MAAM;AAExD;AAEA,MAAM,cAAc,SAA2B;CAC7C,MAAM,SAAmB,CAAC;CAC1B,MAAM,QAAQ,MAAM,KAAK,SAAS,CAAC,GAAG,KAAK,IAAI,GAAG;EAChD,KAAK;GAAE,GAAG,QAAQ;GAAK,GAAG,KAAK;EAAI;EACnC,OAAO;GAAC;GAAU;GAAQ;EAAM;CAClC,CAAC;CACD,MAAM,UAAU,SAAiB;EAC/B,QAAQ,IAAI,IAAI,KAAK,KAAK,IAAI,MAAM;EACpC,OAAO,KAAK,IAAI;EAChB,OAAO,OAAO,GAAG,OAAO,SAAS,SAAS;CAC5C;CACA,SAAS,MAAM,QAAQ,MAAM;CAC7B,SAAS,MAAM,QAAQ,MAAM;CAC7B,OAAO;EAAE,MAAM,KAAK;EAAM;EAAQ,SAAS;CAAM;AACnD;AAEA,MAAM,WAAW,UACf,MAAM,QAAQ,aAAa,QAAQ,MAAM,QAAQ,eAAe;;AAGlE,MAAM,gBAAgB,aACpB,OAAO,QAAQ,YAAY;CACzB,MAAM,QAAQ,SAAS,QAAQ,UAAU,QAAQ,KAAK,CAAC;CACvD,MAAM,QAAQ,MAAM,KAAK,UAAU,KAAK,MAAM,SAAS,MAAM,CAAC;CAC9D,KAAK,MAAM,SAAS,OAClB,MAAM,QAAQ,KAAK,SAAS;CAE9B,MAAM,QAAQ,iBAAiB;EAC7B,KAAK,MAAM,SAAS,MAAM,QAAQ,cAAc,QAAQ,SAAS,CAAC,GAChE,MAAM,QAAQ,KAAK,SAAS;CAEhC,GAAG,eAAe;CAClB,MAAM,QAAQ,IAAI,KAAK;CACvB,aAAa,KAAK;AACpB,CAAC;;AAGH,MAAM,iBAAiB,UACrB,OAAO,eACL,OAAO,WAAW,MAAM,KAAK,SAAS,WAAW,IAAI,CAAC,CAAC,IACtD,aAA+B,aAAa,QAAQ,CACvD;AAEF,MAAM,aAAa,EAAE,MAAM,QAAQ,SAAS,YAC1C,OAAO,UAAkB,WAAW;CAClC,MAAM,KAAK,UAAU,UAA2B;EAC9C,OAAO,OAAO,QAAQ;GAAE;GAAM;GAAQ,QAAQ,MAAM;EAAQ,CAAC,CAAC;CAChE,CAAC;CAED,MAAM,KAAK,UAAU,MAAM,WAAW;EACpC,OAAO,OAAO,QAAQ;GAAE;GAAM;GAAQ,QAAQ,QAAQ,KAAK,UAAU;EAAS,CAAC,CAAC;CAClF,CAAC;AACH,CAAC;;AAGH,MAAM,aAAa,aACjB,OAAO,QAAQ,SAAS,KAAK,UAAU,UAAU,KAAK,CAAC,CAAC"}