@tafrahq/wt-tunnel 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +225 -2
  3. package/dist/alchemy.js +40 -0
  4. package/dist/alchemy.js.map +1 -0
  5. package/dist/bin.js +21 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/ca.js +88 -0
  8. package/dist/ca.js.map +1 -0
  9. package/dist/cli.js +182 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/config.js +81 -0
  12. package/dist/config.js.map +1 -0
  13. package/dist/create-root.js +85 -0
  14. package/dist/create-root.js.map +1 -0
  15. package/dist/create-server-dir.js +153 -0
  16. package/dist/create-server-dir.js.map +1 -0
  17. package/dist/deployment.js +122 -0
  18. package/dist/deployment.js.map +1 -0
  19. package/dist/errors.js +7 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/init.js +89 -0
  22. package/dist/init.js.map +1 -0
  23. package/dist/outputs.js +38 -0
  24. package/dist/outputs.js.map +1 -0
  25. package/dist/packages/contract/src/index.js +12 -0
  26. package/dist/packages/contract/src/index.js.map +1 -0
  27. package/dist/packages/contract/src/root-ca.js +94 -0
  28. package/dist/packages/contract/src/root-ca.js.map +1 -0
  29. package/dist/packages/contract/src/server-config.js +99 -0
  30. package/dist/packages/contract/src/server-config.js.map +1 -0
  31. package/dist/prepare.js +73 -0
  32. package/dist/prepare.js.map +1 -0
  33. package/dist/providers.js +82 -0
  34. package/dist/providers.js.map +1 -0
  35. package/dist/secrets.js +39 -0
  36. package/dist/secrets.js.map +1 -0
  37. package/dist/server-dir.js +141 -0
  38. package/dist/server-dir.js.map +1 -0
  39. package/dist/server-machine.js +136 -0
  40. package/dist/server-machine.js.map +1 -0
  41. package/dist/stack.js +104 -0
  42. package/dist/stack.js.map +1 -0
  43. package/dist/uploads.js +24 -0
  44. package/dist/uploads.js.map +1 -0
  45. package/package.json +59 -3
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,226 @@
1
- # Temporary Holding Version
1
+ # wt-tunnel
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
+ `wt-tunnel` sets up the recommended [wt-tunnel](../../README.md) server: one Fly.io Machine running the published server image, with its DNS records in Cloudflare or created by you. A deployment is two things in one directory:
4
+
5
+ - `wt-tunnel.deploy.json` says where and how the server runs: the Fly app, the image, the tunnel host, the DNS zones and where Alchemy keeps its state. It holds no secrets.
6
+ - The server folder, `.server/`, says what the server does. It holds the server config `wt-tunnel-server.json`, the root CA's `ca.crt` and `ca.key`, and anything else the server reads. The first `wt-tunnel deploy` creates it. Every deploy uploads it to the Machine as it is.
7
+
8
+ The CLI checks both, then runs an Alchemy stack that ships inside the package. You do not install Alchemy yourself. The stack creates:
9
+
10
+ - a Fly app in your organization, with a dedicated IPv4 (billed by Fly) and an IPv6;
11
+ - one Fly secret per file in the server folder, which Fly writes to `/etc/wt-tunnel-server/` in the Machine;
12
+ - one Machine (shared CPU, 512 MB by default) running `ghcr.io/tafrahq/wt-tunnel-server` with `--config /etc/wt-tunnel-server/wt-tunnel-server.json`, with raw TCP on 443, 80 and 7000, so the server ends TLS itself;
13
+ - the DNS records: `*.<domain>` for each dev domain, the tunnel host and the sign-in host, all pointing at the Machine directly. The stack creates the records in Cloudflare zones. For a `manual` zone, the CLI lists the records for you to create instead.
14
+
15
+ A change to any file in the server folder rolls the Machine, because the Machine's environment carries each file secret's digest. A new image tag also rolls it.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install -g @tafrahq/wt-tunnel
21
+ ```
22
+
23
+ It needs Node.js 22.22.3 or later (Alchemy's TypeScript loader needs it), and `openssl` to sign a new root CA.
24
+
25
+ ## Set up a deployment
26
+
27
+ Work in a private directory of your own. It holds the deploy file, the server folder and, with local state, Alchemy's record of what it created.
28
+
29
+ ### 1. Write the deploy file
30
+
31
+ ```sh
32
+ mkdir my-wt-tunnel && cd my-wt-tunnel
33
+ wt-tunnel init
34
+ ```
35
+
36
+ `init` writes a commented `wt-tunnel.deploy.json`, adds `.server/` and `.alchemy/` to `.gitignore`, and lists the secrets to create. Edit the file. This is a complete example. Its names sit in three zones: two Cloudflare zones, in any accounts, and one zone whose records you create yourself.
37
+
38
+ ```json
39
+ {
40
+ "fly": { "org": "my-org", "app": "wt-tunnel-my-org", "region": "ams" },
41
+ "tunnelHost": "wt-tunnel.example.com",
42
+ "dns": [
43
+ {
44
+ "provider": "cloudflare",
45
+ "zone": "example.com",
46
+ "zoneId": "fedcba9876543210fedcba9876543210"
47
+ },
48
+ {
49
+ "provider": "cloudflare",
50
+ "zone": "example.net",
51
+ "zoneId": "0123456789abcdeffedcba9876543210"
52
+ },
53
+ { "provider": "manual", "zone": "example.org" }
54
+ ],
55
+ "state": { "provider": "cloudflare", "accountId": "0123456789abcdef0123456789abcdef" }
56
+ }
57
+ ```
58
+
59
+ | Field | Required | Meaning |
60
+ | ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
61
+ | `fly.org` | yes | The Fly organization slug, as `fly orgs list` shows it. |
62
+ | `fly.app` | yes | The Fly app name. Fly app names are global. |
63
+ | `fly.region` | yes | The Fly region, such as `ams` or `iad`. |
64
+ | `fly.memoryMb` | no | The Machine's memory. Default 512. |
65
+ | `tunnelHost` | yes | The host tunnel clients connect to. A new root CA is named after it. |
66
+ | `dns` | yes | One entry per zone, each with a `provider` and the `zone` name. `{ "provider": "cloudflare", "zone", "zoneId" }`: the stack creates the records in that Cloudflare zone. `{ "provider": "manual", "zone" }`: you create them, and `wt-tunnel outputs` lists them. Each record (`*.<domain>` for each dev domain, the tunnel host and the sign-in host) goes in the most specific zone its name sits in. A name that no zone covers, or a zone listed twice, fails. |
67
+ | `state` | yes | `{ "provider": "cloudflare", "accountId" }` keeps Alchemy's state in a state store Worker in that Cloudflare account, so any machine with the secrets can deploy. `"local"` keeps it in `.alchemy/` next to the deploy file. Back that directory up and keep it out of git: updating or destroying needs it. |
68
+ | `image` | no | The server image. Default: `ghcr.io/tafrahq/wt-tunnel-server:<version>`, where `<version>` is this CLI's version. |
69
+ | `serverDir` | no | The server folder, relative to the deploy file. Default `.server`. |
70
+ | `stack`, `stage` | no | Alchemy's names for the deployment. Default `wt-tunnel-server` and `prod`. |
71
+
72
+ The file may contain `//` and `/* */` comments. Pass `--config <file>` to use another path.
73
+
74
+ Cloudflare is optional. This deploy file needs no Cloudflare account: you create the DNS records yourself, and Alchemy keeps its state in `.alchemy/`. Sign-in can use Cloudflare Access or not, independently.
75
+
76
+ ```json
77
+ {
78
+ "fly": { "org": "personal", "app": "wt-tunnel-my-team", "region": "ams" },
79
+ "tunnelHost": "wt-tunnel.example.com",
80
+ "dns": [{ "provider": "manual", "zone": "example.com" }],
81
+ "state": "local"
82
+ }
83
+ ```
84
+
85
+ ### 2. Create the secrets
86
+
87
+ Every command needs these in the environment. A secret manager that exports environment variables, such as fnox, 1Password CLI or Doppler, works well.
88
+
89
+ | Variable | How to create it |
90
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
91
+ | `FLY_API_TOKEN` | `fly tokens create org <org>`. An org token can manage every app in the organization. |
92
+ | `CLOUDFLARE_API_TOKEN` | Needed when a `dns` entry or the `state` uses Cloudflare. In the Cloudflare dashboard, under My Profile, API Tokens, create a custom token with Zone, DNS, Edit on every Cloudflare zone in `dns`. With Cloudflare state, also give it Account permissions Workers Scripts Edit, Account Settings Edit, Secrets Store Edit and Workers Tail Read on the state's account. |
93
+ | `CLOUDFLARE_ACCOUNT_ID` | Only with a Cloudflare zone in `dns` and `"state": "local"`: the ID of an account that holds one of those zones. Alchemy's Cloudflare credentials need an account even though DNS records need only the zone ID. With Cloudflare state, the CLI sets it from `state.accountId`. |
94
+
95
+ Alchemy takes one set of Cloudflare credentials per deployment, so one `CLOUDFLARE_API_TOKEN` must be able to edit every Cloudflare zone in `dns`. A user API token, created under My Profile, can cover zones in several accounts. An account API token covers only its own account. A missing variable fails the command and names it.
96
+
97
+ The server's own secrets live in the server folder. The first deploy reads these only to create it:
98
+
99
+ | Variable | Use |
100
+ | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
101
+ | Sign-in providers | At least one, or chosen and typed at the prompt. A provider is set when its client ID is. See [Sign-in providers](#sign-in-providers). |
102
+ | `WT_TUNNEL_SERVER_TOKEN`, `WT_AUTH_SECRET` | Optional. Without them, the deploy generates each one: 32 random bytes, base64url. |
103
+ | `WT_CA_KEY` or `WT_CA_KEY_FILE` | Optional: an existing root's key, as PEM text or a file. See [The root CA](#the-root-ca). |
104
+
105
+ ### Sign-in providers
106
+
107
+ Set up one or more. Each provider's redirect URI is `https://<authHost>/api/auth/callback/<provider>`. With several, the sign-in page lets people choose.
108
+
109
+ | Provider | Variables | Where to create the client |
110
+ | ----------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
111
+ | Google | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | Google Cloud console, APIs and Services, Credentials: an OAuth client ID of type Web application. |
112
+ | GitHub | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | GitHub, Settings, Developer settings, OAuth Apps. The redirect URI is the authorization callback URL. |
113
+ | Microsoft | `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, optional `MICROSOFT_TENANT_ID` | Microsoft Entra admin center, App registrations, with a Web redirect URI and a client secret. Under Token configuration, add the optional ID token claim `verified_primary_email`. The tenant ID limits sign-in to one tenant (default: any account). |
114
+ | Cloudflare Access | `CLOUDFLARE_ACCESS_CLIENT_ID`, `CLOUDFLARE_ACCESS_CLIENT_SECRET`, `CLOUDFLARE_ACCESS_TEAM_DOMAIN` | Cloudflare Zero Trust, Access, Applications: a SaaS application with OIDC. The team domain is like `acme.cloudflareaccess.com`. |
115
+
116
+ To add or remove a provider later, edit `providers` in `.server/wt-tunnel-server.json` and deploy again.
117
+
118
+ ### 3. Deploy
119
+
120
+ ```sh
121
+ wt-tunnel deploy --domain dev.example.com --auth-host auth-wt-tunnel.example.com \
122
+ --allow-email someone@example.com --allow-email-domain example.com
123
+ ```
124
+
125
+ The first deploy creates `.server/`:
126
+
127
+ - `--domain` (repeatable): the dev domains. Worktree URLs are `https://<app>.<worktree>.<domain>`.
128
+ - `--auth-host`: the sign-in host, shared by every dev domain. It must sit outside every dev domain. See [the sign-in host](#the-sign-in-host).
129
+ - `--allow-email` and `--allow-email-domain` (both repeatable): who may sign in. At least one.
130
+
131
+ At a terminal, the deploy asks for any of these you leave out, and for the sign-in providers and their clients, with each secret's input hidden. Without a terminal, as in CI, it fails and names every missing flag and variable. It then writes the folder, mode 0700, with `wt-tunnel-server.json` and `ca.key` readable by you only, and prints what it created and what it generated.
132
+
133
+ `wt-tunnel prepare` takes the same flags and does only this step: it creates the folder, or checks the one there, and touches nothing in the cloud. `wt-tunnel plan` previews the folder it would create without writing anything, and shows the plan. The plan reads your Fly organization, so it needs a valid `FLY_API_TOKEN`.
134
+
135
+ To try the server before you deploy it, run the folder `prepare` wrote on your machine, on ports that need no root, with [`wt-tunnel-server`](../server/README.md#run-without-docker):
136
+
137
+ ```sh
138
+ wt-tunnel-server start --config .server --detach --https-port 8443 --http-port 8081
139
+ curl --cacert .server/ca.crt --resolve app.feat-x.dev.example.com:8443:127.0.0.1 \
140
+ -H 'Accept: text/html' -i https://app.feat-x.dev.example.com:8443/
141
+ wt-tunnel-server stop
142
+ ```
143
+
144
+ The `curl` gets a redirect to the sign-in host, which shows that TLS from your root, the sign-in check and the routing work.
145
+
146
+ Then the deploy shows the plan, asks for approval, and applies it. `deploy --yes` applies without asking. Without a terminal to ask in, `deploy` and `destroy` fail unless you pass `--yes`. A second `deploy` with nothing changed does nothing. After a deploy, the CLI prints the app, its IPs, the tunnel host, the CA page, and which zone holds each DNS record. For a `manual` zone, it lists the records to create. Run `wt-tunnel outputs` to print them again.
147
+
148
+ `wt-tunnel destroy` deletes everything the stack created. It leaves the server folder alone.
149
+
150
+ For anything else Alchemy can do, `wt-tunnel alchemy -- <command>` runs that alchemy command against this deployment's stack, with the same checks and environment. For example, `wt-tunnel alchemy -- state ls wt-tunnel-server/prod --recursive` lists what the state holds.
151
+
152
+ ### The sign-in host
153
+
154
+ Each device opens the sign-in host (`--auth-host`, `authHost` in the config) before it trusts your root: that is where the `/ca` page lives. Browsers must trust the certificate there, and your root cannot vouch for it, because the root is name-constrained to the dev domains. So the server gets a public certificate for that one name from Let's Encrypt each time it starts, over ports 80 and 443, which the stack opens.
155
+
156
+ Let's Encrypt issues at most five certificates for the same name in a week, and the server keeps none across restarts. After a sixth deploy or restart in a week, the sign-in host falls back to an untrusted certificate until the week is over, and nobody can sign in. Batch config changes into fewer deploys.
157
+
158
+ A deployment from an earlier version had the sign-in record proxied by Cloudflare. The next deploy makes it DNS only, like the others.
159
+
160
+ ### 4. Trust the root on each device
161
+
162
+ After the deploy, open `https://<authHost>/ca` on every device that opens dev URLs. `wt-tunnel outputs` prints the address as `CA page`. The page shows the root's fingerprint and permitted names, offers `ca.crt` and an iPhone and iPad profile for download, and gives the trust steps for the device's platform first.
163
+
164
+ To trust the root from the file instead, on macOS: `sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain .server/ca.crt`. The page lists the steps for the other platforms.
165
+
166
+ ### 5. Point the clients at the server
167
+
168
+ In each repository's `wt-tunnel.json`, set `domain` to a dev domain and `server.host` to the tunnel host:
169
+
170
+ ```json
171
+ {
172
+ "domain": "dev.example.com",
173
+ "server": { "host": "wt-tunnel.example.com" },
174
+ "apps": { "app": { "portEnv": "APP_PORT" } }
175
+ }
176
+ ```
177
+
178
+ Each developer sets `WT_TUNNEL_SERVER_TOKEN` to `tunnelToken` from `.server/wt-tunnel-server.json`. See the [wt-tunnel client](../client/README.md).
179
+
180
+ ## The server folder
181
+
182
+ > [!WARNING]
183
+ > The server folder holds the server's secrets in plain text: the sign-in providers' client secrets, the tunnel token, the auth secret and the root CA's key. Never commit it. Back it up somewhere safe, such as a secret manager: without `ca.key`, a new root means every device must trust it again.
184
+
185
+ To change what the server does, edit `.server/wt-tunnel-server.json` and run `wt-tunnel deploy` again. [docs/server-mode.md](../../docs/server-mode.md#server-config) lists its fields. A deploy never rewrites the folder. It checks it first, and any problem stops the deploy before anything changes in the cloud:
186
+
187
+ - the config decodes with the server's own schema, and every problem is listed at once;
188
+ - `ca.cert` and `ca.key` name files in the folder that hold a PEM certificate and key;
189
+ - the root's name constraints cover every domain, and the key is the certificate's;
190
+ - every DNS record name sits in a zone in `dns`;
191
+ - the sign-in host is outside every dev domain;
192
+ - no one else may read `wt-tunnel-server.json` or `ca.key`;
193
+ - the folder holds only files, with names of letters, digits, `.`, `_` and `-`.
194
+
195
+ A file the config does not name is uploaded as well, and the deploy says so. The Machine reads every file from `/etc/wt-tunnel-server/`, so a later server version can read a new file there without a change to the stack. Fly writes each file with mode 0444, readable by every user in the Machine. Fly does not document who owns the files it writes, and the server runs as an unprivileged user, so 0600 could leave them unreadable. A tighter mode would hide nothing anyway: Fly puts every app secret in the environment of the Machine's processes.
196
+
197
+ ## The root CA
198
+
199
+ Dev hosts use certificates from the deployment's own root, an EC P-256 root valid for 10 years with `CA:TRUE, pathlen:1` and critical name constraints. The root can issue certificates only for the dev domains and the names under them, so a device that trusts it trusts nothing else. It is named `wt-tunnel root (<tunnelHost>)`. The name is only a label; the constraints decide what it can sign.
200
+
201
+ When the first deploy creates the folder, it decides the root so that a root devices already trust is never replaced by accident:
202
+
203
+ - The certificate comes from `--ca-cert`, else `ca.crt` in the server folder, else `ca.crt` next to the deploy file.
204
+ - The key comes from `--ca-key`, `WT_CA_KEY`, `WT_CA_KEY_FILE`, else `ca.key` in the same two places.
205
+ - With both, the deploy copies them into the folder. With neither, it makes a new root and writes it only into the folder. With only one, it stops: a new root in its place would not be trusted by the devices that trust the old one.
206
+
207
+ `wt-tunnel ca create [<domain>...]` makes a root ahead of the deploy. It writes `ca.crt` and `ca.key` where the deploy reads them, in the deploy file's server folder (or where an existing `wt-tunnel-server.json` points its `ca`), with the folder 0700 and the key 0600. The domains default to the server config's, and at a terminal it asks for them. It refuses to replace an existing root unless you pass `--force`, because every device must then trust the new one. `--out-dir` writes elsewhere, and `--name` sets the label when there is no deploy file.
208
+
209
+ ## Upgrade
210
+
211
+ Each release of this CLI deploys the server image of the same version. To upgrade, install the new CLI and run `wt-tunnel deploy`. To stay on an image, or to try another, set `image` in the deploy file.
212
+
213
+ ## How it runs Alchemy
214
+
215
+ The package depends on `alchemy` and its Fly and Cloudflare providers, and ships the stack as `dist/stack.js`. Each command decodes the deploy file, checks the environment and the server folder. It then starts the `alchemy` launcher from its own dependency with Node, for example `alchemy deploy <dist/stack.js> --stage prod`, in the deploy file's directory. The stack reads the checked deployment and the folder's files from two environment variables that only the CLI sets. Alchemy's own output and approval prompt appear in your terminal as usual.
216
+
217
+ Alchemy's `Fly.Machine` has no `files`. The stack registers its own provider for the same `Fly.Machine` type, which sends the files and treats a change to them as drift, and keeps Alchemy's read, diff and delete. A Machine deployed before keeps its state and updates in place.
218
+
219
+ ## Develop
220
+
221
+ `pnpm check` at the repository root formats, lints, type-checks and tests this package with the rest of the monorepo. `pnpm turbo run build --filter @tafrahq/wt-tunnel` builds `dist/`. To run the workspace build, start it from your deployment directory:
222
+
223
+ ```sh
224
+ cd /path/to/my-wt-tunnel
225
+ node /path/to/wt-tunnel/apps/cli/dist/bin.js plan
226
+ ```
@@ -0,0 +1,40 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { createRequire } from "node:module";
3
+ import { Effect } from "effect";
4
+ import { spawn } from "node:child_process";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ // src/alchemy.ts
8
+ const alchemyBin = path.join(path.dirname(createRequire(import.meta.url).resolve("alchemy")), "..", "bin", "cli.js");
9
+ /** The stack tsdown builds next to this file in dist/. */
10
+ const stackFile = fileURLToPath(new URL("stack.js", import.meta.url));
11
+ /**
12
+ * Runs alchemy in the user's terminal, so its plan view and approval prompt work as usual, and
13
+ * yields its stdout when asked to capture it.
14
+ */
15
+ const runAlchemy = ({ args, capture = false, cwd, env }) => Effect.callback((resume) => {
16
+ const child = spawn(process.execPath, [alchemyBin, ...args], {
17
+ cwd,
18
+ env,
19
+ stdio: capture ? [
20
+ "ignore",
21
+ "pipe",
22
+ "inherit"
23
+ ] : "inherit"
24
+ });
25
+ const chunks = [];
26
+ child.stdout?.on("data", (chunk) => {
27
+ chunks.push(chunk);
28
+ });
29
+ child.on("error", (cause) => {
30
+ resume(Effect.fail(new InfraError({ message: `cannot start alchemy: ${cause.message}` })));
31
+ });
32
+ child.on("close", (code) => {
33
+ if (code !== 0) process.stderr.write(Buffer.concat(chunks));
34
+ const failure = new InfraError({ message: `alchemy ${args[0] ?? ""} failed (exit code ${String(code)})` });
35
+ resume(code === 0 ? Effect.succeed(Buffer.concat(chunks).toString("utf8")) : Effect.fail(failure));
36
+ });
37
+ });
38
+ export { runAlchemy, stackFile };
39
+
40
+ //# sourceMappingURL=alchemy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"alchemy.js","names":[],"sources":["../src/alchemy.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { Effect } from 'effect';\n\nimport { InfraError } from './errors.ts';\nimport type { Env } from './secrets.ts';\n\n/*\n * The alchemy launcher from this package's own dependency, so users never install Alchemy. Its\n * package exports no bin path, so it is found next to the resolved library entry.\n */\nconst alchemyBin = path.join(\n path.dirname(createRequire(import.meta.url).resolve('alchemy')),\n '..',\n 'bin',\n 'cli.js',\n);\n\n/** The stack tsdown builds next to this file in dist/. */\nconst stackFile = fileURLToPath(new URL('stack.js', import.meta.url));\n\ninterface AlchemyRun {\n readonly args: readonly string[];\n /** Capture stdout and return it, rather than printing it. Logs still reach stderr. */\n readonly capture?: boolean;\n readonly cwd: string;\n readonly env: Env;\n}\n\n/**\n * Runs alchemy in the user's terminal, so its plan view and approval prompt work as usual, and\n * yields its stdout when asked to capture it.\n */\nconst runAlchemy = ({ args, capture = false, cwd, env }: AlchemyRun) =>\n Effect.callback<string, InfraError>((resume) => {\n const child = spawn(process.execPath, [alchemyBin, ...args], {\n cwd,\n env,\n stdio: capture ? ['ignore', 'pipe', 'inherit'] : 'inherit',\n });\n const chunks: Buffer[] = [];\n child.stdout?.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n child.on('error', (cause: Readonly<Error>) => {\n resume(Effect.fail(new InfraError({ message: `cannot start alchemy: ${cause.message}` })));\n });\n child.on('close', (code) => {\n if (code !== 0) {\n process.stderr.write(Buffer.concat(chunks));\n }\n const failure = new InfraError({\n message: `alchemy ${args[0] ?? ''} failed (exit code ${String(code)})`,\n });\n resume(\n code === 0 ? Effect.succeed(Buffer.concat(chunks).toString('utf8')) : Effect.fail(failure),\n );\n });\n });\n\nexport { runAlchemy, stackFile };\n"],"mappings":";;;;;;;AAcA,MAAM,aAAa,KAAK,KACtB,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC,CAAC,QAAQ,SAAS,CAAC,GAC9D,MACA,OACA,QACF;;AAGA,MAAM,YAAY,cAAc,IAAI,IAAI,YAAY,YAAY,GAAG,CAAC;;;;;AAcpE,MAAM,cAAc,EAAE,MAAM,UAAU,OAAO,KAAK,UAChD,OAAO,UAA8B,WAAW;CAC9C,MAAM,QAAQ,MAAM,QAAQ,UAAU,CAAC,YAAY,GAAG,IAAI,GAAG;EAC3D;EACA;EACA,OAAO,UAAU;GAAC;GAAU;GAAQ;EAAS,IAAI;CACnD,CAAC;CACD,MAAM,SAAmB,CAAC;CAC1B,MAAM,QAAQ,GAAG,SAAS,UAAkB;EAC1C,OAAO,KAAK,KAAK;CACnB,CAAC;CACD,MAAM,GAAG,UAAU,UAA2B;EAC5C,OAAO,OAAO,KAAK,IAAI,WAAW,EAAE,SAAS,yBAAyB,MAAM,UAAU,CAAC,CAAC,CAAC;CAC3F,CAAC;CACD,MAAM,GAAG,UAAU,SAAS;EAC1B,IAAI,SAAS,GACX,QAAQ,OAAO,MAAM,OAAO,OAAO,MAAM,CAAC;EAE5C,MAAM,UAAU,IAAI,WAAW,EAC7B,SAAS,WAAW,KAAK,MAAM,GAAG,qBAAqB,OAAO,IAAI,EAAE,GACtE,CAAC;EACD,OACE,SAAS,IAAI,OAAO,QAAQ,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,IAAI,OAAO,KAAK,OAAO,CAC3F;CACF,CAAC;AACH,CAAC"}
package/dist/bin.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "./cli.js";
3
+ import { createRequire } from "node:module";
4
+ import { NodeRuntime, NodeServices } from "@effect/platform-node";
5
+ import { Console, Effect, Schema } from "effect";
6
+ // src/bin.ts
7
+ const PackageJson = Schema.Struct({ version: Schema.String });
8
+ const packageJson = createRequire(import.meta.url)("../package.json");
9
+ /** Expected failures carry a message written for the user; skip the stack trace. */
10
+ const report = (message) => Effect.gen(function* reportFailure() {
11
+ yield* Console.error(`wt-tunnel: ${message}`);
12
+ process.exitCode = 1;
13
+ });
14
+ const program = Effect.gen(function* main() {
15
+ const { version } = yield* Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(Effect.orDie);
16
+ yield* run(version);
17
+ }).pipe(Effect.catchTag("InfraError", ({ message }) => report(message)), Effect.provide(NodeServices.layer));
18
+ NodeRuntime.runMain(program);
19
+ export {};
20
+
21
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { createRequire } from 'node:module';\n\nimport { NodeRuntime, NodeServices } from '@effect/platform-node';\nimport { Console, Effect, Schema } from 'effect';\n\nimport { run } from './cli.ts';\n\nconst PackageJson = Schema.Struct({ version: Schema.String });\nconst packageJson: unknown = createRequire(import.meta.url)('../package.json');\n\n/** Expected failures carry a message written for the user; skip the stack trace. */\nconst report = (message: string) =>\n Effect.gen(function* reportFailure() {\n yield* Console.error(`wt-tunnel: ${message}`);\n process.exitCode = 1;\n });\n\nconst program = Effect.gen(function* main() {\n const { version } = yield* Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(\n Effect.orDie,\n );\n yield* run(version);\n}).pipe(\n Effect.catchTag('InfraError', ({ message }: { readonly message: string }) => report(message)),\n Effect.provide(NodeServices.layer),\n);\n\nNodeRuntime.runMain(program);\n"],"mappings":";;;;;;AAQA,MAAM,cAAc,OAAO,OAAO,EAAE,SAAS,OAAO,OAAO,CAAC;AAC5D,MAAM,cAAuB,cAAc,YAAY,GAAG,CAAC,CAAC,iBAAiB;;AAG7E,MAAM,UAAU,YACd,OAAO,IAAI,UAAU,gBAAgB;CACnC,OAAO,QAAQ,MAAM,cAAc,SAAS;CAC5C,QAAQ,WAAW;AACrB,CAAC;AAEH,MAAM,UAAU,OAAO,IAAI,UAAU,OAAO;CAC1C,MAAM,EAAE,YAAY,OAAO,OAAO,oBAAoB,WAAW,CAAC,CAAC,WAAW,CAAC,CAAC,KAC9E,OAAO,KACT;CACA,OAAO,IAAI,OAAO;AACpB,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,eAAe,EAAE,cAA4C,OAAO,OAAO,CAAC,GAC5F,OAAO,QAAQ,aAAa,KAAK,CACnC;AAEA,YAAY,QAAQ,OAAO"}
package/dist/ca.js ADDED
@@ -0,0 +1,88 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { Hostname } from "./packages/contract/src/index.js";
3
+ import { rootCommonName } from "./packages/contract/src/root-ca.js";
4
+ import { Effect, FileSystem, Path, Schema } from "effect";
5
+ import { execFile } from "node:child_process";
6
+ import { generateKeyPair } from "node:crypto";
7
+ import { promisify } from "node:util";
8
+ // src/ca.ts
9
+ const validDays = 3650;
10
+ const ownerOnly = 384;
11
+ /**
12
+ * The root's OpenSSL config. A config file rather than `-addext` flags, because LibreSSL (macOS's
13
+ * `openssl`) reads the same file. No leading dot on a permitted name: the constraint then covers
14
+ * the domain and every name under it. pathlen:1 leaves room for the intermediate Caddy signs.
15
+ */
16
+ const opensslConfig = ({ domains, label }) => [
17
+ "[req]",
18
+ "distinguished_name = dn",
19
+ "prompt = no",
20
+ "x509_extensions = root",
21
+ "[dn]",
22
+ "O = wt-tunnel",
23
+ `CN = ${rootCommonName(label)}`,
24
+ "[root]",
25
+ "basicConstraints = critical,CA:TRUE,pathlen:1",
26
+ "keyUsage = critical,keyCertSign,cRLSign",
27
+ `nameConstraints = critical,${domains.map((domain) => `permitted;DNS:${domain}`).join(",")}`,
28
+ "subjectKeyIdentifier = hash",
29
+ ""
30
+ ].join("\n");
31
+ const decodeDomains = (domains) => Schema.decodeUnknownEffect(Schema.NonEmptyArray(Hostname))(domains).pipe(Effect.mapError(() => new InfraError({ message: `every domain must be a lowercase DNS name with at least two labels, got ${domains.join(" ")}` })));
32
+ const openssl = (args) => Effect.callback((resume) => {
33
+ execFile("openssl", [...args], { encoding: "utf8" }, (failure, _stdout, stderr) => {
34
+ const error = new InfraError({ message: `openssl failed: ${stderr || String(failure)}` });
35
+ resume(failure === null ? Effect.void : Effect.fail(error));
36
+ });
37
+ });
38
+ const generateKeyPairAsync = promisify(generateKeyPair);
39
+ const ecKeyPem = Effect.tryPromise({
40
+ catch: (cause) => new InfraError({ message: `cannot make the CA key: ${String(cause)}` }),
41
+ try: async () => {
42
+ const { privateKey } = await generateKeyPairAsync("ec", { namedCurve: "P-256" });
43
+ return privateKey.export({
44
+ format: "pem",
45
+ type: "pkcs8"
46
+ }).toString();
47
+ }
48
+ });
49
+ const refuseExisting = (file, advice) => FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(Effect.orDie, Effect.filterOrFail((exists) => !exists, () => new InfraError({ message: `${file} already exists; ${advice}` })));
50
+ /**
51
+ * A new root CA as PEM text: an EC P-256 root valid for 10 years, name-constrained to the domains,
52
+ * so a device that trusts it trusts nothing else. Node makes the key; openssl signs the
53
+ * certificate, since Node has no certificate builder. The key touches disk only in a private
54
+ * scratch directory that is removed afterwards.
55
+ */
56
+ const generateRoot = (spec) => Effect.scoped(Effect.gen(function* makeRoot() {
57
+ const fs = yield* FileSystem.FileSystem;
58
+ const path = yield* Path.Path;
59
+ const scratch = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);
60
+ const files = {
61
+ cert: path.join(scratch, "ca.crt"),
62
+ config: path.join(scratch, "openssl.cnf"),
63
+ key: path.join(scratch, "ca.key")
64
+ };
65
+ const key = yield* ecKeyPem;
66
+ yield* Effect.all([fs.writeFileString(files.config, opensslConfig(spec)), fs.writeFileString(files.key, key, { mode: ownerOnly })]).pipe(Effect.orDie);
67
+ yield* openssl([
68
+ "req",
69
+ "-x509",
70
+ "-new",
71
+ "-key",
72
+ files.key,
73
+ "-sha256",
74
+ "-days",
75
+ String(validDays),
76
+ "-config",
77
+ files.config,
78
+ "-out",
79
+ files.cert
80
+ ]);
81
+ return {
82
+ cert: yield* fs.readFileString(files.cert).pipe(Effect.orDie),
83
+ key
84
+ };
85
+ }));
86
+ export { decodeDomains, generateRoot, refuseExisting };
87
+
88
+ //# sourceMappingURL=ca.js.map
package/dist/ca.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ca.js","names":[],"sources":["../src/ca.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { generateKeyPair } from 'node:crypto';\nimport { promisify } from 'node:util';\n\nimport { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { rootCommonName } from '@tafrahq/wt-tunnel-contract/root-ca';\nimport { Effect, FileSystem, Path, Schema } from 'effect';\n\nimport { InfraError } from './errors.ts';\n\nconst validDays = 3650;\nconst ownerOnly = 0o600;\n\n/** What a root is made from: the domains it may sign for, and the label in its name. */\ninterface RootSpec {\n readonly domains: readonly [Hostname, ...Hostname[]];\n /** Only a name, the deployment's tunnel host; the constraints alone decide what it may sign. */\n readonly label: string;\n}\n\n/**\n * The root's OpenSSL config. A config file rather than `-addext` flags, because LibreSSL (macOS's\n * `openssl`) reads the same file. No leading dot on a permitted name: the constraint then covers\n * the domain and every name under it. pathlen:1 leaves room for the intermediate Caddy signs.\n */\nconst opensslConfig = ({ domains, label }: RootSpec) =>\n [\n '[req]',\n 'distinguished_name = dn',\n 'prompt = no',\n 'x509_extensions = root',\n '[dn]',\n 'O = wt-tunnel',\n `CN = ${rootCommonName(label)}`,\n '[root]',\n 'basicConstraints = critical,CA:TRUE,pathlen:1',\n 'keyUsage = critical,keyCertSign,cRLSign',\n `nameConstraints = critical,${domains.map((domain) => `permitted;DNS:${domain}`).join(',')}`,\n 'subjectKeyIdentifier = hash',\n '',\n ].join('\\n');\n\nconst decodeDomains = (domains: readonly string[]) =>\n Schema.decodeUnknownEffect(Schema.NonEmptyArray(Hostname))(domains).pipe(\n Effect.mapError(\n () =>\n new InfraError({\n message: `every domain must be a lowercase DNS name with at least two labels, got ${domains.join(' ')}`,\n }),\n ),\n );\n\nconst openssl = (args: readonly string[]) =>\n Effect.callback<void, InfraError>((resume) => {\n execFile('openssl', [...args], { encoding: 'utf8' }, (failure: unknown, _stdout, stderr) => {\n const error = new InfraError({ message: `openssl failed: ${stderr || String(failure)}` });\n resume(failure === null ? Effect.void : Effect.fail(error));\n });\n });\n\nconst generateKeyPairAsync = promisify(generateKeyPair);\n\nconst ecKeyPem = Effect.tryPromise({\n catch: (cause) => new InfraError({ message: `cannot make the CA key: ${String(cause)}` }),\n try: async () => {\n const { privateKey } = await generateKeyPairAsync('ec', { namedCurve: 'P-256' });\n return privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();\n },\n});\n\nconst refuseExisting = (file: string, advice: string) =>\n FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(\n Effect.orDie,\n Effect.filterOrFail(\n (exists) => !exists,\n () => new InfraError({ message: `${file} already exists; ${advice}` }),\n ),\n );\n\n/**\n * A new root CA as PEM text: an EC P-256 root valid for 10 years, name-constrained to the domains,\n * so a device that trusts it trusts nothing else. Node makes the key; openssl signs the\n * certificate, since Node has no certificate builder. The key touches disk only in a private\n * scratch directory that is removed afterwards.\n */\nconst generateRoot = (spec: RootSpec) =>\n Effect.scoped(\n Effect.gen(function* makeRoot() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const scratch = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);\n const files = {\n cert: path.join(scratch, 'ca.crt'),\n config: path.join(scratch, 'openssl.cnf'),\n key: path.join(scratch, 'ca.key'),\n };\n const key = yield* ecKeyPem;\n yield* Effect.all([\n fs.writeFileString(files.config, opensslConfig(spec)),\n fs.writeFileString(files.key, key, { mode: ownerOnly }),\n ]).pipe(Effect.orDie);\n yield* openssl([\n 'req',\n '-x509',\n '-new',\n '-key',\n files.key,\n '-sha256',\n '-days',\n String(validDays),\n '-config',\n files.config,\n '-out',\n files.cert,\n ]);\n const cert = yield* fs.readFileString(files.cert).pipe(Effect.orDie);\n return { cert, key } as const;\n }),\n );\n\nexport { decodeDomains, generateRoot, refuseExisting };\nexport type { RootSpec };\n"],"mappings":";;;;;;;;AAUA,MAAM,YAAY;AAClB,MAAM,YAAY;;;;;;AAclB,MAAM,iBAAiB,EAAE,SAAS,YAChC;CACE;CACA;CACA;CACA;CACA;CACA;CACA,QAAQ,eAAe,KAAK;CAC5B;CACA;CACA;CACA,8BAA8B,QAAQ,KAAK,WAAW,iBAAiB,QAAQ,CAAC,CAAC,KAAK,GAAG;CACzF;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEb,MAAM,iBAAiB,YACrB,OAAO,oBAAoB,OAAO,cAAc,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,KAClE,OAAO,eAEH,IAAI,WAAW,EACb,SAAS,2EAA2E,QAAQ,KAAK,GAAG,IACtG,CAAC,CACL,CACF;AAEF,MAAM,WAAW,SACf,OAAO,UAA4B,WAAW;CAC5C,SAAS,WAAW,CAAC,GAAG,IAAI,GAAG,EAAE,UAAU,OAAO,IAAI,SAAkB,SAAS,WAAW;EAC1F,MAAM,QAAQ,IAAI,WAAW,EAAE,SAAS,mBAAmB,UAAU,OAAO,OAAO,IAAI,CAAC;EACxF,OAAO,YAAY,OAAO,OAAO,OAAO,OAAO,KAAK,KAAK,CAAC;CAC5D,CAAC;AACH,CAAC;AAEH,MAAM,uBAAuB,UAAU,eAAe;AAEtD,MAAM,WAAW,OAAO,WAAW;CACjC,QAAQ,UAAU,IAAI,WAAW,EAAE,SAAS,2BAA2B,OAAO,KAAK,IAAI,CAAC;CACxF,KAAK,YAAY;EACf,MAAM,EAAE,eAAe,MAAM,qBAAqB,MAAM,EAAE,YAAY,QAAQ,CAAC;EAC/E,OAAO,WAAW,OAAO;GAAE,QAAQ;GAAO,MAAM;EAAQ,CAAC,CAAC,CAAC,SAAS;CACtE;AACF,CAAC;AAED,MAAM,kBAAkB,MAAc,WACpC,WAAW,WAAW,KAAK,OAAO,GAAG,OAAO,IAAI,CAAC,CAAC,CAAC,KACjD,OAAO,OACP,OAAO,cACJ,WAAW,CAAC,cACP,IAAI,WAAW,EAAE,SAAS,GAAG,KAAK,mBAAmB,SAAS,CAAC,CACvE,CACF;;;;;;;AAQF,MAAM,gBAAgB,SACpB,OAAO,OACL,OAAO,IAAI,UAAU,WAAW;CAC9B,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,UAAU,OAAO,GAAG,wBAAwB,CAAC,CAAC,KAAK,OAAO,KAAK;CACrE,MAAM,QAAQ;EACZ,MAAM,KAAK,KAAK,SAAS,QAAQ;EACjC,QAAQ,KAAK,KAAK,SAAS,aAAa;EACxC,KAAK,KAAK,KAAK,SAAS,QAAQ;CAClC;CACA,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,IAAI,CAChB,GAAG,gBAAgB,MAAM,QAAQ,cAAc,IAAI,CAAC,GACpD,GAAG,gBAAgB,MAAM,KAAK,KAAK,EAAE,MAAM,UAAU,CAAC,CACxD,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK;CACpB,OAAO,QAAQ;EACb;EACA;EACA;EACA;EACA,MAAM;EACN;EACA;EACA,OAAO,SAAS;EAChB;EACA,MAAM;EACN;EACA,MAAM;CACR,CAAC;CAED,OAAO;EAAE,MAAA,OADW,GAAG,eAAe,MAAM,IAAI,CAAC,CAAC,KAAK,OAAO,KAAK;EACpD;CAAI;AACrB,CAAC,CACH"}
package/dist/cli.js ADDED
@@ -0,0 +1,182 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { runAlchemy, stackFile } from "./alchemy.js";
3
+ import { deployFileName, loadDeployConfig } from "./config.js";
4
+ import { createRoot } from "./create-root.js";
5
+ import { writeStarterConfig } from "./init.js";
6
+ import { decodeStackOutput, outputsReport } from "./outputs.js";
7
+ import { prepare, serverDirFor } from "./prepare.js";
8
+ import { Console, Effect, Option, Redacted } from "effect";
9
+ import { Argument, Command, Flag, Prompt } from "effect/cli";
10
+ // src/cli.ts
11
+ const configFlag = Flag.String("config").pipe(Flag.withDescription("The deploy file"), Flag.withDefault(deployFileName));
12
+ const yesFlag = Flag.Boolean("yes").pipe(Flag.withDescription("Apply without asking for approval of the plan"), Flag.withDefault(false));
13
+ const optionalString = (name, description) => Flag.String(name).pipe(Flag.withDescription(description), Flag.optional);
14
+ const repeatedString = (name, description) => Flag.String(name).pipe(Flag.withDescription(description), Flag.atLeast(0));
15
+ /** The flags that fill a new server folder. Once it exists, they are ignored. */
16
+ const createFlags = {
17
+ allowEmail: repeatedString("allow-email", "An email allowed to sign in (repeatable); for a new server folder"),
18
+ allowEmailDomain: repeatedString("allow-email-domain", "An email domain allowed to sign in (repeatable); for a new server folder"),
19
+ authHost: optionalString("auth-host", "The sign-in host, outside the dev domains; for a new server folder"),
20
+ caCert: optionalString("ca-cert", "An existing root's certificate; for a new server folder"),
21
+ caKey: optionalString("ca-key", "An existing root's key file; for a new server folder"),
22
+ domain: repeatedString("domain", "A dev domain (repeatable); for a new server folder")
23
+ };
24
+ const createInputs = (flags) => ({
25
+ allowEmailDomains: flags.allowEmailDomain,
26
+ allowEmails: flags.allowEmail,
27
+ authHost: Option.getOrUndefined(flags.authHost),
28
+ caCert: Option.getOrUndefined(flags.caCert),
29
+ caKey: Option.getOrUndefined(flags.caKey),
30
+ domains: flags.domain
31
+ });
32
+ const noCreateInputs = createInputs({
33
+ allowEmail: [],
34
+ allowEmailDomain: [],
35
+ authHost: Option.none(),
36
+ caCert: Option.none(),
37
+ caKey: Option.none(),
38
+ domain: []
39
+ });
40
+ const cancelled = () => new InfraError({ message: "cancelled" });
41
+ /** Prompts in the terminal, when stdin is one. */
42
+ const terminalAsk = {
43
+ interactive: process.stdin.isTTY,
44
+ line: (message) => Prompt.run(Prompt.String({ message })).pipe(Effect.mapError(cancelled)),
45
+ secret: (message) => Prompt.run(Prompt.Hidden({ message })).pipe(Effect.map((value) => Redacted.value(value)), Effect.mapError(cancelled))
46
+ };
47
+ const prepareFor = ({ config, version }, missing, inputs = noCreateInputs) => prepare({
48
+ ask: terminalAsk,
49
+ config,
50
+ env: process.env,
51
+ inputs,
52
+ missing,
53
+ version
54
+ });
55
+ /**
56
+ * Without a terminal, alchemy cannot ask for approval: it prints the plan and stops without
57
+ * applying it, and exits 0. Fail instead, so a script never mistakes that for success.
58
+ */
59
+ const checkApproval = (operation, yes, interactive) => operation === "plan" || yes || interactive ? Effect.void : Effect.fail(new InfraError({ message: `${operation} asks for approval, but stdin is not a terminal: pass --yes to apply without a prompt` }));
60
+ const stackRun = ({ cwd, deployment, env }, operation, yes) => checkApproval(operation, yes, process.stdin.isTTY).pipe(Effect.andThen(runAlchemy({
61
+ args: [
62
+ operation,
63
+ stackFile,
64
+ "--stage",
65
+ deployment.stage,
66
+ ...yes ? ["--yes"] : []
67
+ ],
68
+ cwd,
69
+ env
70
+ })));
71
+ const printOutputs = ({ cwd, deployment, env }) => runAlchemy({
72
+ args: [
73
+ "state",
74
+ "read",
75
+ `${deployment.stack}/${deployment.stage}/output`,
76
+ "--config",
77
+ stackFile,
78
+ "--no-input",
79
+ "--log-level",
80
+ "error"
81
+ ],
82
+ capture: true,
83
+ cwd,
84
+ env
85
+ }).pipe(Effect.flatMap(decodeStackOutput), Effect.flatMap((output) => Console.log(outputsReport(deployment, output))));
86
+ const alchemyCommand = (version) => Command.make("alchemy", {
87
+ args: Argument.String("arg").pipe(Argument.withDescription("The alchemy command and its arguments, after --"), Argument.variadic()),
88
+ config: configFlag
89
+ }, ({ args, config }) => prepareFor({
90
+ config,
91
+ version
92
+ }, "require").pipe(Effect.flatMap(({ cwd, env }) => runAlchemy({
93
+ args: [
94
+ ...args,
95
+ "--config",
96
+ stackFile
97
+ ],
98
+ cwd,
99
+ env
100
+ })))).pipe(Command.withDescription("Run another alchemy command against this deployment's stack, such as: alchemy -- state ls <stack>/<stage>"));
101
+ const prepareCommand = Command.make("prepare", {
102
+ config: configFlag,
103
+ ...createFlags
104
+ }, (flags) => Effect.gen(function* prepareServerDir() {
105
+ const loaded = yield* loadDeployConfig(flags.config);
106
+ const server = yield* serverDirFor({
107
+ ask: terminalAsk,
108
+ env: process.env,
109
+ inputs: createInputs(flags),
110
+ loaded,
111
+ missing: "create"
112
+ });
113
+ yield* Console.log(`${server.dir} is a valid server folder.`);
114
+ })).pipe(Command.withDescription("Create the server folder as deploy would, or check the existing one, without touching the cloud"));
115
+ const commands = (version) => {
116
+ const plan = Command.make("plan", {
117
+ config: configFlag,
118
+ ...createFlags
119
+ }, (flags) => prepareFor({
120
+ config: flags.config,
121
+ version
122
+ }, "preview", createInputs(flags)).pipe(Effect.flatMap((prepared) => stackRun(prepared, "plan", false)))).pipe(Command.withDescription("Show what deploy would create, change or delete. Without a server folder, preview the one deploy would create; write nothing."));
123
+ const deploy = Command.make("deploy", {
124
+ config: configFlag,
125
+ yes: yesFlag,
126
+ ...createFlags
127
+ }, (flags) => Effect.gen(function* deployStack() {
128
+ const prepared = yield* prepareFor({
129
+ config: flags.config,
130
+ version
131
+ }, "create", createInputs(flags));
132
+ yield* stackRun(prepared, "deploy", flags.yes);
133
+ yield* printOutputs(prepared);
134
+ })).pipe(Command.withDescription("Create the server folder if it is missing, else check it; then create or update the Fly app, its IPs, one secret per server file, the Machine and the DNS records"));
135
+ const destroy = Command.make("destroy", {
136
+ config: configFlag,
137
+ yes: yesFlag
138
+ }, ({ config, yes }) => prepareFor({
139
+ config,
140
+ version
141
+ }, "require").pipe(Effect.flatMap((prepared) => stackRun(prepared, "destroy", yes)))).pipe(Command.withDescription("Delete everything deploy created"));
142
+ const outputs = Command.make("outputs", { config: configFlag }, ({ config }) => prepareFor({
143
+ config,
144
+ version
145
+ }, "require").pipe(Effect.flatMap(printOutputs))).pipe(Command.withDescription("Print the app, its IPs, the tunnel host and the CA page, and the DNS records to create in manual zones"));
146
+ return [
147
+ prepareCommand,
148
+ plan,
149
+ deploy,
150
+ destroy,
151
+ outputs,
152
+ alchemyCommand(version)
153
+ ];
154
+ };
155
+ const init = Command.make("init", {}, () => writeStarterConfig(process.cwd()).pipe(Effect.flatMap(Console.log))).pipe(Command.withDescription(`Write a commented starter ${deployFileName} and a .gitignore for the server folder here, and list the secrets to create`));
156
+ const caCreate = Command.make("create", {
157
+ config: configFlag,
158
+ domains: Argument.String("domain").pipe(Argument.withDescription("A dev domain the root may sign for, with every name under it. Default: the server config's domains"), Argument.variadic()),
159
+ force: Flag.Boolean("force").pipe(Flag.withDescription("Replace an existing root. Every device that trusts the old root must then trust the new one."), Flag.withDefault(false)),
160
+ name: optionalString("name", "The label in the root's name, wt-tunnel root (<label>). Default: the deploy file's tunnelHost, else the first domain. Only a name: the name constraints, the domains, decide what the root may sign."),
161
+ outDir: optionalString("out-dir", "Where to write ca.crt and ca.key. Default: the deploy file's server folder, .server")
162
+ }, (input) => createRoot({
163
+ ask: terminalAsk,
164
+ deployFile: input.config,
165
+ domains: input.domains,
166
+ force: input.force,
167
+ name: Option.getOrUndefined(input.name),
168
+ outDir: Option.getOrUndefined(input.outDir)
169
+ }).pipe(Effect.flatMap(({ cert, domains, key, label }) => Console.log(`Wrote ${cert} and ${key} (readable by you only): wt-tunnel root (${label}), name-constrained to ${domains.join(", ")}. wt-tunnel deploy uploads them with the server config. Keep the key secret, and back it up with the rest of the folder.`)))).pipe(Command.withDescription("Create a root CA name-constrained to the dev domains, in the server folder"));
170
+ const ca = Command.make("ca").pipe(Command.withDescription("Manage the deployment's root CA"), Command.withSubcommands([caCreate]));
171
+ const description = "Set up the wt-tunnel server on Fly.io: a deploy file says where it runs, the server folder what it does";
172
+ const run = (version) => {
173
+ const cli = Command.make("wt-tunnel").pipe(Command.withDescription(description), Command.withSubcommands([
174
+ init,
175
+ ca,
176
+ ...commands(version)
177
+ ]));
178
+ return Command.run(cli, { version });
179
+ };
180
+ export { checkApproval, run };
181
+
182
+ //# sourceMappingURL=cli.js.map