@tafrahq/wt-tunnel 0.7.0 → 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.
- package/README.md +41 -29
- package/dist/bin.js +8 -14
- package/dist/bin.js.map +1 -1
- package/dist/ca.js +1 -1
- package/dist/ca.js.map +1 -1
- package/dist/cli.js +14 -49
- package/dist/cli.js.map +1 -1
- package/dist/config.js +32 -7
- package/dist/config.js.map +1 -1
- package/dist/create-root.js +10 -17
- package/dist/create-root.js.map +1 -1
- package/dist/create-server-dir.js +42 -45
- package/dist/create-server-dir.js.map +1 -1
- package/dist/deployment.js +12 -2
- package/dist/deployment.js.map +1 -1
- package/dist/errors.js +4 -2
- package/dist/errors.js.map +1 -1
- package/dist/init.js +22 -6
- package/dist/init.js.map +1 -1
- package/dist/packages/contract/src/bin.js +20 -0
- package/dist/packages/contract/src/bin.js.map +1 -0
- package/dist/packages/contract/src/server-config.js +1 -1
- package/dist/packages/contract/src/server-config.js.map +1 -1
- package/dist/prepare.js +85 -16
- package/dist/prepare.js.map +1 -1
- package/dist/seed-drift.js +51 -0
- package/dist/seed-drift.js.map +1 -0
- package/dist/server-dir.js +24 -14
- package/dist/server-dir.js.map +1 -1
- package/dist/server-machine.js.map +1 -1
- package/dist/stack.js +2 -2
- package/dist/stack.js.map +1 -1
- package/package.json +13 -9
package/README.md
CHANGED
|
@@ -16,11 +16,15 @@ A change to any file in the server folder rolls the Machine, because the Machine
|
|
|
16
16
|
|
|
17
17
|
## Install
|
|
18
18
|
|
|
19
|
+
The package is published to npm:
|
|
20
|
+
|
|
19
21
|
```sh
|
|
20
22
|
npm install -g @tafrahq/wt-tunnel
|
|
21
23
|
```
|
|
22
24
|
|
|
23
|
-
|
|
25
|
+
To build it from a checkout instead, see the [root README](../../README.md#install).
|
|
26
|
+
|
|
27
|
+
It needs Node.js 26 or later, and `openssl` to sign a new root CA.
|
|
24
28
|
|
|
25
29
|
## Set up a deployment
|
|
26
30
|
|
|
@@ -37,8 +41,11 @@ wt-tunnel init
|
|
|
37
41
|
|
|
38
42
|
```json
|
|
39
43
|
{
|
|
40
|
-
"
|
|
44
|
+
"server": { "provider": "flyio", "org": "my-org", "app": "wt-tunnel-my-org", "region": "ams" },
|
|
41
45
|
"tunnelHost": "wt-tunnel.example.com",
|
|
46
|
+
"authHost": "auth-wt-tunnel.example.com",
|
|
47
|
+
"domains": ["dev.example.com", "dev.example.net"],
|
|
48
|
+
"allow": { "emails": ["someone@example.org"], "emailDomains": ["example.com"] },
|
|
42
49
|
"dns": [
|
|
43
50
|
{
|
|
44
51
|
"provider": "cloudflare",
|
|
@@ -56,18 +63,23 @@ wt-tunnel init
|
|
|
56
63
|
}
|
|
57
64
|
```
|
|
58
65
|
|
|
59
|
-
| Field
|
|
60
|
-
|
|
|
61
|
-
| `
|
|
62
|
-
| `
|
|
63
|
-
| `
|
|
64
|
-
| `
|
|
65
|
-
| `
|
|
66
|
-
| `
|
|
67
|
-
| `
|
|
68
|
-
| `
|
|
69
|
-
| `
|
|
70
|
-
| `
|
|
66
|
+
| Field | Required | Meaning |
|
|
67
|
+
| ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
68
|
+
| `server.provider` | yes | Where the server runs. `"flyio"`, the only provider for now; the fields below are Fly.io's. |
|
|
69
|
+
| `server.org` | yes | The Fly organization slug, as `fly orgs list` shows it. |
|
|
70
|
+
| `server.app` | yes | The Fly app name. Fly app names are global. |
|
|
71
|
+
| `server.region` | yes | The Fly region, such as `ams` or `iad`. |
|
|
72
|
+
| `server.memoryMb` | no | The Machine's memory. Default 512. |
|
|
73
|
+
| `tunnelHost` | yes | The host tunnel clients connect to. A new root CA is named after it. |
|
|
74
|
+
| `authHost` | yes | The sign-in host, shared by every dev domain and outside all of them; see [the sign-in host](#the-sign-in-host). A zone in `dns` must cover it, like the tunnel host. The server folder's config names it too, and a deploy stops if the two differ. |
|
|
75
|
+
| `domains` | new | The dev domains of a new server folder. Worktree URLs are `https://<app>.<worktree>.<domain>`, and a new root may sign only for these and the names under them. Once `.server/` exists, its config's `domains` are used and this is ignored. |
|
|
76
|
+
| `allow` | new | Who may sign in on a new server folder: `{ "emails": [...], "emailDomains": [...] }`, at least one entry. Once `.server/` exists, its config's `allow` is used and this is ignored. |
|
|
77
|
+
| `ca` | no | For a new server folder: `cert` and `key` use an existing root, paths relative to the deploy file; `name` labels a new root, `wt-tunnel root (<name>)`, by default the tunnel host. See [the root CA](#the-root-ca). |
|
|
78
|
+
| `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. |
|
|
79
|
+
| `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. The Worker is the account's default Alchemy store, `alchemy-state-store`, which every Alchemy project in the account shares; Alchemy creates it on first use. Add `"name"` (lowercase letters, digits and dashes, up to 43) to use the store `alchemy-state-store-<name>` instead, such as one another Alchemy project made. Only an Alchemy state store works here, not any Worker. Its URL is that Worker's on the account's workers.dev subdomain. `"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. |
|
|
80
|
+
| `image` | no | The server image. Default: `ghcr.io/tafrahq/wt-tunnel-server:<version>`, where `<version>` is this CLI's version. |
|
|
81
|
+
| `serverDir` | no | The server folder, relative to the deploy file. Default `.server`. |
|
|
82
|
+
| `stack`, `stage` | no | Alchemy's names for the deployment. Default `wt-tunnel-server` and `prod`. |
|
|
71
83
|
|
|
72
84
|
The file may contain `//` and `/* */` comments. Pass `--config <file>` to use another path.
|
|
73
85
|
|
|
@@ -75,8 +87,11 @@ Cloudflare is optional. This deploy file needs no Cloudflare account: you create
|
|
|
75
87
|
|
|
76
88
|
```json
|
|
77
89
|
{
|
|
78
|
-
"
|
|
90
|
+
"server": { "provider": "flyio", "org": "personal", "app": "wt-tunnel-my-team", "region": "ams" },
|
|
79
91
|
"tunnelHost": "wt-tunnel.example.com",
|
|
92
|
+
"authHost": "auth-wt-tunnel.example.com",
|
|
93
|
+
"domains": ["dev.example.com"],
|
|
94
|
+
"allow": { "emailDomains": ["example.com"] },
|
|
80
95
|
"dns": [{ "provider": "manual", "zone": "example.com" }],
|
|
81
96
|
"state": "local"
|
|
82
97
|
}
|
|
@@ -118,19 +133,14 @@ To add or remove a provider later, edit `providers` in `.server/wt-tunnel-server
|
|
|
118
133
|
### 3. Deploy
|
|
119
134
|
|
|
120
135
|
```sh
|
|
121
|
-
wt-tunnel deploy
|
|
122
|
-
--allow-email someone@example.com --allow-email-domain example.com
|
|
136
|
+
wt-tunnel deploy
|
|
123
137
|
```
|
|
124
138
|
|
|
125
|
-
The first deploy creates `.server
|
|
139
|
+
The first deploy creates `.server/` from the deploy file: its `authHost`, `domains` and `allow`, and its `ca` if it sets one. It takes the sign-in providers' clients from the environment, and at a terminal asks for any that are missing, with each secret's input hidden. Without `domains` or `allow`, or, without a terminal as in CI, without a provider's variables, it fails and names everything missing. 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.
|
|
126
140
|
|
|
127
|
-
-
|
|
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.
|
|
141
|
+
After that, `.server/wt-tunnel-server.json` decides what the server does. You may keep `domains` and `allow` in the deploy file as a record: a later deploy compares them with the server config, in any order, and warns only when they differ. `wt-tunnel deploy --force` (or `prepare --force`) then copies them into the server config, keeping everything else in it, after checking the folder with them, so a domain the root cannot sign for stops it before anything is written. A deploy never replaces the root: when `ca` names another root or label, it only warns, and `wt-tunnel ca create --force` is the way to make a new one.
|
|
130
142
|
|
|
131
|
-
|
|
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`.
|
|
143
|
+
`wt-tunnel prepare` 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
144
|
|
|
135
145
|
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
146
|
|
|
@@ -151,7 +161,7 @@ For anything else Alchemy can do, `wt-tunnel alchemy -- <command>` runs that alc
|
|
|
151
161
|
|
|
152
162
|
### The sign-in host
|
|
153
163
|
|
|
154
|
-
Each device opens the sign-in host (
|
|
164
|
+
Each device opens the sign-in host (`authHost` in the deploy file and the server 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
165
|
|
|
156
166
|
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
167
|
|
|
@@ -200,11 +210,13 @@ Dev hosts use certificates from the deployment's own root, an EC P-256 root vali
|
|
|
200
210
|
|
|
201
211
|
When the first deploy creates the folder, it decides the root so that a root devices already trust is never replaced by accident:
|
|
202
212
|
|
|
203
|
-
- The certificate comes from
|
|
204
|
-
- The key comes from
|
|
213
|
+
- The certificate comes from the deploy file's `ca.cert`, else `ca.crt` in the server folder, else `ca.crt` next to the deploy file.
|
|
214
|
+
- The key comes from the deploy file's `ca.key`, `WT_CA_KEY`, `WT_CA_KEY_FILE`, else `ca.key` in the same two places.
|
|
205
215
|
- 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
216
|
|
|
207
|
-
`wt-tunnel ca create
|
|
217
|
+
`wt-tunnel ca create` 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. It names the server config's domains, else the deploy file's, and labels the root with the deploy file's `ca.name`, else its tunnel host. It refuses to replace an existing root unless you pass `--force`, because every device must then trust the new one.
|
|
218
|
+
|
|
219
|
+
The name constraints are signed into the root, so it can never cover another domain. To add a dev domain, add it to `domains` in `.server/wt-tunnel-server.json`; the next deploy stops and says the root does not cover it. Then run `wt-tunnel ca create --force`, deploy, and trust the new root on each device from `https://<authHost>/ca`. List the domains you expect to need when you first make the root, to save the devices that step.
|
|
208
220
|
|
|
209
221
|
## Upgrade
|
|
210
222
|
|
|
@@ -218,7 +230,7 @@ Alchemy's `Fly.Machine` has no `files`. The stack registers its own provider for
|
|
|
218
230
|
|
|
219
231
|
## Develop
|
|
220
232
|
|
|
221
|
-
`
|
|
233
|
+
`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` builds `dist/`. To run the workspace build, start it from your deployment directory:
|
|
222
234
|
|
|
223
235
|
```sh
|
|
224
236
|
cd /path/to/my-wt-tunnel
|
package/dist/bin.js
CHANGED
|
@@ -1,21 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { binProgram } from "./packages/contract/src/bin.js";
|
|
2
3
|
import { run } from "./cli.js";
|
|
3
|
-
import { createRequire } from "node:module";
|
|
4
4
|
import { NodeRuntime, NodeServices } from "@effect/platform-node";
|
|
5
|
-
import {
|
|
5
|
+
import { Effect } from "effect";
|
|
6
6
|
// src/bin.ts
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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);
|
|
7
|
+
const program = binProgram({
|
|
8
|
+
expected: "InfraError",
|
|
9
|
+
name: "wt-tunnel",
|
|
10
|
+
url: import.meta.url
|
|
11
|
+
}, run);
|
|
12
|
+
NodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)));
|
|
19
13
|
export {};
|
|
20
14
|
|
|
21
15
|
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\
|
|
1
|
+
{"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\n// fallow-ignore-file coverage-gaps -- only hands cli.ts's run to NodeRuntime; cli.test.ts runs run in-process, and packages/contract/src/bin.test.ts tests binProgram\nimport { NodeRuntime, NodeServices } from '@effect/platform-node';\nimport { binProgram } from '@tafrahq/wt-tunnel-contract/bin';\nimport { Effect } from 'effect';\n\nimport { run } from './cli.ts';\n\nconst program = binProgram(\n { expected: 'InfraError', name: 'wt-tunnel', url: import.meta.url },\n run,\n);\n\nNodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)));\n"],"mappings":";;;;;;AAQA,MAAM,UAAU,WACd;CAAE,UAAU;CAAc,MAAM;CAAa,KAAK,YAAY;AAAI,GAClE,GACF;AAEA,YAAY,QAAQ,QAAQ,KAAK,OAAO,QAAQ,aAAa,KAAK,CAAC,CAAC"}
|
package/dist/ca.js
CHANGED
|
@@ -43,7 +43,7 @@ const ecKeyPem = Effect.tryPromise({
|
|
|
43
43
|
return privateKey.export({
|
|
44
44
|
format: "pem",
|
|
45
45
|
type: "pkcs8"
|
|
46
|
-
})
|
|
46
|
+
});
|
|
47
47
|
}
|
|
48
48
|
});
|
|
49
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}` })));
|
package/dist/ca.js.map
CHANGED
|
@@ -1 +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' })
|
|
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' });\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,MAA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;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
CHANGED
|
@@ -5,38 +5,12 @@ import { createRoot } from "./create-root.js";
|
|
|
5
5
|
import { writeStarterConfig } from "./init.js";
|
|
6
6
|
import { decodeStackOutput, outputsReport } from "./outputs.js";
|
|
7
7
|
import { prepare, serverDirFor } from "./prepare.js";
|
|
8
|
-
import { Console, Effect,
|
|
8
|
+
import { Console, Effect, Redacted } from "effect";
|
|
9
9
|
import { Argument, Command, Flag, Prompt } from "effect/cli";
|
|
10
10
|
// src/cli.ts
|
|
11
11
|
const configFlag = Flag.String("config").pipe(Flag.withDescription("The deploy file"), Flag.withDefault(deployFileName));
|
|
12
|
+
const forceFlag = Flag.Boolean("force").pipe(Flag.withDescription("Copy the deploy file's domains and allow into the existing server config, where they differ. Never replaces the root: use wt-tunnel ca create --force for that."), Flag.withDefault(false));
|
|
12
13
|
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
14
|
const cancelled = () => new InfraError({ message: "cancelled" });
|
|
41
15
|
/** Prompts in the terminal, when stdin is one. */
|
|
42
16
|
const terminalAsk = {
|
|
@@ -44,11 +18,11 @@ const terminalAsk = {
|
|
|
44
18
|
line: (message) => Prompt.run(Prompt.String({ message })).pipe(Effect.mapError(cancelled)),
|
|
45
19
|
secret: (message) => Prompt.run(Prompt.Hidden({ message })).pipe(Effect.map((value) => Redacted.value(value)), Effect.mapError(cancelled))
|
|
46
20
|
};
|
|
47
|
-
const prepareFor = ({ config, version }, missing
|
|
21
|
+
const prepareFor = ({ config, force = false, version }, missing) => prepare({
|
|
48
22
|
ask: terminalAsk,
|
|
49
23
|
config,
|
|
50
24
|
env: process.env,
|
|
51
|
-
|
|
25
|
+
force,
|
|
52
26
|
missing,
|
|
53
27
|
version
|
|
54
28
|
});
|
|
@@ -100,35 +74,33 @@ const alchemyCommand = (version) => Command.make("alchemy", {
|
|
|
100
74
|
})))).pipe(Command.withDescription("Run another alchemy command against this deployment's stack, such as: alchemy -- state ls <stack>/<stage>"));
|
|
101
75
|
const prepareCommand = Command.make("prepare", {
|
|
102
76
|
config: configFlag,
|
|
103
|
-
|
|
77
|
+
force: forceFlag
|
|
104
78
|
}, (flags) => Effect.gen(function* prepareServerDir() {
|
|
105
79
|
const loaded = yield* loadDeployConfig(flags.config);
|
|
106
80
|
const server = yield* serverDirFor({
|
|
107
81
|
ask: terminalAsk,
|
|
108
82
|
env: process.env,
|
|
109
|
-
|
|
83
|
+
force: flags.force,
|
|
110
84
|
loaded,
|
|
111
85
|
missing: "create"
|
|
112
86
|
});
|
|
113
87
|
yield* Console.log(`${server.dir} is a valid server folder.`);
|
|
114
88
|
})).pipe(Command.withDescription("Create the server folder as deploy would, or check the existing one, without touching the cloud"));
|
|
115
89
|
const commands = (version) => {
|
|
116
|
-
const plan = Command.make("plan", {
|
|
117
|
-
config: configFlag,
|
|
118
|
-
...createFlags
|
|
119
|
-
}, (flags) => prepareFor({
|
|
90
|
+
const plan = Command.make("plan", { config: configFlag }, (flags) => prepareFor({
|
|
120
91
|
config: flags.config,
|
|
121
92
|
version
|
|
122
|
-
}, "preview"
|
|
93
|
+
}, "preview").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
94
|
const deploy = Command.make("deploy", {
|
|
124
95
|
config: configFlag,
|
|
125
|
-
|
|
126
|
-
|
|
96
|
+
force: forceFlag,
|
|
97
|
+
yes: yesFlag
|
|
127
98
|
}, (flags) => Effect.gen(function* deployStack() {
|
|
128
99
|
const prepared = yield* prepareFor({
|
|
129
100
|
config: flags.config,
|
|
101
|
+
force: flags.force,
|
|
130
102
|
version
|
|
131
|
-
}, "create"
|
|
103
|
+
}, "create");
|
|
132
104
|
yield* stackRun(prepared, "deploy", flags.yes);
|
|
133
105
|
yield* printOutputs(prepared);
|
|
134
106
|
})).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"));
|
|
@@ -155,17 +127,10 @@ const commands = (version) => {
|
|
|
155
127
|
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
128
|
const caCreate = Command.make("create", {
|
|
157
129
|
config: configFlag,
|
|
158
|
-
|
|
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")
|
|
130
|
+
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))
|
|
162
131
|
}, (input) => createRoot({
|
|
163
|
-
ask: terminalAsk,
|
|
164
132
|
deployFile: input.config,
|
|
165
|
-
|
|
166
|
-
force: input.force,
|
|
167
|
-
name: Option.getOrUndefined(input.name),
|
|
168
|
-
outDir: Option.getOrUndefined(input.outDir)
|
|
133
|
+
force: input.force
|
|
169
134
|
}).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
135
|
const ca = Command.make("ca").pipe(Command.withDescription("Manage the deployment's root CA"), Command.withSubcommands([caCreate]));
|
|
171
136
|
const description = "Set up the wt-tunnel server on Fly.io: a deploy file says where it runs, the server folder what it does";
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { Console, Effect, Option, Redacted } from 'effect';\nimport { Argument, Command, Flag, Prompt } from 'effect/cli';\n\nimport { runAlchemy, stackFile } from './alchemy.ts';\nimport { deployFileName, loadDeployConfig } from './config.ts';\nimport { createRoot } from './create-root.ts';\nimport type { Ask, CreateInputs } from './create-server-dir.ts';\nimport { InfraError } from './errors.ts';\nimport { writeStarterConfig } from './init.ts';\nimport { decodeStackOutput, outputsReport } from './outputs.ts';\nimport { prepare, serverDirFor } from './prepare.ts';\nimport type { Missing, Prepared } from './prepare.ts';\n\nconst configFlag = Flag.String('config').pipe(\n Flag.withDescription('The deploy file'),\n Flag.withDefault(deployFileName),\n);\n\nconst yesFlag = Flag.Boolean('yes').pipe(\n Flag.withDescription('Apply without asking for approval of the plan'),\n Flag.withDefault(false),\n);\n\nconst optionalString = (name: string, description: string) =>\n Flag.String(name).pipe(Flag.withDescription(description), Flag.optional);\n\nconst repeatedString = (name: string, description: string) =>\n Flag.String(name).pipe(Flag.withDescription(description), Flag.atLeast(0));\n\n/** The flags that fill a new server folder. Once it exists, they are ignored. */\nconst createFlags = {\n allowEmail: repeatedString(\n 'allow-email',\n 'An email allowed to sign in (repeatable); for a new server folder',\n ),\n allowEmailDomain: repeatedString(\n 'allow-email-domain',\n 'An email domain allowed to sign in (repeatable); for a new server folder',\n ),\n authHost: optionalString(\n 'auth-host',\n 'The sign-in host, outside the dev domains; for a new server folder',\n ),\n caCert: optionalString('ca-cert', \"An existing root's certificate; for a new server folder\"),\n caKey: optionalString('ca-key', \"An existing root's key file; for a new server folder\"),\n domain: repeatedString('domain', 'A dev domain (repeatable); for a new server folder'),\n};\n\ninterface CreateFlagValues {\n readonly allowEmail: readonly string[];\n readonly allowEmailDomain: readonly string[];\n readonly authHost: Option.Option<string>;\n readonly caCert: Option.Option<string>;\n readonly caKey: Option.Option<string>;\n readonly domain: readonly string[];\n}\n\nconst createInputs = (flags: CreateFlagValues): CreateInputs => ({\n allowEmailDomains: flags.allowEmailDomain,\n allowEmails: flags.allowEmail,\n authHost: Option.getOrUndefined(flags.authHost),\n caCert: Option.getOrUndefined(flags.caCert),\n caKey: Option.getOrUndefined(flags.caKey),\n domains: flags.domain,\n});\n\nconst noCreateInputs = createInputs({\n allowEmail: [],\n allowEmailDomain: [],\n authHost: Option.none(),\n caCert: Option.none(),\n caKey: Option.none(),\n domain: [],\n});\n\nconst cancelled = () => new InfraError({ message: 'cancelled' });\n\n/** Prompts in the terminal, when stdin is one. */\nconst terminalAsk: Ask = {\n interactive: process.stdin.isTTY,\n line: (message) => Prompt.run(Prompt.String({ message })).pipe(Effect.mapError(cancelled)),\n secret: (message) =>\n Prompt.run(Prompt.Hidden({ message })).pipe(\n Effect.map((value) => Redacted.value(value)),\n Effect.mapError(cancelled),\n ),\n};\n\nconst prepareFor = (\n { config, version }: { readonly config: string; readonly version: string },\n missing: Missing,\n inputs = noCreateInputs,\n) => prepare({ ask: terminalAsk, config, env: process.env, inputs, missing, version });\n\ntype Operation = 'deploy' | 'destroy' | 'plan';\n\n/**\n * Without a terminal, alchemy cannot ask for approval: it prints the plan and stops without\n * applying it, and exits 0. Fail instead, so a script never mistakes that for success.\n */\nconst checkApproval = (operation: Operation, yes: boolean, interactive: boolean) =>\n operation === 'plan' || yes || interactive\n ? Effect.void\n : Effect.fail(\n new InfraError({\n message: `${operation} asks for approval, but stdin is not a terminal: pass --yes to apply without a prompt`,\n }),\n );\n\nconst stackRun = ({ cwd, deployment, env }: Prepared, operation: Operation, yes: boolean) =>\n checkApproval(operation, yes, process.stdin.isTTY).pipe(\n Effect.andThen(\n runAlchemy({\n args: [operation, stackFile, '--stage', deployment.stage, ...(yes ? ['--yes'] : [])],\n cwd,\n env,\n }),\n ),\n );\n\nconst printOutputs = ({ cwd, deployment, env }: Prepared) =>\n runAlchemy({\n args: [\n 'state',\n 'read',\n `${deployment.stack}/${deployment.stage}/output`,\n '--config',\n stackFile,\n '--no-input',\n // Alchemy logs to stdout; below error level a log line would break the JSON.\n '--log-level',\n 'error',\n ],\n capture: true,\n cwd,\n env,\n }).pipe(\n Effect.flatMap(decodeStackOutput),\n Effect.flatMap((output) => Console.log(outputsReport(deployment, output))),\n );\n\nconst alchemyCommand = (version: string) =>\n Command.make(\n 'alchemy',\n {\n args: Argument.String('arg').pipe(\n Argument.withDescription('The alchemy command and its arguments, after --'),\n Argument.variadic(),\n ),\n config: configFlag,\n },\n ({ args, config }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap(({ cwd, env }) =>\n runAlchemy({ args: [...args, '--config', stackFile], cwd, env }),\n ),\n ),\n ).pipe(\n Command.withDescription(\n \"Run another alchemy command against this deployment's stack, such as: alchemy -- state ls <stack>/<stage>\",\n ),\n );\n\nconst prepareCommand = Command.make('prepare', { config: configFlag, ...createFlags }, (flags) =>\n Effect.gen(function* prepareServerDir() {\n const loaded = yield* loadDeployConfig(flags.config);\n const server = yield* serverDirFor({\n ask: terminalAsk,\n env: process.env,\n inputs: createInputs(flags),\n loaded,\n missing: 'create',\n });\n yield* Console.log(`${server.dir} is a valid server folder.`);\n }),\n).pipe(\n Command.withDescription(\n 'Create the server folder as deploy would, or check the existing one, without touching the cloud',\n ),\n);\n\nconst commands = (version: string) => {\n const plan = Command.make('plan', { config: configFlag, ...createFlags }, (flags) =>\n prepareFor({ config: flags.config, version }, 'preview', createInputs(flags)).pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'plan', false)),\n ),\n ).pipe(\n Command.withDescription(\n 'Show what deploy would create, change or delete. Without a server folder, preview the one deploy would create; write nothing.',\n ),\n );\n\n const deploy = Command.make(\n 'deploy',\n { config: configFlag, yes: yesFlag, ...createFlags },\n (flags) =>\n Effect.gen(function* deployStack() {\n const prepared = yield* prepareFor(\n { config: flags.config, version },\n 'create',\n createInputs(flags),\n );\n yield* stackRun(prepared, 'deploy', flags.yes);\n yield* printOutputs(prepared);\n }),\n ).pipe(\n Command.withDescription(\n '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',\n ),\n );\n\n const destroy = Command.make('destroy', { config: configFlag, yes: yesFlag }, ({ config, yes }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'destroy', yes)),\n ),\n ).pipe(Command.withDescription('Delete everything deploy created'));\n\n const outputs = Command.make('outputs', { config: configFlag }, ({ config }) =>\n prepareFor({ config, version }, 'require').pipe(Effect.flatMap(printOutputs)),\n ).pipe(\n Command.withDescription(\n 'Print the app, its IPs, the tunnel host and the CA page, and the DNS records to create in manual zones',\n ),\n );\n\n return [prepareCommand, plan, deploy, destroy, outputs, alchemyCommand(version)];\n};\n\nconst init = Command.make('init', {}, () =>\n writeStarterConfig(process.cwd()).pipe(Effect.flatMap(Console.log)),\n).pipe(\n Command.withDescription(\n `Write a commented starter ${deployFileName} and a .gitignore for the server folder here, and list the secrets to create`,\n ),\n);\n\nconst caCreate = Command.make(\n 'create',\n {\n config: configFlag,\n domains: Argument.String('domain').pipe(\n Argument.withDescription(\n \"A dev domain the root may sign for, with every name under it. Default: the server config's domains\",\n ),\n Argument.variadic(),\n ),\n force: Flag.Boolean('force').pipe(\n Flag.withDescription(\n 'Replace an existing root. Every device that trusts the old root must then trust the new one.',\n ),\n Flag.withDefault(false),\n ),\n name: optionalString(\n 'name',\n \"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.\",\n ),\n outDir: optionalString(\n 'out-dir',\n \"Where to write ca.crt and ca.key. Default: the deploy file's server folder, .server\",\n ),\n },\n (input) =>\n createRoot({\n ask: terminalAsk,\n deployFile: input.config,\n domains: input.domains,\n force: input.force,\n name: Option.getOrUndefined(input.name),\n outDir: Option.getOrUndefined(input.outDir),\n }).pipe(\n Effect.flatMap(({ cert, domains, key, label }) =>\n Console.log(\n `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.`,\n ),\n ),\n ),\n).pipe(\n Command.withDescription(\n 'Create a root CA name-constrained to the dev domains, in the server folder',\n ),\n);\n\nconst ca = Command.make('ca').pipe(\n Command.withDescription(\"Manage the deployment's root CA\"),\n Command.withSubcommands([caCreate]),\n);\n\nconst description =\n 'Set up the wt-tunnel server on Fly.io: a deploy file says where it runs, the server folder what it does';\n\nconst run = (version: string) => {\n const cli = Command.make('wt-tunnel').pipe(\n Command.withDescription(description),\n Command.withSubcommands([init, ca, ...commands(version)]),\n );\n return Command.run(cli, { version });\n};\n\nexport { checkApproval, run };\n"],"mappings":";;;;;;;;;;AAaA,MAAM,aAAa,KAAK,OAAO,QAAQ,CAAC,CAAC,KACvC,KAAK,gBAAgB,iBAAiB,GACtC,KAAK,YAAY,cAAc,CACjC;AAEA,MAAM,UAAU,KAAK,QAAQ,KAAK,CAAC,CAAC,KAClC,KAAK,gBAAgB,+CAA+C,GACpE,KAAK,YAAY,KAAK,CACxB;AAEA,MAAM,kBAAkB,MAAc,gBACpC,KAAK,OAAO,IAAI,CAAC,CAAC,KAAK,KAAK,gBAAgB,WAAW,GAAG,KAAK,QAAQ;AAEzE,MAAM,kBAAkB,MAAc,gBACpC,KAAK,OAAO,IAAI,CAAC,CAAC,KAAK,KAAK,gBAAgB,WAAW,GAAG,KAAK,QAAQ,CAAC,CAAC;;AAG3E,MAAM,cAAc;CAClB,YAAY,eACV,eACA,mEACF;CACA,kBAAkB,eAChB,sBACA,0EACF;CACA,UAAU,eACR,aACA,oEACF;CACA,QAAQ,eAAe,WAAW,yDAAyD;CAC3F,OAAO,eAAe,UAAU,sDAAsD;CACtF,QAAQ,eAAe,UAAU,oDAAoD;AACvF;AAWA,MAAM,gBAAgB,WAA2C;CAC/D,mBAAmB,MAAM;CACzB,aAAa,MAAM;CACnB,UAAU,OAAO,eAAe,MAAM,QAAQ;CAC9C,QAAQ,OAAO,eAAe,MAAM,MAAM;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,OAAO,KAAK,QAAQ,OAAO,CAAC,CAAC,KAC3B,KAAK,gBACH,8FACF,GACA,KAAK,YAAY,KAAK,CACxB;CACA,MAAM,eACJ,QACA,sMACF;CACA,QAAQ,eACN,WACA,qFACF;AACF,IACC,UACC,WAAW;CACT,KAAK;CACL,YAAY,MAAM;CAClB,SAAS,MAAM;CACf,OAAO,MAAM;CACb,MAAM,OAAO,eAAe,MAAM,IAAI;CACtC,QAAQ,OAAO,eAAe,MAAM,MAAM;AAC5C,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,EAAE,MAAM,SAAS,KAAK,YACpC,QAAQ,IACN,SAAS,KAAK,OAAO,IAAI,2CAA2C,MAAM,yBAAyB,QAAQ,KAAK,IAAI,EAAE,yHACxH,CACF,CACF,CACJ,CAAC,CAAC,KACA,QAAQ,gBACN,4EACF,CACF;AAEA,MAAM,KAAK,QAAQ,KAAK,IAAI,CAAC,CAAC,KAC5B,QAAQ,gBAAgB,iCAAiC,GACzD,QAAQ,gBAAgB,CAAC,QAAQ,CAAC,CACpC;AAEA,MAAM,cACJ;AAEF,MAAM,OAAO,YAAoB;CAC/B,MAAM,MAAM,QAAQ,KAAK,WAAW,CAAC,CAAC,KACpC,QAAQ,gBAAgB,WAAW,GACnC,QAAQ,gBAAgB;EAAC;EAAM;EAAI,GAAG,SAAS,OAAO;CAAC,CAAC,CAC1D;CACA,OAAO,QAAQ,IAAI,KAAK,EAAE,QAAQ,CAAC;AACrC"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { Console, Effect, Redacted } from 'effect';\nimport { Argument, Command, Flag, Prompt } from 'effect/cli';\n\nimport { runAlchemy, stackFile } from './alchemy.ts';\nimport { deployFileName, loadDeployConfig } from './config.ts';\nimport { createRoot } from './create-root.ts';\nimport type { Ask } from './create-server-dir.ts';\nimport { InfraError } from './errors.ts';\nimport { writeStarterConfig } from './init.ts';\nimport { decodeStackOutput, outputsReport } from './outputs.ts';\nimport { prepare, serverDirFor } from './prepare.ts';\nimport type { Missing, Prepared } from './prepare.ts';\n\nconst configFlag = Flag.String('config').pipe(\n Flag.withDescription('The deploy file'),\n Flag.withDefault(deployFileName),\n);\n\nconst forceFlag = Flag.Boolean('force').pipe(\n Flag.withDescription(\n \"Copy the deploy file's domains and allow into the existing server config, where they differ. Never replaces the root: use wt-tunnel ca create --force for that.\",\n ),\n Flag.withDefault(false),\n);\n\nconst yesFlag = Flag.Boolean('yes').pipe(\n Flag.withDescription('Apply without asking for approval of the plan'),\n Flag.withDefault(false),\n);\n\nconst cancelled = () => new InfraError({ message: 'cancelled' });\n\n/** Prompts in the terminal, when stdin is one. */\nconst terminalAsk: Ask = {\n interactive: process.stdin.isTTY,\n line: (message) => Prompt.run(Prompt.String({ message })).pipe(Effect.mapError(cancelled)),\n secret: (message) =>\n Prompt.run(Prompt.Hidden({ message })).pipe(\n Effect.map((value) => Redacted.value(value)),\n Effect.mapError(cancelled),\n ),\n};\n\nconst prepareFor = (\n {\n config,\n force = false,\n version,\n }: { readonly config: string; readonly force?: boolean; readonly version: string },\n missing: Missing,\n) => prepare({ ask: terminalAsk, config, env: process.env, force, missing, version });\n\ntype Operation = 'deploy' | 'destroy' | 'plan';\n\n/**\n * Without a terminal, alchemy cannot ask for approval: it prints the plan and stops without\n * applying it, and exits 0. Fail instead, so a script never mistakes that for success.\n */\nconst checkApproval = (operation: Operation, yes: boolean, interactive: boolean) =>\n operation === 'plan' || yes || interactive\n ? Effect.void\n : Effect.fail(\n new InfraError({\n message: `${operation} asks for approval, but stdin is not a terminal: pass --yes to apply without a prompt`,\n }),\n );\n\nconst stackRun = ({ cwd, deployment, env }: Prepared, operation: Operation, yes: boolean) =>\n checkApproval(operation, yes, process.stdin.isTTY).pipe(\n Effect.andThen(\n runAlchemy({\n args: [operation, stackFile, '--stage', deployment.stage, ...(yes ? ['--yes'] : [])],\n cwd,\n env,\n }),\n ),\n );\n\nconst printOutputs = ({ cwd, deployment, env }: Prepared) =>\n runAlchemy({\n args: [\n 'state',\n 'read',\n `${deployment.stack}/${deployment.stage}/output`,\n '--config',\n stackFile,\n '--no-input',\n // Alchemy logs to stdout; below error level a log line would break the JSON.\n '--log-level',\n 'error',\n ],\n capture: true,\n cwd,\n env,\n }).pipe(\n Effect.flatMap(decodeStackOutput),\n Effect.flatMap((output) => Console.log(outputsReport(deployment, output))),\n );\n\nconst alchemyCommand = (version: string) =>\n Command.make(\n 'alchemy',\n {\n args: Argument.String('arg').pipe(\n Argument.withDescription('The alchemy command and its arguments, after --'),\n Argument.variadic(),\n ),\n config: configFlag,\n },\n ({ args, config }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap(({ cwd, env }) =>\n runAlchemy({ args: [...args, '--config', stackFile], cwd, env }),\n ),\n ),\n ).pipe(\n Command.withDescription(\n \"Run another alchemy command against this deployment's stack, such as: alchemy -- state ls <stack>/<stage>\",\n ),\n );\n\nconst prepareCommand = Command.make('prepare', { config: configFlag, force: forceFlag }, (flags) =>\n Effect.gen(function* prepareServerDir() {\n const loaded = yield* loadDeployConfig(flags.config);\n const server = yield* serverDirFor({\n ask: terminalAsk,\n env: process.env,\n force: flags.force,\n loaded,\n missing: 'create',\n });\n yield* Console.log(`${server.dir} is a valid server folder.`);\n }),\n).pipe(\n Command.withDescription(\n 'Create the server folder as deploy would, or check the existing one, without touching the cloud',\n ),\n);\n\nconst commands = (version: string) => {\n const plan = Command.make('plan', { config: configFlag }, (flags) =>\n prepareFor({ config: flags.config, version }, 'preview').pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'plan', false)),\n ),\n ).pipe(\n Command.withDescription(\n 'Show what deploy would create, change or delete. Without a server folder, preview the one deploy would create; write nothing.',\n ),\n );\n\n const deploy = Command.make(\n 'deploy',\n { config: configFlag, force: forceFlag, yes: yesFlag },\n (flags) =>\n Effect.gen(function* deployStack() {\n const prepared = yield* prepareFor(\n { config: flags.config, force: flags.force, version },\n 'create',\n );\n yield* stackRun(prepared, 'deploy', flags.yes);\n yield* printOutputs(prepared);\n }),\n ).pipe(\n Command.withDescription(\n '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',\n ),\n );\n\n const destroy = Command.make('destroy', { config: configFlag, yes: yesFlag }, ({ config, yes }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'destroy', yes)),\n ),\n ).pipe(Command.withDescription('Delete everything deploy created'));\n\n const outputs = Command.make('outputs', { config: configFlag }, ({ config }) =>\n prepareFor({ config, version }, 'require').pipe(Effect.flatMap(printOutputs)),\n ).pipe(\n Command.withDescription(\n 'Print the app, its IPs, the tunnel host and the CA page, and the DNS records to create in manual zones',\n ),\n );\n\n return [prepareCommand, plan, deploy, destroy, outputs, alchemyCommand(version)];\n};\n\nconst init = Command.make('init', {}, () =>\n writeStarterConfig(process.cwd()).pipe(Effect.flatMap(Console.log)),\n).pipe(\n Command.withDescription(\n `Write a commented starter ${deployFileName} and a .gitignore for the server folder here, and list the secrets to create`,\n ),\n);\n\nconst caCreate = Command.make(\n 'create',\n {\n config: configFlag,\n force: Flag.Boolean('force').pipe(\n Flag.withDescription(\n 'Replace an existing root. Every device that trusts the old root must then trust the new one.',\n ),\n Flag.withDefault(false),\n ),\n },\n (input) =>\n createRoot({ deployFile: input.config, force: input.force }).pipe(\n Effect.flatMap(({ cert, domains, key, label }) =>\n Console.log(\n `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.`,\n ),\n ),\n ),\n).pipe(\n Command.withDescription(\n 'Create a root CA name-constrained to the dev domains, in the server folder',\n ),\n);\n\nconst ca = Command.make('ca').pipe(\n Command.withDescription(\"Manage the deployment's root CA\"),\n Command.withSubcommands([caCreate]),\n);\n\nconst description =\n 'Set up the wt-tunnel server on Fly.io: a deploy file says where it runs, the server folder what it does';\n\nconst run = (version: string) => {\n const cli = Command.make('wt-tunnel').pipe(\n Command.withDescription(description),\n Command.withSubcommands([init, ca, ...commands(version)]),\n );\n return Command.run(cli, { version });\n};\n\nexport { checkApproval, run };\n"],"mappings":";;;;;;;;;;AAaA,MAAM,aAAa,KAAK,OAAO,QAAQ,CAAC,CAAC,KACvC,KAAK,gBAAgB,iBAAiB,GACtC,KAAK,YAAY,cAAc,CACjC;AAEA,MAAM,YAAY,KAAK,QAAQ,OAAO,CAAC,CAAC,KACtC,KAAK,gBACH,iKACF,GACA,KAAK,YAAY,KAAK,CACxB;AAEA,MAAM,UAAU,KAAK,QAAQ,KAAK,CAAC,CAAC,KAClC,KAAK,gBAAgB,+CAA+C,GACpE,KAAK,YAAY,KAAK,CACxB;AAEA,MAAM,kBAAkB,IAAI,WAAW,EAAE,SAAS,YAAY,CAAC;;AAG/D,MAAM,cAAmB;CACvB,aAAa,QAAQ,MAAM;CAC3B,OAAO,YAAY,OAAO,IAAI,OAAO,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,SAAS,SAAS,CAAC;CACzF,SAAS,YACP,OAAO,IAAI,OAAO,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,KACrC,OAAO,KAAK,UAAU,SAAS,MAAM,KAAK,CAAC,GAC3C,OAAO,SAAS,SAAS,CAC3B;AACJ;AAEA,MAAM,cACJ,EACE,QACA,QAAQ,OACR,WAEF,YACG,QAAQ;CAAE,KAAK;CAAa;CAAQ,KAAK,QAAQ;CAAK;CAAO;CAAS;AAAQ,CAAC;;;;;AAQpF,MAAM,iBAAiB,WAAsB,KAAc,gBACzD,cAAc,UAAU,OAAO,cAC3B,OAAO,OACP,OAAO,KACL,IAAI,WAAW,EACb,SAAS,GAAG,UAAU,uFACxB,CAAC,CACH;AAEN,MAAM,YAAY,EAAE,KAAK,YAAY,OAAiB,WAAsB,QAC1E,cAAc,WAAW,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,KACjD,OAAO,QAC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KACA,QAAQ,gBACN,6BAA6B,eAAe,6EAC9C,CACF;AAEA,MAAM,WAAW,QAAQ,KACvB,UACA;CACE,QAAQ;CACR,OAAO,KAAK,QAAQ,OAAO,CAAC,CAAC,KAC3B,KAAK,gBACH,8FACF,GACA,KAAK,YAAY,KAAK,CACxB;AACF,IACC,UACC,WAAW;CAAE,YAAY,MAAM;CAAQ,OAAO,MAAM;AAAM,CAAC,CAAC,CAAC,KAC3D,OAAO,SAAS,EAAE,MAAM,SAAS,KAAK,YACpC,QAAQ,IACN,SAAS,KAAK,OAAO,IAAI,2CAA2C,MAAM,yBAAyB,QAAQ,KAAK,IAAI,EAAE,yHACxH,CACF,CACF,CACJ,CAAC,CAAC,KACA,QAAQ,gBACN,4EACF,CACF;AAEA,MAAM,KAAK,QAAQ,KAAK,IAAI,CAAC,CAAC,KAC5B,QAAQ,gBAAgB,iCAAiC,GACzD,QAAQ,gBAAgB,CAAC,QAAQ,CAAC,CACpC;AAEA,MAAM,cACJ;AAEF,MAAM,OAAO,YAAoB;CAC/B,MAAM,MAAM,QAAQ,KAAK,WAAW,CAAC,CAAC,KACpC,QAAQ,gBAAgB,WAAW,GACnC,QAAQ,gBAAgB;EAAC;EAAM;EAAI,GAAG,SAAS,OAAO;CAAC,CAAC,CAC1D;CACA,OAAO,QAAQ,IAAI,KAAK,EAAE,QAAQ,CAAC;AACrC"}
|
package/dist/config.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { InfraError } from "./errors.js";
|
|
2
2
|
import { Hostname } from "./packages/contract/src/index.js";
|
|
3
|
+
import { AllowList } from "./packages/contract/src/server-config.js";
|
|
3
4
|
import { AlchemyName, Dns, FlyName, FlyRegion, ImageRef, MemoryMb, StateStore, repeatedZones } from "./deployment.js";
|
|
4
5
|
import { Effect, FileSystem, Path, Schema } from "effect";
|
|
5
6
|
// src/config.ts
|
|
@@ -16,16 +17,40 @@ const releaseImage = (version) => `ghcr.io/tafrahq/wt-tunnel-server:${version}`;
|
|
|
16
17
|
* `wt-tunnel.deploy.json`: where and how the server runs. What it serves is in the server folder,
|
|
17
18
|
* `.server/` by default.
|
|
18
19
|
*/
|
|
20
|
+
/**
|
|
21
|
+
* The root of a new server folder: an existing root's files, relative to the deploy file, or for a
|
|
22
|
+
* new root, its label, `wt-tunnel root (<name>)`.
|
|
23
|
+
*/
|
|
24
|
+
const RootSeed = Schema.Struct({
|
|
25
|
+
cert: Schema.optionalKey(Schema.NonEmptyString),
|
|
26
|
+
key: Schema.optionalKey(Schema.NonEmptyString),
|
|
27
|
+
name: Schema.optionalKey(Schema.NonEmptyString)
|
|
28
|
+
});
|
|
19
29
|
const DeployConfig = Schema.Struct({
|
|
30
|
+
/** Who may sign in, for a new server folder. Once it exists, its config's `allow` is used. */
|
|
31
|
+
allow: Schema.optionalKey(AllowList),
|
|
32
|
+
/**
|
|
33
|
+
* The sign-in host, shared by every dev domain and outside all of them: `authHost` in the server
|
|
34
|
+
* folder's config, which must name the same host.
|
|
35
|
+
*/
|
|
36
|
+
authHost: Hostname,
|
|
37
|
+
ca: Schema.optionalKey(RootSeed),
|
|
20
38
|
/** Who creates the records in each zone the record names sit in. */
|
|
21
39
|
dns: Dns,
|
|
22
|
-
|
|
40
|
+
/** The dev domains of a new server folder. Once it exists, its config's `domains` are used. */
|
|
41
|
+
domains: Schema.optionalKey(Schema.NonEmptyArray(Hostname)),
|
|
42
|
+
image: Schema.optionalKey(ImageRef),
|
|
43
|
+
/**
|
|
44
|
+
* Where the server runs, by `provider`. Fly.io is the only one for now; another would add its own
|
|
45
|
+
* shape here.
|
|
46
|
+
*/
|
|
47
|
+
server: Schema.Struct({
|
|
23
48
|
app: FlyName,
|
|
24
49
|
memoryMb: Schema.optionalKey(MemoryMb),
|
|
25
50
|
org: FlyName,
|
|
51
|
+
provider: Schema.Literal("flyio"),
|
|
26
52
|
region: FlyRegion
|
|
27
53
|
}),
|
|
28
|
-
image: Schema.optionalKey(ImageRef),
|
|
29
54
|
/** The folder uploaded to the Machine, relative to this file. */
|
|
30
55
|
serverDir: Schema.optionalKey(Schema.NonEmptyString),
|
|
31
56
|
stack: Schema.optionalKey(AlchemyName),
|
|
@@ -61,14 +86,14 @@ const loadDeployConfig = (configFile) => Effect.gen(function* loadConfig() {
|
|
|
61
86
|
});
|
|
62
87
|
/** The deployment: the deploy file with every default filled in, and the names the server serves. */
|
|
63
88
|
const resolveDeployment = (config, server, version) => ({
|
|
64
|
-
authHost:
|
|
89
|
+
authHost: config.authHost,
|
|
65
90
|
dns: config.dns,
|
|
66
91
|
domains: server.domains,
|
|
67
92
|
fly: {
|
|
68
|
-
app: config.
|
|
69
|
-
memoryMb: config.
|
|
70
|
-
org: config.
|
|
71
|
-
region: config.
|
|
93
|
+
app: config.server.app,
|
|
94
|
+
memoryMb: config.server.memoryMb ?? defaults.memoryMb,
|
|
95
|
+
org: config.server.org,
|
|
96
|
+
region: config.server.region
|
|
72
97
|
},
|
|
73
98
|
image: config.image ?? releaseImage(version),
|
|
74
99
|
stack: config.stack ?? defaults.stack,
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Path, Schema } from 'effect';\n\nimport {\n AlchemyName,\n Dns,\n FlyName,\n FlyRegion,\n ImageRef,\n MemoryMb,\n StateStore,\n repeatedZones,\n} from './deployment.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\n\nconst deployFileName = 'wt-tunnel.deploy.json';\n\nconst defaults = {\n memoryMb: 512,\n serverDir: '.server',\n stack: 'wt-tunnel-server',\n stage: 'prod',\n} as const;\n\n/** The image a release of this CLI deploys unless the config pins another. */\nconst releaseImage = (version: string) => `ghcr.io/tafrahq/wt-tunnel-server:${version}`;\n\n/**\n * `wt-tunnel.deploy.json`: where and how the server runs. What it serves is in the server folder,\n * `.server/` by default.\n */\nconst DeployConfig = Schema.Struct({\n /** Who creates the records in each zone the record names sit in. */\n dns: Dns,\n
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { AllowList } from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Path, Schema } from 'effect';\n\nimport {\n AlchemyName,\n Dns,\n FlyName,\n FlyRegion,\n ImageRef,\n MemoryMb,\n StateStore,\n repeatedZones,\n} from './deployment.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\n\nconst deployFileName = 'wt-tunnel.deploy.json';\n\nconst defaults = {\n memoryMb: 512,\n serverDir: '.server',\n stack: 'wt-tunnel-server',\n stage: 'prod',\n} as const;\n\n/** The image a release of this CLI deploys unless the config pins another. */\nconst releaseImage = (version: string) => `ghcr.io/tafrahq/wt-tunnel-server:${version}`;\n\n/**\n * `wt-tunnel.deploy.json`: where and how the server runs. What it serves is in the server folder,\n * `.server/` by default.\n */\n/**\n * The root of a new server folder: an existing root's files, relative to the deploy file, or for a\n * new root, its label, `wt-tunnel root (<name>)`.\n */\nconst RootSeed = Schema.Struct({\n cert: Schema.optionalKey(Schema.NonEmptyString),\n key: Schema.optionalKey(Schema.NonEmptyString),\n name: Schema.optionalKey(Schema.NonEmptyString),\n});\n\nconst DeployConfig = Schema.Struct({\n /** Who may sign in, for a new server folder. Once it exists, its config's `allow` is used. */\n allow: Schema.optionalKey(AllowList),\n /**\n * The sign-in host, shared by every dev domain and outside all of them: `authHost` in the server\n * folder's config, which must name the same host.\n */\n authHost: Hostname,\n ca: Schema.optionalKey(RootSeed),\n /** Who creates the records in each zone the record names sit in. */\n dns: Dns,\n /** The dev domains of a new server folder. Once it exists, its config's `domains` are used. */\n domains: Schema.optionalKey(Schema.NonEmptyArray(Hostname)),\n image: Schema.optionalKey(ImageRef),\n /**\n * Where the server runs, by `provider`. Fly.io is the only one for now; another would add its own\n * shape here.\n */\n server: Schema.Struct({\n app: FlyName,\n memoryMb: Schema.optionalKey(MemoryMb),\n org: FlyName,\n provider: Schema.Literal('flyio'),\n region: FlyRegion,\n }),\n /** The folder uploaded to the Machine, relative to this file. */\n serverDir: Schema.optionalKey(Schema.NonEmptyString),\n stack: Schema.optionalKey(AlchemyName),\n stage: Schema.optionalKey(AlchemyName),\n state: StateStore,\n /** The name tunnel clients connect to: `server.host` in their wt-tunnel.json. */\n tunnelHost: Hostname,\n});\ntype DeployConfig = typeof DeployConfig.Type;\n\nconst DeployConfigJson = Schema.fromJsonString(DeployConfig);\n\n/**\n * Blanks out `//` and `/* *\\/` comments outside strings, keeping every newline and column, so the\n * config file can explain itself and JSON errors still point at the right place.\n */\nconst blankComments = (text: string) =>\n text.replaceAll(\n /(?<quoted>\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//gu,\n (match, quoted?: string) => quoted ?? match.replaceAll(/[^\\n]/gu, ' '),\n );\n\nconst decodeDeployConfig = (text: string, source: string) =>\n Schema.decodeUnknownEffect(DeployConfigJson)(blankComments(text), { errors: 'all' }).pipe(\n Effect.mapError(\n (schemaError) =>\n new InfraError({ message: `${source} is not a valid config: ${schemaError.message}` }),\n ),\n Effect.flatMap((config) => {\n const problems = repeatedZones(config.dns);\n return problems.length === 0\n ? Effect.succeed(config)\n : Effect.fail(\n new InfraError({\n message: `${source} is not a valid config: ${problems.join('; ')}`,\n }),\n );\n }),\n );\n\n/** The deploy file, its directory, its decoded content, and the server folder it names. */\nconst loadDeployConfig = (configFile: string) =>\n Effect.gen(function* loadConfig() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.resolve(configFile);\n const text = yield* fs.readFileString(file).pipe(\n Effect.mapError(\n () =>\n new InfraError({\n message: `cannot read ${file}. Pass --config <file>, or run \\`wt-tunnel init\\` to write a starter ${deployFileName}.`,\n }),\n ),\n );\n const config = yield* decodeDeployConfig(text, file);\n const dir = path.dirname(file);\n return {\n config,\n dir,\n file,\n serverDir: path.resolve(dir, config.serverDir ?? defaults.serverDir),\n };\n });\n\n/** A loaded deploy file. */\ninterface LoadedDeploy {\n readonly config: DeployConfig;\n /** The deploy file's directory, where relative paths in it start. */\n readonly dir: string;\n readonly file: string;\n /** The server folder, absolute. */\n readonly serverDir: string;\n}\n\n/** The deployment: the deploy file with every default filled in, and the names the server serves. */\nconst resolveDeployment = (\n config: DeployConfig,\n server: Pick<ServerConfig, 'domains'>,\n version: string,\n): Deployment => ({\n authHost: config.authHost,\n dns: config.dns,\n domains: server.domains,\n fly: {\n app: config.server.app,\n memoryMb: config.server.memoryMb ?? defaults.memoryMb,\n org: config.server.org,\n region: config.server.region,\n },\n image: config.image ?? releaseImage(version),\n stack: config.stack ?? defaults.stack,\n stage: config.stage ?? defaults.stage,\n state: config.state,\n tunnelHost: config.tunnelHost,\n});\n\nexport {\n blankComments,\n decodeDeployConfig,\n defaults,\n deployFileName,\n loadDeployConfig,\n releaseImage,\n resolveDeployment,\n};\nexport type { DeployConfig, LoadedDeploy };\n"],"mappings":";;;;;;AAkBA,MAAM,iBAAiB;AAEvB,MAAM,WAAW;CACf,UAAU;CACV,WAAW;CACX,OAAO;CACP,OAAO;AACT;;AAGA,MAAM,gBAAgB,YAAoB,oCAAoC;;;;;;;;;AAU9E,MAAM,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO,YAAY,OAAO,cAAc;CAC9C,KAAK,OAAO,YAAY,OAAO,cAAc;CAC7C,MAAM,OAAO,YAAY,OAAO,cAAc;AAChD,CAAC;AAED,MAAM,eAAe,OAAO,OAAO;;CAEjC,OAAO,OAAO,YAAY,SAAS;;;;;CAKnC,UAAU;CACV,IAAI,OAAO,YAAY,QAAQ;;CAE/B,KAAK;;CAEL,SAAS,OAAO,YAAY,OAAO,cAAc,QA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