@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.
- package/README.md +41 -29
- package/dist/bin.js +8 -14
- package/dist/bin.js.map +1 -1
- package/dist/ca.js +1 -1
- package/dist/ca.js.map +1 -1
- package/dist/cli.js +14 -49
- package/dist/cli.js.map +1 -1
- package/dist/config.js +32 -7
- package/dist/config.js.map +1 -1
- package/dist/create-root.js +10 -17
- package/dist/create-root.js.map +1 -1
- package/dist/create-server-dir.js +42 -45
- package/dist/create-server-dir.js.map +1 -1
- package/dist/deployment.js +12 -2
- package/dist/deployment.js.map +1 -1
- package/dist/errors.js +4 -2
- package/dist/errors.js.map +1 -1
- package/dist/init.js +22 -6
- package/dist/init.js.map +1 -1
- package/dist/packages/contract/src/bin.js +20 -0
- package/dist/packages/contract/src/bin.js.map +1 -0
- package/dist/packages/contract/src/server-config.js +1 -1
- package/dist/packages/contract/src/server-config.js.map +1 -1
- package/dist/prepare.js +85 -16
- package/dist/prepare.js.map +1 -1
- package/dist/seed-drift.js +51 -0
- package/dist/seed-drift.js.map +1 -0
- package/dist/server-dir.js +24 -14
- package/dist/server-dir.js.map +1 -1
- package/dist/server-machine.js.map +1 -1
- package/dist/stack.js +2 -2
- package/dist/stack.js.map +1 -1
- package/package.json +13 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-config.js","names":[],"sources":["../../../../../../packages/contract/src/server-config.ts"],"sourcesContent":["import { isAbsolute, join } from 'node:path';\n\nimport { Effect, Redacted, Schema } from 'effect';\n\nimport { Hostname } from './index.ts';\n\nconst authSecretMinLength = 32;\nconst tunnelTokenMinLength = 16;\n\n/** The name `wt-tunnel deploy` writes the config under, and the server looks for by default. */\nconst serverConfigFileName = 'wt-tunnel-server.json';\n\nconst Email = Schema.String.check(Schema.isPattern(/^[^@\\s]+@[^@\\s]+$/u));\n\nconst Secret = (minLength: number) =>\n Schema.RedactedFromValue(Schema.String.check(Schema.isMinLength(minLength)));\n\nconst pemMarkers = {\n cert: /-----BEGIN CERTIFICATE-----/u,\n key: /-----BEGIN (?:EC |RSA )?PRIVATE KEY-----/u,\n} as const;\n\nconst AllowList = Schema.Struct({\n emailDomains: Schema.optionalKey(Schema.Array(Hostname)),\n emails: Schema.optionalKey(Schema.Array(Email)),\n}).check(\n Schema.makeFilter(\n (allow) =>\n (allow.emails?.length ?? 0) + (allow.emailDomains?.length ?? 0) > 0 ||\n 'allow lists no emails and no email domains',\n ),\n);\n\nconst OAuthClient = {\n clientId: Schema.NonEmptyString,\n clientSecret: Schema.RedactedFromValue(Schema.NonEmptyString),\n};\n\n/** The sign-in providers a user may pick from, in the order the sign-in page lists them. */\nconst providerIds = ['google', 'github', 'microsoft', 'cloudflare'] as const;\ntype ProviderId = (typeof providerIds)[number];\n\n/**\n * Where people sign in. Each provider is optional, and at least one must be set. `microsoft` takes\n * the Entra ID tenant (default `common`, any account). `cloudflare` is a Cloudflare Access OIDC app\n * in the Zero Trust team at `teamDomain`, such as `acme.cloudflareaccess.com`.\n */\nconst MicrosoftClient = Schema.Struct({\n ...OAuthClient,\n tenantId: Schema.optionalKey(Schema.NonEmptyString),\n});\n\nconst Providers = Schema.Struct({\n cloudflare: Schema.optionalKey(Schema.Struct({ ...OAuthClient, teamDomain: Hostname })),\n github: Schema.optionalKey(Schema.Struct(OAuthClient)),\n google: Schema.optionalKey(Schema.Struct(OAuthClient)),\n microsoft: Schema.optionalKey(MicrosoftClient),\n}).check(\n Schema.makeFilter(\n (providers) =>\n providerIds.some((id) => providers[id] !== undefined) ||\n `providers sets none of ${providerIds.join(', ')}`,\n ),\n);\ntype Providers = typeof Providers.Type;\n\n/**\n * The tunnel server's config file. The server decodes it at startup; the wt-tunnel CLI writes it\n * and checks it against this same schema before deploying.\n */\nconst ServerConfigFile = Schema.Struct({\n allow: AllowList,\n /** The sign-in host, shared by every dev domain. */\n authHost: Hostname,\n /** Keys Better Auth and the dev-domain session cookie. */\n authSecret: Secret(authSecretMinLength),\n /**\n * The name-constrained root that issues every dev-host certificate: its PEM files, relative to\n * the config file's directory.\n */\n ca: Schema.Struct({ cert: Schema.NonEmptyString, key: Schema.NonEmptyString }),\n domains: Schema.NonEmptyArray(Hostname),\n providers: Providers,\n /** Shared secret that frpc presents to frps. */\n tunnelToken: Secret(tunnelTokenMinLength),\n});\ntype ServerConfigFile = typeof ServerConfigFile.Type;\n\nconst ServerConfigFileJson = Schema.fromJsonString(ServerConfigFile);\n\n/** The config as the server holds it: the root's PEM text in place of its file names. */\ninterface ServerConfig extends Omit<ServerConfigFile, 'ca'> {\n readonly ca: { readonly cert: string; readonly key: Redacted.Redacted };\n}\n\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass ServerConfigError extends taggedErrorClass<ServerConfigError>()('ServerConfigError', {\n message: Schema.String,\n}) {}\n\n/** Where a `ca` path in a config file in `dir` points. */\nconst caFile = (dir: string, file: string) => (isAbsolute(file) ? file : join(dir, file));\n\n/**\n * Decodes a config file's text, reads the root's files relative to `dir` with `read`, and checks\n * that they hold PEM. Every schema problem is reported at once.\n */\nconst readServerConfig = <ReadError>(input: {\n readonly dir: string;\n readonly read: (file: string) => Effect.Effect<string, ReadError>;\n readonly source: string;\n readonly text: string;\n}) =>\n Effect.gen(function* readConfig() {\n const invalid = (message: string) =>\n new ServerConfigError({\n message: `${input.source} is not a valid server config: ${message}`,\n });\n const file = yield* Schema.decodeUnknownEffect(ServerConfigFileJson)(input.text, {\n errors: 'all',\n }).pipe(Effect.mapError((schemaError) => invalid(schemaError.message)));\n /** Never echoes the file's content: the key is secret. */\n const readCa = (field: keyof typeof pemMarkers) => {\n const path = caFile(input.dir, file.ca[field]);\n return input.read(path).pipe(\n Effect.mapError(() => invalid(`cannot read ca.${field} at ${path}`)),\n Effect.filterOrFail(\n (text) => pemMarkers[field].test(text),\n () =>\n invalid(\n `ca.${field} at ${path} holds no PEM ${field === 'cert' ? 'certificate' : 'private key'}`,\n ),\n ),\n );\n };\n const ca = { cert: yield* readCa('cert'), key: Redacted.make(yield* readCa('key')) };\n const config: ServerConfig = { ...file, ca };\n return config;\n });\n\nexport {\n AllowList,\n
|
|
1
|
+
{"version":3,"file":"server-config.js","names":[],"sources":["../../../../../../packages/contract/src/server-config.ts"],"sourcesContent":["import { isAbsolute, join } from 'node:path';\n\nimport { Effect, Redacted, Schema } from 'effect';\n\nimport { Hostname } from './index.ts';\n\nconst authSecretMinLength = 32;\nconst tunnelTokenMinLength = 16;\n\n/** The name `wt-tunnel deploy` writes the config under, and the server looks for by default. */\nconst serverConfigFileName = 'wt-tunnel-server.json';\n\nconst Email = Schema.String.check(Schema.isPattern(/^[^@\\s]+@[^@\\s]+$/u));\n\nconst Secret = (minLength: number) =>\n Schema.RedactedFromValue(Schema.String.check(Schema.isMinLength(minLength)));\n\nconst pemMarkers = {\n cert: /-----BEGIN CERTIFICATE-----/u,\n key: /-----BEGIN (?:EC |RSA )?PRIVATE KEY-----/u,\n} as const;\n\nconst AllowList = Schema.Struct({\n emailDomains: Schema.optionalKey(Schema.Array(Hostname)),\n emails: Schema.optionalKey(Schema.Array(Email)),\n}).check(\n Schema.makeFilter(\n (allow) =>\n (allow.emails?.length ?? 0) + (allow.emailDomains?.length ?? 0) > 0 ||\n 'allow lists no emails and no email domains',\n ),\n);\n\nconst OAuthClient = {\n clientId: Schema.NonEmptyString,\n clientSecret: Schema.RedactedFromValue(Schema.NonEmptyString),\n};\n\n/** The sign-in providers a user may pick from, in the order the sign-in page lists them. */\nconst providerIds = ['google', 'github', 'microsoft', 'cloudflare'] as const;\ntype ProviderId = (typeof providerIds)[number];\n\n/**\n * Where people sign in. Each provider is optional, and at least one must be set. `microsoft` takes\n * the Entra ID tenant (default `common`, any account). `cloudflare` is a Cloudflare Access OIDC app\n * in the Zero Trust team at `teamDomain`, such as `acme.cloudflareaccess.com`.\n */\nconst MicrosoftClient = Schema.Struct({\n ...OAuthClient,\n tenantId: Schema.optionalKey(Schema.NonEmptyString),\n});\n\nconst Providers = Schema.Struct({\n cloudflare: Schema.optionalKey(Schema.Struct({ ...OAuthClient, teamDomain: Hostname })),\n github: Schema.optionalKey(Schema.Struct(OAuthClient)),\n google: Schema.optionalKey(Schema.Struct(OAuthClient)),\n microsoft: Schema.optionalKey(MicrosoftClient),\n}).check(\n Schema.makeFilter(\n (providers) =>\n providerIds.some((id) => providers[id] !== undefined) ||\n `providers sets none of ${providerIds.join(', ')}`,\n ),\n);\ntype Providers = typeof Providers.Type;\n\n/**\n * The tunnel server's config file. The server decodes it at startup; the wt-tunnel CLI writes it\n * and checks it against this same schema before deploying.\n */\nconst ServerConfigFile = Schema.Struct({\n allow: AllowList,\n /** The sign-in host, shared by every dev domain. */\n authHost: Hostname,\n /** Keys Better Auth and the dev-domain session cookie. */\n authSecret: Secret(authSecretMinLength),\n /**\n * The name-constrained root that issues every dev-host certificate: its PEM files, relative to\n * the config file's directory.\n */\n ca: Schema.Struct({ cert: Schema.NonEmptyString, key: Schema.NonEmptyString }),\n domains: Schema.NonEmptyArray(Hostname),\n providers: Providers,\n /** Shared secret that frpc presents to frps. */\n tunnelToken: Secret(tunnelTokenMinLength),\n});\ntype ServerConfigFile = typeof ServerConfigFile.Type;\n\nconst ServerConfigFileJson = Schema.fromJsonString(ServerConfigFile);\n\n/** The config as the server holds it: the root's PEM text in place of its file names. */\ninterface ServerConfig extends Omit<ServerConfigFile, 'ca'> {\n readonly ca: { readonly cert: string; readonly key: Redacted.Redacted };\n}\n\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass ServerConfigError extends taggedErrorClass<ServerConfigError>()('ServerConfigError', {\n message: Schema.String,\n}) {}\n\n/** Where a `ca` path in a config file in `dir` points. */\nconst caFile = (dir: string, file: string) => (isAbsolute(file) ? file : join(dir, file));\n\n/**\n * Decodes a config file's text, reads the root's files relative to `dir` with `read`, and checks\n * that they hold PEM. Every schema problem is reported at once.\n */\nconst readServerConfig = <ReadError>(input: {\n readonly dir: string;\n readonly read: (file: string) => Effect.Effect<string, ReadError>;\n readonly source: string;\n readonly text: string;\n}) =>\n Effect.gen(function* readConfig() {\n const invalid = (message: string) =>\n new ServerConfigError({\n message: `${input.source} is not a valid server config: ${message}`,\n });\n const file = yield* Schema.decodeUnknownEffect(ServerConfigFileJson)(input.text, {\n errors: 'all',\n }).pipe(Effect.mapError((schemaError) => invalid(schemaError.message)));\n /** Never echoes the file's content: the key is secret. */\n const readCa = (field: keyof typeof pemMarkers) => {\n const path = caFile(input.dir, file.ca[field]);\n return input.read(path).pipe(\n Effect.mapError(() => invalid(`cannot read ca.${field} at ${path}`)),\n Effect.filterOrFail(\n (text) => pemMarkers[field].test(text),\n () =>\n invalid(\n `ca.${field} at ${path} holds no PEM ${field === 'cert' ? 'certificate' : 'private key'}`,\n ),\n ),\n );\n };\n const ca = { cert: yield* readCa('cert'), key: Redacted.make(yield* readCa('key')) };\n const config: ServerConfig = { ...file, ca };\n return config;\n });\n\nexport {\n AllowList,\n providerIds,\n ServerConfigFileJson,\n caFile,\n readServerConfig,\n serverConfigFileName,\n};\nexport type { ProviderId, ServerConfig, ServerConfigFile };\n"],"mappings":";;;;AAMA,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;;AAG7B,MAAM,uBAAuB;AAE7B,MAAM,QAAQ,OAAO,OAAO,MAAM,OAAO,UAAU,oBAAoB,CAAC;AAExE,MAAM,UAAU,cACd,OAAO,kBAAkB,OAAO,OAAO,MAAM,OAAO,YAAY,SAAS,CAAC,CAAC;AAE7E,MAAM,aAAa;CACjB,MAAM;CACN,KAAK;AACP;AAEA,MAAM,YAAY,OAAO,OAAO;CAC9B,cAAc,OAAO,YAAY,OAAO,MAAM,QAAQ,CAAC;CACvD,QAAQ,OAAO,YAAY,OAAO,MAAM,KAAK,CAAC;AAChD,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,WACE,MAAM,QAAQ,UAAU,MAAM,MAAM,cAAc,UAAU,KAAK,KAClE,4CACJ,CACF;AAEA,MAAM,c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AC5D,CAAC;CACH,MAAM,OAAO,OAAO,OAAO,oBAAoB,oBAAoB,CAAC,CAAC,MAAM,MAAM,EAC/E,QAAQ,MACV,CAAC,CAAC,CAAC,KAAK,OAAO,UAAU,gBAAgB,QAAQ,YAAY,OAAO,CAAC,CAAC;;CAEtE,MAAM,UAAU,UAAmC;EACjD,MAAM,OAAO,OAAO,MAAM,KAAK,KAAK,GAAG,MAAM;EAC7C,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,KACtB,OAAO,eAAe,QAAQ,kBAAkB,MAAM,MAAM,MAAM,CAAC,GACnE,OAAO,cACJ,SAAS,WAAW,MAAM,CAAC,KAAK,IAAI,SAEnC,QACE,MAAM,MAAM,MAAM,KAAK,gBAAgB,UAAU,SAAS,gBAAgB,eAC5E,CACJ,CACF;CACF;CACA,MAAM,KAAK;EAAE,MAAM,OAAO,OAAO,MAAM;EAAG,KAAK,SAAS,KAAK,OAAO,OAAO,KAAK,CAAC;CAAE;CAEnF,OAAO;EADwB,GAAG;EAAM;CAC5B;AACd,CAAC"}
|
package/dist/prepare.js
CHANGED
|
@@ -1,23 +1,93 @@
|
|
|
1
1
|
import { InfraError } from "./errors.js";
|
|
2
|
+
import { serverConfigFileName } from "./packages/contract/src/server-config.js";
|
|
2
3
|
import { loadDeployConfig, resolveDeployment } from "./config.js";
|
|
3
|
-
import {
|
|
4
|
+
import { rootProblems } from "./packages/contract/src/root-ca.js";
|
|
5
|
+
import { checkServerFiles, hasServerConfig, readServerDir, serverFile, textOf, writeServerDir } from "./server-dir.js";
|
|
4
6
|
import { createdSummary, draftServerDir } from "./create-server-dir.js";
|
|
5
7
|
import { checkEnv, stackEnv } from "./secrets.js";
|
|
6
|
-
import {
|
|
8
|
+
import { seedDrift } from "./seed-drift.js";
|
|
9
|
+
import { Console, Effect, FileSystem, Option, Path, Redacted, Schema } from "effect";
|
|
7
10
|
// src/prepare.ts
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
11
|
+
/** The server config as plain JSON, to rewrite some keys and keep the rest as they are. */
|
|
12
|
+
const ConfigJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
|
|
13
|
+
/** The text of the deploy file's `ca.cert`, if it names one that can be read. */
|
|
14
|
+
const seededCert = (loaded) => Effect.gen(function* read() {
|
|
15
|
+
const { cert } = loaded.config.ca ?? {};
|
|
16
|
+
if (cert === void 0) return Option.none();
|
|
17
|
+
const path = yield* Path.Path;
|
|
18
|
+
return yield* (yield* FileSystem.FileSystem).readFileString(path.resolve(loaded.dir, cert)).pipe(Effect.option);
|
|
19
|
+
});
|
|
20
|
+
/** The fields `--force` copies into an existing server config. Never `ca`: see the warning. */
|
|
21
|
+
const copyable = (drift) => [...new Set(drift.map(({ field }) => field))].filter((field) => field !== "ca");
|
|
22
|
+
/** The config file with the deploy file's values for `fields`, every other key kept as it is. */
|
|
23
|
+
const withSeeds = (file, seeds, fields) => Schema.decodeUnknownEffect(ConfigJson)(textOf(file)).pipe(Effect.orDie, Effect.map((json) => {
|
|
24
|
+
const copied = Object.fromEntries(fields.map((field) => [field, seeds[field]]));
|
|
25
|
+
const indent = 2;
|
|
26
|
+
return serverFile(file.name, `${JSON.stringify({
|
|
27
|
+
...json,
|
|
28
|
+
...copied
|
|
29
|
+
}, void 0, indent)}\n`, file.mode);
|
|
30
|
+
}));
|
|
31
|
+
/** Writes the folder's config file from `files` over the one on disk, with its mode. */
|
|
32
|
+
const writeConfigFile = (dir, files) => Effect.gen(function* write() {
|
|
33
|
+
const updated = files.find((file) => file.name === serverConfigFileName);
|
|
34
|
+
if (updated === void 0) return;
|
|
35
|
+
const fs = yield* FileSystem.FileSystem;
|
|
36
|
+
const target = (yield* Path.Path).join(dir, serverConfigFileName);
|
|
37
|
+
yield* fs.writeFile(target, Buffer.from(updated.base64, "base64")).pipe(Effect.orDie);
|
|
38
|
+
yield* fs.chmod(target, updated.mode).pipe(Effect.orDie);
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* Fails when the deploy file's domains are not all ones the current root may sign for. `ca create`
|
|
42
|
+
* signs for the server config's domains, so the way out is to add them there first.
|
|
43
|
+
*/
|
|
44
|
+
const refuseUncoveredDomains = (request, server) => {
|
|
45
|
+
const { authHost, domains = [] } = request.loaded.config;
|
|
46
|
+
const problems = rootProblems({
|
|
47
|
+
cert: server.config.ca.cert,
|
|
48
|
+
domains,
|
|
49
|
+
key: Redacted.value(server.config.ca.key)
|
|
50
|
+
});
|
|
51
|
+
const file = `${server.dir}/${serverConfigFileName}`;
|
|
52
|
+
return problems.length === 0 ? Effect.void : Effect.fail(new InfraError({ message: `--force cannot copy domains into ${file}: ${problems.join("; ")}. The root's name constraints are signed into it, so it needs a new root: set domains in ${file} to ${domains.join(", ")}, run wt-tunnel ca create --force, which signs for that config's domains, deploy, then trust the new root on each device from https://${authHost}/ca. Nothing was written.` }));
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Copies `fields` from the deploy file into the server config: checks the folder with the new
|
|
56
|
+
* config first, so a change the root cannot sign for stops before anything is written.
|
|
57
|
+
*/
|
|
58
|
+
const copySeeds = (request, server, fields) => Effect.gen(function* copy() {
|
|
59
|
+
const { config: deploy } = request.loaded;
|
|
60
|
+
if (fields.includes("domains")) yield* refuseUncoveredDomains(request, server);
|
|
61
|
+
const files = yield* Effect.all(server.files.map((file) => file.name === "wt-tunnel-server.json" ? withSeeds(file, deploy, fields) : Effect.succeed(file)));
|
|
62
|
+
const checked = yield* checkServerFiles({
|
|
63
|
+
deploy,
|
|
64
|
+
dir: server.dir,
|
|
65
|
+
files
|
|
66
|
+
});
|
|
67
|
+
yield* writeConfigFile(server.dir, files);
|
|
68
|
+
yield* Console.log(`Copied ${fields.join(" and ")} from the deploy file into ${server.dir}/${serverConfigFileName}.`);
|
|
69
|
+
return checked;
|
|
70
|
+
});
|
|
71
|
+
/** How to resolve what is left: copy the settings with --force; a root is replaced on purpose only. */
|
|
72
|
+
const driftAdvice = (drift) => [...copyable(drift).length > 0 ? [`To copy ${copyable(drift).join(" and ")} from the deploy file into it, run wt-tunnel deploy --force (or prepare --force). Otherwise make the deploy file match.`] : [], ...drift.some(({ field }) => field === "ca") ? ["A deploy never replaces the root, which every device trusts. For a new one, run wt-tunnel ca create --force, deploy, then trust it on each device; or remove ca from the deploy file."] : []];
|
|
73
|
+
/** Warns about what the deploy file says differently from the server config, and what to do. */
|
|
74
|
+
const warnOnDrift = (dir, drift) => drift.length === 0 ? Effect.void : Console.warn([
|
|
75
|
+
`Warning: the deploy file differs from ${dir}/${serverConfigFileName}, which decides what the server does:`,
|
|
76
|
+
...drift.map(({ message }) => ` - ${message}`),
|
|
77
|
+
...driftAdvice(drift)
|
|
78
|
+
].join("\n"));
|
|
79
|
+
/**
|
|
80
|
+
* Reads and checks the existing folder. With `force`, the deploy file's `domains` and `allow` are
|
|
81
|
+
* copied into its config; otherwise it is never rewritten, and differences only warn.
|
|
82
|
+
*/
|
|
83
|
+
const existingServerDir = (request) => Effect.gen(function* existing() {
|
|
84
|
+
const { loaded } = request;
|
|
85
|
+
const read = yield* readServerDir(loaded.serverDir, loaded.config);
|
|
86
|
+
const cert = Option.getOrUndefined(yield* seededCert(loaded));
|
|
87
|
+
const drift = seedDrift(loaded.config, read.config, cert);
|
|
88
|
+
const fields = request.force === true ? copyable(drift) : [];
|
|
89
|
+
const server = fields.length === 0 ? read : yield* copySeeds(request, read, fields);
|
|
90
|
+
yield* warnOnDrift(server.dir, drift.filter(({ field }) => field === "ca" || !fields.includes(field)));
|
|
21
91
|
if (server.unreferenced.length > 0) yield* Console.log(`Uploading ${server.unreferenced.join(", ")} from ${loaded.serverDir} as well; the server config names none of them.`);
|
|
22
92
|
return server;
|
|
23
93
|
});
|
|
@@ -29,7 +99,6 @@ const newServerDir = (request) => Effect.gen(function* create() {
|
|
|
29
99
|
deploy: loaded.config,
|
|
30
100
|
deployDir: loaded.dir,
|
|
31
101
|
env: request.env,
|
|
32
|
-
inputs: request.inputs,
|
|
33
102
|
serverDir: loaded.serverDir
|
|
34
103
|
});
|
|
35
104
|
const server = yield* checkServerFiles({
|
package/dist/prepare.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.js","names":[],"sources":["../src/prepare.ts"],"sourcesContent":["import { Console, Effect } from 'effect';\n\nimport { loadDeployConfig, resolveDeployment } from './config.ts';\nimport type { LoadedDeploy } from './config.ts';\nimport { createdSummary, draftServerDir } from './create-server-dir.ts';\nimport type { Ask, CreateInputs } from './create-server-dir.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\nimport { checkEnv, stackEnv } from './secrets.ts';\nimport type { Env } from './secrets.ts';\nimport { checkServerFiles, hasServerConfig, readServerDir, writeServerDir } from './server-dir.ts';\n\n/**\n * What a command does when the server folder has no config yet: `create` writes it (deploy and\n * prepare), `preview` builds it in memory only (plan), `require` fails (everything else).\n */\ntype Missing = 'create' | 'preview' | 'require';\n\ninterface ServerDirRequest {\n readonly ask: Ask;\n readonly env: Env;\n readonly inputs: CreateInputs;\n readonly loaded: LoadedDeploy;\n readonly missing: Missing;\n}\n\nconst creationFlags = (inputs: CreateInputs) => [\n ...(inputs.domains.length > 0 ? ['--domain'] : []),\n ...(inputs.authHost === undefined ? [] : ['--auth-host']),\n ...(inputs.allowEmails.length > 0 ? ['--allow-email'] : []),\n ...(inputs.allowEmailDomains.length > 0 ? ['--allow-email-domain'] : []),\n ...(inputs.caCert === undefined ? [] : ['--ca-cert']),\n ...(inputs.caKey === undefined ? [] : ['--ca-key']),\n];\n\n/** Reads and checks the existing folder. It is never rewritten. */\nconst existingServerDir = ({ inputs, loaded }: ServerDirRequest) =>\n Effect.gen(function* existing() {\n const server = yield* readServerDir(loaded.serverDir, loaded.config);\n const ignored = creationFlags(inputs);\n if (ignored.length > 0) {\n yield* Console.log(\n `Ignoring ${ignored.join(', ')}: ${loaded.serverDir} exists. Edit it to change what the server does.`,\n );\n }\n if (server.unreferenced.length > 0) {\n yield* Console.log(\n `Uploading ${server.unreferenced.join(', ')} from ${loaded.serverDir} as well; the server config names none of them.`,\n );\n }\n return server;\n });\n\n/** Drafts a new folder, checks it like an existing one, then writes it or only previews it. */\nconst newServerDir = (request: ServerDirRequest) =>\n Effect.gen(function* create() {\n const { loaded } = request;\n const draft = yield* draftServerDir({\n ask: request.ask,\n deploy: loaded.config,\n deployDir: loaded.dir,\n env: request.env,\n inputs: request.inputs,\n serverDir: loaded.serverDir,\n });\n const server = yield* checkServerFiles({\n deploy: loaded.config,\n dir: loaded.serverDir,\n files: draft.files,\n });\n if (request.missing === 'create') {\n yield* writeServerDir(loaded.serverDir, draft.files);\n yield* Console.log(\n createdSummary({ authHost: server.config.authHost, draft, serverDir: loaded.serverDir }),\n );\n } else {\n yield* Console.log(\n `${loaded.serverDir} has no server config yet; deploy would create it.${draft.generated.length === 0 ? '' : ` This plan uses a ${draft.generated.join(', ')} made for the preview only; deploy makes its own.`} Nothing was written.`,\n );\n }\n return server;\n });\n\n/** The server folder, checked, creating it or previewing it as the command asks. */\nconst serverDirFor = (request: ServerDirRequest) =>\n Effect.gen(function* serverDir() {\n if (yield* hasServerConfig(request.loaded.serverDir)) {\n return yield* existingServerDir(request);\n }\n if (request.missing === 'require') {\n return yield* new InfraError({\n message: `${request.loaded.serverDir} has no server config; run wt-tunnel deploy to create it`,\n });\n }\n return yield* newServerDir(request);\n });\n\n/** What every alchemy run needs: where to run, the deployment, and the stack's environment. */\ninterface Prepared {\n readonly cwd: string;\n readonly deployment: Deployment;\n readonly env: Env;\n}\n\n/** Loads the deploy file, checks the environment, then reads, creates or previews the folder. */\nconst prepare = (input: {\n readonly ask: Ask;\n readonly config: string;\n readonly env: Env;\n readonly inputs: CreateInputs;\n readonly missing: Missing;\n readonly version: string;\n}) =>\n Effect.gen(function* prepareRun() {\n const loaded = yield* loadDeployConfig(input.config);\n yield* checkEnv(loaded.config, input.env);\n const server = yield* serverDirFor({ ...input, loaded });\n const deployment = resolveDeployment(loaded.config, server.config, input.version);\n const prepared: Prepared = {\n cwd: loaded.dir,\n deployment,\n env: stackEnv(deployment, server.files, input.env),\n };\n return prepared;\n });\n\nexport { prepare, serverDirFor };\nexport type { Missing, Prepared };\n"],"mappings":";;;;;;;AA0BA,MAAM,iBAAiB,WAAyB;CAC9C,GAAI,OAAO,QAAQ,SAAS,IAAI,CAAC,UAAU,IAAI,CAAC;CAChD,GAAI,OAAO,aAAa,KAAA,IAAY,CAAC,IAAI,CAAC,aAAa;CACvD,GAAI,OAAO,YAAY,SAAS,IAAI,CAAC,eAAe,IAAI,CAAC;CACzD,GAAI,OAAO,kBAAkB,SAAS,IAAI,CAAC,sBAAsB,IAAI,CAAC;CACtE,GAAI,OAAO,WAAW,KAAA,IAAY,CAAC,IAAI,CAAC,WAAW;CACnD,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,UAAU;AACnD;;AAGA,MAAM,qBAAqB,EAAE,QAAQ,aACnC,OAAO,IAAI,UAAU,WAAW;CAC9B,MAAM,SAAS,OAAO,cAAc,OAAO,WAAW,OAAO,MAAM;CACnE,MAAM,UAAU,cAAc,MAAM;CACpC,IAAI,QAAQ,SAAS,GACnB,OAAO,QAAQ,IACb,YAAY,QAAQ,KAAK,IAAI,EAAE,IAAI,OAAO,UAAU,iDACtD;CAEF,IAAI,OAAO,aAAa,SAAS,GAC/B,OAAO,QAAQ,IACb,aAAa,OAAO,aAAa,KAAK,IAAI,EAAE,QAAQ,OAAO,UAAU,gDACvE;CAEF,OAAO;AACT,CAAC;;AAGH,MAAM,gBAAgB,YACpB,OAAO,IAAI,UAAU,SAAS;CAC5B,MAAM,EAAE,WAAW;CACnB,MAAM,QAAQ,OAAO,eAAe;EAClC,KAAK,QAAQ;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,KAAK,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-ca';\nimport { serverConfigFileName } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Console, Effect, FileSystem, Option, Path, Redacted, Schema } from 'effect';\n\nimport { loadDeployConfig, resolveDeployment } from './config.ts';\nimport type { LoadedDeploy } from './config.ts';\nimport { createdSummary, draftServerDir } from './create-server-dir.ts';\nimport type { Ask } from './create-server-dir.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\nimport { checkEnv, stackEnv } from './secrets.ts';\nimport type { Env } from './secrets.ts';\nimport { seedDrift } from './seed-drift.ts';\nimport type { Drift } from './seed-drift.ts';\nimport {\n checkServerFiles,\n hasServerConfig,\n readServerDir,\n serverFile,\n textOf,\n writeServerDir,\n} from './server-dir.ts';\nimport type { ServerDir, ServerFile } from './server-dir.ts';\n\n/** The server config as plain JSON, to rewrite some keys and keep the rest as they are. */\nconst ConfigJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));\n\n/**\n * What a command does when the server folder has no config yet: `create` writes it (deploy and\n * prepare), `preview` builds it in memory only (plan), `require` fails (everything else).\n */\ntype Missing = 'create' | 'preview' | 'require';\n\ninterface ServerDirRequest {\n readonly ask: Ask;\n readonly env: Env;\n /** Copy the deploy file's `domains` and `allow` into an existing server config. */\n readonly force?: boolean;\n readonly loaded: LoadedDeploy;\n readonly missing: Missing;\n}\n\n/** The text of the deploy file's `ca.cert`, if it names one that can be read. */\nconst seededCert = (loaded: LoadedDeploy) =>\n Effect.gen(function* read() {\n const { cert } = loaded.config.ca ?? {};\n if (cert === undefined) {\n return Option.none();\n }\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n return yield* fs.readFileString(path.resolve(loaded.dir, cert)).pipe(Effect.option);\n });\n\n/** The fields `--force` copies into an existing server config. Never `ca`: see the warning. */\nconst copyable = (drift: readonly Drift[]) =>\n [...new Set(drift.map(({ field }) => field))].filter(\n (field): field is 'allow' | 'domains' => field !== 'ca',\n );\n\n/** The config file with the deploy file's values for `fields`, every other key kept as it is. */\nconst withSeeds = (\n file: ServerFile,\n seeds: LoadedDeploy['config'],\n fields: readonly ('allow' | 'domains')[],\n) =>\n Schema.decodeUnknownEffect(ConfigJson)(textOf(file)).pipe(\n Effect.orDie,\n Effect.map((json) => {\n const copied = Object.fromEntries(fields.map((field) => [field, seeds[field]]));\n const indent = 2;\n return serverFile(\n file.name,\n `${JSON.stringify({ ...json, ...copied }, undefined, indent)}\\n`,\n file.mode,\n );\n }),\n );\n\n/** Writes the folder's config file from `files` over the one on disk, with its mode. */\nconst writeConfigFile = (dir: string, files: readonly ServerFile[]) =>\n Effect.gen(function* write() {\n const updated = files.find((file) => file.name === serverConfigFileName);\n if (updated === undefined) {\n return;\n }\n const fs = yield* FileSystem.FileSystem;\n const target = (yield* Path.Path).join(dir, serverConfigFileName);\n yield* fs.writeFile(target, Buffer.from(updated.base64, 'base64')).pipe(Effect.orDie);\n yield* fs.chmod(target, updated.mode).pipe(Effect.orDie);\n });\n\n/**\n * Fails when the deploy file's domains are not all ones the current root may sign for. `ca create`\n * signs for the server config's domains, so the way out is to add them there first.\n */\nconst refuseUncoveredDomains = (request: ServerDirRequest, server: ServerDir) => {\n const { authHost, domains = [] } = request.loaded.config;\n const problems = rootProblems({\n cert: server.config.ca.cert,\n domains,\n key: Redacted.value(server.config.ca.key),\n });\n const file = `${server.dir}/${serverConfigFileName}`;\n return problems.length === 0\n ? Effect.void\n : Effect.fail(\n new InfraError({\n message: `--force cannot copy domains into ${file}: ${problems.join('; ')}. The root's name constraints are signed into it, so it needs a new root: set domains in ${file} to ${domains.join(', ')}, run wt-tunnel ca create --force, which signs for that config's domains, deploy, then trust the new root on each device from https://${authHost}/ca. Nothing was written.`,\n }),\n );\n};\n\n/**\n * Copies `fields` from the deploy file into the server config: checks the folder with the new\n * config first, so a change the root cannot sign for stops before anything is written.\n */\nconst copySeeds = (\n request: ServerDirRequest,\n server: ServerDir,\n fields: readonly ('allow' | 'domains')[],\n) =>\n Effect.gen(function* copy() {\n const { config: deploy } = request.loaded;\n if (fields.includes('domains')) {\n yield* refuseUncoveredDomains(request, server);\n }\n const files = yield* Effect.all(\n server.files.map((file) =>\n file.name === serverConfigFileName ? withSeeds(file, deploy, fields) : Effect.succeed(file),\n ),\n );\n const checked = yield* checkServerFiles({ deploy, dir: server.dir, files });\n yield* writeConfigFile(server.dir, files);\n yield* Console.log(\n `Copied ${fields.join(' and ')} from the deploy file into ${server.dir}/${serverConfigFileName}.`,\n );\n return checked;\n });\n\n/** How to resolve what is left: copy the settings with --force; a root is replaced on purpose only. */\nconst driftAdvice = (drift: readonly Drift[]) => [\n ...(copyable(drift).length > 0\n ? [\n `To copy ${copyable(drift).join(' and ')} from the deploy file into it, run wt-tunnel deploy --force (or prepare --force). Otherwise make the deploy file match.`,\n ]\n : []),\n ...(drift.some(({ field }) => field === 'ca')\n ? [\n 'A deploy never replaces the root, which every device trusts. For a new one, run wt-tunnel ca create --force, deploy, then trust it on each device; or remove ca from the deploy file.',\n ]\n : []),\n];\n\n/** Warns about what the deploy file says differently from the server config, and what to do. */\nconst warnOnDrift = (dir: string, drift: readonly Drift[]) =>\n drift.length === 0\n ? Effect.void\n : Console.warn(\n [\n `Warning: the deploy file differs from ${dir}/${serverConfigFileName}, which decides what the server does:`,\n ...drift.map(({ message }) => ` - ${message}`),\n ...driftAdvice(drift),\n ].join('\\n'),\n );\n\n/**\n * Reads and checks the existing folder. With `force`, the deploy file's `domains` and `allow` are\n * copied into its config; otherwise it is never rewritten, and differences only warn.\n */\nconst existingServerDir = (request: ServerDirRequest) =>\n Effect.gen(function* existing() {\n const { loaded } = request;\n const read = yield* readServerDir(loaded.serverDir, loaded.config);\n const cert = Option.getOrUndefined(yield* seededCert(loaded));\n const drift = seedDrift(loaded.config, read.config, cert);\n const fields = request.force === true ? copyable(drift) : [];\n const server = fields.length === 0 ? read : yield* copySeeds(request, read, fields);\n yield* warnOnDrift(\n server.dir,\n drift.filter(({ field }) => field === 'ca' || !fields.includes(field)),\n );\n if (server.unreferenced.length > 0) {\n yield* Console.log(\n `Uploading ${server.unreferenced.join(', ')} from ${loaded.serverDir} as well; the server config names none of them.`,\n );\n }\n return server;\n });\n\n/** Drafts a new folder, checks it like an existing one, then writes it or only previews it. */\nconst newServerDir = (request: ServerDirRequest) =>\n Effect.gen(function* create() {\n const { loaded } = request;\n const draft = yield* draftServerDir({\n ask: request.ask,\n deploy: loaded.config,\n deployDir: loaded.dir,\n env: request.env,\n serverDir: loaded.serverDir,\n });\n const server = yield* checkServerFiles({\n deploy: loaded.config,\n dir: loaded.serverDir,\n files: draft.files,\n });\n if (request.missing === 'create') {\n yield* writeServerDir(loaded.serverDir, draft.files);\n yield* Console.log(\n createdSummary({ authHost: server.config.authHost, draft, serverDir: loaded.serverDir }),\n );\n } else {\n yield* Console.log(\n `${loaded.serverDir} has no server config yet; deploy would create it.${draft.generated.length === 0 ? '' : ` This plan uses a ${draft.generated.join(', ')} made for the preview only; deploy makes its own.`} Nothing was written.`,\n );\n }\n return server;\n });\n\n/** The server folder, checked, creating it or previewing it as the command asks. */\nconst serverDirFor = (request: ServerDirRequest) =>\n Effect.gen(function* serverDir() {\n if (yield* hasServerConfig(request.loaded.serverDir)) {\n return yield* existingServerDir(request);\n }\n if (request.missing === 'require') {\n return yield* new InfraError({\n message: `${request.loaded.serverDir} has no server config; run wt-tunnel deploy to create it`,\n });\n }\n return yield* newServerDir(request);\n });\n\n/** What every alchemy run needs: where to run, the deployment, and the stack's environment. */\ninterface Prepared {\n readonly cwd: string;\n readonly deployment: Deployment;\n readonly env: Env;\n}\n\n/** Loads the deploy file, checks the environment, then reads, creates or previews the folder. */\nconst prepare = (input: {\n readonly ask: Ask;\n readonly config: string;\n readonly env: Env;\n readonly force?: boolean;\n readonly missing: Missing;\n readonly version: string;\n}) =>\n Effect.gen(function* prepareRun() {\n const loaded = yield* loadDeployConfig(input.config);\n yield* checkEnv(loaded.config, input.env);\n const server = yield* serverDirFor({ ...input, loaded });\n const deployment = resolveDeployment(loaded.config, server.config, input.version);\n const prepared: Prepared = {\n cwd: loaded.dir,\n deployment,\n env: stackEnv(deployment, server.files, input.env),\n };\n return prepared;\n });\n\nexport { prepare, serverDirFor };\nexport type { Missing, Prepared };\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,aAAa,OAAO,eAAe,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC;;AAkBrF,MAAM,cAAc,WAClB,OAAO,IAAI,UAAU,OAAO;CAC1B,MAAM,EAAE,SAAS,OAAO,OAAO,MAAM,CAAC;CACtC,IAAI,SAAS,KAAA,GACX,OAAO,OAAO,KAAK;CAErB,MAAM,OAAO,OAAO,KAAK;CAEzB,OAAO,QAAO,OADI,WAAW,WAAA,CACZ,eAAe,KAAK,QAAQ,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM;AACpF,CAAC;;AAGH,MAAM,YAAY,UAChB,CAAC,GAAG,IAAI,IAAI,MAAM,KAAK,EAAE,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,QAC3C,UAAwC,UAAU,IACrD;;AAGF,MAAM,aACJ,MACA,OACA,WAEA,OAAO,oBAAoB,UAAU,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC,KACnD,OAAO,OACP,OAAO,KAAK,SAAS;CACnB,MAAM,SAAS,OAAO,YAAY,OAAO,KAAK,UAAU,CAAC,OAAO,MAAM,MAAM,CAAC,CAAC;CAC9E,MAAM,SAAS;CACf,OAAO,WACL,KAAK,MACL,GAAG,KAAK,UAAU;EAAE,GAAG;EAAM,GAAG;CAAO,GAAG,KAAA,GAAW,MAAM,EAAE,KAC7D,KAAK,IACP;AACF,CAAC,CACH;;AAGF,MAAM,mBAAmB,KAAa,UACpC,OAAO,IAAI,UAAU,QAAQ;CAC3B,MAAM,UAAU,MAAM,MAAM,SAAS,KAAK,SAAS,oBAAoB;CACvE,IAAI,YAAY,KAAA,GACd;CAEF,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,UAAU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=> values === void 0 || values.length === 0 ? "(none)" : values.join(", ");
|
|
4
|
+
/** The same values, in any order. */
|
|
5
|
+
const sameValues = (left = [], right = []) => left.toSorted().join("\n") === right.toSorted().join("\n");
|
|
6
|
+
/** One field's difference, unless the deploy file leaves it out or it matches. */
|
|
7
|
+
const listDrift = (field, name, values) => values.seeded === void 0 || sameValues(values.seeded, values.served) ? [] : [{
|
|
8
|
+
field,
|
|
9
|
+
message: `${name}: ${listed(values.seeded)} in the deploy file, ${listed(values.served)} in the server folder`
|
|
10
|
+
}];
|
|
11
|
+
const allowDrift = (seeds, served) => seeds.allow === void 0 ? [] : [...listDrift("allow", "allow.emails", {
|
|
12
|
+
seeded: seeds.allow.emails ?? [],
|
|
13
|
+
served: served.allow.emails
|
|
14
|
+
}), ...listDrift("allow", "allow.emailDomains", {
|
|
15
|
+
seeded: seeds.allow.emailDomains ?? [],
|
|
16
|
+
served: served.allow.emailDomains
|
|
17
|
+
})];
|
|
18
|
+
const fingerprint = (pem) => new X509Certificate(pem).fingerprint256;
|
|
19
|
+
/**
|
|
20
|
+
* The root the deploy file names, against the one the server folder holds: `ca.cert` by
|
|
21
|
+
* fingerprint, given the file's text (undefined when it cannot be read), and `ca.name` by the label
|
|
22
|
+
* in the root's name.
|
|
23
|
+
*/
|
|
24
|
+
const rootDrift = (seeds, served, seededCert) => {
|
|
25
|
+
const { cert, name } = seeds.ca ?? {};
|
|
26
|
+
const certDrift = cert === void 0 || seededCert !== void 0 && fingerprint(seededCert) === fingerprint(served.ca.cert) ? [] : [{
|
|
27
|
+
field: "ca",
|
|
28
|
+
message: `ca.cert: ${cert} is not the root in the server folder`
|
|
29
|
+
}];
|
|
30
|
+
const label = `CN=wt-tunnel root (${name ?? ""})`;
|
|
31
|
+
const nameDrift = name === void 0 || new X509Certificate(served.ca.cert).subject.includes(label) ? [] : [{
|
|
32
|
+
field: "ca",
|
|
33
|
+
message: `ca.name: ${name} is not the label of the root in the server folder`
|
|
34
|
+
}];
|
|
35
|
+
return [...certDrift, ...nameDrift];
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Where the deploy file's copies of what seeds a new server folder differ from the folder's config,
|
|
39
|
+
* which decides what the server does. Fields the deploy file leaves out are not compared.
|
|
40
|
+
*/
|
|
41
|
+
const seedDrift = (seeds, served, seededCert) => [
|
|
42
|
+
...listDrift("domains", "domains", {
|
|
43
|
+
seeded: seeds.domains,
|
|
44
|
+
served: served.domains
|
|
45
|
+
}),
|
|
46
|
+
...allowDrift(seeds, served),
|
|
47
|
+
...rootDrift(seeds, served, seededCert)
|
|
48
|
+
];
|
|
49
|
+
export { seedDrift };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=seed-drift.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"seed-drift.js","names":[],"sources":["../src/seed-drift.ts"],"sourcesContent":["import { X509Certificate } from 'node:crypto';\n\ninterface AllowList {\n readonly emailDomains?: readonly string[];\n readonly emails?: readonly string[];\n}\n\n/** What the deploy file says to seed a new server folder with; only text is compared. */\ninterface Seeds {\n readonly allow?: AllowList;\n readonly ca?: { readonly cert?: string; readonly name?: string };\n readonly domains?: readonly string[];\n}\n\n/** What the server folder's config serves. */\ninterface Served {\n readonly allow: AllowList;\n readonly ca: { readonly cert: string };\n readonly domains: readonly string[];\n}\n\n/** A deploy file field whose copy differs from the server folder's, and how. */\ninterface Drift {\n readonly field: 'allow' | 'ca' | 'domains';\n readonly message: string;\n}\n\nconst listed = (values: readonly string[] | undefined) =>\n values === undefined || values.length === 0 ? '(none)' : values.join(', ');\n\n/** The same values, in any order. */\nconst sameValues = (left: readonly string[] = [], right: readonly string[] = []) =>\n left.toSorted().join('\\n') === right.toSorted().join('\\n');\n\n/** One field's difference, unless the deploy file leaves it out or it matches. */\nconst listDrift = (\n field: Drift['field'],\n name: string,\n values: {\n readonly seeded: readonly string[] | undefined;\n readonly served: readonly string[] | undefined;\n },\n): readonly Drift[] =>\n values.seeded === undefined || sameValues(values.seeded, values.served)\n ? []\n : [\n {\n field,\n message: `${name}: ${listed(values.seeded)} in the deploy file, ${listed(values.served)} in the server folder`,\n },\n ];\n\nconst allowDrift = (seeds: Seeds, served: Served) =>\n seeds.allow === undefined\n ? []\n : [\n ...listDrift('allow', 'allow.emails', {\n seeded: seeds.allow.emails ?? [],\n served: served.allow.emails,\n }),\n ...listDrift('allow', 'allow.emailDomains', {\n seeded: seeds.allow.emailDomains ?? [],\n served: served.allow.emailDomains,\n }),\n ];\n\nconst fingerprint = (pem: string) => new X509Certificate(pem).fingerprint256;\n\n/**\n * The root the deploy file names, against the one the server folder holds: `ca.cert` by\n * fingerprint, given the file's text (undefined when it cannot be read), and `ca.name` by the label\n * in the root's name.\n */\nconst rootDrift = (seeds: Seeds, served: Served, seededCert?: string) => {\n const { cert, name } = seeds.ca ?? {};\n const certDrift =\n cert === undefined ||\n (seededCert !== undefined && fingerprint(seededCert) === fingerprint(served.ca.cert))\n ? []\n : [\n {\n field: 'ca' as const,\n message: `ca.cert: ${cert} is not the root in the server folder`,\n },\n ];\n const label = `CN=wt-tunnel root (${name ?? ''})`;\n const nameDrift =\n name === undefined || new X509Certificate(served.ca.cert).subject.includes(label)\n ? []\n : [\n {\n field: 'ca' as const,\n message: `ca.name: ${name} is not the label of the root in the server folder`,\n },\n ];\n return [...certDrift, ...nameDrift];\n};\n\n/**\n * Where the deploy file's copies of what seeds a new server folder differ from the folder's config,\n * which decides what the server does. Fields the deploy file leaves out are not compared.\n */\nconst seedDrift = (seeds: Seeds, served: Served, seededCert?: string): readonly Drift[] => [\n ...listDrift('domains', 'domains', { seeded: seeds.domains, served: served.domains }),\n ...allowDrift(seeds, served),\n ...rootDrift(seeds, served, seededCert),\n];\n\nexport { seedDrift };\nexport type { Drift };\n"],"mappings":";;AA2BA,MAAM,UAAU,WACd,WAAW,KAAA,KAAa,OAAO,WAAW,IAAI,WAAW,OAAO,KAAK,IAAI;;AAG3E,MAAM,cAAc,OAA0B,CAAC,GAAG,QAA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AW,WAAW;EAAE,QAAQ,MAAM;EAAS,QAAQ,OAAO;CAAQ,CAAC;CACpF,GAAG,WAAW,OAAO,MAAM;CAC3B,GAAG,UAAU,OAAO,QAAQ,UAAU;AACxC"}
|
package/dist/server-dir.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { InfraError } from "./errors.js";
|
|
2
|
-
import { uncoveredNames } from "./deployment.js";
|
|
1
|
+
import { InfraError, failWith } from "./errors.js";
|
|
3
2
|
import { ServerConfigFileJson, caFile, readServerConfig, serverConfigFileName } from "./packages/contract/src/server-config.js";
|
|
3
|
+
import { uncoveredNames } from "./deployment.js";
|
|
4
4
|
import { rootProblems } from "./packages/contract/src/root-ca.js";
|
|
5
5
|
import { secretNameOf } from "./uploads.js";
|
|
6
6
|
import { Effect, FileSystem, Path, Redacted, Schema } from "effect";
|
|
@@ -20,6 +20,8 @@ const reader = (dir, files) => (file) => {
|
|
|
20
20
|
};
|
|
21
21
|
/** The domain `authHost` sits under, if any: dev hosts there belong to worktrees. */
|
|
22
22
|
const authHostProblems = (config) => config.domains.filter((domain) => config.authHost === domain || config.authHost.endsWith(`.${domain}`)).map((domain) => `authHost ${config.authHost} sits under the dev domain ${domain}, whose names belong to worktrees; pick a name outside every dev domain`);
|
|
23
|
+
/** The server serves the sign-in host its config names; DNS points the deploy file's at it. */
|
|
24
|
+
const authHostMismatch = (config, deploy) => config.authHost === deploy.authHost ? [] : [`authHost is ${config.authHost} in the server folder but ${deploy.authHost} in the deploy file; make them the same`];
|
|
23
25
|
const nameProblem = (file) => /^[A-Za-z0-9._-]+$/u.test(file.name) ? [] : [`${file.name}: only letters, digits, ".", "_" and "-" may name a file`];
|
|
24
26
|
/** Problems with the files themselves: names the Machine cannot take, and readable secrets. */
|
|
25
27
|
const fileProblems = (keyName, files) => {
|
|
@@ -48,18 +50,27 @@ const caNames = (dir, text) => Schema.decodeUnknownEffect(ServerConfigFileJson)(
|
|
|
48
50
|
cert: caFile(dir, ca.cert).slice(dir.length + 1),
|
|
49
51
|
key: caFile(dir, ca.key).slice(dir.length + 1)
|
|
50
52
|
})));
|
|
53
|
+
/**
|
|
54
|
+
* The root's problems, and when its name constraints leave out a dev domain, how to make one that
|
|
55
|
+
* covers them all: constraints are signed into the certificate, so the root cannot be extended.
|
|
56
|
+
*/
|
|
57
|
+
const rootCoverage = (config, deploy) => {
|
|
58
|
+
const problems = rootProblems({
|
|
59
|
+
cert: config.ca.cert,
|
|
60
|
+
domains: config.domains,
|
|
61
|
+
key: Redacted.value(config.ca.key)
|
|
62
|
+
});
|
|
63
|
+
return problems.some((problem) => problem.includes("do not cover")) ? [...problems, `to sign for every domain in domains, make a new root with wt-tunnel ca create --force, deploy, then trust the new root on each device from https://${deploy.authHost}/ca`] : problems;
|
|
64
|
+
};
|
|
51
65
|
/** Everything wrong with a decoded config and its folder, beyond the schema. */
|
|
52
66
|
const folderProblems = (input) => [
|
|
53
|
-
...
|
|
54
|
-
cert: input.config.ca.cert,
|
|
55
|
-
domains: input.config.domains,
|
|
56
|
-
key: Redacted.value(input.config.ca.key)
|
|
57
|
-
}),
|
|
67
|
+
...rootCoverage(input.config, input.deploy),
|
|
58
68
|
...uncoveredNames({
|
|
59
|
-
...input.
|
|
60
|
-
...input.
|
|
69
|
+
...input.config,
|
|
70
|
+
...input.deploy
|
|
61
71
|
}),
|
|
62
72
|
...authHostProblems(input.config),
|
|
73
|
+
...authHostMismatch(input.config, input.deploy),
|
|
63
74
|
...fileProblems(input.keyName, input.files)
|
|
64
75
|
];
|
|
65
76
|
/**
|
|
@@ -101,10 +112,9 @@ const hasServerConfig = (dir) => FileSystem.FileSystem.use((fs) => fs.exists(`${
|
|
|
101
112
|
const readServerFile = (dir, name) => Effect.gen(function* readFile() {
|
|
102
113
|
const fs = yield* FileSystem.FileSystem;
|
|
103
114
|
const file = (yield* Path.Path).join(dir, name);
|
|
104
|
-
const
|
|
105
|
-
const info = yield* fs.stat(file).pipe(Effect.mapError(cannotRead));
|
|
115
|
+
const info = yield* fs.stat(file).pipe(failWith(`cannot read ${file}`));
|
|
106
116
|
if (info.type !== "File") return yield* new InfraError({ message: `${file} is not a file; the server folder holds only files, uploaded as they are` });
|
|
107
|
-
const content = yield* fs.readFile(file).pipe(
|
|
117
|
+
const content = yield* fs.readFile(file).pipe(failWith(`cannot read ${file}`));
|
|
108
118
|
return {
|
|
109
119
|
base64: Buffer.from(content).toString("base64"),
|
|
110
120
|
mode: info.mode & permissionBits,
|
|
@@ -112,7 +122,7 @@ const readServerFile = (dir, name) => Effect.gen(function* readFile() {
|
|
|
112
122
|
};
|
|
113
123
|
});
|
|
114
124
|
/** Reads and checks the server folder on disk. */
|
|
115
|
-
const readServerDir = (dir, deploy) => FileSystem.FileSystem.use((fs) => fs.readDirectory(dir)).pipe(
|
|
125
|
+
const readServerDir = (dir, deploy) => FileSystem.FileSystem.use((fs) => fs.readDirectory(dir)).pipe(failWith(`cannot read the server folder ${dir}`), Effect.flatMap((names) => Effect.forEach(names.toSorted(), (name) => readServerFile(dir, name))), Effect.flatMap((files) => checkServerFiles({
|
|
116
126
|
deploy,
|
|
117
127
|
dir,
|
|
118
128
|
files
|
|
@@ -136,6 +146,6 @@ const writeServerDir = (dir, files) => Effect.gen(function* write() {
|
|
|
136
146
|
}).pipe(Effect.orDie);
|
|
137
147
|
}
|
|
138
148
|
});
|
|
139
|
-
export { checkServerFiles, hasServerConfig, readServerDir, serverFile, writeServerDir };
|
|
149
|
+
export { checkServerFiles, hasServerConfig, readServerDir, serverFile, textOf, writeServerDir };
|
|
140
150
|
|
|
141
151
|
//# sourceMappingURL=server-dir.js.map
|
package/dist/server-dir.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-dir.js","names":[],"sources":["../src/server-dir.ts"],"sourcesContent":["import { rootProblems } from '@tafrahq/wt-tunnel-contract/root-ca';\nimport {\n ServerConfigFileJson,\n caFile,\n readServerConfig,\n serverConfigFileName,\n} from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ServerConfig, ServerConfigFile } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Path, Redacted, Schema } from 'effect';\n\nimport type { DeployConfig } from './config.ts';\nimport { uncoveredNames } from './deployment.ts';\nimport { InfraError } from './errors.ts';\nimport { secretNameOf } from './uploads.ts';\n\nconst folderMode = 0o700;\nconst secretMode = 0o600;\nconst publicMode = 0o644;\nconst groupOrOther = 0o077;\nconst permissionBits = 0o777;\n\n/** A file of the server folder: uploaded to the Machine as it is. */\ninterface ServerFile {\n /** The content, which may be any bytes. */\n readonly base64: string;\n /** Permission bits on disk. */\n readonly mode: number;\n /** The file's name in the folder, which holds no subfolders. */\n readonly name: string;\n}\n\n/** A checked server folder: its decoded config, and every file to upload. */\ninterface ServerDir {\n readonly config: ServerConfig;\n readonly dir: string;\n readonly files: readonly ServerFile[];\n /** Files no field of the config names. They are uploaded anyway. */\n readonly unreferenced: readonly string[];\n}\n\nconst textOf = ({ base64 }: ServerFile) => Buffer.from(base64, 'base64').toString('utf8');\n\n/** A file for the folder, from its text. */\nconst serverFile = (name: string, text: string, mode: number): ServerFile => ({\n base64: Buffer.from(text).toString('base64'),\n mode,\n name,\n});\n\n/** The folder's files by path, read the way the server reads them on the Machine. */\nconst reader = (dir: string, files: readonly ServerFile[]) => (file: string) => {\n const found = files.find((candidate) => `${dir}/${candidate.name}` === file);\n return found === undefined ? Effect.fail('missing') : Effect.succeed(textOf(found));\n};\n\n/** The domain `authHost` sits under, if any: dev hosts there belong to worktrees. */\nconst authHostProblems = (config: ServerConfig): readonly string[] =>\n config.domains\n .filter((domain) => config.authHost === domain || config.authHost.endsWith(`.${domain}`))\n .map(\n (domain) =>\n `authHost ${config.authHost} sits under the dev domain ${domain}, whose names belong to worktrees; pick a name outside every dev domain`,\n );\n\nconst nameProblem = (file: ServerFile) =>\n /^[A-Za-z0-9._-]+$/u.test(file.name)\n ? []\n : [`${file.name}: only letters, digits, \".\", \"_\" and \"-\" may name a file`];\n\n/** Problems with the files themselves: names the Machine cannot take, and readable secrets. */\nconst fileProblems = (keyName: string, files: readonly ServerFile[]): readonly string[] => {\n const secretFiles = new Set([serverConfigFileName, keyName]);\n const secrets = files.map((file) => secretNameOf(file.name));\n return files.flatMap((file, index) => [\n ...nameProblem(file),\n ...(secretFiles.has(file.name) && (file.mode & groupOrOther) !== 0\n ? [`${file.name} holds secrets but others may read it: chmod 600 it`]\n : []),\n ...(secrets.indexOf(secretNameOf(file.name)) === index\n ? []\n : [`${file.name} maps to the same Fly secret as another file; rename one`]),\n ]);\n};\n\n/** A `ca` path the Machine can follow names a file in the folder itself. */\nconst caPathProblems = (dir: string, ca: ServerConfigFile['ca']): readonly string[] =>\n (['cert', 'key'] as const).flatMap((field) => {\n const file = caFile(dir, ca[field]);\n return file.startsWith(`${dir}/`) && !file.slice(dir.length + 1).includes('/')\n ? []\n : [`ca.${field} must name a file in ${dir}, the folder uploaded to the Machine`];\n });\n\nconst invalidFolder = (dir: string, problems: readonly string[]) =>\n new InfraError({\n message: `${dir}/${serverConfigFileName} is not valid:\\n ${problems.join('\\n ')}`,\n });\n\n/**\n * The root's file names, in the folder. When the config does not decode, readServerConfig says why,\n * so the defaults stand in until then.\n */\nconst caNames = (dir: string, text: string) =>\n Schema.decodeUnknownEffect(ServerConfigFileJson)(text).pipe(\n Effect.map((file): ServerConfigFile['ca'] => file.ca),\n Effect.orElseSucceed((): ServerConfigFile['ca'] => ({ cert: 'ca.crt', key: 'ca.key' })),\n Effect.filterOrFail(\n (ca) => caPathProblems(dir, ca).length === 0,\n (ca) => invalidFolder(dir, caPathProblems(dir, ca)),\n ),\n Effect.map((ca) => ({\n cert: caFile(dir, ca.cert).slice(dir.length + 1),\n key: caFile(dir, ca.key).slice(dir.length + 1),\n })),\n );\n\n/** Everything wrong with a decoded config and its folder, beyond the schema. */\nconst folderProblems = (input: {\n readonly config: ServerConfig;\n readonly deploy: DeployConfig;\n readonly files: readonly ServerFile[];\n readonly keyName: string;\n}) => [\n ...rootProblems({\n cert: input.config.ca.cert,\n domains: input.config.domains,\n key: Redacted.value(input.config.ca.key),\n }),\n ...uncoveredNames({ ...input.deploy, ...input.config }),\n ...authHostProblems(input.config),\n ...fileProblems(input.keyName, input.files),\n];\n\n/**\n * Checks a server folder, on disk or not yet written, before anything is deployed: the config\n * decodes with the server's own schema, its root files are in the folder and hold PEM, the root\n * covers every domain and matches its key, every DNS name sits in a zone, the sign-in host is\n * outside the dev domains, and the secret files are private. Every problem is reported at once.\n */\nconst checkServerFiles = (input: {\n readonly deploy: DeployConfig;\n readonly dir: string;\n readonly files: readonly ServerFile[];\n}) =>\n Effect.gen(function* check() {\n const configFile = input.files.find((file) => file.name === serverConfigFileName);\n if (configFile === undefined) {\n return yield* invalidFolder(input.dir, ['it is missing']);\n }\n const names = yield* caNames(input.dir, textOf(configFile));\n const config = yield* readServerConfig({\n dir: input.dir,\n read: reader(input.dir, input.files),\n source: `${input.dir}/${serverConfigFileName}`,\n text: textOf(configFile),\n }).pipe(\n Effect.mapError(({ message }: { readonly message: string }) => new InfraError({ message })),\n );\n const problems = folderProblems({ ...input, config, keyName: names.key });\n if (problems.length > 0) {\n return yield* invalidFolder(input.dir, problems);\n }\n const checked: ServerDir = {\n config,\n dir: input.dir,\n files: input.files,\n unreferenced: input.files\n .map(({ name }) => name)\n .filter((name) => ![serverConfigFileName, names.cert, names.key].includes(name)),\n };\n return checked;\n });\n\n/** Whether the folder holds a server config yet. */\nconst hasServerConfig = (dir: string) =>\n FileSystem.FileSystem.use((fs) => fs.exists(`${dir}/${serverConfigFileName}`)).pipe(\n Effect.orElseSucceed(() => false),\n );\n\n/** One file of the folder. Anything that is not a file fails. */\nconst readServerFile = (dir: string, name: string) =>\n Effect.gen(function* readFile() {\n const fs = yield* FileSystem.FileSystem;\n const file = (yield* Path.Path).join(dir, name);\n const cannotRead = () => new InfraError({ message: `cannot read ${file}` });\n const info = yield* fs.stat(file).pipe(Effect.mapError(cannotRead));\n if (info.type !== 'File') {\n return yield* new InfraError({\n message: `${file} is not a file; the server folder holds only files, uploaded as they are`,\n });\n }\n const content = yield* fs.readFile(file).pipe(Effect.mapError(cannotRead));\n const read: ServerFile = {\n base64: Buffer.from(content).toString('base64'),\n mode: info.mode & permissionBits,\n name,\n };\n return read;\n });\n\n/** Reads and checks the server folder on disk. */\nconst readServerDir = (dir: string, deploy: DeployConfig) =>\n FileSystem.FileSystem.use((fs) => fs.readDirectory(dir)).pipe(\n Effect.mapError(() => new InfraError({ message: `cannot read the server folder ${dir}` })),\n Effect.flatMap((names: readonly string[]) =>\n Effect.forEach(names.toSorted(), (name) => readServerFile(dir, name)),\n ),\n Effect.flatMap((files: readonly ServerFile[]) => checkServerFiles({ deploy, dir, files })),\n );\n\n/** The config sorts last, so a run that stops halfway leaves no config and the next drafts again. */\nconst configLast = (left: ServerFile, right: ServerFile) =>\n Number(left.name === serverConfigFileName) - Number(right.name === serverConfigFileName);\n\n/** Writes a drafted folder: private, each file with its mode, the config last. Never overwrites. */\nconst writeServerDir = (dir: string, files: readonly ServerFile[]) =>\n Effect.gen(function* write() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n yield* fs.makeDirectory(dir, { mode: folderMode, recursive: true }).pipe(Effect.orDie);\n yield* fs.chmod(dir, folderMode).pipe(Effect.orDie);\n for (const file of files.toSorted(configLast)) {\n const target = path.join(dir, file.name);\n if (!(yield* fs.exists(target).pipe(Effect.orDie))) {\n yield* fs\n .writeFile(target, Buffer.from(file.base64, 'base64'), { flag: 'wx', mode: file.mode })\n .pipe(Effect.orDie);\n }\n }\n });\n\nexport {\n checkServerFiles,\n folderMode,\n hasServerConfig,\n publicMode,\n readServerDir,\n secretMode,\n serverFile,\n writeServerDir,\n};\nexport type { ServerFile };\n"],"mappings":";;;;;;AAkBA,MAAM,eAAe;AACrB,MAAM,iBAAiB;AAqBvB,MAAM,UAAU,EAAE,aAAyB,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,SAAS,MAAM;;AAGxF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3,"file":"server-dir.js","names":[],"sources":["../src/server-dir.ts"],"sourcesContent":["import { rootProblems } from '@tafrahq/wt-tunnel-contract/root-ca';\nimport {\n ServerConfigFileJson,\n caFile,\n readServerConfig,\n serverConfigFileName,\n} from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ServerConfig, ServerConfigFile } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, FileSystem, Path, Redacted, Schema } from 'effect';\n\nimport type { DeployConfig } from './config.ts';\nimport { uncoveredNames } from './deployment.ts';\nimport { failWith, InfraError } from './errors.ts';\nimport { secretNameOf } from './uploads.ts';\n\nconst folderMode = 0o700;\nconst secretMode = 0o600;\nconst publicMode = 0o644;\nconst groupOrOther = 0o077;\nconst permissionBits = 0o777;\n\n/** A file of the server folder: uploaded to the Machine as it is. */\ninterface ServerFile {\n /** The content, which may be any bytes. */\n readonly base64: string;\n /** Permission bits on disk. */\n readonly mode: number;\n /** The file's name in the folder, which holds no subfolders. */\n readonly name: string;\n}\n\n/** A checked server folder: its decoded config, and every file to upload. */\ninterface ServerDir {\n readonly config: ServerConfig;\n readonly dir: string;\n readonly files: readonly ServerFile[];\n /** Files no field of the config names. They are uploaded anyway. */\n readonly unreferenced: readonly string[];\n}\n\nconst textOf = ({ base64 }: ServerFile) => Buffer.from(base64, 'base64').toString('utf8');\n\n/** A file for the folder, from its text. */\nconst serverFile = (name: string, text: string, mode: number): ServerFile => ({\n base64: Buffer.from(text).toString('base64'),\n mode,\n name,\n});\n\n/** The folder's files by path, read the way the server reads them on the Machine. */\nconst reader = (dir: string, files: readonly ServerFile[]) => (file: string) => {\n const found = files.find((candidate) => `${dir}/${candidate.name}` === file);\n return found === undefined ? Effect.fail('missing') : Effect.succeed(textOf(found));\n};\n\n/** The domain `authHost` sits under, if any: dev hosts there belong to worktrees. */\nconst authHostProblems = (config: ServerConfig): readonly string[] =>\n config.domains\n .filter((domain) => config.authHost === domain || config.authHost.endsWith(`.${domain}`))\n .map(\n (domain) =>\n `authHost ${config.authHost} sits under the dev domain ${domain}, whose names belong to worktrees; pick a name outside every dev domain`,\n );\n\n/** The server serves the sign-in host its config names; DNS points the deploy file's at it. */\nconst authHostMismatch = (config: ServerConfig, deploy: DeployConfig): readonly string[] =>\n config.authHost === deploy.authHost\n ? []\n : [\n `authHost is ${config.authHost} in the server folder but ${deploy.authHost} in the deploy file; make them the same`,\n ];\n\nconst nameProblem = (file: ServerFile) =>\n /^[A-Za-z0-9._-]+$/u.test(file.name)\n ? []\n : [`${file.name}: only letters, digits, \".\", \"_\" and \"-\" may name a file`];\n\n/** Problems with the files themselves: names the Machine cannot take, and readable secrets. */\nconst fileProblems = (keyName: string, files: readonly ServerFile[]): readonly string[] => {\n const secretFiles = new Set([serverConfigFileName, keyName]);\n const secrets = files.map((file) => secretNameOf(file.name));\n return files.flatMap((file, index) => [\n ...nameProblem(file),\n ...(secretFiles.has(file.name) && (file.mode & groupOrOther) !== 0\n ? [`${file.name} holds secrets but others may read it: chmod 600 it`]\n : []),\n ...(secrets.indexOf(secretNameOf(file.name)) === index\n ? []\n : [`${file.name} maps to the same Fly secret as another file; rename one`]),\n ]);\n};\n\n/** A `ca` path the Machine can follow names a file in the folder itself. */\nconst caPathProblems = (dir: string, ca: ServerConfigFile['ca']): readonly string[] =>\n (['cert', 'key'] as const).flatMap((field) => {\n const file = caFile(dir, ca[field]);\n return file.startsWith(`${dir}/`) && !file.slice(dir.length + 1).includes('/')\n ? []\n : [`ca.${field} must name a file in ${dir}, the folder uploaded to the Machine`];\n });\n\nconst invalidFolder = (dir: string, problems: readonly string[]) =>\n new InfraError({\n message: `${dir}/${serverConfigFileName} is not valid:\\n ${problems.join('\\n ')}`,\n });\n\n/**\n * The root's file names, in the folder. When the config does not decode, readServerConfig says why,\n * so the defaults stand in until then.\n */\nconst caNames = (dir: string, text: string) =>\n Schema.decodeUnknownEffect(ServerConfigFileJson)(text).pipe(\n Effect.map((file): ServerConfigFile['ca'] => file.ca),\n Effect.orElseSucceed((): ServerConfigFile['ca'] => ({ cert: 'ca.crt', key: 'ca.key' })),\n Effect.filterOrFail(\n (ca) => caPathProblems(dir, ca).length === 0,\n (ca) => invalidFolder(dir, caPathProblems(dir, ca)),\n ),\n Effect.map((ca) => ({\n cert: caFile(dir, ca.cert).slice(dir.length + 1),\n key: caFile(dir, ca.key).slice(dir.length + 1),\n })),\n );\n\n/**\n * The root's problems, and when its name constraints leave out a dev domain, how to make one that\n * covers them all: constraints are signed into the certificate, so the root cannot be extended.\n */\nconst rootCoverage = (config: ServerConfig, deploy: DeployConfig): readonly string[] => {\n const problems = rootProblems({\n cert: config.ca.cert,\n domains: config.domains,\n key: Redacted.value(config.ca.key),\n });\n return problems.some((problem) => problem.includes('do not cover'))\n ? [\n ...problems,\n `to sign for every domain in domains, make a new root with wt-tunnel ca create --force, deploy, then trust the new root on each device from https://${deploy.authHost}/ca`,\n ]\n : problems;\n};\n\n/** Everything wrong with a decoded config and its folder, beyond the schema. */\nconst folderProblems = (input: {\n readonly config: ServerConfig;\n readonly deploy: DeployConfig;\n readonly files: readonly ServerFile[];\n readonly keyName: string;\n}) => [\n ...rootCoverage(input.config, input.deploy),\n // DNS records go to the deploy file's names, so its authHost is the one a zone must cover.\n ...uncoveredNames({ ...input.config, ...input.deploy }),\n ...authHostProblems(input.config),\n ...authHostMismatch(input.config, input.deploy),\n ...fileProblems(input.keyName, input.files),\n];\n\n/**\n * Checks a server folder, on disk or not yet written, before anything is deployed: the config\n * decodes with the server's own schema, its root files are in the folder and hold PEM, the root\n * covers every domain and matches its key, every DNS name sits in a zone, the sign-in host is\n * outside the dev domains, and the secret files are private. Every problem is reported at once.\n */\nconst checkServerFiles = (input: {\n readonly deploy: DeployConfig;\n readonly dir: string;\n readonly files: readonly ServerFile[];\n}) =>\n Effect.gen(function* check() {\n const configFile = input.files.find((file) => file.name === serverConfigFileName);\n if (configFile === undefined) {\n return yield* invalidFolder(input.dir, ['it is missing']);\n }\n const names = yield* caNames(input.dir, textOf(configFile));\n const config = yield* readServerConfig({\n dir: input.dir,\n read: reader(input.dir, input.files),\n source: `${input.dir}/${serverConfigFileName}`,\n text: textOf(configFile),\n }).pipe(\n Effect.mapError(({ message }: { readonly message: string }) => new InfraError({ message })),\n );\n const problems = folderProblems({ ...input, config, keyName: names.key });\n if (problems.length > 0) {\n return yield* invalidFolder(input.dir, problems);\n }\n const checked: ServerDir = {\n config,\n dir: input.dir,\n files: input.files,\n unreferenced: input.files\n .map(({ name }) => name)\n .filter((name) => ![serverConfigFileName, names.cert, names.key].includes(name)),\n };\n return checked;\n });\n\n/** Whether the folder holds a server config yet. */\nconst hasServerConfig = (dir: string) =>\n FileSystem.FileSystem.use((fs) => fs.exists(`${dir}/${serverConfigFileName}`)).pipe(\n Effect.orElseSucceed(() => false),\n );\n\n/** One file of the folder. Anything that is not a file fails. */\nconst readServerFile = (dir: string, name: string) =>\n Effect.gen(function* readFile() {\n const fs = yield* FileSystem.FileSystem;\n const file = (yield* Path.Path).join(dir, name);\n const info = yield* fs.stat(file).pipe(failWith(`cannot read ${file}`));\n if (info.type !== 'File') {\n return yield* new InfraError({\n message: `${file} is not a file; the server folder holds only files, uploaded as they are`,\n });\n }\n const content = yield* fs.readFile(file).pipe(failWith(`cannot read ${file}`));\n const read: ServerFile = {\n base64: Buffer.from(content).toString('base64'),\n mode: info.mode & permissionBits,\n name,\n };\n return read;\n });\n\n/** Reads and checks the server folder on disk. */\nconst readServerDir = (dir: string, deploy: DeployConfig) =>\n FileSystem.FileSystem.use((fs) => fs.readDirectory(dir)).pipe(\n failWith(`cannot read the server folder ${dir}`),\n Effect.flatMap((names: readonly string[]) =>\n Effect.forEach(names.toSorted(), (name) => readServerFile(dir, name)),\n ),\n Effect.flatMap((files: readonly ServerFile[]) => checkServerFiles({ deploy, dir, files })),\n );\n\n/** The config sorts last, so a run that stops halfway leaves no config and the next drafts again. */\nconst configLast = (left: ServerFile, right: ServerFile) =>\n Number(left.name === serverConfigFileName) - Number(right.name === serverConfigFileName);\n\n/** Writes a drafted folder: private, each file with its mode, the config last. Never overwrites. */\nconst writeServerDir = (dir: string, files: readonly ServerFile[]) =>\n Effect.gen(function* write() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n yield* fs.makeDirectory(dir, { mode: folderMode, recursive: true }).pipe(Effect.orDie);\n yield* fs.chmod(dir, folderMode).pipe(Effect.orDie);\n for (const file of files.toSorted(configLast)) {\n const target = path.join(dir, file.name);\n if (!(yield* fs.exists(target).pipe(Effect.orDie))) {\n yield* fs\n .writeFile(target, Buffer.from(file.base64, 'base64'), { flag: 'wx', mode: file.mode })\n .pipe(Effect.orDie);\n }\n }\n });\n\nexport {\n checkServerFiles,\n folderMode,\n hasServerConfig,\n publicMode,\n readServerDir,\n secretMode,\n serverFile,\n textOf,\n writeServerDir,\n};\nexport type { ServerDir, ServerFile };\n"],"mappings":";;;;;;AAkBA,MAAM,eAAe;AACrB,MAAM,iBAAiB;AAqBvB,MAAM,UAAU,EAAE,aAAyB,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,SAAS,MAAM;;AAGxF,MAAM,cAAc,MAAc,MAAc,UAA8B;CAC5E,QAAQ,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,QAAQ;CAC3C;CACA;AACF;;AAGA,MAAM,UAAU,KAAa,WAAkC,SAAiB;CAC9E,MAAM,QAAQ,MAAM,MAAM,cAAc,GAAG,IAAI,GAAG,UAAU,WAAW,IAAI;CAC3E,OAAO,UAAU,KAAA,IAAY,OAAO,KAAK,SAAS,IAAI,OAAO,QAAQ,OAAO,KAAK,CAAC;AACpF;;AAGA,MAAM,oBAAoB,WACxB,OAAO,QACJ,QAAQ,WAAW,OAAO,aAAa,UAAU,OAAO,SAAS,SAAS,IAAI,QAAQ,CAAC,CAAC,CACxF,KACE,WACC,YAAY,OAAO,SAAS,6BAA6B,OAAO,wEACpE;;AAGJ,MAAM,oBAAoB,QAAsB,WAC9C,OAAO,aAAa,OAAO,WACvB,CAAC,IACD,CACE,eAAe,O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D,SAAS,iCAAiC,KAAK,GAC/C,OAAO,SAAS,UACd,OAAO,QAAQ,MAAM,SAAS,IAAI,SAAS,eAAe,KAAK,IAAI,CAAC,CACtE,GACA,OAAO,SAAS,UAAiC,iBAAiB;CAAE;CAAQ;CAAK;AAAM,CAAC,CAAC,CAC3F;;AAGF,MAAM,cAAc,MAAkB,UACpC,OAAO,KAAK,SAAS,oBAAoB,IAAI,OAAO,MAAM,SAAS,oBAAoB;;AAGzF,MAAM,kBAAkB,KAAa,UACnC,OAAO,IAAI,UAAU,QAAQ;CAC3B,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,OAAO,GAAG,cAAc,KAAK;EAAE,MAAA;EAAkB,WAAW;CAAK,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK;CACrF,OAAO,GAAG,MAAM,KAAA,GAAe,CAAC,CAAC,KAAK,OAAO,KAAK;CAClD,KAAK,MAAM,QAAQ,MAAM,SAAS,UAAU,GAAG;EAC7C,MAAM,SAAS,KAAK,KAAK,KAAK,KAAK,IAAI;EACvC,IAAI,EAAE,OAAO,GAAG,OAAO,MAAM,CAAC,CAAC,KAAK,OAAO,KAAK,IAC9C,OAAO,GACJ,UAAU,QAAQ,OAAO,KAAK,KAAK,QAAQ,QAAQ,GAAG;GAAE,MAAM;GAAM,MAAM,KAAK;EAAK,CAAC,CAAC,CACtF,KAAK,OAAO,KAAK;CAExB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-machine.js","names":["providerLayer"],"sources":["../src/server-machine.ts"],"sourcesContent":["import { deploymentPolicy } from '@alchemy.run/fly/Deployment';\nimport { MachineProvider } from '@alchemy.run/fly/Machine';\nimport type { Machine, MachineProps } from '@alchemy.run/fly/Machine';\nimport { createFlyResourceName, sanitizeFlyAppName } from '@alchemy.run/fly/Metadata';\nimport type { Providers } from '@alchemy.run/fly/Providers';\nimport { reconcileReplicas, sameServices, toFlyService } from '@alchemy.run/fly/replicas';\nimport type { ReconcileReplicasInput } from '@alchemy.run/fly/replicas';\nimport { deepEqual } from 'alchemy/Diff';\nimport { Provider, effect as providerLayer } from 'alchemy/Provider';\nimport { Resource } from 'alchemy/Resource';\nimport { Effect } from 'effect';\n\ntype FlyMachine = Parameters<ReconcileReplicasInput['configDrifted']>[0];\ntype FlyMachineConfig = ReturnType<ReconcileReplicasInput['buildConfig']>;\n\n/** A file Fly writes into the Machine at boot, from the base64 value of an app secret. */\ninterface MachineFile {\n readonly guestPath: string;\n readonly mode: number;\n readonly secretName: string;\n}\n\n/** What Alchemy's Machine assumes for what its props leave out. */\nconst alchemyDefaults = {\n memoryMb: 256,\n region: 'iad',\n restart: { max_retries: 10, policy: 'on-failure' },\n} as const;\n\ntype ServerMachineProps = Extract<MachineProps, { readonly image: string }> & {\n readonly files: readonly MachineFile[];\n};\n\ntype ServerMachine = Resource<\n 'Fly.Machine',\n ServerMachineProps,\n Machine['Attributes'],\n never,\n Providers\n>;\n\n/**\n * Alchemy's Fly.Machine with `files`, which Alchemy's own Machine lacks. It keeps the Fly.Machine\n * type, so the state of a Machine deployed before carries over and an update changes it in place.\n * Its provider takes Alchemy's for this stack, because a provider registered on its own wins over\n * one in a collection. Read, diff, list and delete are Alchemy's; only reconcile differs: it sends\n * the files and treats a change to them as drift.\n */\nconst ServerMachine = Resource<ServerMachine>('Fly.Machine');\n\nconst flyFiles = (files: readonly MachineFile[]) =>\n files.map((file) => ({\n guest_path: file.guestPath,\n mode: file.mode,\n secret_name: file.secretName,\n }));\n\nconst fileKey = (file: { guest_path?: string; mode?: number; secret_name?: string }) =>\n `${file.guest_path ?? ''}:${String(file.mode ?? '')}:${file.secret_name ?? ''}`;\n\nconst sameFiles = (observed: FlyMachineConfig['files'], desired: FlyMachineConfig['files']) =>\n deepEqual(\n (observed ?? []).map((file) => fileKey(file)).toSorted(),\n (desired ?? []).map((file) => fileKey(file)).toSorted(),\n );\n\nconst appNameOf = (app: unknown) =>\n typeof app === 'object' && app !== null && 'appName' in app && typeof app.appName === 'string'\n ? app.appName\n : undefined;\n\n/** The Machine config for one replica, the way Alchemy's Machine builds it, plus the files. */\nconst desiredConfig = (\n props: Pick<\n ServerMachineProps,\n 'env' | 'files' | 'guest' | 'image' | 'init' | 'metadata' | 'restart' | 'services'\n >,\n metadata: Record<string, string>,\n): FlyMachineConfig => ({\n ...(props.env === undefined ? {} : { env: props.env }),\n files: flyFiles(props.files),\n guest: {\n cpu_kind: props.guest?.cpuKind ?? 'shared',\n cpus: props.guest?.cpus ?? 1,\n memory_mb: props.guest?.memoryMb ?? alchemyDefaults.memoryMb,\n },\n image: props.image,\n ...(props.init?.cmd === undefined ? {} : { init: { cmd: props.init.cmd } }),\n metadata: { ...props.metadata, ...metadata },\n ...(props.restart?.policy === undefined ? {} : { restart: { policy: props.restart.policy } }),\n ...(props.services === undefined ? {} : { services: props.services.map(toFlyService) }),\n});\n\n/** The repository and tag of an image reference, as Fly reports them in `image_ref`. */\nconst imageParts = (image: string) => {\n const colon = image.lastIndexOf(':');\n return colon > image.lastIndexOf('/')\n ? { repository: image.slice(0, colon), tag: image.slice(colon + 1) }\n : { repository: image, tag: 'latest' };\n};\n\n/** Fly may report the image resolved to a digest; Alchemy then compares the repository and tag. */\nconst sameImage = (machine: FlyMachine, image: string) => {\n const { repository, tag } = imageParts(image);\n const observed = machine.image_ref?.repository ?? '';\n return (\n machine.config?.image === image ||\n (machine.image_ref?.tag === tag &&\n (observed === repository || observed.endsWith(`/${repository}`)))\n );\n};\n\n/** Drops the keys whose value is null or undefined. */\nconst compact = (record: object | null | undefined): Record<string, unknown> =>\n Object.fromEntries(\n Object.entries(record ?? {}).filter(([, value]) => value !== null && value !== undefined),\n );\n\nconst guestOf = (guest: FlyMachineConfig['guest']) => ({\n cpu_kind: guest?.cpu_kind,\n cpus: guest?.cpus,\n memory_mb: guest?.memory_mb,\n});\n\nconst restartOf = (restart: FlyMachineConfig['restart']) => ({\n ...alchemyDefaults.restart,\n ...compact(restart),\n});\n\n/**\n * Whether the running Machine differs from the props, as Alchemy's Machine judges it, or in its\n * files.\n */\nconst drifted = (machine: FlyMachine, desired: FlyMachineConfig) => {\n const config = machine.config ?? {};\n const same = [\n sameImage(machine, desired.image ?? ''),\n deepEqual(guestOf(config.guest), guestOf(desired.guest)),\n deepEqual(compact(config.env), desired.env ?? {}),\n sameServices(config.services, desired.services),\n deepEqual(restartOf(config.restart), restartOf(desired.restart)),\n deepEqual(config.init ?? {}, desired.init ?? {}, { stripNullish: true }),\n sameFiles(config.files, desired.files),\n Object.entries(desired.metadata ?? {}).every(\n ([key, value]) => config.metadata?.[key] === value,\n ),\n ];\n return same.includes(false);\n};\n\n/** The Machine's name: the props', else the one it has, else one Alchemy makes up. */\nconst baseNameOf = (\n id: string,\n name: string | undefined,\n output: Machine['Attributes'] | undefined,\n) =>\n name === undefined\n ? Effect.succeed(output?.baseName ?? output?.name).pipe(\n Effect.flatMap((existing) =>\n existing === undefined ? createFlyResourceName(id) : Effect.succeed(existing),\n ),\n )\n : Effect.succeed(sanitizeFlyAppName(name));\n\nconst reconcile = Effect.fn(function* reconcileServerMachine({\n fqn,\n id,\n instanceId,\n news,\n output,\n}: {\n readonly fqn: string;\n readonly id: string;\n readonly instanceId: string;\n readonly news: ServerMachineProps;\n readonly output: Machine['Attributes'] | undefined;\n}) {\n const set = yield* reconcileReplicas({\n appName: appNameOf(news.app) ?? output?.appName ?? '',\n baseName: yield* baseNameOf(id, news.name, output),\n buildConfig: ({ metadata }) => desiredConfig(news, metadata),\n configDrifted: (machine, { metadata }) => drifted(machine, desiredConfig(news, metadata)),\n count: 1,\n disks: [],\n fqn,\n id,\n outputMachineIds: output?.machineIds ?? [],\n policy: yield* deploymentPolicy(news.deploy, news.shutdown),\n regions: [news.region ?? alchemyDefaults.region],\n resourceInstanceId: instanceId,\n type: 'Fly.Machine',\n });\n const { regions: _regions, services: _services, ...attributes } = set;\n return attributes;\n});\n\n/** Alchemy's own Machine provider, whose read, diff, list and delete this one keeps. */\nconst alchemyMachineProvider = Effect.gen(function* alchemyMachine() {\n return yield* Provider<Machine>('Fly.Machine');\n}).pipe(Effect.provide(MachineProvider()));\n\nconst serverMachineProvider = () =>\n providerLayer(\n ServerMachine,\n Effect.gen(function* serverMachine() {\n const alchemy = yield* alchemyMachineProvider;\n const missing = Effect.die(\"Alchemy's Fly.Machine provider lacks an operation\");\n return {\n delete: (input: Parameters<typeof alchemy.delete>[0]) => alchemy.delete(input),\n diff: (input: Parameters<NonNullable<typeof alchemy.diff>>[0]) =>\n alchemy.diff === undefined ? missing : alchemy.diff(input),\n list: () => (alchemy.list === undefined ? missing : alchemy.list()),\n read: (input: Parameters<NonNullable<typeof alchemy.read>>[0]) =>\n alchemy.read === undefined ? missing : alchemy.read(input),\n reconcile,\n ...(alchemy.stables === undefined ? {} : { stables: alchemy.stables }),\n };\n }),\n );\n\nexport { ServerMachine, desiredConfig, drifted, serverMachineProvider };\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,kBAAkB;CACtB,UAAU;CACV,QAAQ;CACR,SAAS;EAAE,aAAa;EAAI,QAAQ;CAAa;AACnD;;;;;;;;AAqBA,MAAM,gBAAgB,SAAwB,aAAa;AAE3D,MAAM,YAAY,UAChB,MAAM,KAAK,UAAU;CACnB,YAAY,KAAK;CACjB,MAAM,KAAK;CACX,aAAa,KAAK;AACpB,EAAE;AAEJ,MAAM,WAAW,SACf,GAAG,KAAK,cAAc,GAAG,GAAG,OAAO,KAAK,QAAQ,EAAE,EAAE,GAAG,KAAK,eAAe;AAE7E,MAAM,aAAa,UAAqC,YACtD,WACG,YAAY,CAAC,EAAA,CAAG,KAAK,SAAS,QAAQ,IAAI,CAAC,CAAC,CAAC,SAAS,IACtD,WAAW,CAAC,EAAA,CAAG,KAAK,SAAS,QAAQ,IAAI,CAAC,CAAC,CAAC,SAAS,CACxD;AAEF,MAAM,aAAa,QACjB,OAAO,QAAQ,YAAY,QAAQ,QAAQ,aAAa,OAAO,OAAO,IAAI,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ACnD,UAAU,OAAO,WAAW,IAAI,KAAK,MAAM,MAAM;EACjD,cAAc,EAAE,eAAe,cAAc,MAAM,QAAQ;EAC3D,gBAAgB,SAAS,EAAE,eAAe,QAAQ,SAAS,cAAc,MAAM,QAAQ,CAAC;EACxF,OAAO;EACP,OAAO,CAAC;EACR;EACA;EACA,kBAAkB,QAAQ,cAAc,CAAC;EACzC,QAAQ,OAAO,iBAAiB,KAAK,QAAQ,KAAK,QAAQ;EAC1D,SAAS,CAAC,KAAK,UAAU,gBAAgB,MAAM;EAC/C,oBAAoB;EACpB,MAAM;CACR,CAAC;CAED,OAAO;AACT,CAAC;;AAGD,MAAM,yBAAyB,OAAO,IAAI,UAAU,iBAAiB;CACnE,OAAO,OAAO,SAAkB,aAAa;AAC/C,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,gBAAgB,CAAC,CAAC;AAEzC,MAAM,8BACJA,OACE,eACA,OAAO,IAAI,UAAU,gBAAgB;CACnC,MAAM,UAAU,OAAO;CACvB,MAAM,UAAU,OAAO,IAAI,mDAAmD;CAC9E,OAAO;EACL,SAAS,UAAgD,QAAQ,OAAO,KAAK;EAC7E,OAAO,UACL,QAAQ,SAAS,KAAA,IAAY,UAAU,QAAQ,KAAK,KAAK;EAC3D,YAAa,QAAQ,SAAS,KAAA,IAAY,UAAU,QAAQ,KAAK;EACjE,OAAO,UACL,QAAQ,SAAS,KAAA,IAAY,UAAU,QAAQ,KAAK,KAAK;EAC3D;EACA,GAAI,QAAQ,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;CACtE;AACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"server-machine.js","names":["providerLayer"],"sources":["../src/server-machine.ts"],"sourcesContent":["// fallow-ignore-file coverage-gaps -- ServerMachine and serverMachineProvider run only in the Alchemy stack (stack.ts), against Fly's API; server-machine.test.ts tests desiredConfig and drifted, which they use\nimport { deploymentPolicy } from '@alchemy.run/fly/Deployment';\nimport { MachineProvider } from '@alchemy.run/fly/Machine';\nimport type { Machine, MachineProps } from '@alchemy.run/fly/Machine';\nimport { createFlyResourceName, sanitizeFlyAppName } from '@alchemy.run/fly/Metadata';\nimport type { Providers } from '@alchemy.run/fly/Providers';\nimport { reconcileReplicas, sameServices, toFlyService } from '@alchemy.run/fly/replicas';\nimport type { ReconcileReplicasInput } from '@alchemy.run/fly/replicas';\nimport { deepEqual } from 'alchemy/Diff';\nimport { Provider, effect as providerLayer } from 'alchemy/Provider';\nimport { Resource } from 'alchemy/Resource';\nimport { Effect } from 'effect';\n\ntype FlyMachine = Parameters<ReconcileReplicasInput['configDrifted']>[0];\ntype FlyMachineConfig = ReturnType<ReconcileReplicasInput['buildConfig']>;\n\n/** A file Fly writes into the Machine at boot, from the base64 value of an app secret. */\ninterface MachineFile {\n readonly guestPath: string;\n readonly mode: number;\n readonly secretName: string;\n}\n\n/** What Alchemy's Machine assumes for what its props leave out. */\nconst alchemyDefaults = {\n memoryMb: 256,\n region: 'iad',\n restart: { max_retries: 10, policy: 'on-failure' },\n} as const;\n\ntype ServerMachineProps = Extract<MachineProps, { readonly image: string }> & {\n readonly files: readonly MachineFile[];\n};\n\ntype ServerMachine = Resource<\n 'Fly.Machine',\n ServerMachineProps,\n Machine['Attributes'],\n never,\n Providers\n>;\n\n/**\n * Alchemy's Fly.Machine with `files`, which Alchemy's own Machine lacks. It keeps the Fly.Machine\n * type, so the state of a Machine deployed before carries over and an update changes it in place.\n * Its provider takes Alchemy's for this stack, because a provider registered on its own wins over\n * one in a collection. Read, diff, list and delete are Alchemy's; only reconcile differs: it sends\n * the files and treats a change to them as drift.\n */\nconst ServerMachine = Resource<ServerMachine>('Fly.Machine');\n\nconst flyFiles = (files: readonly MachineFile[]) =>\n files.map((file) => ({\n guest_path: file.guestPath,\n mode: file.mode,\n secret_name: file.secretName,\n }));\n\nconst fileKey = (file: { guest_path?: string; mode?: number; secret_name?: string }) =>\n `${file.guest_path ?? ''}:${String(file.mode ?? '')}:${file.secret_name ?? ''}`;\n\nconst sameFiles = (observed: FlyMachineConfig['files'], desired: FlyMachineConfig['files']) =>\n deepEqual(\n (observed ?? []).map((file) => fileKey(file)).toSorted(),\n (desired ?? []).map((file) => fileKey(file)).toSorted(),\n );\n\nconst appNameOf = (app: unknown) =>\n typeof app === 'object' && app !== null && 'appName' in app && typeof app.appName === 'string'\n ? app.appName\n : undefined;\n\n/** The Machine config for one replica, the way Alchemy's Machine builds it, plus the files. */\nconst desiredConfig = (\n props: Pick<\n ServerMachineProps,\n 'env' | 'files' | 'guest' | 'image' | 'init' | 'metadata' | 'restart' | 'services'\n >,\n metadata: Record<string, string>,\n): FlyMachineConfig => ({\n ...(props.env === undefined ? {} : { env: props.env }),\n files: flyFiles(props.files),\n guest: {\n cpu_kind: props.guest?.cpuKind ?? 'shared',\n cpus: props.guest?.cpus ?? 1,\n memory_mb: props.guest?.memoryMb ?? alchemyDefaults.memoryMb,\n },\n image: props.image,\n ...(props.init?.cmd === undefined ? {} : { init: { cmd: props.init.cmd } }),\n metadata: { ...props.metadata, ...metadata },\n ...(props.restart?.policy === undefined ? {} : { restart: { policy: props.restart.policy } }),\n ...(props.services === undefined ? {} : { services: props.services.map(toFlyService) }),\n});\n\n/** The repository and tag of an image reference, as Fly reports them in `image_ref`. */\nconst imageParts = (image: string) => {\n const colon = image.lastIndexOf(':');\n return colon > image.lastIndexOf('/')\n ? { repository: image.slice(0, colon), tag: image.slice(colon + 1) }\n : { repository: image, tag: 'latest' };\n};\n\n/** Fly may report the image resolved to a digest; Alchemy then compares the repository and tag. */\nconst sameImage = (machine: FlyMachine, image: string) => {\n const { repository, tag } = imageParts(image);\n const observed = machine.image_ref?.repository ?? '';\n return (\n machine.config?.image === image ||\n (machine.image_ref?.tag === tag &&\n (observed === repository || observed.endsWith(`/${repository}`)))\n );\n};\n\n/** Drops the keys whose value is null or undefined. */\nconst compact = (record: object | null | undefined): Record<string, unknown> =>\n Object.fromEntries(\n Object.entries(record ?? {}).filter(([, value]) => value !== null && value !== undefined),\n );\n\nconst guestOf = (guest: FlyMachineConfig['guest']) => ({\n cpu_kind: guest?.cpu_kind,\n cpus: guest?.cpus,\n memory_mb: guest?.memory_mb,\n});\n\nconst restartOf = (restart: FlyMachineConfig['restart']) => ({\n ...alchemyDefaults.restart,\n ...compact(restart),\n});\n\n/**\n * Whether the running Machine differs from the props, as Alchemy's Machine judges it, or in its\n * files.\n */\nconst drifted = (machine: FlyMachine, desired: FlyMachineConfig) => {\n const config = machine.config ?? {};\n const same = [\n sameImage(machine, desired.image ?? ''),\n deepEqual(guestOf(config.guest), guestOf(desired.guest)),\n deepEqual(compact(config.env), desired.env ?? {}),\n sameServices(config.services, desired.services),\n deepEqual(restartOf(config.restart), restartOf(desired.restart)),\n deepEqual(config.init ?? {}, desired.init ?? {}, { stripNullish: true }),\n sameFiles(config.files, desired.files),\n Object.entries(desired.metadata ?? {}).every(\n ([key, value]) => config.metadata?.[key] === value,\n ),\n ];\n return same.includes(false);\n};\n\n/** The Machine's name: the props', else the one it has, else one Alchemy makes up. */\nconst baseNameOf = (\n id: string,\n name: string | undefined,\n output: Machine['Attributes'] | undefined,\n) =>\n name === undefined\n ? Effect.succeed(output?.baseName ?? output?.name).pipe(\n Effect.flatMap((existing) =>\n existing === undefined ? createFlyResourceName(id) : Effect.succeed(existing),\n ),\n )\n : Effect.succeed(sanitizeFlyAppName(name));\n\nconst reconcile = Effect.fn(function* reconcileServerMachine({\n fqn,\n id,\n instanceId,\n news,\n output,\n}: {\n readonly fqn: string;\n readonly id: string;\n readonly instanceId: string;\n readonly news: ServerMachineProps;\n readonly output: Machine['Attributes'] | undefined;\n}) {\n const set = yield* reconcileReplicas({\n appName: appNameOf(news.app) ?? output?.appName ?? '',\n baseName: yield* baseNameOf(id, news.name, output),\n buildConfig: ({ metadata }) => desiredConfig(news, metadata),\n configDrifted: (machine, { metadata }) => drifted(machine, desiredConfig(news, metadata)),\n count: 1,\n disks: [],\n fqn,\n id,\n outputMachineIds: output?.machineIds ?? [],\n policy: yield* deploymentPolicy(news.deploy, news.shutdown),\n regions: [news.region ?? alchemyDefaults.region],\n resourceInstanceId: instanceId,\n type: 'Fly.Machine',\n });\n const { regions: _regions, services: _services, ...attributes } = set;\n return attributes;\n});\n\n/** Alchemy's own Machine provider, whose read, diff, list and delete this one keeps. */\nconst alchemyMachineProvider = Effect.gen(function* alchemyMachine() {\n return yield* Provider<Machine>('Fly.Machine');\n}).pipe(Effect.provide(MachineProvider()));\n\nconst serverMachineProvider = () =>\n providerLayer(\n ServerMachine,\n Effect.gen(function* serverMachine() {\n const alchemy = yield* alchemyMachineProvider;\n const missing = Effect.die(\"Alchemy's Fly.Machine provider lacks an operation\");\n return {\n delete: (input: Parameters<typeof alchemy.delete>[0]) => alchemy.delete(input),\n diff: (input: Parameters<NonNullable<typeof alchemy.diff>>[0]) =>\n alchemy.diff === undefined ? missing : alchemy.diff(input),\n list: () => (alchemy.list === undefined ? missing : alchemy.list()),\n read: (input: Parameters<NonNullable<typeof alchemy.read>>[0]) =>\n alchemy.read === undefined ? missing : alchemy.read(input),\n reconcile,\n ...(alchemy.stables === undefined ? {} : { stables: alchemy.stables }),\n };\n }),\n );\n\nexport { ServerMachine, desiredConfig, drifted, serverMachineProvider };\n"],"mappings":";;;;;;;;;;AAwBA,MAAM,kBAAkB;CACtB,UAAU;CACV,QAAQ;CACR,SAAS;EAAE,aAAa;EAAI,QAAQ;CAAa;AACnD;;;;;;;;AAqBA,MAAM,gBAAgB,SAAwB,aAAa;AAE3D,MAAM,YAAY,UAChB,MAAM,KAAK,UAAU;CACnB,YAAY,KAAK;CACjB,MAAM,KAAK;CACX,aAAa,KAAK;AACpB,EAAE;AAEJ,MAAM,WAAW,SACf,GAAG,KAAK,cAAc,GAAG,GAAG,OAAO,KAAK,QAAQ,EAAE,EAAE,GAAG,KAAK,eAAe;AAE7E,MAAM,aAAa,UAAqC,YACtD,WACG,YAAY,CAAC,EAAA,CAAG,KAAK,SAAS,QAAQ,IAAI,CAA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5 @@
|
|
|
1
1
|
import { tunnelPort } from "./packages/contract/src/index.js";
|
|
2
|
-
import { DeploymentJson, deploymentEnv, placeHosts, serverFilesEnv } from "./deployment.js";
|
|
2
|
+
import { DeploymentJson, cloudflareStateOptions, deploymentEnv, placeHosts, serverFilesEnv } from "./deployment.js";
|
|
3
3
|
import { UploadsJson, machineFileOf, serverArgs } from "./uploads.js";
|
|
4
4
|
import { ServerMachine, serverMachineProvider } from "./server-machine.js";
|
|
5
5
|
import { Effect, Layer, Redacted, Schema } from "effect";
|
|
@@ -44,7 +44,7 @@ const createRecords = (provider, host, ips) => recordCreators[provider](host, ip
|
|
|
44
44
|
const flyWithServerMachine = serverMachineProvider().pipe(Layer.provideMerge(providers$1()));
|
|
45
45
|
const stack = Stack(deployment.stack, {
|
|
46
46
|
providers: Layer.mergeAll(flyWithServerMachine, providers()),
|
|
47
|
-
state: deployment.state === "local" ? localState() : state()
|
|
47
|
+
state: deployment.state === "local" ? localState() : state(cloudflareStateOptions(deployment.state))
|
|
48
48
|
}, Effect.gen(function* server() {
|
|
49
49
|
const { fly } = deployment;
|
|
50
50
|
const app = yield* App("App", {
|
package/dist/stack.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stack.js","names":["flyProviders","cloudflareProviders","cloudflareState","mapOutput"],"sources":["../src/stack.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"stack.js","names":["flyProviders","cloudflareProviders","cloudflareState","mapOutput"],"sources":["../src/stack.ts"],"sourcesContent":["// fallow-ignore-file coverage-gaps -- Alchemy imports it in its own process during plan and deploy; no test runs the stack against Fly or Cloudflare, and alchemy.test.ts checks that its Alchemy modules load\nimport {\n DNS,\n providers as cloudflareProviders,\n state as cloudflareState,\n} from '@alchemy.run/cloudflare';\nimport { App, IpAssignment, Secret, providers as flyProviders } from '@alchemy.run/fly';\nimport { tunnelPort } from '@tafrahq/wt-tunnel-contract';\nimport { Stack } from 'alchemy';\nimport type { Output } from 'alchemy';\nimport { map as mapOutput } from 'alchemy/Output';\nimport { localState } from 'alchemy/State';\nimport { Effect, Layer, Redacted, Schema } from 'effect';\n\nimport {\n DeploymentJson,\n cloudflareStateOptions,\n deploymentEnv,\n placeHosts,\n serverFilesEnv,\n} from './deployment.ts';\nimport type { DnsZone, PlacedHost } from './deployment.ts';\nimport { ServerMachine, serverMachineProvider } from './server-machine.ts';\nimport { UploadsJson, machineFileOf, serverArgs } from './uploads.ts';\n\n/*\n * The alchemy process imports this file; wt-tunnel puts the checked deployment and the server\n * folder's files in its environment. The stack name and the state store must be known when the\n * module loads.\n */\nconst deployment = await Effect.runPromise(\n Schema.decodeUnknownEffect(DeploymentJson)(process.env[deploymentEnv]),\n);\nconst uploads = await Effect.runPromise(\n Schema.decodeUnknownEffect(UploadsJson)(process.env[serverFilesEnv]),\n);\n\n/** Raw TCP on every port: Caddy and frps terminate TLS themselves, with the deployment's CA. */\nconst tcpPassthrough = (port: number) => ({\n autostop: 'off' as const,\n internalPort: port,\n ports: [{ port }],\n protocol: 'tcp',\n});\n\nconst httpsPort = 443;\nconst httpPort = 80;\nconst publicPorts = [httpsPort, httpPort, tunnelPort];\n\ninterface Ips {\n readonly ipv4: Output<string>;\n readonly ipv6: Output<string>;\n}\n\ntype ZoneByProvider = { readonly [Zone in DnsZone as Zone['provider']]: Zone };\ntype Provider = keyof ZoneByProvider;\n/** A host whose zone belongs to the provider `Name`. */\ntype HostIn<Name extends Provider> = PlacedHost & { readonly zone: ZoneByProvider[Name] };\n\nconst cloudflareRecords = (host: HostIn<'cloudflare'>, { ipv4, ipv6 }: Ips) =>\n Effect.all(\n (['A', 'AAAA'] as const).map((type) =>\n DNS.Record(`${host.id}-${type}`, {\n content: type === 'A' ? ipv4 : ipv6,\n name: host.name,\n // Unproxied, also for a sign-in host that an earlier version put behind Cloudflare.\n proxied: false,\n ttl: '1',\n type,\n zoneId: host.zone.zoneId,\n }),\n ),\n );\n\ntype CloudflareRecords = ReturnType<typeof cloudflareRecords>;\n\n/**\n * How each DNS provider creates a host's A and AAAA records in its zone. The error and services\n * types are the union of every provider's; a provider besides Cloudflare adds its own to them.\n */\nconst recordCreators: {\n readonly [Name in Provider]: (\n host: HostIn<Name>,\n ips: Ips,\n ) => Effect.Effect<unknown, Effect.Error<CloudflareRecords>, Effect.Services<CloudflareRecords>>;\n} = {\n cloudflare: cloudflareRecords,\n manual: () => Effect.void,\n};\n\nconst createRecords = <Name extends Provider>(provider: Name, host: HostIn<Name>, ips: Ips) =>\n recordCreators[provider](host, ips);\n\n/** Fly's providers, with the server Machine's in place of Alchemy's Machine provider. */\nconst flyWithServerMachine = serverMachineProvider().pipe(Layer.provideMerge(flyProviders()));\n\nconst stack = Stack(\n deployment.stack,\n {\n /*\n * Cloudflare's providers are always present, even with only manual zones and local state: the\n * stack's type needs them, and they read no credentials until a Cloudflare resource is planned.\n */\n providers: Layer.mergeAll(flyWithServerMachine, cloudflareProviders()),\n state:\n deployment.state === 'local'\n ? localState()\n : cloudflareState(cloudflareStateOptions(deployment.state)),\n },\n Effect.gen(function* server() {\n const { fly } = deployment;\n const app = yield* App('App', { name: fly.app, orgSlug: fly.org });\n const ipv4 = yield* IpAssignment('IPv4', { app, region: fly.region, type: 'v4' });\n const ipv6 = yield* IpAssignment('IPv6', { app, region: fly.region, type: 'v6' });\n // One secret per file, so Fly writes each file from it and its content never shows in the Machine config.\n const files = yield* Effect.all(\n uploads.map((upload) => {\n const file = machineFileOf(upload.name);\n return Secret(file.secretName, {\n app,\n name: file.secretName,\n value: Redacted.make(upload.base64),\n }).pipe(Effect.map((secret) => ({ file, secret })));\n }),\n );\n yield* ServerMachine('Server', {\n app,\n /*\n * Fly hands secrets to a Machine only when it starts or updates. Each digest changes with its\n * file's content, so a change to any file rolls the Machine.\n */\n env: Object.fromEntries(\n files.map(({ file, secret }) => [\n `${file.secretName}_DIGEST`,\n mapOutput(secret.digest, (digest) => digest ?? ''),\n ]),\n ),\n files: files.map(({ file }) => file),\n guest: { cpuKind: 'shared', cpus: 1, memoryMb: fly.memoryMb },\n image: deployment.image,\n // Appended to the image's `wt-tunnel-server start` entrypoint, as Docker's CMD would be.\n init: { cmd: serverArgs },\n region: fly.region,\n restart: { policy: 'always' },\n services: publicPorts.map((port) => tcpPassthrough(port)),\n });\n const ips = { ipv4: ipv4.ip, ipv6: ipv6.ip };\n yield* Effect.all(\n placeHosts(deployment).placed.map((host) => createRecords(host.zone.provider, host, ips)),\n );\n return { app: app.appName, ipv4: ipv4.ip, ipv6: ipv6.ip, tunnelHost: deployment.tunnelHost };\n }),\n);\n\nexport default stack;\n"],"mappings":";;;;;;;;;;;AA8BA,MAAM,aAAa,MAAM,OAAO,WAC9B,OAAO,oBAAoB,cAAc,CAAC,CAAC,QAAQ,IAAI,cAAc,CACvE;AACA,MAAM,UAAU,MAAM,OAAO,WAC3B,OAAO,oBAAoB,WAAW,CAAC,CAAC,QAAQ,IAAI,eAAe,CACrE;;AAGA,MAAM,kBAAkB,UAAkB;CACxC,UAAU;CACV,cAAc;CACd,OAAO,CAAC,EAAE,KAAK,CAAC;CAChB,UAAU;AACZ;AAIA,MAAM,cAAc;CAAC;CAAW;CAAU;AAAU;AAYpD,MAAM,qBAAqB,MAA4B,EAAE,MAAM,WAC7D,OAAO,IACJ,CAAC,KAAK,MAAM,CAAC,CAAW,KAAK,SAC5B,IAAI,OAAO,GAAG,KAAK,GAAG,GAAG,QAAQ;CAC/B,SAAS,SAAS,MAAM,OAAO;CAC/B,MAAM,KAAK;CAEX,SAAS;CACT,KAAK;CACL;CACA,QAAQ,KAAK,KAAK;AACpB,CAAC,CACH,CACF;;;;;AAQF,MAAM,iBAKF;CACF,YAAY;CACZ,cAAc,OAAO;AACvB;AAEA,MAAM,iBAAwC,UAAgB,MAAoB,QAChF,eAAe,SAAS,CAAC,MAAM,GAAG;;AAGpC,MAAM,uBAAuB,sBAAsB,CAAC,CAAC,KAAK,MAAM,aAAaA,YAAa,CAAC,CAAC;AAE5F,MAAM,QAAQ,MACZ,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