@tafrahq/wt-tunnel 0.0.0-stage → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +237 -2
- package/dist/alchemy.js +40 -0
- package/dist/alchemy.js.map +1 -0
- package/dist/bin.js +15 -0
- package/dist/bin.js.map +1 -0
- package/dist/ca.js +88 -0
- package/dist/ca.js.map +1 -0
- package/dist/cli.js +147 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.js +106 -0
- package/dist/config.js.map +1 -0
- package/dist/create-root.js +78 -0
- package/dist/create-root.js.map +1 -0
- package/dist/create-server-dir.js +150 -0
- package/dist/create-server-dir.js.map +1 -0
- package/dist/deployment.js +132 -0
- package/dist/deployment.js.map +1 -0
- package/dist/errors.js +9 -0
- package/dist/errors.js.map +1 -0
- package/dist/init.js +105 -0
- package/dist/init.js.map +1 -0
- package/dist/outputs.js +38 -0
- package/dist/outputs.js.map +1 -0
- package/dist/packages/contract/src/bin.js +20 -0
- package/dist/packages/contract/src/bin.js.map +1 -0
- package/dist/packages/contract/src/index.js +12 -0
- package/dist/packages/contract/src/index.js.map +1 -0
- package/dist/packages/contract/src/root-ca.js +94 -0
- package/dist/packages/contract/src/root-ca.js.map +1 -0
- package/dist/packages/contract/src/server-config.js +99 -0
- package/dist/packages/contract/src/server-config.js.map +1 -0
- package/dist/prepare.js +142 -0
- package/dist/prepare.js.map +1 -0
- package/dist/providers.js +82 -0
- package/dist/providers.js.map +1 -0
- package/dist/secrets.js +39 -0
- package/dist/secrets.js.map +1 -0
- package/dist/seed-drift.js +51 -0
- package/dist/seed-drift.js.map +1 -0
- package/dist/server-dir.js +151 -0
- package/dist/server-dir.js.map +1 -0
- package/dist/server-machine.js +136 -0
- package/dist/server-machine.js.map +1 -0
- package/dist/stack.js +104 -0
- package/dist/stack.js.map +1 -0
- package/dist/uploads.js +24 -0
- package/dist/uploads.js.map +1 -0
- package/package.json +63 -3
package/dist/init.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { defaults, deployFileName } from "./config.js";
|
|
2
|
+
import { refuseExisting } from "./ca.js";
|
|
3
|
+
import { providerSteps } from "./providers.js";
|
|
4
|
+
import { Effect, FileSystem, Path } from "effect";
|
|
5
|
+
// src/init.ts
|
|
6
|
+
/** Marks every value `init` cannot guess; each one fails decoding until the user replaces it. */
|
|
7
|
+
const placeholder = "REPLACE_ME";
|
|
8
|
+
const serverDirLine = `${defaults.serverDir}/`;
|
|
9
|
+
/**
|
|
10
|
+
* The server folder holds the server's secrets, and `.alchemy/` holds Alchemy's local state and
|
|
11
|
+
* logs, which may record what the stack sent to Fly. Neither belongs in git.
|
|
12
|
+
*/
|
|
13
|
+
const ignoreLines = [serverDirLine, ".alchemy/"];
|
|
14
|
+
const starterConfig = `// Where and how wt-tunnel runs. What the server does lives in ${defaults.serverDir}/, which the
|
|
15
|
+
// first \`wt-tunnel deploy\` creates.
|
|
16
|
+
{
|
|
17
|
+
// Where the server runs. "flyio", the only provider for now: your Fly.io organization slug
|
|
18
|
+
// (\`fly orgs list\`), a name for the new app (Fly app names are global), and a region
|
|
19
|
+
// (\`fly platform regions\`). memoryMb is optional (default ${String(defaults.memoryMb)}).
|
|
20
|
+
"server": { "provider": "flyio", "org": "personal", "app": "${placeholder}", "region": "ams" },
|
|
21
|
+
|
|
22
|
+
// The name tunnel clients connect to: server.host in each wt-tunnel.json. New roots are named
|
|
23
|
+
// after it.
|
|
24
|
+
"tunnelHost": "wt-tunnel.example.com",
|
|
25
|
+
|
|
26
|
+
// The sign-in host, shared by every dev domain and outside all of them. Devices open its /ca page
|
|
27
|
+
// to trust the root, and each sign-in provider redirects to it.
|
|
28
|
+
"authHost": "auth-wt-tunnel.example.com",
|
|
29
|
+
|
|
30
|
+
// The first deploy creates ${defaults.serverDir}/ from these. After that, ${defaults.serverDir}/wt-tunnel-server.json
|
|
31
|
+
// decides what the server does. Keep them as a record: a deploy warns when they differ from it,
|
|
32
|
+
// and \`wt-tunnel deploy --force\` copies domains and allow into it.
|
|
33
|
+
// domains: the dev domains. Worktree URLs are https://<app>.<worktree>.<domain>, and a new root
|
|
34
|
+
// may sign only for these and the names under them.
|
|
35
|
+
// allow: who may sign in, by email and by email domain. At least one.
|
|
36
|
+
// ca (optional): "cert" and "key" use an existing root (paths relative to this file), and
|
|
37
|
+
// "name" labels a new one, wt-tunnel root (<name>). Default name: the tunnel host.
|
|
38
|
+
"domains": ["dev.example.com"],
|
|
39
|
+
"allow": { "emails": ["you@example.com"], "emailDomains": [] },
|
|
40
|
+
|
|
41
|
+
// Who creates the DNS records, one entry per zone: *.<domain> for each dev domain, the tunnel host
|
|
42
|
+
// and the sign-in host. Each record goes in the most specific zone its name sits in, and every
|
|
43
|
+
// name must sit in one.
|
|
44
|
+
// "cloudflare": the stack creates the records. zoneId is on the zone's Overview page.
|
|
45
|
+
// "manual": you create them; \`wt-tunnel outputs\` lists them.
|
|
46
|
+
// One CLOUDFLARE_API_TOKEN serves every Cloudflare zone listed. A user API token (My Profile,
|
|
47
|
+
// API Tokens) can cover zones in several accounts.
|
|
48
|
+
"dns": [{ "provider": "cloudflare", "zone": "example.com", "zoneId": "${placeholder}" }],
|
|
49
|
+
|
|
50
|
+
// Where Alchemy records what it created. { "provider": "cloudflare", "accountId": "..." }: a
|
|
51
|
+
// state store Worker in that Cloudflare account, usable from any machine: the account's default
|
|
52
|
+
// alchemy-state-store, or alchemy-state-store-<name> with "name". "local": .alchemy/
|
|
53
|
+
// next to this file, which is git-ignored; back it up, because updating or destroying the
|
|
54
|
+
// deployment needs it. Without Cloudflare, use "manual" dns entries and "local" state.
|
|
55
|
+
"state": { "provider": "cloudflare", "accountId": "${placeholder}" }
|
|
56
|
+
|
|
57
|
+
// Optional: "image" (default: the server release that matches this CLI's version), "serverDir"
|
|
58
|
+
// (default "${defaults.serverDir}"), and "stack" and "stage", Alchemy's names for the deployment
|
|
59
|
+
// (default "${defaults.stack}" and "${defaults.stage}").
|
|
60
|
+
}
|
|
61
|
+
`;
|
|
62
|
+
const nextSteps = (file) => `Wrote ${file}, and ${ignoreLines.join(" and ")} to .gitignore. Next:
|
|
63
|
+
|
|
64
|
+
1. Edit it: replace each ${placeholder} and the example names.
|
|
65
|
+
2. Export these secrets (from a secret manager, never from a committed file):
|
|
66
|
+
FLY_API_TOKEN fly tokens create org <org>
|
|
67
|
+
CLOUDFLARE_API_TOKEN with a "cloudflare" dns entry or state: one Cloudflare user API token
|
|
68
|
+
with Zone > DNS > Edit on every Cloudflare zone in "dns", even zones
|
|
69
|
+
in different accounts. With Cloudflare state it also needs Workers
|
|
70
|
+
Scripts Edit, Account Settings Edit, Secrets Store Edit and Workers
|
|
71
|
+
Tail Read on the state's account.
|
|
72
|
+
CLOUDFLARE_ACCOUNT_ID only with a "cloudflare" dns entry and "state": "local": the account
|
|
73
|
+
of any of those zones. Otherwise the CLI sets it from state.accountId.
|
|
74
|
+
3. Create an OAuth client with one or more sign-in providers, and export its variables for the
|
|
75
|
+
first deploy (GOOGLE_*, GITHUB_*, MICROSOFT_* or CLOUDFLARE_ACCESS_*):
|
|
76
|
+
${providerSteps().split("\n").map((line) => ` - ${line}`).join("\n")}
|
|
77
|
+
4. wt-tunnel deploy
|
|
78
|
+
The first deploy creates ${serverDirLine} (the server config, a new root CA, and generated tokens),
|
|
79
|
+
then deploys. It holds secrets: back it up, and never commit it. Later deploys upload it as it
|
|
80
|
+
is; edit it and deploy again to change what the server does.
|
|
81
|
+
`;
|
|
82
|
+
/** Adds each of `ignoreLines` that `dir`'s .gitignore does not list yet, creating the file. */
|
|
83
|
+
const ignoreServerDir = (dir) => Effect.gen(function* ignore() {
|
|
84
|
+
const fs = yield* FileSystem.FileSystem;
|
|
85
|
+
const file = (yield* Path.Path).join(dir, ".gitignore");
|
|
86
|
+
const current = (yield* fs.exists(file).pipe(Effect.orDie)) ? yield* fs.readFileString(file).pipe(Effect.orDie) : "";
|
|
87
|
+
const listed = new Set(current.split("\n").map((line) => line.trim()));
|
|
88
|
+
const missing = ignoreLines.filter((line) => !listed.has(line));
|
|
89
|
+
if (missing.length > 0) {
|
|
90
|
+
const separator = current === "" || current.endsWith("\n") ? "" : "\n";
|
|
91
|
+
yield* fs.writeFileString(file, `${current}${separator}${missing.map((line) => `${line}\n`).join("")}`).pipe(Effect.orDie);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
/** Writes the starter deploy file into `dir` and returns what to do next. Never overwrites it. */
|
|
95
|
+
const writeStarterConfig = (dir) => Effect.gen(function* init() {
|
|
96
|
+
const fs = yield* FileSystem.FileSystem;
|
|
97
|
+
const file = (yield* Path.Path).join(dir, deployFileName);
|
|
98
|
+
yield* refuseExisting(file, "edit it, or delete it to start over");
|
|
99
|
+
yield* fs.writeFileString(file, starterConfig, { flag: "wx" }).pipe(Effect.orDie);
|
|
100
|
+
yield* ignoreServerDir(dir);
|
|
101
|
+
return nextSteps(file);
|
|
102
|
+
});
|
|
103
|
+
export { placeholder, writeStarterConfig };
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=init.js.map
|
package/dist/init.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.js","names":[],"sources":["../src/init.ts"],"sourcesContent":["import { Effect, FileSystem, Path } from 'effect';\n\nimport { refuseExisting } from './ca.ts';\nimport { defaults, deployFileName } from './config.ts';\nimport { providerSteps } from './providers.ts';\n\n/** Marks every value `init` cannot guess; each one fails decoding until the user replaces it. */\nconst placeholder = 'REPLACE_ME';\n\nconst serverDirLine = `${defaults.serverDir}/`;\n\n/**\n * The server folder holds the server's secrets, and `.alchemy/` holds Alchemy's local state and\n * logs, which may record what the stack sent to Fly. Neither belongs in git.\n */\nconst ignoreLines = [serverDirLine, '.alchemy/'];\n\nconst starterConfig = `// Where and how wt-tunnel runs. What the server does lives in ${defaults.serverDir}/, which the\n// first \\`wt-tunnel deploy\\` creates.\n{\n // Where the server runs. \"flyio\", the only provider for now: your Fly.io organization slug\n // (\\`fly orgs list\\`), a name for the new app (Fly app names are global), and a region\n // (\\`fly platform regions\\`). memoryMb is optional (default ${String(defaults.memoryMb)}).\n \"server\": { \"provider\": \"flyio\", \"org\": \"personal\", \"app\": \"${placeholder}\", \"region\": \"ams\" },\n\n // The name tunnel clients connect to: server.host in each wt-tunnel.json. New roots are named\n // after it.\n \"tunnelHost\": \"wt-tunnel.example.com\",\n\n // The sign-in host, shared by every dev domain and outside all of them. Devices open its /ca page\n // to trust the root, and each sign-in provider redirects to it.\n \"authHost\": \"auth-wt-tunnel.example.com\",\n\n // The first deploy creates ${defaults.serverDir}/ from these. After that, ${defaults.serverDir}/wt-tunnel-server.json\n // decides what the server does. Keep them as a record: a deploy warns when they differ from it,\n // and \\`wt-tunnel deploy --force\\` copies domains and allow into it.\n // domains: the dev domains. Worktree URLs are https://<app>.<worktree>.<domain>, and a new root\n // may sign only for these and the names under them.\n // allow: who may sign in, by email and by email domain. At least one.\n // ca (optional): \"cert\" and \"key\" use an existing root (paths relative to this file), and\n // \"name\" labels a new one, wt-tunnel root (<name>). Default name: the tunnel host.\n \"domains\": [\"dev.example.com\"],\n \"allow\": { \"emails\": [\"you@example.com\"], \"emailDomains\": [] },\n\n // Who creates the DNS records, one entry per zone: *.<domain> for each dev domain, the tunnel host\n // and the sign-in host. Each record goes in the most specific zone its name sits in, and every\n // name must sit in one.\n // \"cloudflare\": the stack creates the records. zoneId is on the zone's Overview page.\n // \"manual\": you create them; \\`wt-tunnel outputs\\` lists them.\n // One CLOUDFLARE_API_TOKEN serves every Cloudflare zone listed. A user API token (My Profile,\n // API Tokens) can cover zones in several accounts.\n \"dns\": [{ \"provider\": \"cloudflare\", \"zone\": \"example.com\", \"zoneId\": \"${placeholder}\" }],\n\n // Where Alchemy records what it created. { \"provider\": \"cloudflare\", \"accountId\": \"...\" }: a\n // state store Worker in that Cloudflare account, usable from any machine: the account's default\n // alchemy-state-store, or alchemy-state-store-<name> with \"name\". \"local\": .alchemy/\n // next to this file, which is git-ignored; back it up, because updating or destroying the\n // deployment needs it. Without Cloudflare, use \"manual\" dns entries and \"local\" state.\n \"state\": { \"provider\": \"cloudflare\", \"accountId\": \"${placeholder}\" }\n\n // Optional: \"image\" (default: the server release that matches this CLI's version), \"serverDir\"\n // (default \"${defaults.serverDir}\"), and \"stack\" and \"stage\", Alchemy's names for the deployment\n // (default \"${defaults.stack}\" and \"${defaults.stage}\").\n}\n`;\n\nconst nextSteps = (\n file: string,\n) => `Wrote ${file}, and ${ignoreLines.join(' and ')} to .gitignore. Next:\n\n1. Edit it: replace each ${placeholder} and the example names.\n2. Export these secrets (from a secret manager, never from a committed file):\n FLY_API_TOKEN fly tokens create org <org>\n CLOUDFLARE_API_TOKEN with a \"cloudflare\" dns entry or state: one Cloudflare user API token\n with Zone > DNS > Edit on every Cloudflare zone in \"dns\", even zones\n in different accounts. With Cloudflare state it also needs Workers\n Scripts Edit, Account Settings Edit, Secrets Store Edit and Workers\n Tail Read on the state's account.\n CLOUDFLARE_ACCOUNT_ID only with a \"cloudflare\" dns entry and \"state\": \"local\": the account\n of any of those zones. Otherwise the CLI sets it from state.accountId.\n3. Create an OAuth client with one or more sign-in providers, and export its variables for the\n first deploy (GOOGLE_*, GITHUB_*, MICROSOFT_* or CLOUDFLARE_ACCESS_*):\n${providerSteps()\n .split('\\n')\n .map((line) => ` - ${line}`)\n .join('\\n')}\n4. wt-tunnel deploy\n The first deploy creates ${serverDirLine} (the server config, a new root CA, and generated tokens),\n then deploys. It holds secrets: back it up, and never commit it. Later deploys upload it as it\n is; edit it and deploy again to change what the server does.\n`;\n\n/** Adds each of `ignoreLines` that `dir`'s .gitignore does not list yet, creating the file. */\nconst ignoreServerDir = (dir: string) =>\n Effect.gen(function* ignore() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(dir, '.gitignore');\n const current = (yield* fs.exists(file).pipe(Effect.orDie))\n ? yield* fs.readFileString(file).pipe(Effect.orDie)\n : '';\n const listed = new Set(current.split('\\n').map((line) => line.trim()));\n const missing = ignoreLines.filter((line) => !listed.has(line));\n if (missing.length > 0) {\n const separator = current === '' || current.endsWith('\\n') ? '' : '\\n';\n yield* fs\n .writeFileString(\n file,\n `${current}${separator}${missing.map((line) => `${line}\\n`).join('')}`,\n )\n .pipe(Effect.orDie);\n }\n });\n\n/** Writes the starter deploy file into `dir` and returns what to do next. Never overwrites it. */\nconst writeStarterConfig = (dir: string) =>\n Effect.gen(function* init() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(dir, deployFileName);\n yield* refuseExisting(file, 'edit it, or delete it to start over');\n yield* fs.writeFileString(file, starterConfig, { flag: 'wx' }).pipe(Effect.orDie);\n yield* ignoreServerDir(dir);\n return nextSteps(file);\n });\n\nexport { placeholder, writeStarterConfig };\n"],"mappings":";;;;;;AAOA,MAAM,cAAc;AAEpB,MAAM,gBAAgB,GAAG,SAAS,UAAU;;;;;AAM5C,MAAM,cAAc,CAAC,eAAe,WAAW;AAE/C,MAAM,gBAAgB,kEAAkE,SAAS,UAAU;;;;;iEAK1C,OAAO,SAAS,QAAQ,EAAE;gEAC3B,YAAY;;;;;;;;;;gCAU5C,SAAS,UAAU,4BAA4B,SAAS,UAAU;;;;;;;;;;;;;;;;;;0EAkBxB,YAAY;;;;;;;uDAO/B,YAAY;;;iBAGlD,SAAS,UAAU;iBACnB,SAAS,MAAM,SAAS,SAAS,MAAM;;;AAIxD,MAAM,aACJ,SACG,SAAS,KAAK,QAAQ,YAAY,KAAK,OAAO,EAAE;;2BAE1B,YAAY;;;;;;;;;;;;EAYrC,cAAc,CAAC,CACd,MAAM,IAAI,CAAC,CACX,KAAK,SAAS,UAAU,MAAM,CAAC,CAC/B,KAAK,IAAI,EAAE;;8BAEgB,cAAc;;;;;AAM5C,MAAM,mBAAmB,QACvB,OAAO,IAAI,UAAU,SAAS;CAC5B,MAAM,KAAK,OAAO,WAAW;CAE7B,MAAM,QAAO,OADO,KAAK,KAAA,CACP,KAAK,KAAK,YAAY;CACxC,MAAM,WAAW,OAAO,GAAG,OAAO,IAAI,CAAC,CAAC,KAAK,OAAO,KAAK,KACrD,OAAO,GAAG,eAAe,IAAI,CAAC,CAAC,KAAK,OAAO,KAAK,IAChD;CACJ,MAAM,SAAS,IAAI,IAAI,QAAQ,MAAM,IAAI,CAAC,CAAC,KAAK,SAAS,KAAK,KAAK,CAAC,CAAC;CACrE,MAAM,UAAU,YAAY,QAAQ,SAAS,CAAC,OAAO,IAAI,IAAI,CAAC;CAC9D,IAAI,QAAQ,SAAS,GAAG;EACtB,MAAM,YAAY,YAAY,MAAM,QAAQ,SAAS,IAAI,IAAI,KAAK;EAClE,OAAO,GACJ,gBACC,MACA,GAAG,UAAU,YAAY,QAAQ,KAAK,SAAS,GAAG,KAAK,GAAG,CAAC,CAAC,KAAK,EAAE,GACrE,CAAC,CACA,KAAK,OAAO,KAAK;CACtB;AACF,CAAC;;AAGH,MAAM,sBAAsB,QAC1B,OAAO,IAAI,UAAU,OAAO;CAC1B,MAAM,KAAK,OAAO,WAAW;CAE7B,MAAM,QAAO,OADO,KAAK,KAAA,CACP,KAAK,KAAK,cAAc;CAC1C,OAAO,eAAe,MAAM,qCAAqC;CACjE,OAAO,GAAG,gBAAgB,MAAM,eAAe,EAAE,MAAM,KAAK,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK;CAChF,OAAO,gBAAgB,GAAG;CAC1B,OAAO,UAAU,IAAI;AACvB,CAAC"}
|
package/dist/outputs.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { InfraError } from "./errors.js";
|
|
2
|
+
import { dnsProviders, placeHosts } from "./deployment.js";
|
|
3
|
+
import { Effect, Schema } from "effect";
|
|
4
|
+
// src/outputs.ts
|
|
5
|
+
/** What the stack returns, as Alchemy stores it. */
|
|
6
|
+
const StackOutput = Schema.Struct({
|
|
7
|
+
app: Schema.String,
|
|
8
|
+
ipv4: Schema.String,
|
|
9
|
+
ipv6: Schema.String,
|
|
10
|
+
tunnelHost: Schema.String
|
|
11
|
+
});
|
|
12
|
+
const decodeStackOutput = (text) => Schema.decodeUnknownEffect(Schema.fromJsonString(StackOutput))(text).pipe(Effect.mapError(() => new InfraError({ message: "no stack outputs found; has this deployment been deployed yet?" })));
|
|
13
|
+
const recordLines = (hosts, output) => hosts.flatMap((host) => [["A", output.ipv4], ["AAAA", output.ipv6]].map(([type, content]) => ` ${host.name} ${type} ${content}`));
|
|
14
|
+
/** Who creates each zone's records: a provider, or the user, who gets the records to create. */
|
|
15
|
+
const dnsReport = (deployment, output) => {
|
|
16
|
+
const { placed } = placeHosts(deployment);
|
|
17
|
+
return deployment.dns.flatMap((entry) => {
|
|
18
|
+
const hosts = placed.filter((host) => host.zone.zone === entry.zone);
|
|
19
|
+
const { creator } = dnsProviders[entry.provider];
|
|
20
|
+
if (hosts.length === 0) return [];
|
|
21
|
+
return creator === void 0 ? [
|
|
22
|
+
"",
|
|
23
|
+
`Create these DNS records in ${entry.zone}:`,
|
|
24
|
+
...recordLines(hosts, output)
|
|
25
|
+
] : ["", `${creator} manages the DNS records in ${entry.zone}: ${hosts.map((host) => host.name).join(", ")}`];
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
const outputsReport = (deployment, output) => [
|
|
29
|
+
`Fly app ${output.app}`,
|
|
30
|
+
`IPv4 ${output.ipv4}`,
|
|
31
|
+
`IPv6 ${output.ipv6}`,
|
|
32
|
+
`Tunnel host ${output.tunnelHost} (server.host in each wt-tunnel.json)`,
|
|
33
|
+
`CA page https://${deployment.authHost}/ca (open it on each device to trust the root)`,
|
|
34
|
+
...dnsReport(deployment, output)
|
|
35
|
+
].join("\n");
|
|
36
|
+
export { decodeStackOutput, outputsReport };
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=outputs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"outputs.js","names":[],"sources":["../src/outputs.ts"],"sourcesContent":["import { Effect, Schema } from 'effect';\n\nimport { dnsProviders, placeHosts } from './deployment.ts';\nimport type { Deployment, PlacedHost } from './deployment.ts';\nimport { InfraError } from './errors.ts';\n\n/** What the stack returns, as Alchemy stores it. */\nconst StackOutput = Schema.Struct({\n app: Schema.String,\n ipv4: Schema.String,\n ipv6: Schema.String,\n tunnelHost: Schema.String,\n});\ntype StackOutput = typeof StackOutput.Type;\n\nconst decodeStackOutput = (text: string) =>\n Schema.decodeUnknownEffect(Schema.fromJsonString(StackOutput))(text).pipe(\n Effect.mapError(\n () =>\n new InfraError({\n message: 'no stack outputs found; has this deployment been deployed yet?',\n }),\n ),\n );\n\nconst recordLines = (hosts: readonly PlacedHost[], output: StackOutput) =>\n hosts.flatMap((host) =>\n (\n [\n ['A', output.ipv4],\n ['AAAA', output.ipv6],\n ] as const\n ).map(([type, content]) => ` ${host.name} ${type} ${content}`),\n );\n\n/** Who creates each zone's records: a provider, or the user, who gets the records to create. */\nconst dnsReport = (deployment: Deployment, output: StackOutput): readonly string[] => {\n const { placed } = placeHosts(deployment);\n return deployment.dns.flatMap((entry) => {\n const hosts = placed.filter((host) => host.zone.zone === entry.zone);\n const { creator } = dnsProviders[entry.provider];\n if (hosts.length === 0) {\n return [];\n }\n return creator === undefined\n ? ['', `Create these DNS records in ${entry.zone}:`, ...recordLines(hosts, output)]\n : [\n '',\n `${creator} manages the DNS records in ${entry.zone}: ${hosts.map((host) => host.name).join(', ')}`,\n ];\n });\n};\n\nconst outputsReport = (deployment: Deployment, output: StackOutput) =>\n [\n `Fly app ${output.app}`,\n `IPv4 ${output.ipv4}`,\n `IPv6 ${output.ipv6}`,\n `Tunnel host ${output.tunnelHost} (server.host in each wt-tunnel.json)`,\n `CA page https://${deployment.authHost}/ca (open it on each device to trust the root)`,\n ...dnsReport(deployment, output),\n ].join('\\n');\n\nexport { decodeStackOutput, outputsReport };\n"],"mappings":";;;;;AAOA,MAAM,cAAc,OAAO,OAAO;CAChC,KAAK,OAAO;CACZ,MAAM,OAAO;CACb,MAAM,OAAO;CACb,YAAY,OAAO;AACrB,CAAC;AAGD,MAAM,qBAAqB,SACzB,OAAO,oBAAoB,OAAO,eAAe,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,KACnE,OAAO,eAEH,IAAI,WAAW,EACb,SAAS,iEACX,CAAC,CACL,CACF;AAEF,MAAM,eAAe,OAA8B,WACjD,MAAM,SAAS,SAEX,CACE,CAAC,KAAK,OAAO,IAAI,GACjB,CAAC,QAAQ,OAAO,IAAI,CACtB,CAAC,CACD,KAAK,CAAC,MAAM,aAAa,KAAK,KAAK,KAAK,GAAG,KAAK,GAAG,SAAS,CAChE;;AAGF,MAAM,aAAa,YAAwB,WAA2C;CACpF,MAAM,EAAE,WAAW,WAAW,UAAU;CACxC,OAAO,WAAW,IAAI,SAAS,UAAU;EACvC,MAAM,QAAQ,OAAO,QAAQ,SAAS,KAAK,KAAK,SAAS,MAAM,IAAI;EACnE,MAAM,EAAE,YAAY,aAAa,MAAM;EACvC,IAAI,MAAM,WAAW,GACnB,OAAO,CAAC;EAEV,OAAO,YAAY,KAAA,IACf;GAAC;GAAI,+BAA+B,MAAM,KAAK;GAAI,GAAG,YAAY,OAAO,MAAM;EAAC,IAChF,CACE,IACA,GAAG,QAAQ,8BAA8B,MAAM,KAAK,IAAI,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,GAClG;CACN,CAAC;AACH;AAEA,MAAM,iBAAiB,YAAwB,WAC7C;CACE,gBAAgB,OAAO;CACvB,gBAAgB,OAAO;CACvB,gBAAgB,OAAO;CACvB,gBAAgB,OAAO,WAAW;CAClC,wBAAwB,WAAW,SAAS;CAC5C,GAAG,UAAU,YAAY,MAAM;AACjC,CAAC,CAAC,KAAK,IAAI"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { Console, Effect, Schema } from "effect";
|
|
3
|
+
// ../../packages/contract/src/bin.ts
|
|
4
|
+
const PackageJson = Schema.Struct({ version: Schema.String });
|
|
5
|
+
/** The version in the package.json one level above the built bin at `binUrl`. */
|
|
6
|
+
const packageVersion = (binUrl) => {
|
|
7
|
+
const packageJson = createRequire(binUrl)("../package.json");
|
|
8
|
+
return Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(Effect.map(({ version }) => version), Effect.orDie);
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Runs the CLI at the version of the package whose bin is at `url`. `name` is the name it prints.
|
|
12
|
+
* An `expected` failure carries a message written for the user, so it is printed as `<name>:
|
|
13
|
+
* <message>` without a stack trace, and the bin exits 1.
|
|
14
|
+
*/
|
|
15
|
+
const binProgram = (bin, run) => packageVersion(bin.url).pipe(Effect.flatMap(run), Effect.catchIf((failure) => failure._tag === bin.expected, ({ message }) => Console.error(`${bin.name}: ${message}`).pipe(Effect.andThen(Effect.sync(() => {
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
})))));
|
|
18
|
+
export { binProgram };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=bin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.js","names":[],"sources":["../../../../../../packages/contract/src/bin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\n\nimport { Console, Effect, Schema } from 'effect';\n\nconst PackageJson = Schema.Struct({ version: Schema.String });\n\n/** The version in the package.json one level above the built bin at `binUrl`. */\nconst packageVersion = (binUrl: string) => {\n const packageJson: unknown = createRequire(binUrl)('../package.json');\n return Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(\n Effect.map(({ version }) => version),\n Effect.orDie,\n );\n};\n\n/**\n * Runs the CLI at the version of the package whose bin is at `url`. `name` is the name it prints.\n * An `expected` failure carries a message written for the user, so it is printed as `<name>:\n * <message>` without a stack trace, and the bin exits 1.\n */\nconst binProgram = <\n Failure extends { readonly _tag: string },\n Requirements,\n Tag extends Extract<Failure, { readonly message: string }>['_tag'],\n>(\n bin: { readonly expected: Tag; readonly name: string; readonly url: string },\n run: (version: string) => Effect.Effect<void, Failure, Requirements>,\n) =>\n packageVersion(bin.url).pipe(\n Effect.flatMap(run),\n Effect.catchIf(\n (failure): failure is Extract<Failure, { readonly _tag: Tag; readonly message: string }> =>\n failure._tag === bin.expected,\n ({ message }) =>\n Console.error(`${bin.name}: ${message}`).pipe(\n Effect.andThen(\n Effect.sync(() => {\n process.exitCode = 1;\n }),\n ),\n ),\n ),\n );\n\nexport { binProgram };\n"],"mappings":";;;AAIA,MAAM,cAAc,OAAO,OAAO,EAAE,SAAS,OAAO,OAAO,CAAC;;AAG5D,MAAM,kBAAkB,WAAmB;CACzC,MAAM,cAAuB,cAAc,MAAM,CAAC,CAAC,iBAAiB;CACpE,OAAO,OAAO,oBAAoB,WAAW,CAAC,CAAC,WAAW,CAAC,CAAC,KAC1D,OAAO,KAAK,EAAE,cAAc,OAAO,GACnC,OAAO,KACT;AACF;;;;;;AAOA,MAAM,cAKJ,KACA,QAEA,eAAe,IAAI,GAAG,CAAC,CAAC,KACtB,OAAO,QAAQ,GAAG,GAClB,OAAO,SACJ,YACC,QAAQ,SAAS,IAAI,WACtB,EAAE,cACD,QAAQ,MAAM,GAAG,IAAI,KAAK,IAAI,SAAS,CAAC,CAAC,KACvC,OAAO,QACL,OAAO,WAAW;CAChB,QAAQ,WAAW;AACrB,CAAC,CACH,CACF,CACJ,CACF"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
// ../../packages/contract/src/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* A lowercase DNS name with at least two labels: the dev domains, the sign-in host and every dev
|
|
5
|
+
* host. The CLI accepts a domain only if the server could serve it.
|
|
6
|
+
*/
|
|
7
|
+
const Hostname = Schema.String.check(Schema.isPattern(/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u)).pipe(Schema.brand("Hostname"));
|
|
8
|
+
/** The port frps listens on for frpc, and the CLI's default `server.port`. */
|
|
9
|
+
const tunnelPort = 7e3;
|
|
10
|
+
export { Hostname, tunnelPort };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../packages/contract/src/index.ts"],"sourcesContent":["import { Schema } from 'effect';\n\nconst dnsName =\n /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\n\n/**\n * A lowercase DNS name with at least two labels: the dev domains, the sign-in host and every dev\n * host. The CLI accepts a domain only if the server could serve it.\n */\nconst Hostname = Schema.String.check(Schema.isPattern(dnsName)).pipe(Schema.brand('Hostname'));\ntype Hostname = typeof Hostname.Type;\n\n/** The port frps listens on for frpc, and the CLI's default `server.port`. */\nconst tunnelPort = 7000;\n\nexport { Hostname, tunnelPort };\n"],"mappings":";;;;;;AASA,MAAM,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,iGAAO,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,UAAU,CAAC;;AAI7F,MAAM,aAAa"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { X509Certificate, createPrivateKey, createPublicKey } from "node:crypto";
|
|
3
|
+
// ../../packages/contract/src/root-ca.ts
|
|
4
|
+
const der = {
|
|
5
|
+
contextZero: 160,
|
|
6
|
+
dnsName: 130,
|
|
7
|
+
extensions: 163,
|
|
8
|
+
longLengthFlag: 128,
|
|
9
|
+
octetString: 4,
|
|
10
|
+
oid: 6
|
|
11
|
+
};
|
|
12
|
+
const headerBytes = 2;
|
|
13
|
+
/** 2.5.29.30, id-ce-nameConstraints. */
|
|
14
|
+
const nameConstraintsOid = Buffer.from("551d1e", "hex");
|
|
15
|
+
/** The TLV starting at `at`, and where the next one starts. */
|
|
16
|
+
const readTlv = (bytes, at) => {
|
|
17
|
+
const tag = bytes.readUInt8(at);
|
|
18
|
+
const short = bytes.readUInt8(at + 1);
|
|
19
|
+
const lengthBytes = short >= der.longLengthFlag ? short - der.longLengthFlag : 0;
|
|
20
|
+
const length = lengthBytes === 0 ? short : bytes.readUIntBE(at + headerBytes, lengthBytes);
|
|
21
|
+
const start = at + headerBytes + lengthBytes;
|
|
22
|
+
return {
|
|
23
|
+
next: start + length,
|
|
24
|
+
tlv: {
|
|
25
|
+
tag,
|
|
26
|
+
value: bytes.subarray(start, start + length)
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/** The TLVs packed one after another in `bytes`. */
|
|
31
|
+
const readTlvs = (bytes) => {
|
|
32
|
+
const tlvs = [];
|
|
33
|
+
for (let at = 0; at + headerBytes <= bytes.length;) {
|
|
34
|
+
const { next, tlv } = readTlv(bytes, at);
|
|
35
|
+
tlvs.push(tlv);
|
|
36
|
+
at = next;
|
|
37
|
+
}
|
|
38
|
+
return tlvs;
|
|
39
|
+
};
|
|
40
|
+
const firstValue = (bytes) => readTlvs(bytes)[0]?.value ?? Buffer.alloc(0);
|
|
41
|
+
/** The name constraints extension's value, or undefined when the certificate has none. */
|
|
42
|
+
const nameConstraints = (certificate) => {
|
|
43
|
+
const tbs = firstValue(firstValue(certificate));
|
|
44
|
+
const wrapper = readTlvs(tbs).find(({ tag }) => tag === der.extensions);
|
|
45
|
+
return readTlvs(firstValue(wrapper?.value ?? Buffer.alloc(0))).map(({ value }) => readTlvs(value)).find(([id]) => id?.tag === der.oid && id.value.equals(nameConstraintsOid))?.findLast(({ tag }) => tag === der.octetString)?.value;
|
|
46
|
+
};
|
|
47
|
+
/** `NameConstraints ::= SEQUENCE { permittedSubtrees [0] GeneralSubtrees OPTIONAL, ... }`. */
|
|
48
|
+
const permittedDnsNames = (certificate) => {
|
|
49
|
+
const constraints = nameConstraints(certificate);
|
|
50
|
+
const permitted = constraints === void 0 ? void 0 : readTlvs(firstValue(constraints)).find(({ tag }) => tag === der.contextZero);
|
|
51
|
+
return readTlvs(permitted?.value ?? Buffer.alloc(0)).map(({ value }) => readTlvs(value)[0]).filter((name) => name?.tag === der.dnsName).map((name) => name?.value.toString("ascii") ?? "");
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* The subject's common name a wt-tunnel root carries. The label is only a name; the constraints
|
|
55
|
+
* decide what the root may sign.
|
|
56
|
+
*/
|
|
57
|
+
const rootCommonName = (label) => `wt-tunnel root (${label})`;
|
|
58
|
+
/**
|
|
59
|
+
* Whether a DNS name constraint covers `name`. Without a leading dot it covers the name itself and
|
|
60
|
+
* every name under it; with one, only the names under it.
|
|
61
|
+
*/
|
|
62
|
+
const constraintCovers = (constraint, name) => constraint.startsWith(".") ? name.endsWith(constraint) : name === constraint || name.endsWith(`.${constraint}`);
|
|
63
|
+
const spki = (key) => key.export({
|
|
64
|
+
format: "der",
|
|
65
|
+
type: "spki"
|
|
66
|
+
});
|
|
67
|
+
const keyMatches = (certificate, keyPem) => {
|
|
68
|
+
try {
|
|
69
|
+
return spki(createPublicKey(createPrivateKey(keyPem))).equals(spki(certificate.publicKey));
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const parseCertificate = Option.liftThrowable((pem) => new X509Certificate(pem));
|
|
75
|
+
/**
|
|
76
|
+
* What makes a root unusable for these domains: a certificate that does not parse, no name
|
|
77
|
+
* constraints, a domain they do not cover, or a key that is not the certificate's. Empty when the
|
|
78
|
+
* root is fine. It reads the constraints the way the trust page does.
|
|
79
|
+
*/
|
|
80
|
+
const rootProblems = (input) => {
|
|
81
|
+
const parsed = parseCertificate(input.cert);
|
|
82
|
+
if (Option.isNone(parsed)) return ["ca.cert is not a readable certificate"];
|
|
83
|
+
const certificate = parsed.value;
|
|
84
|
+
const permitted = permittedDnsNames(certificate.raw);
|
|
85
|
+
const uncovered = input.domains.filter((domain) => !permitted.some((constraint) => constraintCovers(constraint, domain)));
|
|
86
|
+
return [
|
|
87
|
+
...permitted.length === 0 ? ["ca.cert has no DNS name constraints, so it could vouch for any site"] : [],
|
|
88
|
+
...permitted.length > 0 && uncovered.length > 0 ? [`ca.cert's name constraints (${permitted.join(", ")}) do not cover ${uncovered.join(", ")}`] : [],
|
|
89
|
+
...keyMatches(certificate, input.key) ? [] : ["ca.key is not the key of ca.cert"]
|
|
90
|
+
];
|
|
91
|
+
};
|
|
92
|
+
export { permittedDnsNames, rootCommonName, rootProblems };
|
|
93
|
+
|
|
94
|
+
//# sourceMappingURL=root-ca.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root-ca.js","names":[],"sources":["../../../../../../packages/contract/src/root-ca.ts"],"sourcesContent":["import { X509Certificate, createPrivateKey, createPublicKey } from 'node:crypto';\n\nimport { Option } from 'effect';\n\n/** A DER tag and its contents. Tags in an X.509 certificate fit in one byte. */\ninterface Tlv {\n readonly tag: number;\n readonly value: Buffer;\n}\n\nconst der = {\n contextZero: 0xa0,\n dnsName: 0x82,\n extensions: 0xa3,\n longLengthFlag: 0x80,\n octetString: 0x04,\n oid: 0x06,\n} as const;\nconst headerBytes = 2;\n/** 2.5.29.30, id-ce-nameConstraints. */\nconst nameConstraintsOid = Buffer.from('551d1e', 'hex');\n\n/** The TLV starting at `at`, and where the next one starts. */\nconst readTlv = (bytes: Buffer, at: number) => {\n const tag = bytes.readUInt8(at);\n const short = bytes.readUInt8(at + 1);\n const lengthBytes = short >= der.longLengthFlag ? short - der.longLengthFlag : 0;\n const length = lengthBytes === 0 ? short : bytes.readUIntBE(at + headerBytes, lengthBytes);\n const start = at + headerBytes + lengthBytes;\n return { next: start + length, tlv: { tag, value: bytes.subarray(start, start + length) } };\n};\n\n/** The TLVs packed one after another in `bytes`. */\nconst readTlvs = (bytes: Buffer): readonly Tlv[] => {\n const tlvs: Tlv[] = [];\n for (let at = 0; at + headerBytes <= bytes.length;) {\n const { next, tlv } = readTlv(bytes, at);\n tlvs.push(tlv);\n at = next;\n }\n return tlvs;\n};\n\nconst firstValue = (bytes: Buffer) => readTlvs(bytes)[0]?.value ?? Buffer.alloc(0);\n\n/** The name constraints extension's value, or undefined when the certificate has none. */\nconst nameConstraints = (certificate: Buffer) => {\n const tbs = firstValue(firstValue(certificate));\n const wrapper = readTlvs(tbs).find(({ tag }) => tag === der.extensions);\n const extensions = readTlvs(firstValue(wrapper?.value ?? Buffer.alloc(0)));\n const fields = extensions\n .map(({ value }) => readTlvs(value))\n .find(([id]) => id?.tag === der.oid && id.value.equals(nameConstraintsOid));\n return fields?.findLast(({ tag }) => tag === der.octetString)?.value;\n};\n\n/** `NameConstraints ::= SEQUENCE { permittedSubtrees [0] GeneralSubtrees OPTIONAL, ... }`. */\nconst permittedDnsNames = (certificate: Buffer): readonly string[] => {\n const constraints = nameConstraints(certificate);\n const permitted =\n constraints === undefined\n ? undefined\n : readTlvs(firstValue(constraints)).find(({ tag }) => tag === der.contextZero);\n return readTlvs(permitted?.value ?? Buffer.alloc(0))\n .map(({ value }) => readTlvs(value)[0])\n .filter((name) => name?.tag === der.dnsName)\n .map((name) => name?.value.toString('ascii') ?? '');\n};\n\n/**\n * The subject's common name a wt-tunnel root carries. The label is only a name; the constraints\n * decide what the root may sign.\n */\nconst rootCommonName = (label: string) => `wt-tunnel root (${label})`;\n\n/**\n * The label in a wt-tunnel root's common name, or undefined for another subject. Only DNS-name\n * characters, since the trust page puts it in a download's file name.\n */\nconst rootLabel = (certificate: X509Certificate) =>\n /^CN=wt-tunnel root \\((?<label>[a-z0-9.-]+)\\)$/mu.exec(certificate.subject)?.groups?.label;\n\n/**\n * Whether a DNS name constraint covers `name`. Without a leading dot it covers the name itself and\n * every name under it; with one, only the names under it.\n */\nconst constraintCovers = (constraint: string, name: string) =>\n constraint.startsWith('.')\n ? name.endsWith(constraint)\n : name === constraint || name.endsWith(`.${constraint}`);\n\nconst spki = (key: ReturnType<typeof createPublicKey>) =>\n key.export({ format: 'der', type: 'spki' });\n\nconst keyMatches = (certificate: X509Certificate, keyPem: string) => {\n try {\n return spki(createPublicKey(createPrivateKey(keyPem))).equals(spki(certificate.publicKey));\n } catch {\n return false;\n }\n};\n\nconst parseCertificate = Option.liftThrowable((pem: string) => new X509Certificate(pem));\n\n/**\n * What makes a root unusable for these domains: a certificate that does not parse, no name\n * constraints, a domain they do not cover, or a key that is not the certificate's. Empty when the\n * root is fine. It reads the constraints the way the trust page does.\n */\nconst rootProblems = (input: {\n readonly cert: string;\n readonly domains: readonly string[];\n readonly key: string;\n}): readonly string[] => {\n const parsed = parseCertificate(input.cert);\n if (Option.isNone(parsed)) {\n return ['ca.cert is not a readable certificate'];\n }\n const certificate = parsed.value;\n const permitted = permittedDnsNames(certificate.raw);\n const uncovered = input.domains.filter(\n (domain) => !permitted.some((constraint) => constraintCovers(constraint, domain)),\n );\n return [\n ...(permitted.length === 0\n ? ['ca.cert has no DNS name constraints, so it could vouch for any site']\n : []),\n ...(permitted.length > 0 && uncovered.length > 0\n ? [\n `ca.cert's name constraints (${permitted.join(', ')}) do not cover ${uncovered.join(', ')}`,\n ]\n : []),\n ...(keyMatches(certificate, input.key) ? [] : ['ca.key is not the key of ca.cert']),\n ];\n};\n\nexport { permittedDnsNames, rootCommonName, rootLabel, rootProblems };\n"],"mappings":"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"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { Hostname } from "./index.js";
|
|
2
|
+
import { Effect, Redacted, Schema } from "effect";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
// ../../packages/contract/src/server-config.ts
|
|
5
|
+
const authSecretMinLength = 32;
|
|
6
|
+
const tunnelTokenMinLength = 16;
|
|
7
|
+
/** The name `wt-tunnel deploy` writes the config under, and the server looks for by default. */
|
|
8
|
+
const serverConfigFileName = "wt-tunnel-server.json";
|
|
9
|
+
const Email = Schema.String.check(Schema.isPattern(/^[^@\s]+@[^@\s]+$/u));
|
|
10
|
+
const Secret = (minLength) => Schema.RedactedFromValue(Schema.String.check(Schema.isMinLength(minLength)));
|
|
11
|
+
const pemMarkers = {
|
|
12
|
+
cert: /-----BEGIN CERTIFICATE-----/u,
|
|
13
|
+
key: /-----BEGIN (?:EC |RSA )?PRIVATE KEY-----/u
|
|
14
|
+
};
|
|
15
|
+
const AllowList = Schema.Struct({
|
|
16
|
+
emailDomains: Schema.optionalKey(Schema.Array(Hostname)),
|
|
17
|
+
emails: Schema.optionalKey(Schema.Array(Email))
|
|
18
|
+
}).check(Schema.makeFilter((allow) => (allow.emails?.length ?? 0) + (allow.emailDomains?.length ?? 0) > 0 || "allow lists no emails and no email domains"));
|
|
19
|
+
const OAuthClient = {
|
|
20
|
+
clientId: Schema.NonEmptyString,
|
|
21
|
+
clientSecret: Schema.RedactedFromValue(Schema.NonEmptyString)
|
|
22
|
+
};
|
|
23
|
+
/** The sign-in providers a user may pick from, in the order the sign-in page lists them. */
|
|
24
|
+
const providerIds = [
|
|
25
|
+
"google",
|
|
26
|
+
"github",
|
|
27
|
+
"microsoft",
|
|
28
|
+
"cloudflare"
|
|
29
|
+
];
|
|
30
|
+
/**
|
|
31
|
+
* Where people sign in. Each provider is optional, and at least one must be set. `microsoft` takes
|
|
32
|
+
* the Entra ID tenant (default `common`, any account). `cloudflare` is a Cloudflare Access OIDC app
|
|
33
|
+
* in the Zero Trust team at `teamDomain`, such as `acme.cloudflareaccess.com`.
|
|
34
|
+
*/
|
|
35
|
+
const MicrosoftClient = Schema.Struct({
|
|
36
|
+
...OAuthClient,
|
|
37
|
+
tenantId: Schema.optionalKey(Schema.NonEmptyString)
|
|
38
|
+
});
|
|
39
|
+
const Providers = Schema.Struct({
|
|
40
|
+
cloudflare: Schema.optionalKey(Schema.Struct({
|
|
41
|
+
...OAuthClient,
|
|
42
|
+
teamDomain: Hostname
|
|
43
|
+
})),
|
|
44
|
+
github: Schema.optionalKey(Schema.Struct(OAuthClient)),
|
|
45
|
+
google: Schema.optionalKey(Schema.Struct(OAuthClient)),
|
|
46
|
+
microsoft: Schema.optionalKey(MicrosoftClient)
|
|
47
|
+
}).check(Schema.makeFilter((providers) => providerIds.some((id) => providers[id] !== void 0) || `providers sets none of ${providerIds.join(", ")}`));
|
|
48
|
+
/**
|
|
49
|
+
* The tunnel server's config file. The server decodes it at startup; the wt-tunnel CLI writes it
|
|
50
|
+
* and checks it against this same schema before deploying.
|
|
51
|
+
*/
|
|
52
|
+
const ServerConfigFile = Schema.Struct({
|
|
53
|
+
allow: AllowList,
|
|
54
|
+
/** The sign-in host, shared by every dev domain. */
|
|
55
|
+
authHost: Hostname,
|
|
56
|
+
/** Keys Better Auth and the dev-domain session cookie. */
|
|
57
|
+
authSecret: Secret(authSecretMinLength),
|
|
58
|
+
/**
|
|
59
|
+
* The name-constrained root that issues every dev-host certificate: its PEM files, relative to
|
|
60
|
+
* the config file's directory.
|
|
61
|
+
*/
|
|
62
|
+
ca: Schema.Struct({
|
|
63
|
+
cert: Schema.NonEmptyString,
|
|
64
|
+
key: Schema.NonEmptyString
|
|
65
|
+
}),
|
|
66
|
+
domains: Schema.NonEmptyArray(Hostname),
|
|
67
|
+
providers: Providers,
|
|
68
|
+
/** Shared secret that frpc presents to frps. */
|
|
69
|
+
tunnelToken: Secret(tunnelTokenMinLength)
|
|
70
|
+
});
|
|
71
|
+
const ServerConfigFileJson = Schema.fromJsonString(ServerConfigFile);
|
|
72
|
+
const { TaggedError: taggedErrorClass } = Schema;
|
|
73
|
+
var ServerConfigError = class extends taggedErrorClass()("ServerConfigError", { message: Schema.String }) {};
|
|
74
|
+
/** Where a `ca` path in a config file in `dir` points. */
|
|
75
|
+
const caFile = (dir, file) => isAbsolute(file) ? file : join(dir, file);
|
|
76
|
+
/**
|
|
77
|
+
* Decodes a config file's text, reads the root's files relative to `dir` with `read`, and checks
|
|
78
|
+
* that they hold PEM. Every schema problem is reported at once.
|
|
79
|
+
*/
|
|
80
|
+
const readServerConfig = (input) => Effect.gen(function* readConfig() {
|
|
81
|
+
const invalid = (message) => new ServerConfigError({ message: `${input.source} is not a valid server config: ${message}` });
|
|
82
|
+
const file = yield* Schema.decodeUnknownEffect(ServerConfigFileJson)(input.text, { errors: "all" }).pipe(Effect.mapError((schemaError) => invalid(schemaError.message)));
|
|
83
|
+
/** Never echoes the file's content: the key is secret. */
|
|
84
|
+
const readCa = (field) => {
|
|
85
|
+
const path = caFile(input.dir, file.ca[field]);
|
|
86
|
+
return input.read(path).pipe(Effect.mapError(() => invalid(`cannot read ca.${field} at ${path}`)), Effect.filterOrFail((text) => pemMarkers[field].test(text), () => invalid(`ca.${field} at ${path} holds no PEM ${field === "cert" ? "certificate" : "private key"}`)));
|
|
87
|
+
};
|
|
88
|
+
const ca = {
|
|
89
|
+
cert: yield* readCa("cert"),
|
|
90
|
+
key: Redacted.make(yield* readCa("key"))
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
...file,
|
|
94
|
+
ca
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
export { AllowList, ServerConfigFileJson, caFile, providerIds, readServerConfig, serverConfigFileName };
|
|
98
|
+
|
|
99
|
+
//# sourceMappingURL=server-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-config.js","names":[],"sources":["../../../../../../packages/contract/src/server-config.ts"],"sourcesContent":["import { isAbsolute, join } from 'node:path';\n\nimport { Effect, Redacted, Schema } from 'effect';\n\nimport { Hostname } from './index.ts';\n\nconst authSecretMinLength = 32;\nconst tunnelTokenMinLength = 16;\n\n/** The name `wt-tunnel deploy` writes the config under, and the server looks for by default. */\nconst serverConfigFileName = 'wt-tunnel-server.json';\n\nconst Email = Schema.String.check(Schema.isPattern(/^[^@\\s]+@[^@\\s]+$/u));\n\nconst Secret = (minLength: number) =>\n Schema.RedactedFromValue(Schema.String.check(Schema.isMinLength(minLength)));\n\nconst pemMarkers = {\n cert: /-----BEGIN CERTIFICATE-----/u,\n key: /-----BEGIN (?:EC |RSA )?PRIVATE KEY-----/u,\n} as const;\n\nconst AllowList = Schema.Struct({\n emailDomains: Schema.optionalKey(Schema.Array(Hostname)),\n emails: Schema.optionalKey(Schema.Array(Email)),\n}).check(\n Schema.makeFilter(\n (allow) =>\n (allow.emails?.length ?? 0) + (allow.emailDomains?.length ?? 0) > 0 ||\n 'allow lists no emails and no email domains',\n ),\n);\n\nconst OAuthClient = {\n clientId: Schema.NonEmptyString,\n clientSecret: Schema.RedactedFromValue(Schema.NonEmptyString),\n};\n\n/** The sign-in providers a user may pick from, in the order the sign-in page lists them. */\nconst providerIds = ['google', 'github', 'microsoft', 'cloudflare'] as const;\ntype ProviderId = (typeof providerIds)[number];\n\n/**\n * Where people sign in. Each provider is optional, and at least one must be set. `microsoft` takes\n * the Entra ID tenant (default `common`, any account). `cloudflare` is a Cloudflare Access OIDC app\n * in the Zero Trust team at `teamDomain`, such as `acme.cloudflareaccess.com`.\n */\nconst MicrosoftClient = Schema.Struct({\n ...OAuthClient,\n tenantId: Schema.optionalKey(Schema.NonEmptyString),\n});\n\nconst Providers = Schema.Struct({\n cloudflare: Schema.optionalKey(Schema.Struct({ ...OAuthClient, teamDomain: Hostname })),\n github: Schema.optionalKey(Schema.Struct(OAuthClient)),\n google: Schema.optionalKey(Schema.Struct(OAuthClient)),\n microsoft: Schema.optionalKey(MicrosoftClient),\n}).check(\n Schema.makeFilter(\n (providers) =>\n providerIds.some((id) => providers[id] !== undefined) ||\n `providers sets none of ${providerIds.join(', ')}`,\n ),\n);\ntype Providers = typeof Providers.Type;\n\n/**\n * The tunnel server's config file. The server decodes it at startup; the wt-tunnel CLI writes it\n * and checks it against this same schema before deploying.\n */\nconst ServerConfigFile = Schema.Struct({\n allow: AllowList,\n /** The sign-in host, shared by every dev domain. */\n authHost: Hostname,\n /** Keys Better Auth and the dev-domain session cookie. */\n authSecret: Secret(authSecretMinLength),\n /**\n * The name-constrained root that issues every dev-host certificate: its PEM files, relative to\n * the config file's directory.\n */\n ca: Schema.Struct({ cert: Schema.NonEmptyString, key: Schema.NonEmptyString }),\n domains: Schema.NonEmptyArray(Hostname),\n providers: Providers,\n /** Shared secret that frpc presents to frps. */\n tunnelToken: Secret(tunnelTokenMinLength),\n});\ntype ServerConfigFile = typeof ServerConfigFile.Type;\n\nconst ServerConfigFileJson = Schema.fromJsonString(ServerConfigFile);\n\n/** The config as the server holds it: the root's PEM text in place of its file names. */\ninterface ServerConfig extends Omit<ServerConfigFile, 'ca'> {\n readonly ca: { readonly cert: string; readonly key: Redacted.Redacted };\n}\n\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass ServerConfigError extends taggedErrorClass<ServerConfigError>()('ServerConfigError', {\n message: Schema.String,\n}) {}\n\n/** Where a `ca` path in a config file in `dir` points. */\nconst caFile = (dir: string, file: string) => (isAbsolute(file) ? file : join(dir, file));\n\n/**\n * Decodes a config file's text, reads the root's files relative to `dir` with `read`, and checks\n * that they hold PEM. Every schema problem is reported at once.\n */\nconst readServerConfig = <ReadError>(input: {\n readonly dir: string;\n readonly read: (file: string) => Effect.Effect<string, ReadError>;\n readonly source: string;\n readonly text: string;\n}) =>\n Effect.gen(function* readConfig() {\n const invalid = (message: string) =>\n new ServerConfigError({\n message: `${input.source} is not a valid server config: ${message}`,\n });\n const file = yield* Schema.decodeUnknownEffect(ServerConfigFileJson)(input.text, {\n errors: 'all',\n }).pipe(Effect.mapError((schemaError) => invalid(schemaError.message)));\n /** Never echoes the file's content: the key is secret. */\n const readCa = (field: keyof typeof pemMarkers) => {\n const path = caFile(input.dir, file.ca[field]);\n return input.read(path).pipe(\n Effect.mapError(() => invalid(`cannot read ca.${field} at ${path}`)),\n Effect.filterOrFail(\n (text) => pemMarkers[field].test(text),\n () =>\n invalid(\n `ca.${field} at ${path} holds no PEM ${field === 'cert' ? 'certificate' : 'private key'}`,\n ),\n ),\n );\n };\n const ca = { cert: yield* readCa('cert'), key: Redacted.make(yield* readCa('key')) };\n const config: ServerConfig = { ...file, ca };\n return config;\n });\n\nexport {\n AllowList,\n providerIds,\n ServerConfigFileJson,\n caFile,\n readServerConfig,\n serverConfigFileName,\n};\nexport type { ProviderId, ServerConfig, ServerConfigFile };\n"],"mappings":"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"}
|
package/dist/prepare.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { InfraError } from "./errors.js";
|
|
2
|
+
import { serverConfigFileName } from "./packages/contract/src/server-config.js";
|
|
3
|
+
import { loadDeployConfig, resolveDeployment } from "./config.js";
|
|
4
|
+
import { rootProblems } from "./packages/contract/src/root-ca.js";
|
|
5
|
+
import { checkServerFiles, hasServerConfig, readServerDir, serverFile, textOf, writeServerDir } from "./server-dir.js";
|
|
6
|
+
import { createdSummary, draftServerDir } from "./create-server-dir.js";
|
|
7
|
+
import { checkEnv, stackEnv } from "./secrets.js";
|
|
8
|
+
import { seedDrift } from "./seed-drift.js";
|
|
9
|
+
import { Console, Effect, FileSystem, Option, Path, Redacted, Schema } from "effect";
|
|
10
|
+
// src/prepare.ts
|
|
11
|
+
/** The server config as plain JSON, to rewrite some keys and keep the rest as they are. */
|
|
12
|
+
const ConfigJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
|
|
13
|
+
/** The text of the deploy file's `ca.cert`, if it names one that can be read. */
|
|
14
|
+
const seededCert = (loaded) => Effect.gen(function* read() {
|
|
15
|
+
const { cert } = loaded.config.ca ?? {};
|
|
16
|
+
if (cert === void 0) return Option.none();
|
|
17
|
+
const path = yield* Path.Path;
|
|
18
|
+
return yield* (yield* FileSystem.FileSystem).readFileString(path.resolve(loaded.dir, cert)).pipe(Effect.option);
|
|
19
|
+
});
|
|
20
|
+
/** The fields `--force` copies into an existing server config. Never `ca`: see the warning. */
|
|
21
|
+
const copyable = (drift) => [...new Set(drift.map(({ field }) => field))].filter((field) => field !== "ca");
|
|
22
|
+
/** The config file with the deploy file's values for `fields`, every other key kept as it is. */
|
|
23
|
+
const withSeeds = (file, seeds, fields) => Schema.decodeUnknownEffect(ConfigJson)(textOf(file)).pipe(Effect.orDie, Effect.map((json) => {
|
|
24
|
+
const copied = Object.fromEntries(fields.map((field) => [field, seeds[field]]));
|
|
25
|
+
const indent = 2;
|
|
26
|
+
return serverFile(file.name, `${JSON.stringify({
|
|
27
|
+
...json,
|
|
28
|
+
...copied
|
|
29
|
+
}, void 0, indent)}\n`, file.mode);
|
|
30
|
+
}));
|
|
31
|
+
/** Writes the folder's config file from `files` over the one on disk, with its mode. */
|
|
32
|
+
const writeConfigFile = (dir, files) => Effect.gen(function* write() {
|
|
33
|
+
const updated = files.find((file) => file.name === serverConfigFileName);
|
|
34
|
+
if (updated === void 0) return;
|
|
35
|
+
const fs = yield* FileSystem.FileSystem;
|
|
36
|
+
const target = (yield* Path.Path).join(dir, serverConfigFileName);
|
|
37
|
+
yield* fs.writeFile(target, Buffer.from(updated.base64, "base64")).pipe(Effect.orDie);
|
|
38
|
+
yield* fs.chmod(target, updated.mode).pipe(Effect.orDie);
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* Fails when the deploy file's domains are not all ones the current root may sign for. `ca create`
|
|
42
|
+
* signs for the server config's domains, so the way out is to add them there first.
|
|
43
|
+
*/
|
|
44
|
+
const refuseUncoveredDomains = (request, server) => {
|
|
45
|
+
const { authHost, domains = [] } = request.loaded.config;
|
|
46
|
+
const problems = rootProblems({
|
|
47
|
+
cert: server.config.ca.cert,
|
|
48
|
+
domains,
|
|
49
|
+
key: Redacted.value(server.config.ca.key)
|
|
50
|
+
});
|
|
51
|
+
const file = `${server.dir}/${serverConfigFileName}`;
|
|
52
|
+
return problems.length === 0 ? Effect.void : Effect.fail(new InfraError({ message: `--force cannot copy domains into ${file}: ${problems.join("; ")}. The root's name constraints are signed into it, so it needs a new root: set domains in ${file} to ${domains.join(", ")}, run wt-tunnel ca create --force, which signs for that config's domains, deploy, then trust the new root on each device from https://${authHost}/ca. Nothing was written.` }));
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Copies `fields` from the deploy file into the server config: checks the folder with the new
|
|
56
|
+
* config first, so a change the root cannot sign for stops before anything is written.
|
|
57
|
+
*/
|
|
58
|
+
const copySeeds = (request, server, fields) => Effect.gen(function* copy() {
|
|
59
|
+
const { config: deploy } = request.loaded;
|
|
60
|
+
if (fields.includes("domains")) yield* refuseUncoveredDomains(request, server);
|
|
61
|
+
const files = yield* Effect.all(server.files.map((file) => file.name === "wt-tunnel-server.json" ? withSeeds(file, deploy, fields) : Effect.succeed(file)));
|
|
62
|
+
const checked = yield* checkServerFiles({
|
|
63
|
+
deploy,
|
|
64
|
+
dir: server.dir,
|
|
65
|
+
files
|
|
66
|
+
});
|
|
67
|
+
yield* writeConfigFile(server.dir, files);
|
|
68
|
+
yield* Console.log(`Copied ${fields.join(" and ")} from the deploy file into ${server.dir}/${serverConfigFileName}.`);
|
|
69
|
+
return checked;
|
|
70
|
+
});
|
|
71
|
+
/** How to resolve what is left: copy the settings with --force; a root is replaced on purpose only. */
|
|
72
|
+
const driftAdvice = (drift) => [...copyable(drift).length > 0 ? [`To copy ${copyable(drift).join(" and ")} from the deploy file into it, run wt-tunnel deploy --force (or prepare --force). Otherwise make the deploy file match.`] : [], ...drift.some(({ field }) => field === "ca") ? ["A deploy never replaces the root, which every device trusts. For a new one, run wt-tunnel ca create --force, deploy, then trust it on each device; or remove ca from the deploy file."] : []];
|
|
73
|
+
/** Warns about what the deploy file says differently from the server config, and what to do. */
|
|
74
|
+
const warnOnDrift = (dir, drift) => drift.length === 0 ? Effect.void : Console.warn([
|
|
75
|
+
`Warning: the deploy file differs from ${dir}/${serverConfigFileName}, which decides what the server does:`,
|
|
76
|
+
...drift.map(({ message }) => ` - ${message}`),
|
|
77
|
+
...driftAdvice(drift)
|
|
78
|
+
].join("\n"));
|
|
79
|
+
/**
|
|
80
|
+
* Reads and checks the existing folder. With `force`, the deploy file's `domains` and `allow` are
|
|
81
|
+
* copied into its config; otherwise it is never rewritten, and differences only warn.
|
|
82
|
+
*/
|
|
83
|
+
const existingServerDir = (request) => Effect.gen(function* existing() {
|
|
84
|
+
const { loaded } = request;
|
|
85
|
+
const read = yield* readServerDir(loaded.serverDir, loaded.config);
|
|
86
|
+
const cert = Option.getOrUndefined(yield* seededCert(loaded));
|
|
87
|
+
const drift = seedDrift(loaded.config, read.config, cert);
|
|
88
|
+
const fields = request.force === true ? copyable(drift) : [];
|
|
89
|
+
const server = fields.length === 0 ? read : yield* copySeeds(request, read, fields);
|
|
90
|
+
yield* warnOnDrift(server.dir, drift.filter(({ field }) => field === "ca" || !fields.includes(field)));
|
|
91
|
+
if (server.unreferenced.length > 0) yield* Console.log(`Uploading ${server.unreferenced.join(", ")} from ${loaded.serverDir} as well; the server config names none of them.`);
|
|
92
|
+
return server;
|
|
93
|
+
});
|
|
94
|
+
/** Drafts a new folder, checks it like an existing one, then writes it or only previews it. */
|
|
95
|
+
const newServerDir = (request) => Effect.gen(function* create() {
|
|
96
|
+
const { loaded } = request;
|
|
97
|
+
const draft = yield* draftServerDir({
|
|
98
|
+
ask: request.ask,
|
|
99
|
+
deploy: loaded.config,
|
|
100
|
+
deployDir: loaded.dir,
|
|
101
|
+
env: request.env,
|
|
102
|
+
serverDir: loaded.serverDir
|
|
103
|
+
});
|
|
104
|
+
const server = yield* checkServerFiles({
|
|
105
|
+
deploy: loaded.config,
|
|
106
|
+
dir: loaded.serverDir,
|
|
107
|
+
files: draft.files
|
|
108
|
+
});
|
|
109
|
+
if (request.missing === "create") {
|
|
110
|
+
yield* writeServerDir(loaded.serverDir, draft.files);
|
|
111
|
+
yield* Console.log(createdSummary({
|
|
112
|
+
authHost: server.config.authHost,
|
|
113
|
+
draft,
|
|
114
|
+
serverDir: loaded.serverDir
|
|
115
|
+
}));
|
|
116
|
+
} else yield* Console.log(`${loaded.serverDir} has no server config yet; deploy would create it.${draft.generated.length === 0 ? "" : ` This plan uses a ${draft.generated.join(", ")} made for the preview only; deploy makes its own.`} Nothing was written.`);
|
|
117
|
+
return server;
|
|
118
|
+
});
|
|
119
|
+
/** The server folder, checked, creating it or previewing it as the command asks. */
|
|
120
|
+
const serverDirFor = (request) => Effect.gen(function* serverDir() {
|
|
121
|
+
if (yield* hasServerConfig(request.loaded.serverDir)) return yield* existingServerDir(request);
|
|
122
|
+
if (request.missing === "require") return yield* new InfraError({ message: `${request.loaded.serverDir} has no server config; run wt-tunnel deploy to create it` });
|
|
123
|
+
return yield* newServerDir(request);
|
|
124
|
+
});
|
|
125
|
+
/** Loads the deploy file, checks the environment, then reads, creates or previews the folder. */
|
|
126
|
+
const prepare = (input) => Effect.gen(function* prepareRun() {
|
|
127
|
+
const loaded = yield* loadDeployConfig(input.config);
|
|
128
|
+
yield* checkEnv(loaded.config, input.env);
|
|
129
|
+
const server = yield* serverDirFor({
|
|
130
|
+
...input,
|
|
131
|
+
loaded
|
|
132
|
+
});
|
|
133
|
+
const deployment = resolveDeployment(loaded.config, server.config, input.version);
|
|
134
|
+
return {
|
|
135
|
+
cwd: loaded.dir,
|
|
136
|
+
deployment,
|
|
137
|
+
env: stackEnv(deployment, server.files, input.env)
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
export { prepare, serverDirFor };
|
|
141
|
+
|
|
142
|
+
//# sourceMappingURL=prepare.js.map
|