@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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +237 -2
  3. package/dist/alchemy.js +40 -0
  4. package/dist/alchemy.js.map +1 -0
  5. package/dist/bin.js +15 -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 +147 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/config.js +106 -0
  12. package/dist/config.js.map +1 -0
  13. package/dist/create-root.js +78 -0
  14. package/dist/create-root.js.map +1 -0
  15. package/dist/create-server-dir.js +150 -0
  16. package/dist/create-server-dir.js.map +1 -0
  17. package/dist/deployment.js +132 -0
  18. package/dist/deployment.js.map +1 -0
  19. package/dist/errors.js +9 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/init.js +105 -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/bin.js +20 -0
  26. package/dist/packages/contract/src/bin.js.map +1 -0
  27. package/dist/packages/contract/src/index.js +12 -0
  28. package/dist/packages/contract/src/index.js.map +1 -0
  29. package/dist/packages/contract/src/root-ca.js +94 -0
  30. package/dist/packages/contract/src/root-ca.js.map +1 -0
  31. package/dist/packages/contract/src/server-config.js +99 -0
  32. package/dist/packages/contract/src/server-config.js.map +1 -0
  33. package/dist/prepare.js +142 -0
  34. package/dist/prepare.js.map +1 -0
  35. package/dist/providers.js +82 -0
  36. package/dist/providers.js.map +1 -0
  37. package/dist/secrets.js +39 -0
  38. package/dist/secrets.js.map +1 -0
  39. package/dist/seed-drift.js +51 -0
  40. package/dist/seed-drift.js.map +1 -0
  41. package/dist/server-dir.js +151 -0
  42. package/dist/server-dir.js.map +1 -0
  43. package/dist/server-machine.js +136 -0
  44. package/dist/server-machine.js.map +1 -0
  45. package/dist/stack.js +104 -0
  46. package/dist/stack.js.map +1 -0
  47. package/dist/uploads.js +24 -0
  48. package/dist/uploads.js.map +1 -0
  49. package/package.json +63 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { Console, Effect, Redacted } from 'effect';\nimport { Argument, Command, Flag, Prompt } from 'effect/cli';\n\nimport { runAlchemy, stackFile } from './alchemy.ts';\nimport { deployFileName, loadDeployConfig } from './config.ts';\nimport { createRoot } from './create-root.ts';\nimport type { Ask } from './create-server-dir.ts';\nimport { InfraError } from './errors.ts';\nimport { writeStarterConfig } from './init.ts';\nimport { decodeStackOutput, outputsReport } from './outputs.ts';\nimport { prepare, serverDirFor } from './prepare.ts';\nimport type { Missing, Prepared } from './prepare.ts';\n\nconst configFlag = Flag.String('config').pipe(\n Flag.withDescription('The deploy file'),\n Flag.withDefault(deployFileName),\n);\n\nconst forceFlag = Flag.Boolean('force').pipe(\n Flag.withDescription(\n \"Copy the deploy file's domains and allow into the existing server config, where they differ. Never replaces the root: use wt-tunnel ca create --force for that.\",\n ),\n Flag.withDefault(false),\n);\n\nconst yesFlag = Flag.Boolean('yes').pipe(\n Flag.withDescription('Apply without asking for approval of the plan'),\n Flag.withDefault(false),\n);\n\nconst cancelled = () => new InfraError({ message: 'cancelled' });\n\n/** Prompts in the terminal, when stdin is one. */\nconst terminalAsk: Ask = {\n interactive: process.stdin.isTTY,\n line: (message) => Prompt.run(Prompt.String({ message })).pipe(Effect.mapError(cancelled)),\n secret: (message) =>\n Prompt.run(Prompt.Hidden({ message })).pipe(\n Effect.map((value) => Redacted.value(value)),\n Effect.mapError(cancelled),\n ),\n};\n\nconst prepareFor = (\n {\n config,\n force = false,\n version,\n }: { readonly config: string; readonly force?: boolean; readonly version: string },\n missing: Missing,\n) => prepare({ ask: terminalAsk, config, env: process.env, force, missing, version });\n\ntype Operation = 'deploy' | 'destroy' | 'plan';\n\n/**\n * Without a terminal, alchemy cannot ask for approval: it prints the plan and stops without\n * applying it, and exits 0. Fail instead, so a script never mistakes that for success.\n */\nconst checkApproval = (operation: Operation, yes: boolean, interactive: boolean) =>\n operation === 'plan' || yes || interactive\n ? Effect.void\n : Effect.fail(\n new InfraError({\n message: `${operation} asks for approval, but stdin is not a terminal: pass --yes to apply without a prompt`,\n }),\n );\n\nconst stackRun = ({ cwd, deployment, env }: Prepared, operation: Operation, yes: boolean) =>\n checkApproval(operation, yes, process.stdin.isTTY).pipe(\n Effect.andThen(\n runAlchemy({\n args: [operation, stackFile, '--stage', deployment.stage, ...(yes ? ['--yes'] : [])],\n cwd,\n env,\n }),\n ),\n );\n\nconst printOutputs = ({ cwd, deployment, env }: Prepared) =>\n runAlchemy({\n args: [\n 'state',\n 'read',\n `${deployment.stack}/${deployment.stage}/output`,\n '--config',\n stackFile,\n '--no-input',\n // Alchemy logs to stdout; below error level a log line would break the JSON.\n '--log-level',\n 'error',\n ],\n capture: true,\n cwd,\n env,\n }).pipe(\n Effect.flatMap(decodeStackOutput),\n Effect.flatMap((output) => Console.log(outputsReport(deployment, output))),\n );\n\nconst alchemyCommand = (version: string) =>\n Command.make(\n 'alchemy',\n {\n args: Argument.String('arg').pipe(\n Argument.withDescription('The alchemy command and its arguments, after --'),\n Argument.variadic(),\n ),\n config: configFlag,\n },\n ({ args, config }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap(({ cwd, env }) =>\n runAlchemy({ args: [...args, '--config', stackFile], cwd, env }),\n ),\n ),\n ).pipe(\n Command.withDescription(\n \"Run another alchemy command against this deployment's stack, such as: alchemy -- state ls <stack>/<stage>\",\n ),\n );\n\nconst prepareCommand = Command.make('prepare', { config: configFlag, force: forceFlag }, (flags) =>\n Effect.gen(function* prepareServerDir() {\n const loaded = yield* loadDeployConfig(flags.config);\n const server = yield* serverDirFor({\n ask: terminalAsk,\n env: process.env,\n force: flags.force,\n loaded,\n missing: 'create',\n });\n yield* Console.log(`${server.dir} is a valid server folder.`);\n }),\n).pipe(\n Command.withDescription(\n 'Create the server folder as deploy would, or check the existing one, without touching the cloud',\n ),\n);\n\nconst commands = (version: string) => {\n const plan = Command.make('plan', { config: configFlag }, (flags) =>\n prepareFor({ config: flags.config, version }, 'preview').pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'plan', false)),\n ),\n ).pipe(\n Command.withDescription(\n 'Show what deploy would create, change or delete. Without a server folder, preview the one deploy would create; write nothing.',\n ),\n );\n\n const deploy = Command.make(\n 'deploy',\n { config: configFlag, force: forceFlag, yes: yesFlag },\n (flags) =>\n Effect.gen(function* deployStack() {\n const prepared = yield* prepareFor(\n { config: flags.config, force: flags.force, version },\n 'create',\n );\n yield* stackRun(prepared, 'deploy', flags.yes);\n yield* printOutputs(prepared);\n }),\n ).pipe(\n Command.withDescription(\n 'Create the server folder if it is missing, else check it; then create or update the Fly app, its IPs, one secret per server file, the Machine and the DNS records',\n ),\n );\n\n const destroy = Command.make('destroy', { config: configFlag, yes: yesFlag }, ({ config, yes }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'destroy', yes)),\n ),\n ).pipe(Command.withDescription('Delete everything deploy created'));\n\n const outputs = Command.make('outputs', { config: configFlag }, ({ config }) =>\n prepareFor({ config, version }, 'require').pipe(Effect.flatMap(printOutputs)),\n ).pipe(\n Command.withDescription(\n 'Print the app, its IPs, the tunnel host and the CA page, and the DNS records to create in manual zones',\n ),\n );\n\n return [prepareCommand, plan, deploy, destroy, outputs, alchemyCommand(version)];\n};\n\nconst init = Command.make('init', {}, () =>\n writeStarterConfig(process.cwd()).pipe(Effect.flatMap(Console.log)),\n).pipe(\n Command.withDescription(\n `Write a commented starter ${deployFileName} and a .gitignore for the server folder here, and list the secrets to create`,\n ),\n);\n\nconst caCreate = Command.make(\n 'create',\n {\n config: configFlag,\n force: Flag.Boolean('force').pipe(\n Flag.withDescription(\n 'Replace an existing root. Every device that trusts the old root must then trust the new one.',\n ),\n Flag.withDefault(false),\n ),\n },\n (input) =>\n createRoot({ deployFile: input.config, force: input.force }).pipe(\n Effect.flatMap(({ cert, domains, key, label }) =>\n Console.log(\n `Wrote ${cert} and ${key} (readable by you only): wt-tunnel root (${label}), name-constrained to ${domains.join(', ')}. wt-tunnel deploy uploads them with the server config. Keep the key secret, and back it up with the rest of the folder.`,\n ),\n ),\n ),\n).pipe(\n Command.withDescription(\n 'Create a root CA name-constrained to the dev domains, in the server folder',\n ),\n);\n\nconst ca = Command.make('ca').pipe(\n Command.withDescription(\"Manage the deployment's root CA\"),\n Command.withSubcommands([caCreate]),\n);\n\nconst description =\n 'Set up the wt-tunnel server on Fly.io: a deploy file says where it runs, the server folder what it does';\n\nconst run = (version: string) => {\n const cli = Command.make('wt-tunnel').pipe(\n Command.withDescription(description),\n Command.withSubcommands([init, ca, ...commands(version)]),\n );\n return Command.run(cli, { version });\n};\n\nexport { checkApproval, run };\n"],"mappings":";;;;;;;;;;AAaA,MAAM,aAAa,KAAK,OAAO,QAAQ,CAAC,CAAC,KACvC,KAAK,gBAAgB,iBAAiB,GACtC,KAAK,YAAY,cAAc,CACjC;AAEA,MAAM,YAAY,KAAK,QAAQ,OAAO,CAAC,CAAC,KACtC,KAAK,gBACH,iKACF,GACA,KAAK,YAAY,KAAK,CACxB;AAEA,MAAM,UAAU,KAAK,QAAQ,KAAK,CAAC,CAAC,KAClC,KAAK,gBAAgB,+CAA+C,GACpE,KAAK,YAAY,KAAK,CACxB;AAEA,MAAM,kBAAkB,IAAI,WAAW,EAAE,SAAS,YAAY,CAAC;;AAG/D,MAAM,cAAmB;CACvB,aAAa,QAAQ,MAAM;CAC3B,OAAO,YAAY,OAAO,IAAI,OAAO,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,SAAS,SAAS,CAAC;CACzF,SAAS,YACP,OAAO,IAAI,OAAO,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,KACrC,OAAO,KAAK,U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,OAAO;CAAC,CAAC,CAC1D;CACA,OAAO,QAAQ,IAAI,KAAK,EAAE,QAAQ,CAAC;AACrC"}
