@tafrahq/wt-tunnel 0.7.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { InfraError } from "./errors.js";
2
- import { defaults, loadDeployConfig } from "./config.js";
3
2
  import { ServerConfigFileJson, caFile, serverConfigFileName } from "./packages/contract/src/server-config.js";
3
+ import { defaults, loadDeployConfig } from "./config.js";
4
4
  import { decodeDomains, generateRoot } from "./ca.js";
5
5
  import "./server-dir.js";
6
6
  import { Effect, FileSystem, Option, Path, Schema } from "effect";
@@ -12,11 +12,10 @@ const existingServerConfig = (dir) => FileSystem.FileSystem.use((fs) => fs.readF
12
12
  onNone: () => Effect.succeedNone,
13
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
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);
15
+ /** The domains: the server config's, else the deploy file's, which seed a new server folder. */
16
+ const rootDomains = (config, deploy) => {
18
17
  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>..." }));
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);
20
19
  };
21
20
  const exists = (file) => FileSystem.FileSystem.use((fs) => fs.exists(file)).pipe(Effect.orElseSucceed(() => false));
22
21
  /** Fails when the root's files exist, unless replacing them was asked for. */
@@ -33,16 +32,10 @@ const writeRoot = (target, root) => Effect.gen(function* write() {
33
32
  yield* fs.chmod(target.key, 384);
34
33
  yield* fs.writeFileString(target.cert, root.cert, { mode: 420 });
35
34
  }).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
35
  /** The server folder, and where in it the root goes: where its config's `ca` points, if it has one. */
