@tafrahq/wt-tunnel 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +225 -2
  3. package/dist/alchemy.js +40 -0
  4. package/dist/alchemy.js.map +1 -0
  5. package/dist/bin.js +21 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/ca.js +88 -0
  8. package/dist/ca.js.map +1 -0
  9. package/dist/cli.js +182 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/config.js +81 -0
  12. package/dist/config.js.map +1 -0
  13. package/dist/create-root.js +85 -0
  14. package/dist/create-root.js.map +1 -0
  15. package/dist/create-server-dir.js +153 -0
  16. package/dist/create-server-dir.js.map +1 -0
  17. package/dist/deployment.js +122 -0
  18. package/dist/deployment.js.map +1 -0
  19. package/dist/errors.js +7 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/init.js +89 -0
  22. package/dist/init.js.map +1 -0
  23. package/dist/outputs.js +38 -0
  24. package/dist/outputs.js.map +1 -0
  25. package/dist/packages/contract/src/index.js +12 -0
  26. package/dist/packages/contract/src/index.js.map +1 -0
  27. package/dist/packages/contract/src/root-ca.js +94 -0
  28. package/dist/packages/contract/src/root-ca.js.map +1 -0
  29. package/dist/packages/contract/src/server-config.js +99 -0
  30. package/dist/packages/contract/src/server-config.js.map +1 -0
  31. package/dist/prepare.js +73 -0
  32. package/dist/prepare.js.map +1 -0
  33. package/dist/providers.js +82 -0
  34. package/dist/providers.js.map +1 -0
  35. package/dist/secrets.js +39 -0
  36. package/dist/secrets.js.map +1 -0
  37. package/dist/server-dir.js +141 -0
  38. package/dist/server-dir.js.map +1 -0
  39. package/dist/server-machine.js +136 -0
  40. package/dist/server-machine.js.map +1 -0
  41. package/dist/stack.js +104 -0
  42. package/dist/stack.js.map +1 -0
  43. package/dist/uploads.js +24 -0
  44. package/dist/uploads.js.map +1 -0
  45. package/package.json +59 -3