package/dist/config.js ADDED
@@ -0,0 +1,106 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { Hostname } from "./packages/contract/src/index.js";
3
+ import { AllowList } from "./packages/contract/src/server-config.js";
4
+ import { AlchemyName, Dns, FlyName, FlyRegion, ImageRef, MemoryMb, StateStore, repeatedZones } from "./deployment.js";
5
+ import { Effect, FileSystem, Path, Schema } from "effect";
6
+ // src/config.ts
7
+ const deployFileName = "wt-tunnel.deploy.json";
8
+ const defaults = {
9
+ memoryMb: 512,
10
+ serverDir: ".server",
11
+ stack: "wt-tunnel-server",
12
+ stage: "prod"
13
+ };
14
+ /** The image a release of this CLI deploys unless the config pins another. */
15
+ const releaseImage = (version) => `ghcr.io/tafrahq/wt-tunnel-server:${version}`;
16
+ /**
17
+ * `wt-tunnel.deploy.json`: where and how the server runs. What it serves is in the server folder,
18
+ * `.server/` by default.
19
+ */
20
+ /**
21
+ * The root of a new server folder: an existing root's files, relative to the deploy file, or for a
22
+ * new root, its label, `wt-tunnel root (<name>)`.
23
+ */
24
+ const RootSeed = Schema.Struct({
25
+ cert: Schema.optionalKey(Schema.NonEmptyString),
26
+ key: Schema.optionalKey(Schema.NonEmptyString),
27
+ name: Schema.optionalKey(Schema.NonEmptyString)
28
+ });
29
+ const DeployConfig = Schema.Struct({
30
+ /** Who may sign in, for a new server folder. Once it exists, its config's `allow` is used. */
31
+ allow: Schema.optionalKey(AllowList),
32
+ /**
33
+ * The sign-in host, shared by every dev domain and outside all of them: `authHost` in the server
34
+ * folder's config, which must name the same host.
35
+ */
36
+ authHost: Hostname,
37
+ ca: Schema.optionalKey(RootSeed),
38
+ /** Who creates the records in each zone the record names sit in. */
39
+ dns: Dns,
40
+ /** The dev domains of a new server folder. Once it exists, its config's `domains` are used. */
41
+ domains: Schema.optionalKey(Schema.NonEmptyArray(Hostname)),
42
+ image: Schema.optionalKey(ImageRef),
43
+ /**
44
+ * Where the server runs, by `provider`. Fly.io is the only one for now; another would add its own
45
+ * shape here.
46
+ */
47
+ server: Schema.Struct({
48
+ app: FlyName,
49
+ memoryMb: Schema.optionalKey(MemoryMb),
50
+ org: FlyName,
51
+ provider: Schema.Literal("flyio"),
52
+ region: FlyRegion
53
+ }),
54
+ /** The folder uploaded to the Machine, relative to this file. */
55
+ serverDir: Schema.optionalKey(Schema.NonEmptyString),
56
+ stack: Schema.optionalKey(AlchemyName),
57
+ stage: Schema.optionalKey(AlchemyName),
58
+ state: StateStore,
59
+ /** The name tunnel clients connect to: `server.host` in their wt-tunnel.json. */
60
+ tunnelHost: Hostname
61
+ });
62
+ const DeployConfigJson = Schema.fromJsonString(DeployConfig);
63
+ /**
64
+ * Blanks out `//` and `/* *\/` comments outside strings, keeping every newline and column, so the
65
+ * config file can explain itself and JSON errors still point at the right place.
66
+ */
67
+ const blankComments = (text) => text.replaceAll(/(?<quoted>"(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//gu, (match, quoted) => quoted ?? match.replaceAll(/[^\n]/gu, " "));
68
+ const decodeDeployConfig = (text, source) => Schema.decodeUnknownEffect(DeployConfigJson)(blankComments(text), { errors: "all" }).pipe(Effect.mapError((schemaError) => new InfraError({ message: `${source} is not a valid config: ${schemaError.message}` })), Effect.flatMap((config) => {
69
+ const problems = repeatedZones(config.dns);
70
+ return problems.length === 0 ? Effect.succeed(config) : Effect.fail(new InfraError({ message: `${source} is not a valid config: ${problems.join("; ")}` }));
71
+ }));
72
+ /** The deploy file, its directory, its decoded content, and the server folder it names. */
73
+ const loadDeployConfig = (configFile) => Effect.gen(function* loadConfig() {
74
+ const fs = yield* FileSystem.FileSystem;
75
+ const path = yield* Path.Path;
76
+ const file = path.resolve(configFile);
77
+ const text = yield* fs.readFileString(file).pipe(Effect.mapError(() => new InfraError({ message: `cannot read ${file}. Pass --config <file>, or run \`wt-tunnel init\` to write a starter ${deployFileName}.` })));
78
+ const config = yield* decodeDeployConfig(text, file);
79
+ const dir = path.dirname(file);
80
+ return {
81
+ config,
82
+ dir,
83
+ file,
84
+ serverDir: path.resolve(dir, config.serverDir ?? defaults.serverDir)
85
+ };
86
+ });
87
+ /** The deployment: the deploy file with every default filled in, and the names the server serves. */
88
+ const resolveDeployment = (config, server, version) => ({
89
+ authHost: config.authHost,
90
+ dns: config.dns,
91
+ domains: server.domains,
92
+ fly: {
93
+ app: config.server.app,
94
+ memoryMb: config.server.memoryMb ?? defaults.memoryMb,
95
+ org: config.server.org,
96
+ region: config.server.region
97
+ },
98
+ image: config.image ?? releaseImage(version),
99
+ stack: config.stack ?? defaults.stack,
100
+ stage: config.stage ?? defaults.stage,
101
+ state: config.state,
102
+ tunnelHost: config.tunnelHost
103
+ });
104
+ export { blankComments, decodeDeployConfig, defaults, deployFileName, loadDeployConfig, releaseImage, resolveDeployment };
105
+
106
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { AllowList } from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Path, Schema } from 'effect';\n\nimport {\n AlchemyName,\n Dns,\n FlyName,\n FlyRegion,\n ImageRef,\n MemoryMb,\n StateStore,\n repeatedZones,\n} from './deployment.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\n\nconst deployFileName = 'wt-tunnel.deploy.json';\n\nconst defaults = {\n memoryMb: 512,\n serverDir: '.server',\n stack: 'wt-tunnel-server',\n stage: 'prod',\n} as const;\n\n/** The image a release of this CLI deploys unless the config pins another. */\nconst releaseImage = (version: string) => `ghcr.io/tafrahq/wt-tunnel-server:${version}`;\n\n/**\n * `wt-tunnel.deploy.json`: where and how the server runs. What it serves is in the server folder,\n * `.server/` by default.\n */\n/**\n * The root of a new server folder: an existing root's files, relative to the deploy file, or for a\n * new root, its label, `wt-tunnel root (<name>)`.\n */\nconst RootSeed = Schema.Struct({\n cert: Schema.optionalKey(Schema.NonEmptyString),\n key: Schema.optionalKey(Schema.NonEmptyString),\n name: Schema.optionalKey(Schema.NonEmptyString),\n});\n\nconst DeployConfig = Schema.Struct({\n /** Who may sign in, for a new server folder. Once it exists, its config's `allow` is used. */\n allow: Schema.optionalKey(AllowList),\n /**\n * The sign-in host, shared by every dev domain and outside all of them: `authHost` in the server\n * folder's config, which must name the same host.\n */\n authHost: Hostname,\n ca: Schema.optionalKey(RootSeed),\n /** Who creates the records in each zone the record names sit in. */\n dns: Dns,\n /** The dev domains of a new server folder. Once it exists, its config's `domains` are used. */\n domains: Schema.optionalKey(Schema.NonEmptyArray(Hostname)),\n image: Schema.optionalKey(ImageRef),\n /**\n * Where the server runs, by `provider`. Fly.io is the only one for now; another would add its own\n * shape here.\n */\n server: Schema.Struct({\n app: FlyName,\n memoryMb: Schema.optionalKey(MemoryMb),\n org: FlyName,\n provider: Schema.Literal('flyio'),\n region: FlyRegion,\n }),\n /** The folder uploaded to the Machine, relative to this file. */\n serverDir: Schema.optionalKey(Schema.NonEmptyString),\n stack: Schema.optionalKey(AlchemyName),\n stage: Schema.optionalKey(AlchemyName),\n state: StateStore,\n /** The name tunnel clients connect to: `server.host` in their wt-tunnel.json. */\n tunnelHost: Hostname,\n});\ntype DeployConfig = typeof DeployConfig.Type;\n\nconst DeployConfigJson = Schema.fromJsonString(DeployConfig);\n\n/**\n * Blanks out `//` and `/* *\\/` comments outside strings, keeping every newline and column, so the\n * config file can explain itself and JSON errors still point at the right place.\n */\nconst blankComments = (text: string) =>\n text.replaceAll(\n /(?<quoted>\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//gu,\n (match, quoted?: string) => quoted ?? match.replaceAll(/[^\\n]/gu, ' '),\n );\n\nconst decodeDeployConfig = (text: string, source: string) =>\n Schema.decodeUnknownEffect(DeployConfigJson)(blankComments(text), { errors: 'all' }).pipe(\n Effect.mapError(\n (schemaError) =>\n new InfraError({ message: `${source} is not a valid config: ${schemaError.message}` }),\n ),\n Effect.flatMap((config) => {\n const problems = repeatedZones(config.dns);\n return problems.length === 0\n ? Effect.succeed(config)\n : Effect.fail(\n new InfraError({\n message: `${source} is not a valid config: ${problems.join('; ')}`,\n }),\n );\n }),\n );\n\n/** The deploy file, its directory, its decoded content, and the server folder it names. */\nconst loadDeployConfig = (configFile: string) =>\n Effect.gen(function* loadConfig() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.resolve(configFile);\n const text = yield* fs.readFileString(file).pipe(\n Effect.mapError(\n () =>\n new InfraError({\n message: `cannot read ${file}. Pass --config <file>, or run \\`wt-tunnel init\\` to write a starter ${deployFileName}.`,\n }),\n ),\n );\n const config = yield* decodeDeployConfig(text, file);\n const dir = path.dirname(file);\n return {\n config,\n dir,\n file,\n serverDir: path.resolve(dir, config.serverDir ?? defaults.serverDir),\n };\n });\n\n/** A loaded deploy file. */\ninterface LoadedDeploy {\n readonly config: DeployConfig;\n /** The deploy file's directory, where relative paths in it start. */\n readonly dir: string;\n readonly file: string;\n /** The server folder, absolute. */\n readonly serverDir: string;\n}\n\n/** The deployment: the deploy file with every default filled in, and the names the server serves. */\nconst resolveDeployment = (\n config: DeployConfig,\n server: Pick<ServerConfig, 'domains'>,\n version: string,\n): Deployment => ({\n authHost: config.authHost,\n dns: config.dns,\n domains: server.domains,\n fly: {\n app: config.server.app,\n memoryMb: config.server.memoryMb ?? defaults.memoryMb,\n org: config.server.org,\n region: config.server.region,\n },\n image: config.image ?? releaseImage(version),\n stack: config.stack ?? defaults.stack,\n stage: config.stage ?? defaults.stage,\n state: config.state,\n tunnelHost: config.tunnelHost,\n});\n\nexport {\n blankComments,\n decodeDeployConfig,\n defaults,\n deployFileName,\n loadDeployConfig,\n releaseImage,\n resolveDeployment,\n};\nexport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,SAAS,WAAW,IACvB,OAAO,QAAQ,MAAM,IACrB,OAAO,KACL,IAAI,WAAW,EACb,SAAS,GAAG,OAAO,0BAA0B,SAAS,KAAK,IAAI,IACjE,CAAC,CACH;AACN,CAAC,CACH;;AAGF,MAAM,oBAAoB,eACxB,OAAO,IAAI,UAAU,aAAa;CAChC,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,OAAO,KAAK,QAAQ,UAAU;CACpC,MAAM,OAAO,OAAO,GAAG,eAAe,IAAI,CAAC,CAAC,KAC1C,OAAO,eAEH,IAAI,WAAW,EACb,SAAS,eAAe,KAAK,uEAAuE,eAAe,GACrH,CAAC,CACL,CACF;CACA,MAAM,SAAS,OAAO,mBAAmB,MAAM,IAAI;CACnD,MAAM,MAAM,KAAK,QAAQ,IAAI;CAC7B,OAAO;EACL;EACA;EACA;EACA,WAAW,KAAK,QAAQ,KAAK,OAAO,aAAa,SAAS,SAAS;CACrE;AACF,CAAC;;AAaH,MAAM,qBACJ,QACA,QACA,aACgB;CAChB,UAAU,OAAO;CACjB,KAAK,OAAO;CACZ,SAAS,OAAO;CAChB,KAAK;EACH,KAAK,OAAO,OAAO;EACnB,UAAU,OAAO,OAAO,YAAY,SAAS;EAC7C,KAAK,OAAO,OAAO;EACnB,QAAQ,OAAO,OAAO;CACxB;CACA,OAAO,OAAO,SAAS,aAAa,OAAO;CAC3C,OAAO,OAAO,SAAS,SAAS;CAChC,OAAO,OAAO,SAAS,SAAS;CAChC,OAAO,OAAO;CACd,YAAY,OAAO;AACrB"}
@@ -0,0 +1,78 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { ServerConfigFileJson, caFile, serverConfigFileName } from "./packages/contract/src/server-config.js";
3
+ import { defaults, loadDeployConfig } from "./config.js";
4
+ import { decodeDomains, generateRoot } from "./ca.js";
5
+ import "./server-dir.js";
6
+ import { Effect, FileSystem, Option, Path, Schema } from "effect";
7
+ // src/create-root.ts
8
+ /** The deploy file if it exists. Any other problem with it fails. */
9
+ const optionalDeploy = (file) => FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(Effect.orElseSucceed(() => false), Effect.flatMap((exists) => exists ? loadDeployConfig(file).pipe(Effect.map(Option.some)) : Effect.succeedNone));
10
+ /** The server config in `dir`, if there is one: its domains and where its root's files are. */
11
+ const existingServerConfig = (dir) => FileSystem.FileSystem.use((fs) => fs.readFileString(`${dir}/${serverConfigFileName}`)).pipe(Effect.option, Effect.flatMap(Option.match({
12
+ onNone: () => Effect.succeedNone,
13
+ onSome: (text) => Schema.decodeUnknownEffect(ServerConfigFileJson)(text).pipe(Effect.map(Option.some), Effect.mapError((schemaError) => new InfraError({ message: `${dir}/${serverConfigFileName} is not a valid server config: ${schemaError.message}` })))
14
+ })));
15
+ /** The domains: the server config's, else the deploy file's, which seed a new server folder. */
16
+ const rootDomains = (config, deploy) => {
17
+ if (Option.isSome(config)) return Effect.succeed(config.value.domains);
18
+ return deploy?.domains === void 0 ? Effect.fail(new InfraError({ message: "no server config and no domains in the deploy file: add \"domains\" to wt-tunnel.deploy.json, the dev domains the root may sign for" })) : decodeDomains(deploy.domains);
19
+ };
20
+ const exists = (file) => FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(Effect.orElseSucceed(() => false));
21
+ /** Fails when the root's files exist, unless replacing them was asked for. */
22
+ const refuseReplacing = (target, force) => Effect.all([exists(target.cert), exists(target.key)]).pipe(Effect.map(([cert, key]) => [...cert ? [target.cert] : [], ...key ? [target.key] : []]), Effect.filterOrFail((existing) => existing.length === 0 || force, (existing) => new InfraError({ message: `${existing.join(" and ")} already exist. Replacing the root means every device that trusts it must trust the new one instead; pass --force to do that.` })));
23
+ /** Writes the root: the folder private, the key readable by its owner only. */
24
+ const writeRoot = (target, root) => Effect.gen(function* write() {
25
+ const fs = yield* FileSystem.FileSystem;
26
+ yield* fs.makeDirectory(target.dir, {
27
+ mode: 448,
28
+ recursive: true
29
+ });
30
+ yield* fs.chmod(target.dir, 448);
31
+ yield* fs.writeFileString(target.key, root.key, { mode: 384 });
32
+ yield* fs.chmod(target.key, 384);
33
+ yield* fs.writeFileString(target.cert, root.cert, { mode: 420 });
34
+ }).pipe(Effect.orDie);
35
+ /** The server folder, and where in it the root goes: where its config's `ca` points, if it has one. */
36
+ const rootTarget = (input, serverDir) => Effect.gen(function* target() {
37
+ const path = yield* Path.Path;
38
+ const dir = path.resolve(serverDir ?? path.join(path.dirname(input.deployFile), defaults.serverDir));
39
+ const config = yield* existingServerConfig(dir);
40
+ const ca = Option.isSome(config) ? config.value.ca : {
41
+ cert: "ca.crt",
42
+ key: "ca.key"
43
+ };
44
+ return {
45
+ config,
46
+ target: {
47
+ cert: caFile(dir, ca.cert),
48
+ dir,
49
+ key: caFile(dir, ca.key)
50
+ }
51
+ };
52
+ });
53
+ /**
54
+ * Writes a new root where `deploy` reads it: ca.crt and ca.key in the server folder, or where an
55
+ * existing server config's `ca` points. The domains come from that config, else the deploy file.
56
+ * The name is the deploy file's ca.name, else its tunnel host. An existing root is replaced only
57
+ * with `force`.
58
+ */
59
+ const createRoot = (input) => Effect.gen(function* create() {
60
+ const deploy = Option.getOrUndefined(yield* optionalDeploy(input.deployFile));
61
+ const { config, target } = yield* rootTarget(input, deploy?.serverDir);
62
+ const domains = yield* rootDomains(config, deploy?.config);
63
+ yield* refuseReplacing(target, input.force);
64
+ const label = deploy?.config.ca?.name ?? deploy?.config.tunnelHost ?? domains[0];
65
+ yield* writeRoot(target, yield* generateRoot({
66
+ domains,
67
+ label
68
+ }));
69
+ return {
70
+ cert: target.cert,
71
+ domains,
72
+ key: target.key,
73
+ label
74
+ };
75
+ });
76
+ export { createRoot };
77
+
78
+ //# sourceMappingURL=create-root.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-root.js","names":[],"sources":["../src/create-root.ts"],"sourcesContent":["import {\n ServerConfigFileJson,\n caFile,\n serverConfigFileName,\n} from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ServerConfigFile } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Option, Path, Schema } from 'effect';\n\nimport { decodeDomains, generateRoot } from './ca.ts';\nimport { defaults, loadDeployConfig } from './config.ts';\nimport type { DeployConfig } from './config.ts';\nimport { InfraError } from './errors.ts';\nimport { folderMode, publicMode, secretMode } from './server-dir.ts';\n\n/** Where the root's files go. */\ninterface RootTarget {\n readonly cert: string;\n readonly dir: string;\n readonly key: string;\n}\n\n/** What `ca create` was given. */\ninterface CreateRootInput {\n /** The deploy file, which may not exist yet. */\n readonly deployFile: string;\n readonly force: boolean;\n}\n\n/** The deploy file if it exists. Any other problem with it fails. */\nconst optionalDeploy = (file: string) =>\n FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(\n Effect.orElseSucceed(() => false),\n Effect.flatMap((exists) =>\n exists ? loadDeployConfig(file).pipe(Effect.map(Option.some)) : Effect.succeedNone,\n ),\n );\n\n/** The server config in `dir`, if there is one: its domains and where its root's files are. */\nconst existingServerConfig = (dir: string) =>\n FileSystem.FileSystem.use((fs) => fs.readFileString(`${dir}/${serverConfigFileName}`)).pipe(\n Effect.option,\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.succeedNone,\n onSome: (text) =>\n Schema.decodeUnknownEffect(ServerConfigFileJson)(text).pipe(\n Effect.map(Option.some),\n Effect.mapError(\n (schemaError) =>\n new InfraError({\n message: `${dir}/${serverConfigFileName} is not a valid server config: ${schemaError.message}`,\n }),\n ),\n ),\n }),\n ),\n );\n\n/** The domains: the server config's, else the deploy file's, which seed a new server folder. */\nconst rootDomains = (config: Option.Option<ServerConfigFile>, deploy: DeployConfig | undefined) => {\n if (Option.isSome(config)) {\n return Effect.succeed(config.value.domains);\n }\n return deploy?.domains === undefined\n ? Effect.fail(\n new InfraError({\n message:\n 'no server config and no domains in the deploy file: add \"domains\" to wt-tunnel.deploy.json, the dev domains the root may sign for',\n }),\n )\n : decodeDomains(deploy.domains);\n};\n\nconst exists = (file: string) =>\n FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(Effect.orElseSucceed(() => false));\n\n/** Fails when the root's files exist, unless replacing them was asked for. */\nconst refuseReplacing = (target: RootTarget, force: boolean) =>\n Effect.all([exists(target.cert), exists(target.key)]).pipe(\n Effect.map(([cert, key]: readonly [boolean, boolean]): readonly string[] => [\n ...(cert ? [target.cert] : []),\n ...(key ? [target.key] : []),\n ]),\n Effect.filterOrFail(\n (existing: readonly string[]) => existing.length === 0 || force,\n (existing: readonly string[]) =>\n new InfraError({\n message: `${existing.join(' and ')} already exist. Replacing the root means every device that trusts it must trust the new one instead; pass --force to do that.`,\n }),\n ),\n );\n\n/** Writes the root: the folder private, the key readable by its owner only. */\nconst writeRoot = (target: RootTarget, root: { readonly cert: string; readonly key: string }) =>\n Effect.gen(function* write() {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(target.dir, { mode: folderMode, recursive: true });\n yield* fs.chmod(target.dir, folderMode);\n yield* fs.writeFileString(target.key, root.key, { mode: secretMode });\n yield* fs.chmod(target.key, secretMode);\n yield* fs.writeFileString(target.cert, root.cert, { mode: publicMode });\n }).pipe(Effect.orDie);\n\n/** The server folder, and where in it the root goes: where its config's `ca` points, if it has one. */\nconst rootTarget = (input: CreateRootInput, serverDir: string | undefined) =>\n Effect.gen(function* target() {\n const path = yield* Path.Path;\n const dir = path.resolve(\n serverDir ?? path.join(path.dirname(input.deployFile), defaults.serverDir),\n );\n const config = yield* existingServerConfig(dir);\n const ca = Option.isSome(config) ? config.value.ca : { cert: 'ca.crt', key: 'ca.key' };\n const found: RootTarget = { cert: caFile(dir, ca.cert), dir, key: caFile(dir, ca.key) };\n return { config, target: found };\n });\n\n/**\n * Writes a new root where `deploy` reads it: ca.crt and ca.key in the server folder, or where an\n * existing server config's `ca` points. The domains come from that config, else the deploy file.\n * The name is the deploy file's ca.name, else its tunnel host. An existing root is replaced only\n * with `force`.\n */\nconst createRoot = (input: CreateRootInput) =>\n Effect.gen(function* create() {\n const deploy = Option.getOrUndefined(yield* optionalDeploy(input.deployFile));\n const { config, target } = yield* rootTarget(input, deploy?.serverDir);\n const domains = yield* rootDomains(config, deploy?.config);\n yield* refuseReplacing(target, input.force);\n const label = deploy?.config.ca?.name ?? deploy?.config.tunnelHost ?? domains[0];\n yield* writeRoot(target, yield* generateRoot({ domains, label }));\n return { cert: target.cert, domains, key: target.key, label } as const;\n });\n\nexport { createRoot };\nexport type { CreateRootInput };\n"],"mappings":";;;;;;;;AA6BA,MAAM,kBAAkB,SACtB,WAAW,WAAW,KAAK,OAAO,GAAG,OAAO,IAAI,CAAC,CAAC,CAAC,KACjD,OAAO,oBAAoB,KAAK,GAChC,OAAO,SAAS,WACd,SAAS,iBAAiB,IAAI,CAAC,CAAC,KAAK,OAAO,IAAI,OAAO,IAAI,CAAC,IAAI,OAAO,WACzE,CACF;;AAGF,MAAM,wBAAwB,QAC5B,WAAW,WAAW,KAAK,OAAO,GAAG,eAAe,GAAG,IAAI,GAAG,sBAAsB,CAAC,CAAC,CAAC,KACrF,OAAO,QACP,OAAO,QACL,OAAO,MAAM;CACX,cAAc,OAAO;CACrB,SAAS,SACP,OAAO,oBAAoB,oBAAoB,CAAC,CAAC,IAAI,CAAC,CAAC,KACrD,OAAO,IAAI,OAAO,IAAI,GACtB,OAAO,UACJ,gBACC,IAAI,WAAW,EACb,SAAS,GAAG,IAAI,GAAG,qBAAqB,iCAAiC,YAAY,UACvF,CAAC,CACL,CACF;AACJ,CAAC,CACH,CACF;;AAGF,MAAM,eAAe,QAAyC,WAAqC;CACjG,IAAI,OAAO,OAAO,MAAM,GACtB,OAAO,OAAO,QAAQ,OAAO,MAAM,OAAO;CAE5C,OAAO,QAAQ,YAAY,KAAA,IACvB,OAAO,KACL,IAAI,WAAW,EACb,SACE,sIACJ,CAAC,CACH,IACA,cAAc,OAAO,OAAO;AAClC;AAEA,MAAM,UAAU,SACd,WAAW,WAAW,KAAK,OAAO,GAAG,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,OA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AAK,GAAG,IAAI;GAAG;GAAK,KAAK,OAAO,KAAK,GAAG,GAAG;EACvD;CAAE;AACjC,CAAC;;;;;;;AAQH,MAAM,cAAc,UAClB,OAAO,IAAI,UAAU,SAAS;CAC5B,MAAM,SAAS,OAAO,eAAe,OAAO,eAAe,MAAM,UAAU,CAAC;CAC5E,MAAM,EAAE,QAAQ,WAAW,OAAO,WAAW,OAAO,QAAQ,SAAS;CACrE,MAAM,UAAU,OAAO,YAAY,QAAQ,QAAQ,MAAM;CACzD,OAAO,gBAAgB,QAAQ,MAAM,KAAK;CAC1C,MAAM,QAAQ,QAAQ,OAAO,IAAI,QAAQ,QAAQ,OAAO,cAAc,QAAQ;CAC9E,OAAO,UAAU,QAAQ,OAAO,aAAa;EAAE;EAAS;CAAM,CAAC,CAAC;CAChE,OAAO;EAAE,MAAM,OAAO;EAAM;EAAS,KAAK,OAAO;EAAK;CAAM;AAC9D,CAAC"}
@@ -0,0 +1,150 @@
1
+ import { InfraError, failWith } from "./errors.js";
2
+ import { serverConfigFileName } from "./packages/contract/src/server-config.js";
3
+ import { decodeDomains, generateRoot } from "./ca.js";
4
+ import { serverFile } from "./server-dir.js";
5
+ import { gatherProviders, missingProviderVariables, providerSteps } from "./providers.js";
6
+ import { Effect, FileSystem, Path } from "effect";
7
+ import { randomBytes } from "node:crypto";
8
+ // src/create-server-dir.ts
9
+ const secretBytes = 32;
10
+ const indent = 2;
11
+ /** 43 base64url characters: above both the token's 16 and the auth secret's 32. */
12
+ const generateSecret = () => randomBytes(secretBytes).toString("base64url");
13
+ const isSet = (env, name) => (env[name] ?? "") !== "";
14
+ /** The deploy file fields a new folder needs that it leaves out. */
15
+ const missingFields = (deploy) => [...deploy.domains === void 0 ? ["domains"] : [], ...deploy.allow === void 0 ? ["allow"] : []];
16
+ /** "Add domains to the deploy file. Set GOOGLE_CLIENT_ID." for whichever list is not empty. */
17
+ const whatIsMissing = (fields, variables) => [...fields.length === 0 ? [] : [`Add ${fields.join(" and ")} to the deploy file.`], ...variables.length === 0 ? [] : [`Set ${variables.join(", ")} in the environment.`]].join(" ");
18
+ /**
19
+ * What the server serves: the dev domains, the allow list and the sign-in host from the deploy
20
+ * file, and the sign-in providers from the environment, else prompts. Fails naming everything
21
+ * missing: a field the deploy file leaves out, or, without a terminal, a provider variable.
22
+ */
23
+ const gatherSettings = (input) => Effect.gen(function* gather() {
24
+ const { ask, deploy, env } = input;
25
+ const fields = missingFields(deploy);
26
+ const variables = ask.interactive ? [] : missingProviderVariables(env);
27
+ if (deploy.domains === void 0 || deploy.allow === void 0 || variables.length > 0) return yield* new InfraError({ message: `the server folder does not exist yet. ${whatIsMissing(fields, variables)} Sign-in providers:\n${providerSteps(deploy.authHost)}` });
28
+ return {
29
+ allow: deploy.allow,
30
+ authHost: deploy.authHost,
31
+ domains: deploy.domains,
32
+ providers: yield* gatherProviders(env, ask, deploy.authHost)
33
+ };
34
+ });
35
+ const readText = (file, what) => FileSystem.FileSystem.use((fs) => fs.readFileString(file)).pipe(failWith(`cannot read ${what} at ${file}`));
36
+ const firstExisting = (files) => FileSystem.FileSystem.use((fs) => Effect.findFirst(files, (file) => fs.exists(file).pipe(Effect.orElseSucceed(() => false)))).pipe(Effect.map((found) => found._tag === "Some" ? found.value : void 0));
37
+ /** The deploy file's `ca.cert` and `ca.key`, resolved against its directory. */
38
+ const seededRoot = (input) => Path.Path.use((path) => {
39
+ const { cert, key } = input.deploy.ca ?? {};
40
+ return Effect.succeed({
41
+ cert: cert === void 0 ? void 0 : path.resolve(input.deployDir, cert),
42
+ key: key === void 0 ? void 0 : path.resolve(input.deployDir, key)
43
+ });
44
+ });
45
+ /** Where an existing root's certificate and key are, if anywhere. */
46
+ const rootSources = (input) => Effect.gen(function* sources() {
47
+ const path = yield* Path.Path;
48
+ const near = (name) => [path.join(input.serverDir, name), path.join(input.deployDir, name)];
49
+ const seeded = yield* seededRoot(input);
50
+ const keyFromEnv = isSet(input.env, "WT_CA_KEY") && seeded.key === void 0;
51
+ const keyFile = seeded.key ?? (isSet(input.env, "WT_CA_KEY_FILE") ? input.env.WT_CA_KEY_FILE : void 0) ?? (yield* firstExisting(near("ca.key")));
52
+ return {
53
+ certFile: seeded.cert ?? (yield* firstExisting(near("ca.crt"))),
54
+ keyFile: keyFromEnv ? void 0 : keyFile,
55
+ keySource: keyFromEnv ? "WT_CA_KEY" : keyFile
56
+ };
57
+ });
58
+ /** A new root's label: the deploy file's `ca.name`, else its tunnel host. */
59
+ const rootLabel = (deploy) => deploy.ca?.name ?? deploy.tunnelHost;
60
+ const onlyOneProblem = (certFile, keySource, serverDir) => certFile === void 0 ? `found the root key (${keySource}) but no certificate. Set ca.cert in the deploy file, or put ca.crt in ${serverDir}.` : `found the root certificate ${certFile} but no key. Set ca.key in the deploy file, set WT_CA_KEY or WT_CA_KEY_FILE, or put ca.key in ${serverDir}. wt-tunnel will not make a new root in its place: devices that trust the old one would not trust the new one. To start over with a new root, remove the certificate.`;
61
+ /**
62
+ * The root, decided so that a root devices already trust is never silently replaced. The cert comes
63
+ * from the deploy file's ca.cert, else ca.crt in the server folder or next to the deploy file. The
64
+ * key comes from its ca.key, WT_CA_KEY, WT_CA_KEY_FILE, else ca.key in the same places. With both,
65
+ * they are used; with neither, a new root is made; with only one, the deploy stops.
66
+ */
67
+ const resolveRoot = (input) => Effect.gen(function* root() {
68
+ const { certFile, keyFile, keySource } = yield* rootSources(input);
69
+ if (certFile !== void 0 && keySource !== void 0) {
70
+ const origin = {
71
+ cert: certFile,
72
+ key: keySource,
73
+ kind: "found"
74
+ };
75
+ return {
76
+ cert: yield* readText(certFile, "the root certificate"),
77
+ key: keyFile === void 0 ? input.env.WT_CA_KEY ?? "" : yield* readText(keyFile, "the root key"),
78
+ origin
79
+ };
80
+ }
81
+ if (certFile === void 0 && keySource === void 0) {
82
+ const domains = yield* decodeDomains(input.domains);
83
+ const origin = { kind: "generated" };
84
+ return {
85
+ ...yield* generateRoot({
86
+ domains,
87
+ label: rootLabel(input.deploy)
88
+ }),
89
+ origin
90
+ };
91
+ }
92
+ return yield* new InfraError({ message: onlyOneProblem(certFile, keySource ?? "", input.serverDir) });
93
+ });
94
+ /**
95
+ * A new server folder, in memory: the config from the deploy file, the environment and prompts,
96
+ * generated secrets where the environment has none, and the root's files.
97
+ */
98
+ const draftServerDir = (input) => Effect.gen(function* draft() {
99
+ const settings = yield* gatherSettings(input);
100
+ const root = yield* resolveRoot({
101
+ ...input,
102
+ domains: settings.domains
103
+ });
104
+ const secret = (name, field) => isSet(input.env, name) ? {
105
+ generated: [],
106
+ value: input.env[name] ?? ""
107
+ } : {
108
+ generated: [field],
109
+ value: generateSecret()
110
+ };
111
+ const tunnelToken = secret("WT_TUNNEL_SERVER_TOKEN", "tunnelToken");
112
+ const authSecret = secret("WT_AUTH_SECRET", "authSecret");
113
+ const config = {
114
+ allow: settings.allow,
115
+ authHost: settings.authHost,
116
+ authSecret: authSecret.value,
117
+ ca: {
118
+ cert: "ca.crt",
119
+ key: "ca.key"
120
+ },
121
+ domains: settings.domains,
122
+ providers: settings.providers,
123
+ tunnelToken: tunnelToken.value
124
+ };
125
+ return {
126
+ files: [
127
+ serverFile("ca.crt", root.cert, 420),
128
+ serverFile("ca.key", root.key, 384),
129
+ serverFile(serverConfigFileName, `${JSON.stringify(config, void 0, indent)}\n`, 384)
130
+ ],
131
+ generated: [
132
+ ...tunnelToken.generated,
133
+ ...authSecret.generated,
134
+ ...root.origin.kind === "generated" ? ["the root CA"] : []
135
+ ],
136
+ root: root.origin
137
+ };
138
+ });
139
+ /** What `deploy` tells the user after it creates the folder. */
140
+ const createdSummary = (input) => [
141
+ `Created ${input.serverDir}: ${input.draft.files.map(({ name }) => name).join(", ")}.`,
142
+ input.draft.generated.length === 0 ? "Nothing was generated: every value came from the flags, the environment or existing files." : `Generated: ${input.draft.generated.join(", ")}.`,
143
+ ...input.draft.root.kind === "found" ? [`The root CA is ${input.draft.root.cert}, with its key from ${input.draft.root.key}.`] : [],
144
+ `It holds secrets in plain text. Back it up somewhere safe, such as a secret manager, and never commit it. Edit ${serverConfigFileName} there and run wt-tunnel deploy again to change what the server does.`,
145
+ ...input.draft.generated.includes("tunnelToken") ? [`Tunnel clients need tunnelToken from ${serverConfigFileName} as WT_TUNNEL_SERVER_TOKEN.`] : [],
146
+ `After the deploy, open https://${input.authHost}/ca on each device that opens dev URLs to trust the root.`
147
+ ].join("\n");
148
+ export { createdSummary, draftServerDir };
149
+
150
+ //# sourceMappingURL=create-server-dir.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-server-dir.js","names":[],"sources":["../src/create-server-dir.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\n\nimport { serverConfigFileName } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Path } from 'effect';\nimport type { Prompt } from 'effect/cli';\n\nimport { decodeDomains, generateRoot } from './ca.ts';\nimport type { DeployConfig } from './config.ts';\nimport { failWith, InfraError } from './errors.ts';\nimport { gatherProviders, missingProviderVariables, providerSteps } from './providers.ts';\nimport type { Env } from './providers.ts';\nimport { publicMode, secretMode, serverFile } from './server-dir.ts';\nimport type { ServerFile } from './server-dir.ts';\n\n/** How to ask the user for what the flags and the environment leave out. */\ninterface Ask {\n /** Whether anyone can answer: stdin is a terminal. */\n readonly interactive: boolean;\n readonly line: (message: string) => Effect.Effect<string, InfraError, Prompt.Environment>;\n /** Hidden input, for a secret. */\n readonly secret: (message: string) => Effect.Effect<string, InfraError, Prompt.Environment>;\n}\n\n/** Where the deploy found the root, or that it made a new one. */\ntype RootOrigin =\n | { readonly kind: 'found'; readonly cert: string; readonly key: string }\n | { readonly kind: 'generated' };\n\n/** A folder ready to write, and what the summary says about it. */\ninterface Draft {\n readonly files: readonly ServerFile[];\n /** Values made for this folder rather than taken from the flags or the environment. */\n readonly generated: readonly string[];\n readonly root: RootOrigin;\n}\n\nconst secretBytes = 32;\nconst indent = 2;\n/** 43 base64url characters: above both the token's 16 and the auth secret's 32. */\nconst generateSecret = () => randomBytes(secretBytes).toString('base64url');\n\nconst isSet = (env: Env, name: string) => (env[name] ?? '') !== '';\n\n/** The deploy file fields a new folder needs that it leaves out. */\nconst missingFields = (deploy: DeployConfig) => [\n ...(deploy.domains === undefined ? ['domains'] : []),\n ...(deploy.allow === undefined ? ['allow'] : []),\n];\n\n/** \"Add domains to the deploy file. Set GOOGLE_CLIENT_ID.\" for whichever list is not empty. */\nconst whatIsMissing = (fields: readonly string[], variables: readonly string[]) =>\n [\n ...(fields.length === 0 ? [] : [`Add ${fields.join(' and ')} to the deploy file.`]),\n ...(variables.length === 0 ? [] : [`Set ${variables.join(', ')} in the environment.`]),\n ].join(' ');\n\n/**\n * What the server serves: the dev domains, the allow list and the sign-in host from the deploy\n * file, and the sign-in providers from the environment, else prompts. Fails naming everything\n * missing: a field the deploy file leaves out, or, without a terminal, a provider variable.\n */\nconst gatherSettings = (input: {\n readonly ask: Ask;\n readonly deploy: DeployConfig;\n readonly env: Env;\n}) =>\n Effect.gen(function* gather() {\n const { ask, deploy, env } = input;\n const fields = missingFields(deploy);\n const variables = ask.interactive ? [] : missingProviderVariables(env);\n if (deploy.domains === undefined || deploy.allow === undefined || variables.length > 0) {\n return yield* new InfraError({\n message: `the server folder does not exist yet. ${whatIsMissing(fields, variables)} Sign-in providers:\\n${providerSteps(deploy.authHost)}`,\n });\n }\n return {\n allow: deploy.allow,\n authHost: deploy.authHost,\n domains: deploy.domains,\n providers: yield* gatherProviders(env, ask, deploy.authHost),\n };\n });\n\nconst readText = (file: string, what: string) =>\n FileSystem.FileSystem.use((fs) => fs.readFileString(file)).pipe(\n failWith(`cannot read ${what} at ${file}`),\n );\n\nconst firstExisting = (files: readonly string[]) =>\n FileSystem.FileSystem.use((fs) =>\n Effect.findFirst(files, (file) => fs.exists(file).pipe(Effect.orElseSucceed(() => false))),\n ).pipe(Effect.map((found) => (found._tag === 'Some' ? found.value : undefined)));\n\ninterface RootInput {\n readonly deploy: DeployConfig;\n readonly deployDir: string;\n readonly domains: readonly string[];\n readonly env: Env;\n readonly serverDir: string;\n}\n\n/** The deploy file's `ca.cert` and `ca.key`, resolved against its directory. */\nconst seededRoot = (input: RootInput) =>\n Path.Path.use((path) => {\n const { cert, key } = input.deploy.ca ?? {};\n return Effect.succeed({\n cert: cert === undefined ? undefined : path.resolve(input.deployDir, cert),\n key: key === undefined ? undefined : path.resolve(input.deployDir, key),\n });\n });\n\n/** Where an existing root's certificate and key are, if anywhere. */\nconst rootSources = (input: RootInput) =>\n Effect.gen(function* sources() {\n const path = yield* Path.Path;\n const near = (name: string) => [\n path.join(input.serverDir, name),\n path.join(input.deployDir, name),\n ];\n const seeded = yield* seededRoot(input);\n const keyFromEnv = isSet(input.env, 'WT_CA_KEY') && seeded.key === undefined;\n const keyFile =\n seeded.key ??\n (isSet(input.env, 'WT_CA_KEY_FILE') ? input.env.WT_CA_KEY_FILE : undefined) ??\n (yield* firstExisting(near('ca.key')));\n return {\n certFile: seeded.cert ?? (yield* firstExisting(near('ca.crt'))),\n keyFile: keyFromEnv ? undefined : keyFile,\n keySource: keyFromEnv ? 'WT_CA_KEY' : keyFile,\n };\n });\n\n/** A new root's label: the deploy file's `ca.name`, else its tunnel host. */\nconst rootLabel = (deploy: DeployConfig) => deploy.ca?.name ?? deploy.tunnelHost;\n\nconst onlyOneProblem = (certFile: string | undefined, keySource: string, serverDir: string) =>\n certFile === undefined\n ? `found the root key (${keySource}) but no certificate. Set ca.cert in the deploy file, or put ca.crt in ${serverDir}.`\n : `found the root certificate ${certFile} but no key. Set ca.key in the deploy file, set WT_CA_KEY or WT_CA_KEY_FILE, or put ca.key in ${serverDir}. wt-tunnel will not make a new root in its place: devices that trust the old one would not trust the new one. To start over with a new root, remove the certificate.`;\n\n/**\n * The root, decided so that a root devices already trust is never silently replaced. The cert comes\n * from the deploy file's ca.cert, else ca.crt in the server folder or next to the deploy file. The\n * key comes from its ca.key, WT_CA_KEY, WT_CA_KEY_FILE, else ca.key in the same places. With both,\n * they are used; with neither, a new root is made; with only one, the deploy stops.\n */\nconst resolveRoot = (input: RootInput) =>\n Effect.gen(function* root() {\n const { certFile, keyFile, keySource } = yield* rootSources(input);\n if (certFile !== undefined && keySource !== undefined) {\n const origin: RootOrigin = { cert: certFile, key: keySource, kind: 'found' };\n return {\n cert: yield* readText(certFile, 'the root certificate'),\n key:\n keyFile === undefined\n ? (input.env.WT_CA_KEY ?? '')\n : yield* readText(keyFile, 'the root key'),\n origin,\n };\n }\n if (certFile === undefined && keySource === undefined) {\n const domains = yield* decodeDomains(input.domains);\n const origin: RootOrigin = { kind: 'generated' };\n return { ...(yield* generateRoot({ domains, label: rootLabel(input.deploy) })), origin };\n }\n return yield* new InfraError({\n message: onlyOneProblem(certFile, keySource ?? '', input.serverDir),\n });\n });\n\n/**\n * A new server folder, in memory: the config from the deploy file, the environment and prompts,\n * generated secrets where the environment has none, and the root's files.\n */\nconst draftServerDir = (input: {\n readonly ask: Ask;\n readonly deploy: DeployConfig;\n readonly deployDir: string;\n readonly env: Env;\n readonly serverDir: string;\n}) =>\n Effect.gen(function* draft() {\n const settings = yield* gatherSettings(input);\n const root = yield* resolveRoot({ ...input, domains: settings.domains });\n const secret = (name: string, field: string) =>\n isSet(input.env, name)\n ? { generated: [], value: input.env[name] ?? '' }\n : { generated: [field], value: generateSecret() };\n const tunnelToken = secret('WT_TUNNEL_SERVER_TOKEN', 'tunnelToken');\n const authSecret = secret('WT_AUTH_SECRET', 'authSecret');\n const config = {\n allow: settings.allow,\n authHost: settings.authHost,\n authSecret: authSecret.value,\n ca: { cert: 'ca.crt', key: 'ca.key' },\n domains: settings.domains,\n providers: settings.providers,\n tunnelToken: tunnelToken.value,\n };\n const files: readonly ServerFile[] = [\n serverFile('ca.crt', root.cert, publicMode),\n serverFile('ca.key', root.key, secretMode),\n serverFile(\n serverConfigFileName,\n `${JSON.stringify(config, undefined, indent)}\\n`,\n secretMode,\n ),\n ];\n const result: Draft = {\n files,\n generated: [\n ...tunnelToken.generated,\n ...authSecret.generated,\n ...(root.origin.kind === 'generated' ? ['the root CA'] : []),\n ],\n root: root.origin,\n };\n return result;\n });\n\n/** What `deploy` tells the user after it creates the folder. */\nconst createdSummary = (input: {\n readonly authHost: string;\n readonly draft: Draft;\n readonly serverDir: string;\n}) =>\n [\n `Created ${input.serverDir}: ${input.draft.files.map(({ name }) => name).join(', ')}.`,\n input.draft.generated.length === 0\n ? 'Nothing was generated: every value came from the flags, the environment or existing files.'\n : `Generated: ${input.draft.generated.join(', ')}.`,\n ...(input.draft.root.kind === 'found'\n ? [`The root CA is ${input.draft.root.cert}, with its key from ${input.draft.root.key}.`]\n : []),\n `It holds secrets in plain text. Back it up somewhere safe, such as a secret manager, and never commit it. Edit ${serverConfigFileName} there and run wt-tunnel deploy again to change what the server does.`,\n ...(input.draft.generated.includes('tunnelToken')\n ? [`Tunnel clients need tunnelToken from ${serverConfigFileName} as WT_TUNNEL_SERVER_TOKEN.`]\n : []),\n `After the deploy, open https://${input.authHost}/ca on each device that opens dev URLs to trust the root.`,\n ].join('\\n');\n\nexport { createdSummary, draftServerDir };\nexport type { Ask, Draft };\n"],"mappings":";;;;;;;;AAoCA,MAAM,cAAc;AACpB,MAAM,SAAS;;AAEf,MAAM,uBAAuB,YAAY,WAAW,CAAC,CAAC,SAAS,WAAW;AAE1E,MAAM,SAAS,KAAU,UAAkB,IAAI,SAAS,QAAQ;;AAGhE,MAAM,iBAAiB,WAAyB,CAC9C,GAAI,OAAO,YAAY,KAAA,IAAY,CAAC,SAAS,IAAI,CAAC,GAClD,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,OAAO,IAAI,CAAC,CAChD;;AAGA,MAAM,iBAAiB,QAA2B,cAChD,CACE,GAAI,OAAO,WAAW,IAAI,CAAC,IAAI,CAAC,OAAO,OAAO,KAAK,OAAO,EAAE,qBAAqB,GACjF,GAAI,UAAU,WAAW,IAAI,CAAC,IAAI,CAAC,OAAO,UAAU,KAAK,IAAI,EAAE,qBAAqB,CACtF,CAAC,CAAC,KAAK,GAAG;;;;;;AA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Ac,MAAM,MAAM,UAAU,KAAK,IAAI,EAAE;CACnD,GAAI,MAAM,MAAM,KAAK,SAAS,UAC1B,CAAC,kBAAkB,MAAM,MAAM,KAAK,KAAK,sBAAsB,MAAM,MAAM,KAAK,IAAI,EAAE,IACtF,CAAC;CACL,kHAAkH,qBAAqB;CACvI,GAAI,MAAM,MAAM,UAAU,SAAS,aAAa,IAC5C,CAAC,wCAAwC,qBAAqB,4BAA4B,IAC1F,CAAC;CACL,kCAAkC,MAAM,SAAS;AACnD,CAAC,CAAC,KAAK,IAAI"}
@@ -0,0 +1,132 @@
1
+ import { Hostname } from "./packages/contract/src/index.js";
2
+ import { Schema } from "effect";
3
+ // src/deployment.ts
4
+ const FlyName = Schema.String.check(Schema.isPattern(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u));
5
+ const FlyRegion = Schema.String.check(Schema.isPattern(/^[a-z]{3}$/u));
6
+ const MemoryMb = Schema.Int.check(Schema.isGreaterThanOrEqualTo(256));
7
+ const ImageRef = Schema.String.check(Schema.isPattern(/^[^\s]+$/u));
8
+ /** The names Alchemy accepts for a stack or a stage. */
9
+ const AlchemyName = Schema.String.check(Schema.isPattern(/^[a-z0-9]+(?:[-_a-z0-9]+)*$/iu));
10
+ const CloudflareId = Schema.String.check(Schema.isPattern(/^[0-9a-f]{32}$/u));
11
+ /** A zone whose records Alchemy creates in Cloudflare. A record needs only the zone ID. */
12
+ const CloudflareZone = Schema.Struct({
13
+ provider: Schema.Literal("cloudflare"),
14
+ zone: Hostname,
15
+ zoneId: CloudflareId
16
+ });
17
+ /** A zone whose records the user creates by hand; `wt-tunnel outputs` lists them. */
18
+ const ManualZone = Schema.Struct({
19
+ provider: Schema.Literal("manual"),
20
+ zone: Hostname
21
+ });
22
+ const DnsZone = Schema.Union([CloudflareZone, ManualZone]);
23
+ /** Every zone the record names sit in. Each record goes in the most specific one. */
24
+ const Dns = Schema.NonEmptyArray(DnsZone);
25
+ /**
26
+ * Alchemy's Cloudflare credentials come from the environment and need an account ID even where the
27
+ * API calls need only a zone ID. One token serves every Cloudflare zone and the state store.
28
+ */
29
+ const cloudflareEnv = ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"];
30
+ const dnsProviders = {
31
+ cloudflare: {
32
+ creator: "Cloudflare",
33
+ env: cloudflareEnv
34
+ },
35
+ manual: {
36
+ creator: void 0,
37
+ env: []
38
+ }
39
+ };
40
+ /**
41
+ * A named Alchemy state store, whose Worker is `alchemy-state-store-<name>`. A Worker name holds at
42
+ * most 63 lowercase letters, digits and dashes, and the prefix takes 20.
43
+ */
44
+ const StateStoreName = Schema.String.check(Schema.isPattern(/^[a-z0-9](?:[a-z0-9-]{0,41}[a-z0-9])?$/u));
45
+ /**
46
+ * Where Alchemy keeps what it created: a state store Worker in a Cloudflare account, or `.alchemy/`
47
+ * next to the config. The Worker is the account's default `alchemy-state-store`, which every
48
+ * Alchemy project in the account shares, or `alchemy-state-store-<name>` with a `name`. Its URL is
49
+ * that Worker's on the account's workers.dev subdomain.
50
+ */
51
+ const StateStore = Schema.Union([Schema.Literal("local"), Schema.Struct({
52
+ accountId: CloudflareId,
53
+ name: Schema.optionalKey(StateStoreName),
54
+ provider: Schema.Literal("cloudflare")
55
+ })]);
56
+ /** The options of Alchemy's Cloudflare state for a Cloudflare store: its name, if it has one. */
57
+ const cloudflareStateOptions = ({ name }) => name === void 0 ? {} : { name };
58
+ /** The secrets the state store needs. The CLI sets CLOUDFLARE_ACCOUNT_ID from `state.accountId`. */
59
+ const stateEnv = (state) => state === "local" ? [] : cloudflareEnv;
60
+ /** Everything the stack needs except the secrets, with every default filled in. */
61
+ const Deployment = Schema.Struct({
62
+ authHost: Hostname,
63
+ dns: Dns,
64
+ domains: Schema.NonEmptyArray(Hostname),
65
+ fly: Schema.Struct({
66
+ app: FlyName,
67
+ memoryMb: MemoryMb,
68
+ org: FlyName,
69
+ region: FlyRegion
70
+ }),
71
+ image: ImageRef,
72
+ stack: AlchemyName,
73
+ stage: AlchemyName,
74
+ state: StateStore,
75
+ tunnelHost: Hostname
76
+ });
77
+ const DeploymentJson = Schema.fromJsonString(Deployment);
78
+ /** How the CLI hands the deployment and the server folder's files to the alchemy process. */
79
+ const deploymentEnv = "WT_TUNNEL_INFRA_DEPLOYMENT";
80
+ const serverFilesEnv = "WT_TUNNEL_INFRA_SERVER_FILES";
81
+ /**
82
+ * Every record resolves straight to the Machine, never through a proxy: frpc speaks raw TCP to port
83
+ * 7000, and Caddy ends TLS for the dev hosts and the sign-in host itself.
84
+ */
85
+ const dnsHosts = (deployment) => [
86
+ ...deployment.domains.map((domain) => ({
87
+ id: `Wildcard-${domain}`,
88
+ name: `*.${domain}`
89
+ })),
90
+ {
91
+ id: "TunnelHost",
92
+ name: deployment.tunnelHost
93
+ },
94
+ {
95
+ id: "AuthHost",
96
+ name: deployment.authHost
97
+ }
98
+ ];
99
+ /** The most specific zone `name` sits in: the longest one equal to it or a suffix of it. */
100
+ const zoneOf = (name, dns) => dns.filter(({ zone }) => name === zone || name.endsWith(`.${zone}`)).toSorted((left, right) => right.zone.length - left.zone.length).at(0);
101
+ /** Each record name with the zone it goes in, and the names no zone covers. */
102
+ const placeHosts = (deployment) => {
103
+ const placed = [];
104
+ const uncovered = [];
105
+ for (const host of dnsHosts(deployment)) {
106
+ const zone = zoneOf(host.name, deployment.dns);
107
+ if (zone === void 0) uncovered.push(host.name);
108
+ else placed.push({
109
+ ...host,
110
+ zone
111
+ });
112
+ }
113
+ return {
114
+ placed,
115
+ uncovered
116
+ };
117
+ };
118
+ /** Zones `dns` lists more than once, whatever their provider. */
119
+ const repeatedZones = (dns) => {
120
+ const zones = dns.map(({ zone }) => zone);
121
+ return [...new Set(zones.filter((zone, index) => zones.indexOf(zone) !== index))].map((zone) => `dns lists the zone ${zone} more than once`);
122
+ };
123
+ /** The record names no zone in `dns` covers, as a problem, or nothing. */
124
+ const uncoveredNames = (deployment) => {
125
+ const { uncovered } = placeHosts(deployment);
126
+ return uncovered.length === 0 ? [] : [`no dns entry's zone covers ${uncovered.join(", ")}`];
127
+ };
128
+ /** The secrets the DNS providers and the state store need, each once. */
129
+ const providerEnv = ({ dns, state }) => [.../* @__PURE__ */ new Set([...dns.flatMap(({ provider }) => dnsProviders[provider].env), ...stateEnv(state)])];
130
+ export { AlchemyName, DeploymentJson, Dns, FlyName, FlyRegion, ImageRef, MemoryMb, StateStore, cloudflareStateOptions, deploymentEnv, dnsProviders, placeHosts, providerEnv, repeatedZones, serverFilesEnv, uncoveredNames };
131
+
132
+ //# sourceMappingURL=deployment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deployment.js","names":[],"sources":["../src/deployment.ts"],"sourcesContent":["import { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { Schema } from 'effect';\n\nconst FlyName = Schema.String.check(Schema.isPattern(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u));\nconst FlyRegion = Schema.String.check(Schema.isPattern(/^[a-z]{3}$/u));\nconst minMemoryMb = 256;\nconst MemoryMb = Schema.Int.check(Schema.isGreaterThanOrEqualTo(minMemoryMb));\nconst ImageRef = Schema.String.check(Schema.isPattern(/^[^\\s]+$/u));\n/** The names Alchemy accepts for a stack or a stage. */\nconst AlchemyName = Schema.String.check(Schema.isPattern(/^[a-z0-9]+(?:[-_a-z0-9]+)*$/iu));\nconst CloudflareId = Schema.String.check(Schema.isPattern(/^[0-9a-f]{32}$/u));\n\n/** A zone whose records Alchemy creates in Cloudflare. A record needs only the zone ID. */\nconst CloudflareZone = Schema.Struct({\n provider: Schema.Literal('cloudflare'),\n zone: Hostname,\n zoneId: CloudflareId,\n});\n\n/** A zone whose records the user creates by hand; `wt-tunnel outputs` lists them. */\nconst ManualZone = Schema.Struct({ provider: Schema.Literal('manual'), zone: Hostname });\n\nconst DnsZone = Schema.Union([CloudflareZone, ManualZone]);\ntype DnsZone = typeof DnsZone.Type;\ntype DnsProvider = DnsZone['provider'];\n\n/** Every zone the record names sit in. Each record goes in the most specific one. */\nconst Dns = Schema.NonEmptyArray(DnsZone);\n\n/**\n * Alchemy's Cloudflare credentials come from the environment and need an account ID even where the\n * API calls need only a zone ID. One token serves every Cloudflare zone and the state store.\n */\nconst cloudflareEnv = ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID'] as const;\n\ninterface DnsProviderInfo {\n /** Who creates the records, for `outputs`; `undefined` when the user does. */\n readonly creator: string | undefined;\n /** The secrets the stack needs to create the records. */\n readonly env: readonly string[];\n}\n\nconst dnsProviders: Readonly<Record<DnsProvider, DnsProviderInfo>> = {\n cloudflare: { creator: 'Cloudflare', env: cloudflareEnv },\n manual: { creator: undefined, env: [] },\n};\n\n/**\n * A named Alchemy state store, whose Worker is `alchemy-state-store-<name>`. A Worker name holds at\n * most 63 lowercase letters, digits and dashes, and the prefix takes 20.\n */\nconst StateStoreName = Schema.String.check(\n Schema.isPattern(/^[a-z0-9](?:[a-z0-9-]{0,41}[a-z0-9])?$/u),\n);\n\n/**\n * Where Alchemy keeps what it created: a state store Worker in a Cloudflare account, or `.alchemy/`\n * next to the config. The Worker is the account's default `alchemy-state-store`, which every\n * Alchemy project in the account shares, or `alchemy-state-store-<name>` with a `name`. Its URL is\n * that Worker's on the account's workers.dev subdomain.\n */\nconst StateStore = Schema.Union([\n Schema.Literal('local'),\n Schema.Struct({\n accountId: CloudflareId,\n name: Schema.optionalKey(StateStoreName),\n provider: Schema.Literal('cloudflare'),\n }),\n]);\ntype StateStore = typeof StateStore.Type;\n\n/** The options of Alchemy's Cloudflare state for a Cloudflare store: its name, if it has one. */\nconst cloudflareStateOptions = ({\n name,\n}: Exclude<StateStore, 'local'>): { readonly name?: string } =>\n name === undefined ? {} : { name };\n\n/** The secrets the state store needs. The CLI sets CLOUDFLARE_ACCOUNT_ID from `state.accountId`. */\nconst stateEnv = (state: StateStore): readonly string[] => (state === 'local' ? [] : cloudflareEnv);\n\n/** Everything the stack needs except the secrets, with every default filled in. */\nconst Deployment = Schema.Struct({\n authHost: Hostname,\n dns: Dns,\n domains: Schema.NonEmptyArray(Hostname),\n fly: Schema.Struct({ app: FlyName, memoryMb: MemoryMb, org: FlyName, region: FlyRegion }),\n image: ImageRef,\n stack: AlchemyName,\n stage: AlchemyName,\n state: StateStore,\n tunnelHost: Hostname,\n});\ntype Deployment = typeof Deployment.Type;\n\nconst DeploymentJson = Schema.fromJsonString(Deployment);\n\n/** How the CLI hands the deployment and the server folder's files to the alchemy process. */\nconst deploymentEnv = 'WT_TUNNEL_INFRA_DEPLOYMENT';\nconst serverFilesEnv = 'WT_TUNNEL_INFRA_SERVER_FILES';\n\ninterface DnsHost {\n /** The prefix of the A and AAAA records' logical IDs in the stack. */\n readonly id: string;\n readonly name: string;\n}\n\n/**\n * Every record resolves straight to the Machine, never through a proxy: frpc speaks raw TCP to port\n * 7000, and Caddy ends TLS for the dev hosts and the sign-in host itself.\n */\nconst dnsHosts = (\n deployment: Pick<Deployment, 'authHost' | 'domains' | 'tunnelHost'>,\n): readonly DnsHost[] => [\n ...deployment.domains.map((domain) => ({ id: `Wildcard-${domain}`, name: `*.${domain}` })),\n { id: 'TunnelHost', name: deployment.tunnelHost },\n { id: 'AuthHost', name: deployment.authHost },\n];\n\ninterface PlacedHost extends DnsHost {\n readonly zone: DnsZone;\n}\n\n/** The most specific zone `name` sits in: the longest one equal to it or a suffix of it. */\nconst zoneOf = (name: string, dns: readonly DnsZone[]) =>\n dns\n .filter(({ zone }) => name === zone || name.endsWith(`.${zone}`))\n .toSorted((left, right) => right.zone.length - left.zone.length)\n .at(0);\n\n/** Each record name with the zone it goes in, and the names no zone covers. */\nconst placeHosts = (\n deployment: Pick<Deployment, 'authHost' | 'dns' | 'domains' | 'tunnelHost'>,\n) => {\n const placed: PlacedHost[] = [];\n const uncovered: string[] = [];\n for (const host of dnsHosts(deployment)) {\n const zone = zoneOf(host.name, deployment.dns);\n if (zone === undefined) {\n uncovered.push(host.name);\n } else {\n placed.push({ ...host, zone });\n }\n }\n return { placed, uncovered };\n};\n\n/** Zones `dns` lists more than once, whatever their provider. */\nconst repeatedZones = (dns: readonly DnsZone[]): readonly string[] => {\n const zones = dns.map(({ zone }) => zone);\n return [...new Set(zones.filter((zone, index) => zones.indexOf(zone) !== index))].map(\n (zone) => `dns lists the zone ${zone} more than once`,\n );\n};\n\n/** The record names no zone in `dns` covers, as a problem, or nothing. */\nconst uncoveredNames = (\n deployment: Pick<Deployment, 'authHost' | 'dns' | 'domains' | 'tunnelHost'>,\n): readonly string[] => {\n const { uncovered } = placeHosts(deployment);\n return uncovered.length === 0 ? [] : [`no dns entry's zone covers ${uncovered.join(', ')}`];\n};\n\n/** The secrets the DNS providers and the state store need, each once. */\nconst providerEnv = ({ dns, state }: Pick<Deployment, 'dns' | 'state'>): readonly string[] => [\n ...new Set([...dns.flatMap(({ provider }) => dnsProviders[provider].env), ...stateEnv(state)]),\n];\n\nexport {\n AlchemyName,\n Dns,\n DeploymentJson,\n FlyName,\n FlyRegion,\n ImageRef,\n MemoryMb,\n StateStore,\n cloudflareStateOptions,\n deploymentEnv,\n dnsProviders,\n placeHosts,\n providerEnv,\n repeatedZones,\n serverFilesEnv,\n uncoveredNames,\n};\nexport type { Deployment, DnsZone, PlacedHost };\n"],"mappings":";;;AAGA,MAAM,UAAU,OAAO,OAAO,MAAM,OAAO,UAAU,oCAAoC,CAAC;AAC1F,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,UAAU,aAAa,CAAC;AAErE,MAAM,WAAW,OAAO,IAAI,MAAM,OAAO,uBAAuB,GAAW,CAAC;AAC5E,MAAM,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,WAAW,CAAC;;AAElE,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,UAAU,+BAA+B,CAAC;AACzF,MAAM,eAAe,OAAO,OAAO,MAAM,OAAO,UAAU,iBAAiB,CAAC;;AAG5E,MAAM,iBAAiB,OAAO,OAAO;CACnC,UAAU,OAAO,QAAQ,YAAY;CACrC,MAAM;CACN,QAAQ;AAC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AI;EAAY,MAAM,WAAW;CAAS;AAC9C;;AAOA,MAAM,UAAU,MAAc,QAC5B,IACG,QAAQ,EAAE,WAAW,SAAS,QAAQ,KAAK,SAAS,IAAI,MAAM,CAAC,CAAC,CAChE,UAAU,MAAM,UAAU,MAAM,KAAK,SAAS,KAAK,KAAK,MAAM,CAAC,CAC/D,GAAG,CAAC;;AAGT,MAAM,cACJ,eACG;CACH,MAAM,SAAuB,CAAC;CAC9B,MAAM,YAAsB,CAAC;CAC7B,KAAK,MAAM,QAAQ,SAAS,UAAU,GAAG;EACvC,MAAM,OAAO,OAAO,KAAK,MAAM,WAAW,GAAG;EAC7C,IAAI,SAAS,KAAA,GACX,UAAU,KAAK,KAAK,IAAI;OAExB,OAAO,KAAK;GAAE,GAAG;GAAM;EAAK,CAAC;CAEjC;CACA,OAAO;EAAE;EAAQ;CAAU;AAC7B;;AAGA,MAAM,iBAAiB,QAA+C;CACpE,MAAM,QAAQ,IAAI,KAAK,EAAE,WAAW,IAAI;CACxC,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,MAAM,UAAU,MAAM,QAAQ,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAC/E,SAAS,sBAAsB,KAAK,gBACvC;AACF;;AAGA,MAAM,kBACJ,eACsB;CACtB,MAAM,EAAE,cAAc,WAAW,UAAU;CAC3C,OAAO,UAAU,WAAW,IAAI,CAAC,IAAI,CAAC,8BAA8B,UAAU,KAAK,IAAI,GAAG;AAC5F;;AAGA,MAAM,eAAe,EAAE,KAAK,YAAkE,CAC5F,mBAAG,IAAI,IAAI,CAAC,GAAG,IAAI,SAAS,EAAE,eAAe,aAAa,SAAS,CAAC,GAAG,GAAG,GAAG,SAAS,KAAK,CAAC,CAAC,CAC/F"}
package/dist/errors.js ADDED
@@ -0,0 +1,9 @@
1
+ import { Effect, Schema } from "effect";
2
+ // src/errors.ts
3
+ const { TaggedError: taggedErrorClass } = Schema;
4
+ var InfraError = class extends taggedErrorClass()("InfraError", { message: Schema.String }) {};
5
+ /** Replaces a failure with an InfraError whose message, written for the user, says what failed. */
6
+ const failWith = (message) => Effect.mapError(() => new InfraError({ message }));
7
+ export { InfraError, failWith };
8
+
9
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { Effect, Schema } from 'effect';\n\n/*\n * The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in\n * `Error`, as an error thrown without `new`.\n */\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass InfraError extends taggedErrorClass<InfraError>()('InfraError', {\n message: Schema.String,\n}) {}\n\n/** Replaces a failure with an InfraError whose message, written for the user, says what failed. */\nconst failWith = (message: string) => Effect.mapError(() => new InfraError({ message }));\n\nexport { failWith, InfraError };\n"],"mappings":";;AAMA,MAAM,EAAE,aAAa,qBAAqB;AAE1C,IAAM,aAAN,cAAyB,iBAA6B,CAAC,CAAC,cAAc,EACpE,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAM,YAAY,YAAoB,OAAO,eAAe,IAAI,WAAW,EAAE,QAAQ,CAAC,CAAC"}