43
36
  const rootTarget = (input, serverDir) => Effect.gen(function* target() {
44
37
  const path = yield* Path.Path;
45
- const dir = path.resolve(input.outDir ?? serverDir ?? path.join(path.dirname(input.deployFile), defaults.serverDir));
38
+ const dir = path.resolve(serverDir ?? path.join(path.dirname(input.deployFile), defaults.serverDir));
46
39
  const config = yield* existingServerConfig(dir);
47
40
  const ca = Option.isSome(config) ? config.value.ca : {
48
41
  cert: "ca.crt",
@@ -59,16 +52,16 @@ const rootTarget = (input, serverDir) => Effect.gen(function* target() {
59
52
  });
60
53
  /**
61
54
  * 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`.
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`.
65
58
  */
66
59
  const createRoot = (input) => Effect.gen(function* create() {
67
60
  const deploy = Option.getOrUndefined(yield* optionalDeploy(input.deployFile));
68
61
  const { config, target } = yield* rootTarget(input, deploy?.serverDir);
69
- const domains = yield* rootDomains(input.domains, config, input.ask);
62
+ const domains = yield* rootDomains(config, deploy?.config);
70
63
  yield* refuseReplacing(target, input.force);
71
- const label = input.name ?? deploy?.config.tunnelHost ?? domains[0];
64
+ const label = deploy?.config.ca?.name ?? deploy?.config.tunnelHost ?? domains[0];
72
65
  yield* writeRoot(target, yield* generateRoot({
73
66
  domains,
74
67
  label
@@ -1 +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,C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AC"}
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,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AAqB,GAAG;CAC9C,MAAM,KAAK,OAAO,OAAO,MAAM,IAAI,OAAO,MAAM,KAAK;EAAE,MAAM;EAAU,KAAK;CAAS;CAErF,OAAO;EAAE;EAAQ,QAAQ;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,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"}
@@ -1,4 +1,4 @@
1
- import { InfraError } from "./errors.js";
1
+ import { InfraError, failWith } from "./errors.js";
2
2
  import { serverConfigFileName } from "./packages/contract/src/server-config.js";
3
3
  import { decodeDomains, generateRoot } from "./ca.js";
4
4
  import { serverFile } from "./server-dir.js";
@@ -11,61 +11,58 @@ const indent = 2;
11
11
  /** 43 base64url characters: above both the token's 16 and the auth secret's 32. */
12
12
  const generateSecret = () => randomBytes(secretBytes).toString("base64url");
13
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:"));
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)}` });
42
28
  return {
43
- allow: yield* allowList(inputs, ask),
44
- authHost,
45
- domains,
46
- providers: yield* gatherProviders(env, ask, authHost)
29
+ allow: deploy.allow,
30
+ authHost: deploy.authHost,
31
+ domains: deploy.domains,
32
+ providers: yield* gatherProviders(env, ask, deploy.authHost)
47
33
  };
48
34
  });
49
- const readText = (file, what) => FileSystem.FileSystem.use((fs) => fs.readFileString(file)).pipe(Effect.mapError(() => new InfraError({ message: `cannot read ${what} at ${file}` })));
35
+ const readText = (file, what) => FileSystem.FileSystem.use((fs) => fs.readFileString(file)).pipe(failWith(`cannot read ${what} at ${file}`));
50
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
+ });
51
45
  /** Where an existing root's certificate and key are, if anywhere. */
52
46
  const rootSources = (input) => Effect.gen(function* sources() {
53
47
  const path = yield* Path.Path;
54
48
  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")));
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")));
57
52
  return {
58
- certFile: input.inputs.caCert ?? (yield* firstExisting(near("ca.crt"))),
53
+ certFile: seeded.cert ?? (yield* firstExisting(near("ca.crt"))),
59
54
  keyFile: keyFromEnv ? void 0 : keyFile,
60
55
  keySource: keyFromEnv ? "WT_CA_KEY" : keyFile
61
56
  };
62
57
  });
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.`;
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.`;
64
61
  /**
65
62
  * 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.
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.
69
66
  */
70
67
  const resolveRoot = (input) => Effect.gen(function* root() {
71
68
  const { certFile, keyFile, keySource } = yield* rootSources(input);
@@ -87,7 +84,7 @@ const resolveRoot = (input) => Effect.gen(function* root() {
87
84
  return {
88
85
  ...yield* generateRoot({
89
86
  domains,
90
- label: input.deploy.tunnelHost
87
+ label: rootLabel(input.deploy)
91
88
  }),
92
89
  origin
93
90
  };
@@ -95,11 +92,11 @@ const resolveRoot = (input) => Effect.gen(function* root() {
95
92
  return yield* new InfraError({ message: onlyOneProblem(certFile, keySource ?? "", input.serverDir) });
96
93
  });
97
94
  /**
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.
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.
100
97
  */
101
98
  const draftServerDir = (input) => Effect.gen(function* draft() {
102
- const settings = yield* gatherSettings(input.inputs, input.env, input.ask);
99
+ const settings = yield* gatherSettings(input);
103
100
  const root = yield* resolveRoot({
104
101
  ...input,
105
102
  domains: settings.domains
@@ -1 +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;;A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3B;CAmBA,OAAO;EARL,OAAA;GATA,WAAW,UAAU,KAAK,MAAA,GAAgB;GAC1C,WAAW,UAAU,KAAK,KAAA,GAAe;GACzC,WACE,sBACA,GAAG,KAAK,UAAU,QAAQ,KAAA,GAAW,MAAM,EAAE,KAAA,GAE/C;EAGI;EACJ,WAAW;GACT,GAAG,YAAY;GACf,GAAG,WAAW;GACd,GAAI,KAAK,OAAO,SAAS,cAAc,CAAC,aAAa,IAAI,CAAC;EAC5D;EACA,MAAM,KAAK;CAED;AACd,CAAC;;AAGH,MAAM,kBAAkB,UAKtB;CACE,WAAW,MAAM,UAAU,IAAI,MAAM,MAAM,MAAM,KAAK,EAAE,WAAW,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE;CACpF,MAAM,MAAM,UAAU,WAAW,IAC7B,+FACA,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"}
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,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B,WAAW,SAAS;EACpB,aAAa,YAAY;CAC3B;CAmBA,OAAO;EARL,OAAA;GATA,WAAW,UAAU,KAAK,MAAA,GAAgB;GAC1C,WAAW,UAAU,KAAK,KAAA,GAAe;GACzC,WACE,sBACA,GAAG,KAAK,UAAU,QAAQ,KAAA,GAAW,MAAM,EAAE,KAAA,GAE/C;EAGI;EACJ,WAAW;GACT,GAAG,YAAY;GACf,GAAG,WAAW;GACd,GAAI,KAAK,OAAO,SAAS,cAAc,CAAC,aAAa,IAAI,CAAC;EAC5D;EACA,MAAM,KAAK;CAED;AACd,CAAC;;AAGH,MAAM,kBAAkB,UAKtB;CACE,WAAW,MAAM,UAAU,IAAI,MAAM,MAAM,MAAM,KAAK,EAAE,WAAW,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE;CACpF,MAAM,MAAM,UAAU,WAAW,IAC7B,+FACA,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"}
@@ -38,13 +38,23 @@ const dnsProviders = {
38
38
  }
39
39
  };
40
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
+ /**
41
46
  * Where Alchemy keeps what it created: a state store Worker in a Cloudflare account, or `.alchemy/`
42
- * next to the config.
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.
43
50
  */
44
51
  const StateStore = Schema.Union([Schema.Literal("local"), Schema.Struct({
45
52
  accountId: CloudflareId,
53
+ name: Schema.optionalKey(StateStoreName),
46
54
  provider: Schema.Literal("cloudflare")
47
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 };
48
58
  /** The secrets the state store needs. The CLI sets CLOUDFLARE_ACCOUNT_ID from `state.accountId`. */
49
59
  const stateEnv = (state) => state === "local" ? [] : cloudflareEnv;
50
60
  /** Everything the stack needs except the secrets, with every default filled in. */
@@ -117,6 +127,6 @@ const uncoveredNames = (deployment) => {
117
127
  };
118
128
  /** The secrets the DNS providers and the state store need, each once. */
119
129
  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 };
130
+ export { AlchemyName, DeploymentJson, Dns, FlyName, FlyRegion, ImageRef, MemoryMb, StateStore, cloudflareStateOptions, deploymentEnv, dnsProviders, placeHosts, providerEnv, repeatedZones, serverFilesEnv, uncoveredNames };
121
131
 
122
132
  //# sourceMappingURL=deployment.js.map
@@ -1 +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,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,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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"}
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;AACV,CAAC;;AAGD,MAAM,aAAa,OAAO,OAAO;CAAE,UAAU,OAAO,QAAQ,QAAQ;CAAG,MAAM;AAAS,CAAC;AAEvF,MAAM,UAAU,OAAO,MAAM,CAAC,gBAAgB,UAAU,CAAC;;AAKzD,MAAM,MAAM,OAAO,cAAc,OAAO;;;;;AAMxC,MAAM,gBAAgB,CAAC,wBAAwB,uBAAuB;AAStE,MAAM,eAA+D;CACnE,YAAY;EAAE,SAAS;EAAc,KAAK;CAAc;CACxD,QAAQ;EAAE,SAAS,KAAA;EAAW,KAAK,CAAC;CAAE;AACxC;;;;;AAMA,MAAM,iBAAiB,OAAO,OAAO,MACnC,OAAO,UAAU,yCAAyC,CAC5D;;;;;;;AAQA,MAAM,aAAa,OAAO,MAAM,CAC9B,OAAO,QAAQ,OAAO,GACtB,OAAO,OAAO;CACZ,WAAW;CACX,MAAM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;;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 CHANGED
@@ -1,7 +1,9 @@
1
- import { Schema } from "effect";
1
+ import { Effect, Schema } from "effect";
2
2
  // src/errors.ts
3
3
  const { TaggedError: taggedErrorClass } = Schema;
4
4
  var InfraError = class extends taggedErrorClass()("InfraError", { message: Schema.String }) {};
5
- export { InfraError };
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 };
6
8
 
7
9
  //# sourceMappingURL=errors.js.map
@@ -1 +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"}
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"}
package/dist/init.js CHANGED
@@ -14,14 +14,30 @@ const ignoreLines = [serverDirLine, ".alchemy/"];
14
14
  const starterConfig = `// Where and how wt-tunnel runs. What the server does lives in ${defaults.serverDir}/, which the
15
15
  // first \`wt-tunnel deploy\` creates.
16
16
  {
17
- // Your Fly.io organization slug (\`fly orgs list\`), a name for the new app (Fly app names are
18
- // global), and a region (\`fly platform regions\`). memoryMb is optional (default ${String(defaults.memoryMb)}).
19
- "fly": { "org": "personal", "app": "${placeholder}", "region": "ams" },
17
+ // Where the server runs. "flyio", the only provider for now: your Fly.io organization slug
18
+ // (\`fly orgs list\`), a name for the new app (Fly app names are global), and a region
19
+ // (\`fly platform regions\`). memoryMb is optional (default ${String(defaults.memoryMb)}).
20
+ "server": { "provider": "flyio", "org": "personal", "app": "${placeholder}", "region": "ams" },
20
21
 
21
22
  // The name tunnel clients connect to: server.host in each wt-tunnel.json. New roots are named
22
23
  // after it.
23
24
  "tunnelHost": "wt-tunnel.example.com",
24
25
 
26
+ // The sign-in host, shared by every dev domain and outside all of them. Devices open its /ca page
27
+ // to trust the root, and each sign-in provider redirects to it.
28
+ "authHost": "auth-wt-tunnel.example.com",
29
+
30
+ // The first deploy creates ${defaults.serverDir}/ from these. After that, ${defaults.serverDir}/wt-tunnel-server.json
31
+ // decides what the server does. Keep them as a record: a deploy warns when they differ from it,
32
+ // and \`wt-tunnel deploy --force\` copies domains and allow into it.
33
+ // domains: the dev domains. Worktree URLs are https://<app>.<worktree>.<domain>, and a new root
34
+ // may sign only for these and the names under them.
35
+ // allow: who may sign in, by email and by email domain. At least one.
36
+ // ca (optional): "cert" and "key" use an existing root (paths relative to this file), and
37
+ // "name" labels a new one, wt-tunnel root (<name>). Default name: the tunnel host.
38
+ "domains": ["dev.example.com"],
39
+ "allow": { "emails": ["you@example.com"], "emailDomains": [] },
40
+
25
41
  // Who creates the DNS records, one entry per zone: *.<domain> for each dev domain, the tunnel host
26
42
  // and the sign-in host. Each record goes in the most specific zone its name sits in, and every
27
43
  // name must sit in one.
@@ -32,7 +48,8 @@ const starterConfig = `// Where and how wt-tunnel runs. What the server does liv
32
48
  "dns": [{ "provider": "cloudflare", "zone": "example.com", "zoneId": "${placeholder}" }],
33
49
 
34
50
  // Where Alchemy records what it created. { "provider": "cloudflare", "accountId": "..." }: a
35
- // state store Worker in that Cloudflare account, usable from any machine. "local": .alchemy/
51
+ // state store Worker in that Cloudflare account, usable from any machine: the account's default
52
+ // alchemy-state-store, or alchemy-state-store-<name> with "name". "local": .alchemy/
36
53
  // next to this file, which is git-ignored; back it up, because updating or destroying the
37
54
  // deployment needs it. Without Cloudflare, use "manual" dns entries and "local" state.
38
55
  "state": { "provider": "cloudflare", "accountId": "${placeholder}" }
@@ -57,8 +74,7 @@ const nextSteps = (file) => `Wrote ${file}, and ${ignoreLines.join(" and ")} to
57
74
  3. Create an OAuth client with one or more sign-in providers, and export its variables for the
58
75
  first deploy (GOOGLE_*, GITHUB_*, MICROSOFT_* or CLOUDFLARE_ACCESS_*):
59
76
  ${providerSteps().split("\n").map((line) => ` - ${line}`).join("\n")}
60
- 4. wt-tunnel deploy --domain dev.example.com --auth-host auth-wt-tunnel.example.com \\
61
- --allow-email you@example.com
77
+ 4. wt-tunnel deploy
62
78
  The first deploy creates ${serverDirLine} (the server config, a new root CA, and generated tokens),
63
79
  then deploys. It holds secrets: back it up, and never commit it. Later deploys upload it as it
64
80
  is; edit it and deploy again to change what the server does.
package/dist/init.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":[],"sources":["../src/init.ts"],"sourcesContent":["import { Effect, FileSystem, Path } from 'effect';\n\nimport { refuseExisting } from './ca.ts';\nimport { defaults, deployFileName } from './config.ts';\nimport { providerSteps } from './providers.ts';\n\n/** Marks every value `init` cannot guess; each one fails decoding until the user replaces it. */\nconst placeholder = 'REPLACE_ME';\n\nconst serverDirLine = `${defaults.serverDir}/`;\n\n/**\n * The server folder holds the server's secrets, and `.alchemy/` holds Alchemy's local state and\n * logs, which may record what the stack sent to Fly. Neither belongs in git.\n */\nconst ignoreLines = [serverDirLine, '.alchemy/'];\n\nconst starterConfig = `// Where and how wt-tunnel runs. What the server does lives in ${defaults.serverDir}/, which the\n// first \\`wt-tunnel deploy\\` creates.\n{\n // Your Fly.io organization slug (\\`fly orgs list\\`), a name for the new app (Fly app names are\n // global), and a region (\\`fly platform regions\\`). memoryMb is optional (default ${String(defaults.memoryMb)}).\n \"fly\": { \"org\": \"personal\", \"app\": \"${placeholder}\", \"region\": \"ams\" },\n\n // The name tunnel clients connect to: server.host in each wt-tunnel.json. New roots are named\n // after it.\n \"tunnelHost\": \"wt-tunnel.example.com\",\n\n // Who creates the DNS records, one entry per zone: *.<domain> for each dev domain, the tunnel host\n // and the sign-in host. Each record goes in the most specific zone its name sits in, and every\n // name must sit in one.\n // \"cloudflare\": the stack creates the records. zoneId is on the zone's Overview page.\n // \"manual\": you create them; \\`wt-tunnel outputs\\` lists them.\n // One CLOUDFLARE_API_TOKEN serves every Cloudflare zone listed. A user API token (My Profile,\n // API Tokens) can cover zones in several accounts.\n \"dns\": [{ \"provider\": \"cloudflare\", \"zone\": \"example.com\", \"zoneId\": \"${placeholder}\" }],\n\n // Where Alchemy records what it created. { \"provider\": \"cloudflare\", \"accountId\": \"...\" }: a\n // state store Worker in that Cloudflare account, usable from any machine. \"local\": .alchemy/\n // next to this file, which is git-ignored; back it up, because updating or destroying the\n // deployment needs it. Without Cloudflare, use \"manual\" dns entries and \"local\" state.\n \"state\": { \"provider\": \"cloudflare\", \"accountId\": \"${placeholder}\" }\n\n // Optional: \"image\" (default: the server release that matches this CLI's version), \"serverDir\"\n // (default \"${defaults.serverDir}\"), and \"stack\" and \"stage\", Alchemy's names for the deployment\n // (default \"${defaults.stack}\" and \"${defaults.stage}\").\n}\n`;\n\nconst nextSteps = (\n file: string,\n) => `Wrote ${file}, and ${ignoreLines.join(' and ')} to .gitignore. Next:\n\n1. Edit it: replace each ${placeholder} and the example names.\n2. Export these secrets (from a secret manager, never from a committed file):\n FLY_API_TOKEN fly tokens create org <org>\n CLOUDFLARE_API_TOKEN with a \"cloudflare\" dns entry or state: one Cloudflare user API token\n with Zone > DNS > Edit on every Cloudflare zone in \"dns\", even zones\n in different accounts. With Cloudflare state it also needs Workers\n Scripts Edit, Account Settings Edit, Secrets Store Edit and Workers\n Tail Read on the state's account.\n CLOUDFLARE_ACCOUNT_ID only with a \"cloudflare\" dns entry and \"state\": \"local\": the account\n of any of those zones. Otherwise the CLI sets it from state.accountId.\n3. Create an OAuth client with one or more sign-in providers, and export its variables for the\n first deploy (GOOGLE_*, GITHUB_*, MICROSOFT_* or CLOUDFLARE_ACCESS_*):\n${providerSteps()\n .split('\\n')\n .map((line) => ` - ${line}`)\n .join('\\n')}\n4. wt-tunnel deploy --domain dev.example.com --auth-host auth-wt-tunnel.example.com \\\\\n --allow-email you@example.com\n The first deploy creates ${serverDirLine} (the server config, a new root CA, and generated tokens),\n then deploys. It holds secrets: back it up, and never commit it. Later deploys upload it as it\n is; edit it and deploy again to change what the server does.\n`;\n\n/** Adds each of `ignoreLines` that `dir`'s .gitignore does not list yet, creating the file. */\nconst ignoreServerDir = (dir: string) =>\n Effect.gen(function* ignore() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(dir, '.gitignore');\n const current = (yield* fs.exists(file).pipe(Effect.orDie))\n ? yield* fs.readFileString(file).pipe(Effect.orDie)\n : '';\n const listed = new Set(current.split('\\n').map((line) => line.trim()));\n const missing = ignoreLines.filter((line) => !listed.has(line));\n if (missing.length > 0) {\n const separator = current === '' || current.endsWith('\\n') ? '' : '\\n';\n yield* fs\n .writeFileString(\n file,\n `${current}${separator}${missing.map((line) => `${line}\\n`).join('')}`,\n )\n .pipe(Effect.orDie);\n }\n });\n\n/** Writes the starter deploy file into `dir` and returns what to do next. Never overwrites it. */\nconst writeStarterConfig = (dir: string) =>\n Effect.gen(function* init() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(dir, deployFileName);\n yield* refuseExisting(file, 'edit it, or delete it to start over');\n yield* fs.writeFileString(file, starterConfig, { flag: 'wx' }).pipe(Effect.orDie);\n yield* ignoreServerDir(dir);\n return nextSteps(file);\n });\n\nexport { placeholder, writeStarterConfig };\n"],"mappings":";;;;;;AAOA,MAAM,cAAc;AAEpB,MAAM,gBAAgB,GAAG,SAAS,UAAU;;;;;AAM5C,MAAM,cAAc,CAAC,eAAe,WAAW;AAE/C,MAAM,gBAAgB,kEAAkE,SAAS,UAAU;;;;uFAIpB,OAAO,SAAS,QAAQ,EAAE;wCACzE,YAAY;;;;;;;;;;;;;0EAasB,YAAY;;;;;;uDAM/B,YAAY;;;iBAGlD,SAAS,UAAU;iBACnB,SAAS,MAAM,SAAS,SAAS,MAAM;;;AAIxD,MAAM,aACJ,SACG,SAAS,KAAK,QAAQ,YAAY,KAAK,OAAO,EAAE;;2BAE1B,YAAY;;;;;;;;;;;;EAYrC,c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\nimport { refuseExisting } from './ca.ts';\nimport { defaults, deployFileName } from './config.ts';\nimport { providerSteps } from './providers.ts';\n\n/** Marks every value `init` cannot guess; each one fails decoding until the user replaces it. */\nconst placeholder = 'REPLACE_ME';\n\nconst serverDirLine = `${defaults.serverDir}/`;\n\n/**\n * The server folder holds the server's secrets, and `.alchemy/` holds Alchemy's local state and\n * logs, which may record what the stack sent to Fly. Neither belongs in git.\n */\nconst ignoreLines = [serverDirLine, '.alchemy/'];\n\nconst starterConfig = `// Where and how wt-tunnel runs. What the server does lives in ${defaults.serverDir}/, which the\n// first \\`wt-tunnel deploy\\` creates.\n{\n // Where the server runs. \"flyio\", the only provider for now: your Fly.io organization slug\n // (\\`fly orgs list\\`), a name for the new app (Fly app names are global), and a region\n // (\\`fly platform regions\\`). memoryMb is optional (default ${String(defaults.memoryMb)}).\n \"server\": { \"provider\": \"flyio\", \"org\": \"personal\", \"app\": \"${placeholder}\", \"region\": \"ams\" },\n\n // The name tunnel clients connect to: server.host in each wt-tunnel.json. New roots are named\n // after it.\n \"tunnelHost\": \"wt-tunnel.example.com\",\n\n // The sign-in host, shared by every dev domain and outside all of them. Devices open its /ca page\n // to trust the root, and each sign-in provider redirects to it.\n \"authHost\": \"auth-wt-tunnel.example.com\",\n\n // The first deploy creates ${defaults.serverDir}/ from these. After that, ${defaults.serverDir}/wt-tunnel-server.json\n // decides what the server does. Keep them as a record: a deploy warns when they differ from it,\n // and \\`wt-tunnel deploy --force\\` copies domains and allow into it.\n // domains: the dev domains. Worktree URLs are https://<app>.<worktree>.<domain>, and a new root\n // may sign only for these and the names under them.\n // allow: who may sign in, by email and by email domain. At least one.\n // ca (optional): \"cert\" and \"key\" use an existing root (paths relative to this file), and\n // \"name\" labels a new one, wt-tunnel root (<name>). Default name: the tunnel host.\n \"domains\": [\"dev.example.com\"],\n \"allow\": { \"emails\": [\"you@example.com\"], \"emailDomains\": [] },\n\n // Who creates the DNS records, one entry per zone: *.<domain> for each dev domain, the tunnel host\n // and the sign-in host. Each record goes in the most specific zone its name sits in, and every\n // name must sit in one.\n // \"cloudflare\": the stack creates the records. zoneId is on the zone's Overview page.\n // \"manual\": you create them; \\`wt-tunnel outputs\\` lists them.\n // One CLOUDFLARE_API_TOKEN serves every Cloudflare zone listed. A user API token (My Profile,\n // API Tokens) can cover zones in several accounts.\n \"dns\": [{ \"provider\": \"cloudflare\", \"zone\": \"example.com\", \"zoneId\": \"${placeholder}\" }],\n\n // Where Alchemy records what it created. { \"provider\": \"cloudflare\", \"accountId\": \"...\" }: a\n // state store Worker in that Cloudflare account, usable from any machine: the account's default\n // alchemy-state-store, or alchemy-state-store-<name> with \"name\". \"local\": .alchemy/\n // next to this file, which is git-ignored; back it up, because updating or destroying the\n // deployment needs it. Without Cloudflare, use \"manual\" dns entries and \"local\" state.\n \"state\": { \"provider\": \"cloudflare\", \"accountId\": \"${placeholder}\" }\n\n // Optional: \"image\" (default: the server release that matches this CLI's version), \"serverDir\"\n // (default \"${defaults.serverDir}\"), and \"stack\" and \"stage\", Alchemy's names for the deployment\n // (default \"${defaults.stack}\" and \"${defaults.stage}\").\n}\n`;\n\nconst nextSteps = (\n file: string,\n) => `Wrote ${file}, and ${ignoreLines.join(' and ')} to .gitignore. Next:\n\n1. Edit it: replace each ${placeholder} and the example names.\n2. Export these secrets (from a secret manager, never from a committed file):\n FLY_API_TOKEN fly tokens create org <org>\n CLOUDFLARE_API_TOKEN with a \"cloudflare\" dns entry or state: one Cloudflare user API token\n with Zone > DNS > Edit on every Cloudflare zone in \"dns\", even zones\n in different accounts. With Cloudflare state it also needs Workers\n Scripts Edit, Account Settings Edit, Secrets Store Edit and Workers\n Tail Read on the state's account.\n CLOUDFLARE_ACCOUNT_ID only with a \"cloudflare\" dns entry and \"state\": \"local\": the account\n of any of those zones. Otherwise the CLI sets it from state.accountId.\n3. Create an OAuth client with one or more sign-in providers, and export its variables for the\n first deploy (GOOGLE_*, GITHUB_*, MICROSOFT_* or CLOUDFLARE_ACCESS_*):\n${providerSteps()\n .split('\\n')\n .map((line) => ` - ${line}`)\n .join('\\n')}\n4. wt-tunnel deploy\n The first deploy creates ${serverDirLine} (the server config, a new root CA, and generated tokens),\n then deploys. It holds secrets: back it up, and never commit it. Later deploys upload it as it\n is; edit it and deploy again to change what the server does.\n`;\n\n/** Adds each of `ignoreLines` that `dir`'s .gitignore does not list yet, creating the file. */\nconst ignoreServerDir = (dir: string) =>\n Effect.gen(function* ignore() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(dir, '.gitignore');\n const current = (yield* fs.exists(file).pipe(Effect.orDie))\n ? yield* fs.readFileString(file).pipe(Effect.orDie)\n : '';\n const listed = new Set(current.split('\\n').map((line) => line.trim()));\n const missing = ignoreLines.filter((line) => !listed.has(line));\n if (missing.length > 0) {\n const separator = current === '' || current.endsWith('\\n') ? '' : '\\n';\n yield* fs\n .writeFileString(\n file,\n `${current}${separator}${missing.map((line) => `${line}\\n`).join('')}`,\n )\n .pipe(Effect.orDie);\n }\n });\n\n/** Writes the starter deploy file into `dir` and returns what to do next. Never overwrites it. */\nconst writeStarterConfig = (dir: string) =>\n Effect.gen(function* init() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(dir, deployFileName);\n yield* refuseExisting(file, 'edit it, or delete it to start over');\n yield* fs.writeFileString(file, starterConfig, { flag: 'wx' }).pipe(Effect.orDie);\n yield* ignoreServerDir(dir);\n return nextSteps(file);\n });\n\nexport { placeholder, writeStarterConfig };\n"],"mappings":";;;;;;AAOA,MAAM,cAAc;AAEpB,MAAM,gBAAgB,GAAG,SAAS,UAAU;;;;;AAM5C,MAAM,cAAc,CAAC,eAAe,WAAW;AAE/C,MAAM,gBAAgB,kEAAkE,SAAS,UAAU;;;;;iEAK1C,OAAO,SAAS,QAAQ,EAAE;gEAC3B,YAAY;;;;;;;;;;gCAU5C,SAAS,UAAU,4BAA4B,SAAS,UAAU;;;;;;;;;;;;;;;;;;0EAkBxB,YAAY;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AK,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK;CAChF,OAAO,gBAAgB,GAAG;CAC1B,OAAO,UAAU,IAAI;AACvB,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { createRequire } from "node:module";
2
+ import { Console, Effect, Schema } from "effect";
3
+ // ../../packages/contract/src/bin.ts
4
+ const PackageJson = Schema.Struct({ version: Schema.String });
5
+ /** The version in the package.json one level above the built bin at `binUrl`. */
6
+ const packageVersion = (binUrl) => {
7
+ const packageJson = createRequire(binUrl)("../package.json");
8
+ return Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(Effect.map(({ version }) => version), Effect.orDie);
9
+ };
10
+ /**
11
+ * Runs the CLI at the version of the package whose bin is at `url`. `name` is the name it prints.
12
+ * An `expected` failure carries a message written for the user, so it is printed as `<name>:
13
+ * <message>` without a stack trace, and the bin exits 1.
14
+ */
15
+ const binProgram = (bin, run) => packageVersion(bin.url).pipe(Effect.flatMap(run), Effect.catchIf((failure) => failure._tag === bin.expected, ({ message }) => Console.error(`${bin.name}: ${message}`).pipe(Effect.andThen(Effect.sync(() => {
16
+ process.exitCode = 1;
17
+ })))));
18
+ export { binProgram };
19
+
20
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../../../../../../packages/contract/src/bin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\n\nimport { Console, Effect, Schema } from 'effect';\n\nconst PackageJson = Schema.Struct({ version: Schema.String });\n\n/** The version in the package.json one level above the built bin at `binUrl`. */\nconst packageVersion = (binUrl: string) => {\n const packageJson: unknown = createRequire(binUrl)('../package.json');\n return Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(\n Effect.map(({ version }) => version),\n Effect.orDie,\n );\n};\n\n/**\n * Runs the CLI at the version of the package whose bin is at `url`. `name` is the name it prints.\n * An `expected` failure carries a message written for the user, so it is printed as `<name>:\n * <message>` without a stack trace, and the bin exits 1.\n */\nconst binProgram = <\n Failure extends { readonly _tag: string },\n Requirements,\n Tag extends Extract<Failure, { readonly message: string }>['_tag'],\n>(\n bin: { readonly expected: Tag; readonly name: string; readonly url: string },\n run: (version: string) => Effect.Effect<void, Failure, Requirements>,\n) =>\n packageVersion(bin.url).pipe(\n Effect.flatMap(run),\n Effect.catchIf(\n (failure): failure is Extract<Failure, { readonly _tag: Tag; readonly message: string }> =>\n failure._tag === bin.expected,\n ({ message }) =>\n Console.error(`${bin.name}: ${message}`).pipe(\n Effect.andThen(\n Effect.sync(() => {\n process.exitCode = 1;\n }),\n ),\n ),\n ),\n );\n\nexport { binProgram };\n"],"mappings":";;;AAIA,MAAM,cAAc,OAAO,OAAO,EAAE,SAAS,OAAO,OAAO,CAAC;;AAG5D,MAAM,kBAAkB,WAAmB;CACzC,MAAM,cAAuB,cAAc,MAAM,CAAC,CAAC,iBAAiB;CACpE,OAAO,OAAO,oBAAoB,WAAW,CAAC,CAAC,WAAW,CAAC,CAAC,KAC1D,OAAO,KAAK,EAAE,cAAc,OAAO,GACnC,OAAO,KACT;AACF;;;;;;AAOA,MAAM,cAKJ,KACA,QAEA,eAAe,IAAI,GAAG,CAAC,CAAC,KACtB,OAAO,QAAQ,GAAG,GAClB,OAAO,SACJ,YACC,QAAQ,SAAS,IAAI,WACtB,EAAE,cACD,QAAQ,MAAM,GAAG,IAAI,KAAK,IAAI,SAAS,CAAC,CAAC,KACvC,OAAO,QACL,OAAO,WAAW;CAChB,QAAQ,WAAW;AACrB,CAAC,CACH,CACF,CACJ,CACF"}
@@ -94,6 +94,6 @@ const readServerConfig = (input) => Effect.gen(function* readConfig() {
94
94
  ca
95
95
  };
96
96
  });
97
- export { AllowList, Providers, ServerConfigError, ServerConfigFile, ServerConfigFileJson, caFile, providerIds, readServerConfig, serverConfigFileName };
97
+ export { AllowList, ServerConfigFileJson, caFile, providerIds, readServerConfig, serverConfigFileName };
98
98
 
99
99
  //# sourceMappingURL=server-config.js.map