package/dist/init.js ADDED
@@ -0,0 +1,89 @@
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
+ // Your Fly.io organization slug (\`fly orgs list\`), a name for the new app (Fly app names are
18
+ // global), and a region (\`fly platform regions\`). memoryMb is optional (default ${String(defaults.memoryMb)}).
19
+ "fly": { "org": "personal", "app": "${placeholder}", "region": "ams" },
20
+
21
+ // The name tunnel clients connect to: server.host in each wt-tunnel.json. New roots are named
22
+ // after it.
23
+ "tunnelHost": "wt-tunnel.example.com",
24
+
25
+ // Who creates the DNS records, one entry per zone: *.<domain> for each dev domain, the tunnel host
26
+ // and the sign-in host. Each record goes in the most specific zone its name sits in, and every
27
+ // name must sit in one.
28
+ // "cloudflare": the stack creates the records. zoneId is on the zone's Overview page.
29
+ // "manual": you create them; \`wt-tunnel outputs\` lists them.
30
+ // One CLOUDFLARE_API_TOKEN serves every Cloudflare zone listed. A user API token (My Profile,
31
+ // API Tokens) can cover zones in several accounts.
32
+ "dns": [{ "provider": "cloudflare", "zone": "example.com", "zoneId": "${placeholder}" }],
33
+
34
+ // Where Alchemy records what it created. { "provider": "cloudflare", "accountId": "..." }: a
35
+ // state store Worker in that Cloudflare account, usable from any machine. "local": .alchemy/
36
+ // next to this file, which is git-ignored; back it up, because updating or destroying the
37
+ // deployment needs it. Without Cloudflare, use "manual" dns entries and "local" state.
38
+ "state": { "provider": "cloudflare", "accountId": "${placeholder}" }
39
+
40
+ // Optional: "image" (default: the server release that matches this CLI's version), "serverDir"
41
+ // (default "${defaults.serverDir}"), and "stack" and "stage", Alchemy's names for the deployment
42
+ // (default "${defaults.stack}" and "${defaults.stage}").
43
+ }
44
+ `;
45
+ const nextSteps = (file) => `Wrote ${file}, and ${ignoreLines.join(" and ")} to .gitignore. Next:
46
+
47
+ 1. Edit it: replace each ${placeholder} and the example names.
48
+ 2. Export these secrets (from a secret manager, never from a committed file):
49
+ FLY_API_TOKEN fly tokens create org <org>
50
+ CLOUDFLARE_API_TOKEN with a "cloudflare" dns entry or state: one Cloudflare user API token
51
+ with Zone > DNS > Edit on every Cloudflare zone in "dns", even zones
52
+ in different accounts. With Cloudflare state it also needs Workers
53
+ Scripts Edit, Account Settings Edit, Secrets Store Edit and Workers
54
+ Tail Read on the state's account.
55
+ CLOUDFLARE_ACCOUNT_ID only with a "cloudflare" dns entry and "state": "local": the account
56
+ of any of those zones. Otherwise the CLI sets it from state.accountId.
57
+ 3. Create an OAuth client with one or more sign-in providers, and export its variables for the
58
+ first deploy (GOOGLE_*, GITHUB_*, MICROSOFT_* or CLOUDFLARE_ACCESS_*):
59
+ ${providerSteps().split("\n").map((line) => ` - ${line}`).join("\n")}
60
+ 4. wt-tunnel deploy --domain dev.example.com --auth-host auth-wt-tunnel.example.com \\
61
+ --allow-email you@example.com
62
+ The first deploy creates ${serverDirLine} (the server config, a new root CA, and generated tokens),
63
+ then deploys. It holds secrets: back it up, and never commit it. Later deploys upload it as it
64
+ is; edit it and deploy again to change what the server does.
65
+ `;
66
+ /** Adds each of `ignoreLines` that `dir`'s .gitignore does not list yet, creating the file. */
67
+ const ignoreServerDir = (dir) => Effect.gen(function* ignore() {
68
+ const fs = yield* FileSystem.FileSystem;
69
+ const file = (yield* Path.Path).join(dir, ".gitignore");
70
+ const current = (yield* fs.exists(file).pipe(Effect.orDie)) ? yield* fs.readFileString(file).pipe(Effect.orDie) : "";
71
+ const listed = new Set(current.split("\n").map((line) => line.trim()));
72
+ const missing = ignoreLines.filter((line) => !listed.has(line));
73
+ if (missing.length > 0) {
74
+ const separator = current === "" || current.endsWith("\n") ? "" : "\n";
75
+ yield* fs.writeFileString(file, `${current}${separator}${missing.map((line) => `${line}\n`).join("")}`).pipe(Effect.orDie);
76
+ }
77
+ });
78
+ /** Writes the starter deploy file into `dir` and returns what to do next. Never overwrites it. */
79
+ const writeStarterConfig = (dir) => Effect.gen(function* init() {
80
+ const fs = yield* FileSystem.FileSystem;
81
+ const file = (yield* Path.Path).join(dir, deployFileName);
82
+ yield* refuseExisting(file, "edit it, or delete it to start over");
83
+ yield* fs.writeFileString(file, starterConfig, { flag: "wx" }).pipe(Effect.orDie);
84
+ yield* ignoreServerDir(dir);
85
+ return nextSteps(file);
86
+ });
87
+ export { placeholder, writeStarterConfig };
88
+
89
+ //# sourceMappingURL=init.js.map
@@ -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 // Your Fly.io organization slug (\\`fly orgs list\\`), a name for the new app (Fly app names are\n // global), and a region (\\`fly platform regions\\`). memoryMb is optional (default ${String(defaults.memoryMb)}).\n \"fly\": { \"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 // 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. \"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 --domain dev.example.com --auth-host auth-wt-tunnel.example.com \\\\\n --allow-email you@example.com\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,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AA,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"}
@@ -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,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":";;;AAUA,MAAM,MAAM;CACV,aAAa;CACb,SAAS;CACT,YAAY;CACZ,gBAAgB;CAChB,aAAa;CACb,KAAK;AACP;AACA,MAAM,cAAc;;AAEpB,MAAM,qBAAqB,OAAO,KAAK,UAAU,KAAK;;AAGtD,MAAM,WAAW,OAAe,OAAe;CAC7C,MAAM,MAAM,MAAM,UAAU,EAAE;CAC9B,MAAM,QAAQ,MAAM,UAAU,KAAK,CAAC;CACpC,MAAM,cAAc,SAAS,IAAI,iBAAiB,QAAQ,IAAI,iBAAiB;CAC/E,MAAM,SAAS,gBAAgB,IAAI,QAAQ,MAAM,WAAW,KAAK,aAAa,WAAW;CACzF,MAAM,QAAQ,KAAK,cAAc;CACjC,OAAO;EAAE,MAAM,QAAQ;EAAQ,KAAK;GAAE;GAAK,OAAO,MAAM,SAAS,OAAO,QAAQ,MAAM;EAAE;CAAE;AAC5F;;AAGA,MAAM,YAAY,UAAkC;CAClD,MAAM,OAAc,CAAC;CACrB,KAAK,IAAI,KAAK,GAAG,KAAK,eAAe,MAAM,SAAS;EAClD,MAAM,EAAE,MAAM,QAAQ,QAAQ,OAAO,EAAE;EACvC,KAAK,KAAK,GAAG;EACb,KAAK;CACP;CACA,OAAO;AAC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,OAAO,KAAK,gBAAgB,iBAAiB,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,KAAK,YAAY,SAAS,CAAC;CAC3F,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,mBAAmB,OAAO,eAAe,QAAgB,IAAI,gBAAgB,GAAG,CAAC;;;;;;AAOvF,MAAM,gBAAgB,UAIG;CACvB,MAAM,SAAS,iBAAiB,MAAM,IAAI;CAC1C,IAAI,OAAO,OAAO,MAAM,GACtB,OAAO,CAAC,uCAAuC;CAEjD,MAAM,cAAc,OAAO;CAC3B,MAAM,YAAY,kBAAkB,YAAY,GAAG;CACnD,MAAM,YAAY,MAAM,QAAQ,QAC7B,WAAW,CAAC,UAAU,MAAM,eAAe,iBAAiB,YAAY,MAAM,CAAC,CAClF;CACA,OAAO;EACL,GAAI,UAAU,WAAW,IACrB,CAAC,qEAAqE,IACtE,CAAC;EACL,GAAI,UAAU,SAAS,KAAK,UAAU,SAAS,IAC3C,CACE,+BAA+B,UAAU,KAAK,IAAI,EAAE,iBAAiB,UAAU,KAAK,IAAI,GAC1F,IACA,CAAC;EACL,GAAI,WAAW,aAAa,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,kCAAkC;CACnF;AACF"}
@@ -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, Providers, ServerConfigError, ServerConfigFile, 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 Providers,\n providerIds,\n ServerConfigError,\n ServerConfigFile,\n ServerConfigFileJson,\n caFile,\n readServerConfig,\n serverConfigFileName,\n};\nexport type { ProviderId, ServerConfig };\n"],"mappings":";;;;AAMA,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;;AAG7B,MAAM,uBAAuB;AAE7B,MAAM,QAAQ,OAAO,OAAO,MAAM,OAAO,UAAU,oBAAoB,CAAC;AAExE,MAAM,UAAU,cACd,OAAO,kBAAkB,OAAO,OAAO,MAAM,OAAO,YAAY,SAAS,CAAC,CAAC;AAE7E,MAAM,aAAa;CACjB,MAAM;CACN,KAAK;AACP;AAEA,MAAM,YAAY,OAAO,OAAO;CAC9B,cAAc,OAAO,YAAY,OAAO,MAAM,QAAQ,CAAC;CACvD,QAAQ,OAAO,YAAY,OAAO,MAAM,KAAK,CAAC;AAChD,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,WACE,MAAM,QAAQ,UAAU,MAAM,MAAM,cAAc,UAAU,KAAK,KAClE,4CACJ,CACF;AAEA,MAAM,cAAc;CAClB,UAAU,OAAO;CACjB,cAAc,OAAO,kBAAkB,OAAO,cAAc;AAC9D;;AAGA,MAAM,cAAc;CAAC;CAAU;CAAU;CAAa;AAAY;;;;;;AAQlE,MAAM,kBAAkB,OA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AQ,YAAY,OAAO,CAAC,CAAC;;CAEtE,MAAM,UAAU,UAAmC;EACjD,MAAM,OAAO,OAAO,MAAM,KAAK,KAAK,GAAG,MAAM;EAC7C,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,KACtB,OAAO,eAAe,QAAQ,kBAAkB,MAAM,MAAM,MAAM,CAAC,GACnE,OAAO,cACJ,SAAS,WAAW,MAAM,CAAC,KAAK,IAAI,SAEnC,QACE,MAAM,MAAM,MAAM,KAAK,gBAAgB,UAAU,SAAS,gBAAgB,eAC5E,CACJ,CACF;CACF;CACA,MAAM,KAAK;EAAE,MAAM,OAAO,OAAO,MAAM;EAAG,KAAK,SAAS,KAAK,OAAO,OAAO,KAAK,CAAC;CAAE;CAEnF,OAAO;EADwB,GAAG;EAAM;CAC5B;AACd,CAAC"}
@@ -0,0 +1,73 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { loadDeployConfig, resolveDeployment } from "./config.js";
3
+ import { checkServerFiles, hasServerConfig, readServerDir, writeServerDir } from "./server-dir.js";
4
+ import { createdSummary, draftServerDir } from "./create-server-dir.js";
5
+ import { checkEnv, stackEnv } from "./secrets.js";
6
+ import { Console, Effect } from "effect";
7
+ // src/prepare.ts
8
+ const creationFlags = (inputs) => [
9
+ ...inputs.domains.length > 0 ? ["--domain"] : [],
10
+ ...inputs.authHost === void 0 ? [] : ["--auth-host"],
11
+ ...inputs.allowEmails.length > 0 ? ["--allow-email"] : [],
12
+ ...inputs.allowEmailDomains.length > 0 ? ["--allow-email-domain"] : [],
13
+ ...inputs.caCert === void 0 ? [] : ["--ca-cert"],
14
+ ...inputs.caKey === void 0 ? [] : ["--ca-key"]
15
+ ];
16
+ /** Reads and checks the existing folder. It is never rewritten. */
17
+ const existingServerDir = ({ inputs, loaded }) => Effect.gen(function* existing() {
18
+ const server = yield* readServerDir(loaded.serverDir, loaded.config);
19
+ const ignored = creationFlags(inputs);
20
+ if (ignored.length > 0) yield* Console.log(`Ignoring ${ignored.join(", ")}: ${loaded.serverDir} exists. Edit it to change what the server does.`);
21
+ if (server.unreferenced.length > 0) yield* Console.log(`Uploading ${server.unreferenced.join(", ")} from ${loaded.serverDir} as well; the server config names none of them.`);
22
+ return server;
23
+ });
24
+ /** Drafts a new folder, checks it like an existing one, then writes it or only previews it. */
25
+ const newServerDir = (request) => Effect.gen(function* create() {
26
+ const { loaded } = request;
27
+ const draft = yield* draftServerDir({
28
+ ask: request.ask,
29
+ deploy: loaded.config,
30
+ deployDir: loaded.dir,
31
+ env: request.env,
32
+ inputs: request.inputs,
33
+ serverDir: loaded.serverDir
34
+ });
35
+ const server = yield* checkServerFiles({
36
+ deploy: loaded.config,
37
+ dir: loaded.serverDir,
38
+ files: draft.files
39
+ });
40
+ if (request.missing === "create") {
41
+ yield* writeServerDir(loaded.serverDir, draft.files);
42
+ yield* Console.log(createdSummary({
43
+ authHost: server.config.authHost,
44
+ draft,
45
+ serverDir: loaded.serverDir
46
+ }));
47
+ } 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.`);
48
+ return server;
49
+ });
50
+ /** The server folder, checked, creating it or previewing it as the command asks. */
51
+ const serverDirFor = (request) => Effect.gen(function* serverDir() {
52
+ if (yield* hasServerConfig(request.loaded.serverDir)) return yield* existingServerDir(request);
53
+ if (request.missing === "require") return yield* new InfraError({ message: `${request.loaded.serverDir} has no server config; run wt-tunnel deploy to create it` });
54
+ return yield* newServerDir(request);
55
+ });
56
+ /** Loads the deploy file, checks the environment, then reads, creates or previews the folder. */
57
+ const prepare = (input) => Effect.gen(function* prepareRun() {
58
+ const loaded = yield* loadDeployConfig(input.config);
59
+ yield* checkEnv(loaded.config, input.env);
60
+ const server = yield* serverDirFor({
61
+ ...input,
62
+ loaded
63
+ });
64
+ const deployment = resolveDeployment(loaded.config, server.config, input.version);
65
+ return {
66
+ cwd: loaded.dir,
67
+ deployment,
68
+ env: stackEnv(deployment, server.files, input.env)
69
+ };
70
+ });
71
+ export { prepare, serverDirFor };
72
+
73
+ //# sourceMappingURL=prepare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepare.js","names":[],"sources":["../src/prepare.ts"],"sourcesContent":["import { Console, Effect } from 'effect';\n\nimport { loadDeployConfig, resolveDeployment } from './config.ts';\nimport type { LoadedDeploy } from './config.ts';\nimport { createdSummary, draftServerDir } from './create-server-dir.ts';\nimport type { Ask, CreateInputs } from './create-server-dir.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\nimport { checkEnv, stackEnv } from './secrets.ts';\nimport type { Env } from './secrets.ts';\nimport { checkServerFiles, hasServerConfig, readServerDir, writeServerDir } from './server-dir.ts';\n\n/**\n * What a command does when the server folder has no config yet: `create` writes it (deploy and\n * prepare), `preview` builds it in memory only (plan), `require` fails (everything else).\n */\ntype Missing = 'create' | 'preview' | 'require';\n\ninterface ServerDirRequest {\n readonly ask: Ask;\n readonly env: Env;\n readonly inputs: CreateInputs;\n readonly loaded: LoadedDeploy;\n readonly missing: Missing;\n}\n\nconst creationFlags = (inputs: CreateInputs) => [\n ...(inputs.domains.length > 0 ? ['--domain'] : []),\n ...(inputs.authHost === undefined ? [] : ['--auth-host']),\n ...(inputs.allowEmails.length > 0 ? ['--allow-email'] : []),\n ...(inputs.allowEmailDomains.length > 0 ? ['--allow-email-domain'] : []),\n ...(inputs.caCert === undefined ? [] : ['--ca-cert']),\n ...(inputs.caKey === undefined ? [] : ['--ca-key']),\n];\n\n/** Reads and checks the existing folder. It is never rewritten. */\nconst existingServerDir = ({ inputs, loaded }: ServerDirRequest) =>\n Effect.gen(function* existing() {\n const server = yield* readServerDir(loaded.serverDir, loaded.config);\n const ignored = creationFlags(inputs);\n if (ignored.length > 0) {\n yield* Console.log(\n `Ignoring ${ignored.join(', ')}: ${loaded.serverDir} exists. Edit it to change what the server does.`,\n );\n }\n if (server.unreferenced.length > 0) {\n yield* Console.log(\n `Uploading ${server.unreferenced.join(', ')} from ${loaded.serverDir} as well; the server config names none of them.`,\n );\n }\n return server;\n });\n\n/** Drafts a new folder, checks it like an existing one, then writes it or only previews it. */\nconst newServerDir = (request: ServerDirRequest) =>\n Effect.gen(function* create() {\n const { loaded } = request;\n const draft = yield* draftServerDir({\n ask: request.ask,\n deploy: loaded.config,\n deployDir: loaded.dir,\n env: request.env,\n inputs: request.inputs,\n serverDir: loaded.serverDir,\n });\n const server = yield* checkServerFiles({\n deploy: loaded.config,\n dir: loaded.serverDir,\n files: draft.files,\n });\n if (request.missing === 'create') {\n yield* writeServerDir(loaded.serverDir, draft.files);\n yield* Console.log(\n createdSummary({ authHost: server.config.authHost, draft, serverDir: loaded.serverDir }),\n );\n } else {\n yield* Console.log(\n `${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.`,\n );\n }\n return server;\n });\n\n/** The server folder, checked, creating it or previewing it as the command asks. */\nconst serverDirFor = (request: ServerDirRequest) =>\n Effect.gen(function* serverDir() {\n if (yield* hasServerConfig(request.loaded.serverDir)) {\n return yield* existingServerDir(request);\n }\n if (request.missing === 'require') {\n return yield* new InfraError({\n message: `${request.loaded.serverDir} has no server config; run wt-tunnel deploy to create it`,\n });\n }\n return yield* newServerDir(request);\n });\n\n/** What every alchemy run needs: where to run, the deployment, and the stack's environment. */\ninterface Prepared {\n readonly cwd: string;\n readonly deployment: Deployment;\n readonly env: Env;\n}\n\n/** Loads the deploy file, checks the environment, then reads, creates or previews the folder. */\nconst prepare = (input: {\n readonly ask: Ask;\n readonly config: string;\n readonly env: Env;\n readonly inputs: CreateInputs;\n readonly missing: Missing;\n readonly version: string;\n}) =>\n Effect.gen(function* prepareRun() {\n const loaded = yield* loadDeployConfig(input.config);\n yield* checkEnv(loaded.config, input.env);\n const server = yield* serverDirFor({ ...input, loaded });\n const deployment = resolveDeployment(loaded.config, server.config, input.version);\n const prepared: Prepared = {\n cwd: loaded.dir,\n deployment,\n env: stackEnv(deployment, server.files, input.env),\n };\n return prepared;\n });\n\nexport { prepare, serverDirFor };\nexport type { Missing, Prepared };\n"],"mappings":";;;;;;;AA0BA,MAAM,iBAAiB,WAAyB;CAC9C,GAAI,OAAO,QAAQ,SAAS,IAAI,CAAC,UAAU,IAAI,CAAC;CAChD,GAAI,OAAO,aAAa,KAAA,IAAY,CAAC,IAAI,CAAC,aAAa;CACvD,GAAI,OAAO,YAAY,SAAS,IAAI,CAAC,eAAe,IAAI,CAAC;CACzD,GAAI,OAAO,kBAAkB,SAAS,IAAI,CAAC,sBAAsB,IAAI,CAAC;CACtE,GAAI,OAAO,WAAW,KAAA,IAAY,CAAC,IAAI,CAAC,WAAW;CACnD,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,UAAU;AACnD;;AAGA,MAAM,qBAAqB,EAAE,QAAQ,aACnC,OAAO,IAAI,UAAU,WAAW;CAC9B,MAAM,SAAS,OAAO,cAAc,OAAO,WAAW,OAAO,MAAM;CACnE,MAAM,UAAU,cAAc,MAAM;CACpC,IAAI,QAAQ,SAAS,GACnB,OAAO,QAAQ,IACb,YAAY,QAAQ,KAAK,IAAI,EAAE,IAAI,OAAO,UAAU,iDACtD;CAEF,IAAI,OAAO,aAAa,SAAS,GAC/B,OAAO,QAAQ,IACb,aAAa,OAAO,aAAa,KAAK,IAAI,EAAE,QAAQ,OAAO,UAAU,gDACvE;CAEF,OAAO;AACT,CAAC;;AAGH,MAAM,gBAAgB,YACpB,OAAO,IAAI,UAAU,SAAS;CAC5B,MAAM,EAAE,WAAW;CACnB,MAAM,QAAQ,OAAO,eAAe;EAClC,KAAK,QAAQ;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,KAAK,QAAQ;EACb,QAAQ,QAAQ;EAChB,WAAW,OAAO;CACpB,CAAC;CACD,MAAM,SAAS,OAAO,iBAAiB;EACrC,QAAQ,OAAO;EACf,KAAK,OAAO;EACZ,OAAO,MAAM;CACf,CAAC;CACD,IAAI,QAAQ,YAAY,UAAU;EAChC,OAAO,eAAe,OAAO,WAAW,MAAM,KAAK;EACnD,OAAO,QAAQ,IACb,eAAe;GAAE,UAAU,OAAO,OAAO;GAAU;GAAO,WAAW,OAAO;EAAU,CAAC,CACzF;CACF,OACE,OAAO,QAAQ,IACb,GAAG,OAAO,UAAU,oDAAoD,MAAM,UAAU,WAAW,IAAI,KAAK,qBAAqB,MAAM,UAAU,KAAK,IAAI,EAAE,mDAAmD,sBACjN;CAEF,OAAO;AACT,CAAC;;AAGH,MAAM,gBAAgB,YACpB,OAAO,IAAI,UAAU,YAAY;CAC/B,IAAI,OAAO,gBAAgB,QAAQ,OAAO,SAAS,GACjD,OAAO,OAAO,kBAAkB,OAAO;CAEzC,IAAI,QAAQ,YAAY,WACtB,OAAO,OAAO,IAAI,WAAW,EAC3B,SAAS,GAAG,QAAQ,OAAO,UAAU,0DACvC,CAAC;CAEH,OAAO,OAAO,aAAa,OAAO;AACpC,CAAC;;AAUH,MAAM,WAAW,UAQf,OAAO,IAAI,UAAU,aAAa;CAChC,MAAM,SAAS,OAAO,iBAAiB,MAAM,MAAM;CACnD,OAAO,SAAS,OAAO,QAAQ,MAAM,GAAG;CACxC,MAAM,SAAS,OAAO,aAAa;EAAE,GAAG;EAAO;CAAO,CAAC;CACvD,MAAM,aAAa,kBAAkB,OAAO,QAAQ,OAAO,QAAQ,MAAM,OAAO;CAMhF,OAAO;EAJL,KAAK,OAAO;EACZ;EACA,KAAK,SAAS,YAAY,OAAO,OAAO,MAAM,GAAG;CAErC;AAChB,CAAC"}
@@ -0,0 +1,82 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { providerIds } from "./packages/contract/src/server-config.js";
3
+ import { Console, Effect } from "effect";
4
+ // src/providers.ts
5
+ const clientFields = (prefix) => [{
6
+ key: "clientId",
7
+ variable: `${prefix}_CLIENT_ID`
8
+ }, {
9
+ key: "clientSecret",
10
+ secret: true,
11
+ variable: `${prefix}_CLIENT_SECRET`
12
+ }];
13
+ const specs = {
14
+ cloudflare: {
15
+ fields: [...clientFields("CLOUDFLARE_ACCESS"), {
16
+ key: "teamDomain",
17
+ variable: "CLOUDFLARE_ACCESS_TEAM_DOMAIN"
18
+ }],
19
+ steps: (uri) => `Cloudflare Access: in Zero Trust, under Access, Applications, add a SaaS application with OIDC, and the redirect URL ${uri}. CLOUDFLARE_ACCESS_TEAM_DOMAIN is your team domain, such as acme.cloudflareaccess.com.`
20
+ },
21
+ github: {
22
+ fields: clientFields("GITHUB"),
23
+ steps: (uri) => `GitHub: under Settings, Developer settings, OAuth Apps, register an app with the authorization callback URL ${uri}.`
24
+ },
25
+ google: {
26
+ fields: clientFields("GOOGLE"),
27
+ steps: (uri) => `Google: in the Google Cloud console (APIs and Services, Credentials), create an OAuth client ID of type Web application with the authorized redirect URI ${uri}.`
28
+ },
29
+ microsoft: {
30
+ fields: [...clientFields("MICROSOFT"), {
31
+ key: "tenantId",
32
+ optional: true,
33
+ variable: "MICROSOFT_TENANT_ID"
34
+ }],
35
+ steps: (uri) => `Microsoft: in the Microsoft Entra admin center, under App registrations, register an app with the Web redirect URI ${uri}, add a client secret, and under Token configuration add the optional ID token claim verified_primary_email. MICROSOFT_TENANT_ID limits sign-in to one tenant (default: common, any account).`
36
+ }
37
+ };
38
+ const isSet = (env, name) => (env[name] ?? "") !== "";
39
+ const callbackUri = (authHost, id) => `https://${authHost ?? "<authHost>"}/api/auth/callback/${id}`;
40
+ /** How to create each provider's OAuth client, one line each. */
41
+ const providerSteps = (authHost, ids = providerIds) => ids.map((id) => {
42
+ const variables = specs[id].fields.map(({ variable }) => variable).join(", ");
43
+ return `${specs[id].steps(callbackUri(authHost, id))} Variables: ${variables}.`;
44
+ }).join("\n");
45
+ /** The providers whose client ID is in the environment. */
46
+ const providersInEnv = (env) => providerIds.filter((id) => isSet(env, specs[id].fields[0]?.variable ?? ""));
47
+ /** The required variables of the providers in the environment that are not set. */
48
+ const missingProviderVariables = (env) => {
49
+ const chosen = providersInEnv(env);
50
+ return chosen.length === 0 ? ["the client ID and secret of at least one sign-in provider (such as GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET)"] : chosen.flatMap((id) => specs[id].fields.filter((field) => field.optional !== true && !isSet(env, field.variable)).map(({ variable }) => variable));
51
+ };
52
+ /** Which providers to set up: those in the environment, else the user's choice. */
53
+ const chooseProviders = (env, ask) => Effect.gen(function* choose() {
54
+ const inEnv = providersInEnv(env);
55
+ if (inEnv.length > 0) return inEnv;
56
+ const answer = yield* ask(`Sign-in providers (any of ${providerIds.join(" ")}):`);
57
+ const chosen = providerIds.filter((id) => answer.split(/[\s,]+/u).includes(id));
58
+ return chosen.length > 0 ? chosen : yield* new InfraError({ message: `name at least one of ${providerIds.join(", ")}` });
59
+ });
60
+ /**
61
+ * One provider's fields, each from its variable, else asked for; an optional one only from its
62
+ * variable.
63
+ */
64
+ const providerEntry = (env, ask, id) => Effect.gen(function* entry() {
65
+ const values = {};
66
+ for (const field of specs[id].fields) if (isSet(env, field.variable)) values[field.key] = env[field.variable] ?? "";
67
+ else if (field.optional !== true) values[field.key] = yield* (field.secret === true ? ask.secret : ask.line)(`${field.variable}:`);
68
+ return [id, values];
69
+ });
70
+ /**
71
+ * The `providers` of a new server config: each field from its variable, else asked for, after the
72
+ * steps to create the client. An optional field comes only from its variable.
73
+ */
74
+ const gatherProviders = (env, ask, authHost) => Effect.gen(function* gather() {
75
+ const ids = yield* chooseProviders(env, ask.line);
76
+ const missing = ids.filter((id) => specs[id].fields.some((field) => field.optional !== true && !isSet(env, field.variable)));
77
+ if (missing.length > 0) yield* Console.log(providerSteps(authHost, missing));
78
+ return Object.fromEntries(yield* Effect.all(ids.map((id) => providerEntry(env, ask, id))));
79
+ });
80
+ export { gatherProviders, missingProviderVariables, providerSteps };
81
+
82
+ //# sourceMappingURL=providers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers.js","names":[],"sources":["../src/providers.ts"],"sourcesContent":["import { providerIds } from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ProviderId } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Console, Effect } from 'effect';\nimport type { Prompt } from 'effect/cli';\n\nimport { InfraError } from './errors.ts';\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** One field of a provider's config, and the variable a new server folder takes it from. */\ninterface Field {\n readonly key: 'clientId' | 'clientSecret' | 'teamDomain' | 'tenantId';\n readonly optional?: true;\n readonly secret?: true;\n readonly variable: string;\n}\n\ninterface ProviderSpec {\n readonly fields: readonly Field[];\n /** How to create the OAuth client, given its redirect URI. */\n readonly steps: (redirectUri: string) => string;\n}\n\nconst clientFields = (prefix: string): readonly Field[] => [\n { key: 'clientId', variable: `${prefix}_CLIENT_ID` },\n { key: 'clientSecret', secret: true, variable: `${prefix}_CLIENT_SECRET` },\n];\n\nconst specs: Readonly<Record<ProviderId, ProviderSpec>> = {\n cloudflare: {\n fields: [\n ...clientFields('CLOUDFLARE_ACCESS'),\n { key: 'teamDomain', variable: 'CLOUDFLARE_ACCESS_TEAM_DOMAIN' },\n ],\n steps: (uri) =>\n `Cloudflare Access: in Zero Trust, under Access, Applications, add a SaaS application with OIDC, and the redirect URL ${uri}. CLOUDFLARE_ACCESS_TEAM_DOMAIN is your team domain, such as acme.cloudflareaccess.com.`,\n },\n github: {\n fields: clientFields('GITHUB'),\n steps: (uri) =>\n `GitHub: under Settings, Developer settings, OAuth Apps, register an app with the authorization callback URL ${uri}.`,\n },\n google: {\n fields: clientFields('GOOGLE'),\n steps: (uri) =>\n `Google: in the Google Cloud console (APIs and Services, Credentials), create an OAuth client ID of type Web application with the authorized redirect URI ${uri}.`,\n },\n microsoft: {\n fields: [\n ...clientFields('MICROSOFT'),\n { key: 'tenantId', optional: true, variable: 'MICROSOFT_TENANT_ID' },\n ],\n steps: (uri) =>\n `Microsoft: in the Microsoft Entra admin center, under App registrations, register an app with the Web redirect URI ${uri}, add a client secret, and under Token configuration add the optional ID token claim verified_primary_email. MICROSOFT_TENANT_ID limits sign-in to one tenant (default: common, any account).`,\n },\n};\n\nconst isSet = (env: Env, name: string) => (env[name] ?? '') !== '';\n\nconst callbackUri = (authHost: string | undefined, id: ProviderId) =>\n `https://${authHost ?? '<authHost>'}/api/auth/callback/${id}`;\n\n/** How to create each provider's OAuth client, one line each. */\nconst providerSteps = (authHost?: string, ids: readonly ProviderId[] = providerIds) =>\n ids\n .map((id) => {\n const variables = specs[id].fields.map(({ variable }) => variable).join(', ');\n return `${specs[id].steps(callbackUri(authHost, id))} Variables: ${variables}.`;\n })\n .join('\\n');\n\n/** The providers whose client ID is in the environment. */\nconst providersInEnv = (env: Env) =>\n providerIds.filter((id) => isSet(env, specs[id].fields[0]?.variable ?? ''));\n\n/** The required variables of the providers in the environment that are not set. */\nconst missingProviderVariables = (env: Env) => {\n const chosen = providersInEnv(env);\n return chosen.length === 0\n ? [\n 'the client ID and secret of at least one sign-in provider (such as GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET)',\n ]\n : chosen.flatMap((id) =>\n specs[id].fields\n .filter((field) => field.optional !== true && !isSet(env, field.variable))\n .map(({ variable }) => variable),\n );\n};\n\ninterface ProviderAsk {\n readonly line: (message: string) => Effect.Effect<string, InfraError, Prompt.Environment>;\n readonly secret: (message: string) => Effect.Effect<string, InfraError, Prompt.Environment>;\n}\n\n/** Which providers to set up: those in the environment, else the user's choice. */\nconst chooseProviders = (env: Env, ask: ProviderAsk['line']) =>\n Effect.gen(function* choose() {\n const inEnv = providersInEnv(env);\n if (inEnv.length > 0) {\n return inEnv;\n }\n const answer = yield* ask(`Sign-in providers (any of ${providerIds.join(' ')}):`);\n const chosen = providerIds.filter((id) => answer.split(/[\\s,]+/u).includes(id));\n return chosen.length > 0\n ? chosen\n : yield* new InfraError({ message: `name at least one of ${providerIds.join(', ')}` });\n });\n\n/**\n * One provider's fields, each from its variable, else asked for; an optional one only from its\n * variable.\n */\nconst providerEntry = (env: Env, ask: ProviderAsk, id: ProviderId) =>\n Effect.gen(function* entry() {\n const values: Record<string, string> = {};\n for (const field of specs[id].fields) {\n if (isSet(env, field.variable)) {\n values[field.key] = env[field.variable] ?? '';\n } else if (field.optional !== true) {\n values[field.key] = yield* (field.secret === true ? ask.secret : ask.line)(\n `${field.variable}:`,\n );\n }\n }\n const result: readonly [ProviderId, Readonly<Record<string, string>>] = [id, values];\n return result;\n });\n\n/**\n * The `providers` of a new server config: each field from its variable, else asked for, after the\n * steps to create the client. An optional field comes only from its variable.\n */\nconst gatherProviders = (env: Env, ask: ProviderAsk, authHost: string) =>\n Effect.gen(function* gather() {\n const ids = yield* chooseProviders(env, ask.line);\n const missing = ids.filter((id) =>\n specs[id].fields.some((field) => field.optional !== true && !isSet(env, field.variable)),\n );\n if (missing.length > 0) {\n yield* Console.log(providerSteps(authHost, missing));\n }\n return Object.fromEntries(yield* Effect.all(ids.map((id) => providerEntry(env, ask, id))));\n });\n\nexport { gatherProviders, missingProviderVariables, providerSteps };\nexport type { Env, ProviderAsk };\n"],"mappings":";;;;AAuBA,MAAM,gBAAgB,WAAqC,CACzD;CAAE,KAAK;CAAY,UAAU,GAAG,OAAO;AAAY,GACnD;CAAE,KAAK;CAAgB,QAAQ;CAAM,UAAU,GAAG,OAAO;AAAgB,CAC3E;AAEA,MAAM,QAAoD;CACxD,YAAY;EACV,QAAQ,CACN,GAAG,aAAa,mBAAmB,GACnC;GAAE,KAAK;GAAc,UAAU;EAAgC,CACjE;EACA,QAAQ,QACN,wHAAwH,IAAI;CAChI;CACA,QAAQ;EACN,QAAQ,aAAa,QAAQ;EAC7B,QAAQ,QACN,+GAA+G,IAAI;CACvH;CACA,QAAQ;EACN,QAAQ,aAAa,QAAQ;EAC7B,QAAQ,QACN,4JAA4J,IAAI;CACpK;CACA,WAAW;EACT,QAAQ,CACN,GAAG,aAAa,WAAW,GAC3B;GAAE,KAAK;GAAY,UAAU;GAAM,UAAU;EAAsB,CACrE;EACA,QAAQ,QACN,sHAA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