@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { Console, Effect, Option, Redacted } from 'effect';\nimport { Argument, Command, Flag, Prompt } from 'effect/cli';\n\nimport { runAlchemy, stackFile } from './alchemy.ts';\nimport { deployFileName, loadDeployConfig } from './config.ts';\nimport { createRoot } from './create-root.ts';\nimport type { Ask, CreateInputs } from './create-server-dir.ts';\nimport { InfraError } from './errors.ts';\nimport { writeStarterConfig } from './init.ts';\nimport { decodeStackOutput, outputsReport } from './outputs.ts';\nimport { prepare, serverDirFor } from './prepare.ts';\nimport type { Missing, Prepared } from './prepare.ts';\n\nconst configFlag = Flag.String('config').pipe(\n Flag.withDescription('The deploy file'),\n Flag.withDefault(deployFileName),\n);\n\nconst yesFlag = Flag.Boolean('yes').pipe(\n Flag.withDescription('Apply without asking for approval of the plan'),\n Flag.withDefault(false),\n);\n\nconst optionalString = (name: string, description: string) =>\n Flag.String(name).pipe(Flag.withDescription(description), Flag.optional);\n\nconst repeatedString = (name: string, description: string) =>\n Flag.String(name).pipe(Flag.withDescription(description), Flag.atLeast(0));\n\n/** The flags that fill a new server folder. Once it exists, they are ignored. */\nconst createFlags = {\n allowEmail: repeatedString(\n 'allow-email',\n 'An email allowed to sign in (repeatable); for a new server folder',\n ),\n allowEmailDomain: repeatedString(\n 'allow-email-domain',\n 'An email domain allowed to sign in (repeatable); for a new server folder',\n ),\n authHost: optionalString(\n 'auth-host',\n 'The sign-in host, outside the dev domains; for a new server folder',\n ),\n caCert: optionalString('ca-cert', \"An existing root's certificate; for a new server folder\"),\n caKey: optionalString('ca-key', \"An existing root's key file; for a new server folder\"),\n domain: repeatedString('domain', 'A dev domain (repeatable); for a new server folder'),\n};\n\ninterface CreateFlagValues {\n readonly allowEmail: readonly string[];\n readonly allowEmailDomain: readonly string[];\n readonly authHost: Option.Option<string>;\n readonly caCert: Option.Option<string>;\n readonly caKey: Option.Option<string>;\n readonly domain: readonly string[];\n}\n\nconst createInputs = (flags: CreateFlagValues): CreateInputs => ({\n allowEmailDomains: flags.allowEmailDomain,\n allowEmails: flags.allowEmail,\n authHost: Option.getOrUndefined(flags.authHost),\n caCert: Option.getOrUndefined(flags.caCert),\n caKey: Option.getOrUndefined(flags.caKey),\n domains: flags.domain,\n});\n\nconst noCreateInputs = createInputs({\n allowEmail: [],\n allowEmailDomain: [],\n authHost: Option.none(),\n caCert: Option.none(),\n caKey: Option.none(),\n domain: [],\n});\n\nconst cancelled = () => new InfraError({ message: 'cancelled' });\n\n/** Prompts in the terminal, when stdin is one. */\nconst terminalAsk: Ask = {\n interactive: process.stdin.isTTY,\n line: (message) => Prompt.run(Prompt.String({ message })).pipe(Effect.mapError(cancelled)),\n secret: (message) =>\n Prompt.run(Prompt.Hidden({ message })).pipe(\n Effect.map((value) => Redacted.value(value)),\n Effect.mapError(cancelled),\n ),\n};\n\nconst prepareFor = (\n { config, version }: { readonly config: string; readonly version: string },\n missing: Missing,\n inputs = noCreateInputs,\n) => prepare({ ask: terminalAsk, config, env: process.env, inputs, missing, version });\n\ntype Operation = 'deploy' | 'destroy' | 'plan';\n\n/**\n * Without a terminal, alchemy cannot ask for approval: it prints the plan and stops without\n * applying it, and exits 0. Fail instead, so a script never mistakes that for success.\n */\nconst checkApproval = (operation: Operation, yes: boolean, interactive: boolean) =>\n operation === 'plan' || yes || interactive\n ? Effect.void\n : Effect.fail(\n new InfraError({\n message: `${operation} asks for approval, but stdin is not a terminal: pass --yes to apply without a prompt`,\n }),\n );\n\nconst stackRun = ({ cwd, deployment, env }: Prepared, operation: Operation, yes: boolean) =>\n checkApproval(operation, yes, process.stdin.isTTY).pipe(\n Effect.andThen(\n runAlchemy({\n args: [operation, stackFile, '--stage', deployment.stage, ...(yes ? ['--yes'] : [])],\n cwd,\n env,\n }),\n ),\n );\n\nconst printOutputs = ({ cwd, deployment, env }: Prepared) =>\n runAlchemy({\n args: [\n 'state',\n 'read',\n `${deployment.stack}/${deployment.stage}/output`,\n '--config',\n stackFile,\n '--no-input',\n // Alchemy logs to stdout; below error level a log line would break the JSON.\n '--log-level',\n 'error',\n ],\n capture: true,\n cwd,\n env,\n }).pipe(\n Effect.flatMap(decodeStackOutput),\n Effect.flatMap((output) => Console.log(outputsReport(deployment, output))),\n );\n\nconst alchemyCommand = (version: string) =>\n Command.make(\n 'alchemy',\n {\n args: Argument.String('arg').pipe(\n Argument.withDescription('The alchemy command and its arguments, after --'),\n Argument.variadic(),\n ),\n config: configFlag,\n },\n ({ args, config }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap(({ cwd, env }) =>\n runAlchemy({ args: [...args, '--config', stackFile], cwd, env }),\n ),\n ),\n ).pipe(\n Command.withDescription(\n \"Run another alchemy command against this deployment's stack, such as: alchemy -- state ls <stack>/<stage>\",\n ),\n );\n\nconst prepareCommand = Command.make('prepare', { config: configFlag, ...createFlags }, (flags) =>\n Effect.gen(function* prepareServerDir() {\n const loaded = yield* loadDeployConfig(flags.config);\n const server = yield* serverDirFor({\n ask: terminalAsk,\n env: process.env,\n inputs: createInputs(flags),\n loaded,\n missing: 'create',\n });\n yield* Console.log(`${server.dir} is a valid server folder.`);\n }),\n).pipe(\n Command.withDescription(\n 'Create the server folder as deploy would, or check the existing one, without touching the cloud',\n ),\n);\n\nconst commands = (version: string) => {\n const plan = Command.make('plan', { config: configFlag, ...createFlags }, (flags) =>\n prepareFor({ config: flags.config, version }, 'preview', createInputs(flags)).pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'plan', false)),\n ),\n ).pipe(\n Command.withDescription(\n 'Show what deploy would create, change or delete. Without a server folder, preview the one deploy would create; write nothing.',\n ),\n );\n\n const deploy = Command.make(\n 'deploy',\n { config: configFlag, yes: yesFlag, ...createFlags },\n (flags) =>\n Effect.gen(function* deployStack() {\n const prepared = yield* prepareFor(\n { config: flags.config, version },\n 'create',\n createInputs(flags),\n );\n yield* stackRun(prepared, 'deploy', flags.yes);\n yield* printOutputs(prepared);\n }),\n ).pipe(\n Command.withDescription(\n 'Create the server folder if it is missing, else check it; then create or update the Fly app, its IPs, one secret per server file, the Machine and the DNS records',\n ),\n );\n\n const destroy = Command.make('destroy', { config: configFlag, yes: yesFlag }, ({ config, yes }) =>\n prepareFor({ config, version }, 'require').pipe(\n Effect.flatMap((prepared) => stackRun(prepared, 'destroy', yes)),\n ),\n ).pipe(Command.withDescription('Delete everything deploy created'));\n\n const outputs = Command.make('outputs', { config: configFlag }, ({ config }) =>\n prepareFor({ config, version }, 'require').pipe(Effect.flatMap(printOutputs)),\n ).pipe(\n Command.withDescription(\n 'Print the app, its IPs, the tunnel host and the CA page, and the DNS records to create in manual zones',\n ),\n );\n\n return [prepareCommand, plan, deploy, destroy, outputs, alchemyCommand(version)];\n};\n\nconst init = Command.make('init', {}, () =>\n writeStarterConfig(process.cwd()).pipe(Effect.flatMap(Console.log)),\n).pipe(\n Command.withDescription(\n `Write a commented starter ${deployFileName} and a .gitignore for the server folder here, and list the secrets to create`,\n ),\n);\n\nconst caCreate = Command.make(\n 'create',\n {\n config: configFlag,\n domains: Argument.String('domain').pipe(\n Argument.withDescription(\n \"A dev domain the root may sign for, with every name under it. Default: the server config's domains\",\n ),\n Argument.variadic(),\n ),\n force: Flag.Boolean('force').pipe(\n Flag.withDescription(\n 'Replace an existing root. Every device that trusts the old root must then trust the new one.',\n ),\n Flag.withDefault(false),\n ),\n name: optionalString(\n 'name',\n \"The label in the root's name, wt-tunnel root (<label>). Default: the deploy file's tunnelHost, else the first domain. Only a name: the name constraints, the domains, decide what the root may sign.\",\n ),\n outDir: optionalString(\n 'out-dir',\n \"Where to write ca.crt and ca.key. Default: the deploy file's server folder, .server\",\n ),\n },\n (input) =>\n createRoot({\n ask: terminalAsk,\n deployFile: input.config,\n domains: input.domains,\n force: input.force,\n name: Option.getOrUndefined(input.name),\n outDir: Option.getOrUndefined(input.outDir),\n }).pipe(\n Effect.flatMap(({ cert, domains, key, label }) =>\n Console.log(\n `Wrote ${cert} and ${key} (readable by you only): wt-tunnel root (${label}), name-constrained to ${domains.join(', ')}. wt-tunnel deploy uploads them with the server config. Keep the key secret, and back it up with the rest of the folder.`,\n ),\n ),\n ),\n).pipe(\n Command.withDescription(\n 'Create a root CA name-constrained to the dev domains, in the server folder',\n ),\n);\n\nconst ca = Command.make('ca').pipe(\n Command.withDescription(\"Manage the deployment's root CA\"),\n Command.withSubcommands([caCreate]),\n);\n\nconst description =\n 'Set up the wt-tunnel server on Fly.io: a deploy file says where it runs, the server folder what it does';\n\nconst run = (version: string) => {\n const cli = Command.make('wt-tunnel').pipe(\n Command.withDescription(description),\n Command.withSubcommands([init, ca, ...commands(version)]),\n );\n return Command.run(cli, { version });\n};\n\nexport { checkApproval, run };\n"],"mappings":";;;;;;;;;;AAaA,MAAM,aAAa,KAAK,OAAO,QAAQ,CAAC,CAAC,KACvC,KAAK,gBAAgB,iBAAiB,GACtC,KAAK,YAAY,cAAc,CACjC;AAEA,MAAM,UAAU,KAAK,QAAQ,KAAK,CAAC,CAAC,KAClC,KAAK,gBAAgB,+CAA+C,GACpE,KAAK,YAAY,KAAK,CACxB;AAEA,MAAM,kBAAkB,MAAc,gBACpC,KAAK,OAAO,IAAI,CAAC,CAAC,KAAK,KAAK,gBAAgB,WAAW,GAAG,KAAK,QAAQ;AAEzE,MAAM,kBAAkB,MAAc,gBACpC,KAAK,OAAO,IAAI,CAAC,CAAC,KAAK,KAAK,gBAAgB,WAAW,GAAG,KAAK,QAAQ,CAAC,CAAC;;AAG3E,MAAM,cAAc;CAClB,YAAY,eACV,eACA,mEACF;CACA,kBAAkB,eAChB,sBACA,0EACF;CACA,UAAU,eACR,aACA,oEACF;CACA,QAAQ,eAAe,WAAW,yDAAyD;CAC3F,OAAO,eAAe,UAAU,sDAAsD;CACtF,QAAQ,eAAe,UAAU,oDAAoD;AACvF;AAWA,MAAM,gBAAgB,WAA2C;CAC/D,mBAAmB,MAAM;CACzB,aAAa,MAAM;CACnB,UAAU,OAAO,eAAe,MAAM,QAA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AS,gBACP,oGACF,GACA,SAAS,SAAS,CACpB;CACA,OAAO,KAAK,QAAQ,OAAO,CAAC,CAAC,KAC3B,KAAK,gBACH,8FACF,GACA,KAAK,YAAY,KAAK,CACxB;CACA,MAAM,eACJ,QACA,sMACF;CACA,QAAQ,eACN,WACA,qFACF;AACF,IACC,UACC,WAAW;CACT,KAAK;CACL,YAAY,MAAM;CAClB,SAAS,MAAM;CACf,OAAO,MAAM;CACb,MAAM,OAAO,eAAe,MAAM,IAAI;CACtC,QAAQ,OAAO,eAAe,MAAM,MAAM;AAC5C,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,EAAE,MAAM,SAAS,KAAK,YACpC,QAAQ,IACN,SAAS,KAAK,OAAO,IAAI,2CAA2C,MAAM,yBAAyB,QAAQ,KAAK,IAAI,EAAE,yHACxH,CACF,CACF,CACJ,CAAC,CAAC,KACA,QAAQ,gBACN,4EACF,CACF;AAEA,MAAM,KAAK,QAAQ,KAAK,IAAI,CAAC,CAAC,KAC5B,QAAQ,gBAAgB,iCAAiC,GACzD,QAAQ,gBAAgB,CAAC,QAAQ,CAAC,CACpC;AAEA,MAAM,cACJ;AAEF,MAAM,OAAO,YAAoB;CAC/B,MAAM,MAAM,QAAQ,KAAK,WAAW,CAAC,CAAC,KACpC,QAAQ,gBAAgB,WAAW,GACnC,QAAQ,gBAAgB;EAAC;EAAM;EAAI,GAAG,SAAS,OAAO;CAAC,CAAC,CAC1D;CACA,OAAO,QAAQ,IAAI,KAAK,EAAE,QAAQ,CAAC;AACrC"}
package/dist/config.js ADDED
@@ -0,0 +1,81 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { Hostname } from "./packages/contract/src/index.js";
3
+ import { AlchemyName, Dns, FlyName, FlyRegion, ImageRef, MemoryMb, StateStore, repeatedZones } from "./deployment.js";
4
+ import { Effect, FileSystem, Path, Schema } from "effect";
5
+ // src/config.ts
6
+ const deployFileName = "wt-tunnel.deploy.json";
7
+ const defaults = {
8
+ memoryMb: 512,
9
+ serverDir: ".server",
10
+ stack: "wt-tunnel-server",
11
+ stage: "prod"
12
+ };
13
+ /** The image a release of this CLI deploys unless the config pins another. */
14
+ const releaseImage = (version) => `ghcr.io/tafrahq/wt-tunnel-server:${version}`;
15
+ /**
16
+ * `wt-tunnel.deploy.json`: where and how the server runs. What it serves is in the server folder,
17
+ * `.server/` by default.
18
+ */
19
+ const DeployConfig = Schema.Struct({
20
+ /** Who creates the records in each zone the record names sit in. */
21
+ dns: Dns,
22
+ fly: Schema.Struct({
23
+ app: FlyName,
24
+ memoryMb: Schema.optionalKey(MemoryMb),
25
+ org: FlyName,
26
+ region: FlyRegion
27
+ }),
28
+ image: Schema.optionalKey(ImageRef),
29
+ /** The folder uploaded to the Machine, relative to this file. */
30
+ serverDir: Schema.optionalKey(Schema.NonEmptyString),
31
+ stack: Schema.optionalKey(AlchemyName),
32
+ stage: Schema.optionalKey(AlchemyName),
33
+ state: StateStore,
34
+ /** The name tunnel clients connect to: `server.host` in their wt-tunnel.json. */
35
+ tunnelHost: Hostname
36
+ });
37
+ const DeployConfigJson = Schema.fromJsonString(DeployConfig);
38
+ /**
39
+ * Blanks out `//` and `/* *\/` comments outside strings, keeping every newline and column, so the
40
+ * config file can explain itself and JSON errors still point at the right place.
41
+ */
42
+ const blankComments = (text) => text.replaceAll(/(?<quoted>"(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//gu, (match, quoted) => quoted ?? match.replaceAll(/[^\n]/gu, " "));
43
+ 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) => {
44
+ const problems = repeatedZones(config.dns);
45
+ return problems.length === 0 ? Effect.succeed(config) : Effect.fail(new InfraError({ message: `${source} is not a valid config: ${problems.join("; ")}` }));
46
+ }));
47
+ /** The deploy file, its directory, its decoded content, and the server folder it names. */
48
+ const loadDeployConfig = (configFile) => Effect.gen(function* loadConfig() {
49
+ const fs = yield* FileSystem.FileSystem;
50
+ const path = yield* Path.Path;
51
+ const file = path.resolve(configFile);
52
+ 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}.` })));
53
+ const config = yield* decodeDeployConfig(text, file);
54
+ const dir = path.dirname(file);
55
+ return {
56
+ config,
57
+ dir,
58
+ file,
59
+ serverDir: path.resolve(dir, config.serverDir ?? defaults.serverDir)
60
+ };
61
+ });
62
+ /** The deployment: the deploy file with every default filled in, and the names the server serves. */
63
+ const resolveDeployment = (config, server, version) => ({
64
+ authHost: server.authHost,
65
+ dns: config.dns,
66
+ domains: server.domains,
67
+ fly: {
68
+ app: config.fly.app,
69
+ memoryMb: config.fly.memoryMb ?? defaults.memoryMb,
70
+ org: config.fly.org,
71
+ region: config.fly.region
72
+ },
73
+ image: config.image ?? releaseImage(version),
74
+ stack: config.stack ?? defaults.stack,
75
+ stage: config.stage ?? defaults.stage,
76
+ state: config.state,
77
+ tunnelHost: config.tunnelHost
78
+ });
79
+ export { blankComments, decodeDeployConfig, defaults, deployFileName, loadDeployConfig, releaseImage, resolveDeployment };
80
+
81
+ //# 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 type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Path, Schema } from 'effect';\n\nimport {\n AlchemyName,\n Dns,\n FlyName,\n FlyRegion,\n ImageRef,\n MemoryMb,\n StateStore,\n repeatedZones,\n} from './deployment.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\n\nconst deployFileName = 'wt-tunnel.deploy.json';\n\nconst defaults = {\n memoryMb: 512,\n serverDir: '.server',\n stack: 'wt-tunnel-server',\n stage: 'prod',\n} as const;\n\n/** The image a release of this CLI deploys unless the config pins another. */\nconst releaseImage = (version: string) => `ghcr.io/tafrahq/wt-tunnel-server:${version}`;\n\n/**\n * `wt-tunnel.deploy.json`: where and how the server runs. What it serves is in the server folder,\n * `.server/` by default.\n */\nconst DeployConfig = Schema.Struct({\n /** Who creates the records in each zone the record names sit in. */\n dns: Dns,\n fly: Schema.Struct({\n app: FlyName,\n memoryMb: Schema.optionalKey(MemoryMb),\n org: FlyName,\n region: FlyRegion,\n }),\n image: Schema.optionalKey(ImageRef),\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, 'authHost' | 'domains'>,\n version: string,\n): Deployment => ({\n authHost: server.authHost,\n dns: config.dns,\n domains: server.domains,\n fly: {\n app: config.fly.app,\n memoryMb: config.fly.memoryMb ?? defaults.memoryMb,\n org: config.fly.org,\n region: config.fly.region,\n },\n image: config.image ?? releaseImage(version),\n stack: config.stack ?? defaults.stack,\n stage: config.stage ?? defaults.stage,\n state: config.state,\n tunnelHost: config.tunnelHost,\n});\n\nexport {\n blankComments,\n decodeDeployConfig,\n defaults,\n deployFileName,\n loadDeployConfig,\n releaseImage,\n resolveDeployment,\n};\nexport type { DeployConfig, LoadedDeploy };\n"],"mappings":";;;;;AAiBA,MAAM,iBAAiB;AAEvB,MAAM,WAAW;CACf,UAAU;CACV,WAAW;CACX,OAAO;CACP,OAAO;AACT;;AAGA,MAAM,gBAAgB,YAAoB,oCAAoC;;;;;AAM9E,MAAM,eAAe,OAAO,OAAO;;CAEjC,KAAK;CACL,KAAK,OAAO,OAAO;EACjB,KAAK;EACL,UAAU,OAAO,YAAY,QAAQ;EACrC,KAAK;EACL,QAAQ;CACV,CAAC;CACD,OAAO,OAA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AChB,UAAU,OAAO;CACjB,KAAK,OAAO;CACZ,SAAS,OAAO;CAChB,KAAK;EACH,KAAK,OAAO,IAAI;EAChB,UAAU,OAAO,IAAI,YAAY,SAAS;EAC1C,KAAK,OAAO,IAAI;EAChB,QAAQ,OAAO,IAAI;CACrB;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,85 @@
1
+ import { InfraError } from "./errors.js";
2
+ import { defaults, loadDeployConfig } from "./config.js";
3
+ import { ServerConfigFileJson, caFile, serverConfigFileName } from "./packages/contract/src/server-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 arguments, else the server config's, else asked for at a terminal. */
16
+ const rootDomains = (args, config, ask) => {
17
+ if (args.length > 0) return decodeDomains(args);
18
+ if (Option.isSome(config)) return Effect.succeed(config.value.domains);
19
+ return ask.interactive ? ask.line("Dev domains the root may sign for (space-separated):").pipe(Effect.flatMap((answer) => decodeDomains(answer.split(/[\s,]+/u).filter(Boolean)))) : Effect.fail(new InfraError({ message: "name the dev domains the root may sign for: wt-tunnel ca create <domain>..." }));
20
+ };
21
+ const exists = (file) => FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(Effect.orElseSucceed(() => false));
22
+ /** Fails when the root's files exist, unless replacing them was asked for. */
23
+ 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.` })));
24
+ /** Writes the root: the folder private, the key readable by its owner only. */
25
+ const writeRoot = (target, root) => Effect.gen(function* write() {
26
+ const fs = yield* FileSystem.FileSystem;
27
+ yield* fs.makeDirectory(target.dir, {
28
+ mode: 448,
29
+ recursive: true
30
+ });
31
+ yield* fs.chmod(target.dir, 448);
32
+ yield* fs.writeFileString(target.key, root.key, { mode: 384 });
33
+ yield* fs.chmod(target.key, 384);
34
+ yield* fs.writeFileString(target.cert, root.cert, { mode: 420 });
35
+ }).pipe(Effect.orDie);
36
+ /**
37
+ * Writes a new root where `deploy` reads it: ca.crt and ca.key in the server folder, or where an
38
+ * existing server config's `ca` points. The domains come from the arguments, else that config, else
39
+ * a prompt. The name follows the deploy file's tunnel host. An existing root is replaced only with
40
+ * `force`.
41
+ */
42
+ /** The server folder, and where in it the root goes: where its config's `ca` points, if it has one. */
43
+ const rootTarget = (input, serverDir) => Effect.gen(function* target() {
44
+ const path = yield* Path.Path;
45
+ const dir = path.resolve(input.outDir ?? serverDir ?? path.join(path.dirname(input.deployFile), defaults.serverDir));
46
+ const config = yield* existingServerConfig(dir);
47
+ const ca = Option.isSome(config) ? config.value.ca : {
48
+ cert: "ca.crt",
49
+ key: "ca.key"
50
+ };
51
+ return {
52
+ config,
53
+ target: {
54
+ cert: caFile(dir, ca.cert),
55
+ dir,
56
+ key: caFile(dir, ca.key)
57
+ }
58
+ };
59
+ });
60
+ /**
61
+ * Writes a new root where `deploy` reads it: ca.crt and ca.key in the server folder, or where an
62
+ * existing server config's `ca` points. The domains come from the arguments, else that config, else
63
+ * a prompt. The name follows the deploy file's tunnel host. An existing root is replaced only with
64
+ * `force`.
65
+ */
66
+ const createRoot = (input) => Effect.gen(function* create() {
67
+ const deploy = Option.getOrUndefined(yield* optionalDeploy(input.deployFile));
68
+ const { config, target } = yield* rootTarget(input, deploy?.serverDir);
69
+ const domains = yield* rootDomains(input.domains, config, input.ask);
70
+ yield* refuseReplacing(target, input.force);
71
+ const label = input.name ?? deploy?.config.tunnelHost ?? domains[0];
72
+ yield* writeRoot(target, yield* generateRoot({
73
+ domains,
74
+ label
75
+ }));
76
+ return {
77
+ cert: target.cert,
78
+ domains,
79
+ key: target.key,
80
+ label
81
+ };
82
+ });
83
+ export { createRoot };
84
+
85
+ //# 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 { Ask } from './create-server-dir.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 readonly ask: Ask;\n /** The deploy file, which may not exist yet. */\n readonly deployFile: string;\n readonly domains: readonly string[];\n readonly force: boolean;\n readonly name: string | undefined;\n readonly outDir: string | undefined;\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 arguments, else the server config's, else asked for at a terminal. */\nconst rootDomains = (\n args: readonly string[],\n config: Option.Option<ServerConfigFile>,\n ask: Ask,\n) => {\n if (args.length > 0) {\n return decodeDomains(args);\n }\n if (Option.isSome(config)) {\n return Effect.succeed(config.value.domains);\n }\n return ask.interactive\n ? ask\n .line('Dev domains the root may sign for (space-separated):')\n .pipe(Effect.flatMap((answer) => decodeDomains(answer.split(/[\\s,]+/u).filter(Boolean))))\n : Effect.fail(\n new InfraError({\n message: 'name the dev domains the root may sign for: wt-tunnel ca create <domain>...',\n }),\n );\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/**\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 the arguments, else that config, else\n * a prompt. The name follows the deploy file's tunnel host. An existing root is replaced only with\n * `force`.\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 input.outDir ?? 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 the arguments, else that config, else\n * a prompt. The name follows the deploy file's tunnel host. An existing root is replaced only with\n * `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(input.domains, config, input.ask);\n yield* refuseReplacing(target, input.force);\n const label = input.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":";;;;;;;;AAiCA,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,eACJ,MACA,QACA,QACG;CACH,IAAI,KAAK,SAAS,GAChB,OAAO,cAAc,IAAI;CAE3B,IAAI,OAAO,OAAO,MAAM,GACtB,OAAO,OAAO,QAAQ,OAAO,MAAM,OAAO;CAE5C,OAAO,IAAI,cACP,IACG,KAAK,sDAAsD,CAAC,CAC5D,KAAK,OAAO,SAAS,WAAW,cAAc,OAAO,MAAM,SAAS,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,CAAC,IAC1F,OAAO,KACL,IAAI,WAAW,EACb,SAAS,8EACX,CAAC,CACH;AACN;AAEA,MAAM,UAAU,SACd,WAAW,WAAW,KAAK,OAAO,GAAG,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,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;GADG,MAAM,OAAO,KAAK,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,MAAM,SAAS,QAAQ,MAAM,GAAG;CACnE,OAAO,gBAAgB,QAAQ,MAAM,KAAK;CAC1C,MAAM,QAAQ,MAAM,QAAQ,QAAQ,OAAO,cAAc,QAAQ;CACjE,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,153 @@
1
+ import { InfraError } 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
+ const listOf = (answer) => answer.split(/[\s,]+/u).filter((item) => item !== "");
15
+ /** The flags and variables a new folder needs that neither the flags nor the environment give. */
16
+ const missingFlags = (inputs) => [
17
+ ...inputs.domains.length === 0 ? ["--domain"] : [],
18
+ ...inputs.authHost === void 0 ? ["--auth-host"] : [],
19
+ ...inputs.allowEmails.length + inputs.allowEmailDomains.length === 0 ? ["--allow-email or --allow-email-domain"] : []
20
+ ];
21
+ /** "Pass --domain. Set GOOGLE_CLIENT_ID." for whichever of the two lists is not empty. */
22
+ const whatIsMissing = (flags, variables) => [...flags.length === 0 ? [] : [`Pass ${flags.join(", ")}.`], ...variables.length === 0 ? [] : [`Set ${variables.join(", ")} in the environment.`]].join(" ");
23
+ /** The given list, else the user's answer to `message`. */
24
+ const listOr = (given, ask, message) => given.length > 0 ? Effect.succeed(given) : ask.line(message).pipe(Effect.map(listOf));
25
+ /** Who may sign in. When the flags name nobody, both lists are asked for, and either may be empty. */
26
+ const allowList = (inputs, ask) => Effect.gen(function* allow() {
27
+ const askBoth = inputs.allowEmails.length + inputs.allowEmailDomains.length === 0;
28
+ const emails = askBoth ? listOf(yield* ask.line("Emails allowed to sign in (space-separated, may be empty):")) : inputs.allowEmails;
29
+ const emailDomains = askBoth ? listOf(yield* ask.line("Email domains allowed to sign in (space-separated, may be empty):")) : inputs.allowEmailDomains;
30
+ return {
31
+ ...emails.length === 0 ? {} : { emails },
32
+ ...emailDomains.length === 0 ? {} : { emailDomains }
33
+ };
34
+ });
35
+ /** What the server serves, from the flags, else prompts, else a failure naming every flag missing. */
36
+ const gatherSettings = (inputs, env, ask) => Effect.gen(function* gather() {
37
+ const flags = missingFlags(inputs);
38
+ const variables = missingProviderVariables(env);
39
+ if (flags.length + variables.length > 0 && !ask.interactive) return yield* new InfraError({ message: `the server folder does not exist yet, and stdin is not a terminal to ask in. ${whatIsMissing(flags, variables)} Sign-in providers:\n${providerSteps(inputs.authHost)}` });
40
+ const domains = yield* listOr(inputs.domains, ask, "Dev domains, such as dev.example.com (space-separated):");
41
+ const authHost = inputs.authHost ?? (yield* ask.line("Sign-in host, outside the dev domains:"));
42
+ return {
43
+ allow: yield* allowList(inputs, ask),
44
+ authHost,
45
+ domains,
46
+ providers: yield* gatherProviders(env, ask, authHost)
47
+ };
48
+ });
49
+ const readText = (file, what) => FileSystem.FileSystem.use((fs) => fs.readFileString(file)).pipe(Effect.mapError(() => new InfraError({ message: `cannot read ${what} at ${file}` })));
50
+ 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));
51
+ /** Where an existing root's certificate and key are, if anywhere. */
52
+ const rootSources = (input) => Effect.gen(function* sources() {
53
+ const path = yield* Path.Path;
54
+ const near = (name) => [path.join(input.serverDir, name), path.join(input.deployDir, name)];
55
+ const keyFromEnv = isSet(input.env, "WT_CA_KEY") && input.inputs.caKey === void 0;
56
+ const keyFile = input.inputs.caKey ?? (isSet(input.env, "WT_CA_KEY_FILE") ? input.env.WT_CA_KEY_FILE : void 0) ?? (yield* firstExisting(near("ca.key")));
57
+ return {
58
+ certFile: input.inputs.caCert ?? (yield* firstExisting(near("ca.crt"))),
59
+ keyFile: keyFromEnv ? void 0 : keyFile,
60
+ keySource: keyFromEnv ? "WT_CA_KEY" : keyFile
61
+ };
62
+ });
63
+ const onlyOneProblem = (certFile, keySource, serverDir) => certFile === void 0 ? `found the root key (${keySource}) but no certificate. Pass --ca-cert, or put ca.crt in ${serverDir}.` : `found the root certificate ${certFile} but no key. Pass --ca-key, 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.`;
64
+ /**
65
+ * The root, decided so that a root devices already trust is never silently replaced. The cert comes
66
+ * from --ca-cert, else ca.crt in the server folder or next to the deploy file. The key comes from
67
+ * --ca-key, WT_CA_KEY, WT_CA_KEY_FILE, else ca.key in the same places. With both, they are used;
68
+ * with neither, a new root is made; with only one, the deploy stops.
69
+ */
70
+ const resolveRoot = (input) => Effect.gen(function* root() {
71
+ const { certFile, keyFile, keySource } = yield* rootSources(input);
72
+ if (certFile !== void 0 && keySource !== void 0) {
73
+ const origin = {
74
+ cert: certFile,
75
+ key: keySource,
76
+ kind: "found"
77
+ };
78
+ return {
79
+ cert: yield* readText(certFile, "the root certificate"),
80
+ key: keyFile === void 0 ? input.env.WT_CA_KEY ?? "" : yield* readText(keyFile, "the root key"),
81
+ origin
82
+ };
83
+ }
84
+ if (certFile === void 0 && keySource === void 0) {
85
+ const domains = yield* decodeDomains(input.domains);
86
+ const origin = { kind: "generated" };
87
+ return {
88
+ ...yield* generateRoot({
89
+ domains,
90
+ label: input.deploy.tunnelHost
91
+ }),
92
+ origin
93
+ };
94
+ }
95
+ return yield* new InfraError({ message: onlyOneProblem(certFile, keySource ?? "", input.serverDir) });
96
+ });
97
+ /**
98
+ * A new server folder, in memory: the config from the flags, prompts and environment, generated
99
+ * secrets where the environment has none, and the root's files.
100
+ */
101
+ const draftServerDir = (input) => Effect.gen(function* draft() {
102
+ const settings = yield* gatherSettings(input.inputs, input.env, input.ask);
103
+ const root = yield* resolveRoot({
104
+ ...input,
105
+ domains: settings.domains
106
+ });
107
+ const secret = (name, field) => isSet(input.env, name) ? {
108
+ generated: [],
109
+ value: input.env[name] ?? ""
110
+ } : {
111
+ generated: [field],
112
+ value: generateSecret()
113
+ };
114
+ const tunnelToken = secret("WT_TUNNEL_SERVER_TOKEN", "tunnelToken");
115
+ const authSecret = secret("WT_AUTH_SECRET", "authSecret");
116
+ const config = {
117
+ allow: settings.allow,
118
+ authHost: settings.authHost,
119
+ authSecret: authSecret.value,
120
+ ca: {
121
+ cert: "ca.crt",
122
+ key: "ca.key"
123
+ },
124
+ domains: settings.domains,
125
+ providers: settings.providers,
126
+ tunnelToken: tunnelToken.value
127
+ };
128
+ return {
129
+ files: [
130
+ serverFile("ca.crt", root.cert, 420),
131
+ serverFile("ca.key", root.key, 384),
132
+ serverFile(serverConfigFileName, `${JSON.stringify(config, void 0, indent)}\n`, 384)
133
+ ],
134
+ generated: [
135
+ ...tunnelToken.generated,
136
+ ...authSecret.generated,
137
+ ...root.origin.kind === "generated" ? ["the root CA"] : []
138
+ ],
139
+ root: root.origin
140
+ };
141
+ });
142
+ /** What `deploy` tells the user after it creates the folder. */
143
+ const createdSummary = (input) => [
144
+ `Created ${input.serverDir}: ${input.draft.files.map(({ name }) => name).join(", ")}.`,
145
+ input.draft.generated.length === 0 ? "Nothing was generated: every value came from the flags, the environment or existing files." : `Generated: ${input.draft.generated.join(", ")}.`,
146
+ ...input.draft.root.kind === "found" ? [`The root CA is ${input.draft.root.cert}, with its key from ${input.draft.root.key}.`] : [],
147
+ `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.`,
148
+ ...input.draft.generated.includes("tunnelToken") ? [`Tunnel clients need tunnelToken from ${serverConfigFileName} as WT_TUNNEL_SERVER_TOKEN.`] : [],
149
+ `After the deploy, open https://${input.authHost}/ca on each device that opens dev URLs to trust the root.`
150
+ ].join("\n");
151
+ export { createdSummary, draftServerDir };
152
+
153
+ //# 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 { 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/** What the flags say about a server folder that does not exist yet. */\ninterface CreateInputs {\n readonly allowEmailDomains: readonly string[];\n readonly allowEmails: readonly string[];\n readonly authHost: string | undefined;\n readonly caCert: string | undefined;\n readonly caKey: string | undefined;\n readonly domains: readonly string[];\n}\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\nconst listOf = (answer: string) => answer.split(/[\\s,]+/u).filter((item) => item !== '');\n\n/** The flags and variables a new folder needs that neither the flags nor the environment give. */\nconst missingFlags = (inputs: CreateInputs) => [\n ...(inputs.domains.length === 0 ? ['--domain'] : []),\n ...(inputs.authHost === undefined ? ['--auth-host'] : []),\n ...(inputs.allowEmails.length + inputs.allowEmailDomains.length === 0\n ? ['--allow-email or --allow-email-domain']\n : []),\n];\n\n/** \"Pass --domain. Set GOOGLE_CLIENT_ID.\" for whichever of the two lists is not empty. */\nconst whatIsMissing = (flags: readonly string[], variables: readonly string[]) =>\n [\n ...(flags.length === 0 ? [] : [`Pass ${flags.join(', ')}.`]),\n ...(variables.length === 0 ? [] : [`Set ${variables.join(', ')} in the environment.`]),\n ].join(' ');\n\n/** The given list, else the user's answer to `message`. */\nconst listOr = (given: readonly string[], ask: Ask, message: string) =>\n given.length > 0 ? Effect.succeed(given) : ask.line(message).pipe(Effect.map(listOf));\n\n/** Who may sign in. When the flags name nobody, both lists are asked for, and either may be empty. */\nconst allowList = (inputs: CreateInputs, ask: Ask) =>\n Effect.gen(function* allow() {\n const askBoth = inputs.allowEmails.length + inputs.allowEmailDomains.length === 0;\n const emails = askBoth\n ? listOf(yield* ask.line('Emails allowed to sign in (space-separated, may be empty):'))\n : inputs.allowEmails;\n const emailDomains = askBoth\n ? listOf(yield* ask.line('Email domains allowed to sign in (space-separated, may be empty):'))\n : inputs.allowEmailDomains;\n return {\n ...(emails.length === 0 ? {} : { emails }),\n ...(emailDomains.length === 0 ? {} : { emailDomains }),\n };\n });\n\n/** What the server serves, from the flags, else prompts, else a failure naming every flag missing. */\nconst gatherSettings = (inputs: CreateInputs, env: Env, ask: Ask) =>\n Effect.gen(function* gather() {\n const flags = missingFlags(inputs);\n const variables = missingProviderVariables(env);\n if (flags.length + variables.length > 0 && !ask.interactive) {\n return yield* new InfraError({\n message: `the server folder does not exist yet, and stdin is not a terminal to ask in. ${whatIsMissing(flags, variables)} Sign-in providers:\\n${providerSteps(inputs.authHost)}`,\n });\n }\n const domains = yield* listOr(\n inputs.domains,\n ask,\n 'Dev domains, such as dev.example.com (space-separated):',\n );\n const authHost = inputs.authHost ?? (yield* ask.line('Sign-in host, outside the dev domains:'));\n const allow = yield* allowList(inputs, ask);\n return { allow, authHost, domains, providers: yield* gatherProviders(env, ask, authHost) };\n });\n\nconst readText = (file: string, what: string) =>\n FileSystem.FileSystem.use((fs) => fs.readFileString(file)).pipe(\n Effect.mapError(() => new InfraError({ message: `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 inputs: CreateInputs;\n readonly serverDir: string;\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 keyFromEnv = isSet(input.env, 'WT_CA_KEY') && input.inputs.caKey === undefined;\n const keyFile =\n input.inputs.caKey ??\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: input.inputs.caCert ?? (yield* firstExisting(near('ca.crt'))),\n keyFile: keyFromEnv ? undefined : keyFile,\n keySource: keyFromEnv ? 'WT_CA_KEY' : keyFile,\n };\n });\n\nconst onlyOneProblem = (certFile: string | undefined, keySource: string, serverDir: string) =>\n certFile === undefined\n ? `found the root key (${keySource}) but no certificate. Pass --ca-cert, or put ca.crt in ${serverDir}.`\n : `found the root certificate ${certFile} but no key. Pass --ca-key, 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 --ca-cert, else ca.crt in the server folder or next to the deploy file. The key comes from\n * --ca-key, WT_CA_KEY, WT_CA_KEY_FILE, else ca.key in the same places. With both, they are used;\n * 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: input.deploy.tunnelHost })), 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 flags, prompts and environment, generated\n * 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 inputs: CreateInputs;\n readonly serverDir: string;\n}) =>\n Effect.gen(function* draft() {\n const settings = yield* gatherSettings(input.inputs, input.env, input.ask);\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, CreateInputs, Draft };\n"],"mappings":";;;;;;;;AA8CA,MAAM,cAAc;AACpB,MAAM,SAAS;;AAEf,MAAM,uBAAuB,YAAY,WAAW,CAAC,CAAC,SAAS,WAAW;AAE1E,MAAM,SAAS,KAAU,UAAkB,IAAI,SAAS,QAAQ;AAEhE,MAAM,UAAU,WAAmB,OAAO,MAAM,SAAS,CAAC,CAAC,QAAQ,SAAS,SAAS,EAAE;;AAGvF,MAAM,gBAAgB,WAAyB;CAC7C,GAAI,OAAO,QAAQ,WAAW,IAAI,CAAC,UAAU,IAAI,CAAC;CAClD,GAAI,OAAO,aAAa,KAAA,IAAY,CAAC,aAAa,IAAI,CAAC;CACvD,GAAI,OAAO,YAAY,SAAS,OAAO,kBAAkB,WAAW,IAChE,CAAC,uCAAuC,IACxC,CAAC;AACP;;AAGA,MAAM,iBAAiB,OAA0B,cAC/C,CACE,GAAI,MAAM,WAAW,IAAI,CAAC,IAAI,CAAC,QAAQ,MAAM,KAAK,IAAI,EAAE,EAAE,GAC1D,GAAI,UAAU,WAAW,IAAI,CAAC,IAAI,CAAC,OAAO,UAAU,KAAK,IAAI,EAAE,qBAAqB,CACtF,CAAC,CAAC,KAAK,GAAG;;AAGZ,MAAM,UAAU,OAA0B,KAAU,YAClD,MAAM,SAAS,IAAI,OAAO,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,CAAC,KAAK,OAAO,IAAI,MAAM,CAAC;;AAGtF,MAAM,aAAa,QAAsB,QACvC,OAAO,IAAI,UAAU,QAAQ;CAC3B,MAAM,UAAU,OAAO,YAAY,SAAS,OAAO,kBAAkB,WAAW;CAChF,M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,cAAc,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,122 @@
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
+ * Where Alchemy keeps what it created: a state store Worker in a Cloudflare account, or `.alchemy/`
42
+ * next to the config.
43
+ */
44
+ const StateStore = Schema.Union([Schema.Literal("local"), Schema.Struct({
45
+ accountId: CloudflareId,
46
+ provider: Schema.Literal("cloudflare")
47
+ })]);
48
+ /** The secrets the state store needs. The CLI sets CLOUDFLARE_ACCOUNT_ID from `state.accountId`. */
49
+ const stateEnv = (state) => state === "local" ? [] : cloudflareEnv;
50
+ /** Everything the stack needs except the secrets, with every default filled in. */
51
+ const Deployment = Schema.Struct({
52
+ authHost: Hostname,
53
+ dns: Dns,
54
+ domains: Schema.NonEmptyArray(Hostname),
55
+ fly: Schema.Struct({
56
+ app: FlyName,
57
+ memoryMb: MemoryMb,
58
+ org: FlyName,
59
+ region: FlyRegion
60
+ }),
61
+ image: ImageRef,
62
+ stack: AlchemyName,
63
+ stage: AlchemyName,
64
+ state: StateStore,
65
+ tunnelHost: Hostname
66
+ });
67
+ const DeploymentJson = Schema.fromJsonString(Deployment);
68
+ /** How the CLI hands the deployment and the server folder's files to the alchemy process. */
69
+ const deploymentEnv = "WT_TUNNEL_INFRA_DEPLOYMENT";
70
+ const serverFilesEnv = "WT_TUNNEL_INFRA_SERVER_FILES";
71
+ /**
72
+ * Every record resolves straight to the Machine, never through a proxy: frpc speaks raw TCP to port
73
+ * 7000, and Caddy ends TLS for the dev hosts and the sign-in host itself.
74
+ */
75
+ const dnsHosts = (deployment) => [
76
+ ...deployment.domains.map((domain) => ({
77
+ id: `Wildcard-${domain}`,
78
+ name: `*.${domain}`
79
+ })),
80
+ {
81
+ id: "TunnelHost",
82
+ name: deployment.tunnelHost
83
+ },
84
+ {
85
+ id: "AuthHost",
86
+ name: deployment.authHost
87
+ }
88
+ ];
89
+ /** The most specific zone `name` sits in: the longest one equal to it or a suffix of it. */
90
+ const zoneOf = (name, dns) => dns.filter(({ zone }) => name === zone || name.endsWith(`.${zone}`)).toSorted((left, right) => right.zone.length - left.zone.length).at(0);
91
+ /** Each record name with the zone it goes in, and the names no zone covers. */
92
+ const placeHosts = (deployment) => {
93
+ const placed = [];
94
+ const uncovered = [];
95
+ for (const host of dnsHosts(deployment)) {
96
+ const zone = zoneOf(host.name, deployment.dns);
97
+ if (zone === void 0) uncovered.push(host.name);
98
+ else placed.push({
99
+ ...host,
100
+ zone
101
+ });
102
+ }
103
+ return {
104
+ placed,
105
+ uncovered
106
+ };
107
+ };
108
+ /** Zones `dns` lists more than once, whatever their provider. */
109
+ const repeatedZones = (dns) => {
110
+ const zones = dns.map(({ zone }) => zone);
111
+ return [...new Set(zones.filter((zone, index) => zones.indexOf(zone) !== index))].map((zone) => `dns lists the zone ${zone} more than once`);
112
+ };
113
+ /** The record names no zone in `dns` covers, as a problem, or nothing. */
114
+ const uncoveredNames = (deployment) => {
115
+ const { uncovered } = placeHosts(deployment);
116
+ return uncovered.length === 0 ? [] : [`no dns entry's zone covers ${uncovered.join(", ")}`];
117
+ };
118
+ /** The secrets the DNS providers and the state store need, each once. */
119
+ const providerEnv = ({ dns, state }) => [.../* @__PURE__ */ new Set([...dns.flatMap(({ provider }) => dnsProviders[provider].env), ...stateEnv(state)])];
120
+ export { AlchemyName, DeploymentJson, Dns, FlyName, FlyRegion, ImageRef, MemoryMb, StateStore, deploymentEnv, dnsProviders, placeHosts, providerEnv, repeatedZones, serverFilesEnv, uncoveredNames };
121
+
122
+ //# 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 * Where Alchemy keeps what it created: a state store Worker in a Cloudflare account, or `.alchemy/`\n * next to the config.\n */\nconst StateStore = Schema.Union([\n Schema.Literal('local'),\n Schema.Struct({ accountId: CloudflareId, provider: Schema.Literal('cloudflare') }),\n]);\ntype StateStore = typeof StateStore.Type;\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 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,WA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AAC,CAC/F"}
package/dist/errors.js ADDED
@@ -0,0 +1,7 @@
1
+ import { Schema } from "effect";
2
+ // src/errors.ts
3
+ const { TaggedError: taggedErrorClass } = Schema;
4
+ var InfraError = class extends taggedErrorClass()("InfraError", { message: Schema.String }) {};
5
+ export { InfraError };
6
+
7
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { 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\nexport { InfraError };\n"],"mappings":";;AAMA,MAAM,EAAE,aAAa,qBAAqB;AAE1C,IAAM,aAAN,cAAyB,iBAA6B,CAAC,CAAC,cAAc,EACpE,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC"}