@tafrahq/wt-tunnel 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +225 -2
- package/dist/alchemy.js +40 -0
- package/dist/alchemy.js.map +1 -0
- package/dist/bin.js +21 -0
- package/dist/bin.js.map +1 -0
- package/dist/ca.js +88 -0
- package/dist/ca.js.map +1 -0
- package/dist/cli.js +182 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.js +81 -0
- package/dist/config.js.map +1 -0
- package/dist/create-root.js +85 -0
- package/dist/create-root.js.map +1 -0
- package/dist/create-server-dir.js +153 -0
- package/dist/create-server-dir.js.map +1 -0
- package/dist/deployment.js +122 -0
- package/dist/deployment.js.map +1 -0
- package/dist/errors.js +7 -0
- package/dist/errors.js.map +1 -0
- package/dist/init.js +89 -0
- package/dist/init.js.map +1 -0
- package/dist/outputs.js +38 -0
- package/dist/outputs.js.map +1 -0
- package/dist/packages/contract/src/index.js +12 -0
- package/dist/packages/contract/src/index.js.map +1 -0
- package/dist/packages/contract/src/root-ca.js +94 -0
- package/dist/packages/contract/src/root-ca.js.map +1 -0
- package/dist/packages/contract/src/server-config.js +99 -0
- package/dist/packages/contract/src/server-config.js.map +1 -0
- package/dist/prepare.js +73 -0
- package/dist/prepare.js.map +1 -0
- package/dist/providers.js +82 -0
- package/dist/providers.js.map +1 -0
- package/dist/secrets.js +39 -0
- package/dist/secrets.js.map +1 -0
- package/dist/server-dir.js +141 -0
- package/dist/server-dir.js.map +1 -0
- package/dist/server-machine.js +136 -0
- package/dist/server-machine.js.map +1 -0
- package/dist/stack.js +104 -0
- package/dist/stack.js.map +1 -0
- package/dist/uploads.js +24 -0
- package/dist/uploads.js.map +1 -0
- package/package.json +59 -3
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { InfraError } from "./errors.js";
|
|
2
|
+
import { deploymentEnv, providerEnv, serverFilesEnv } from "./deployment.js";
|
|
3
|
+
import { Effect } from "effect";
|
|
4
|
+
// src/secrets.ts
|
|
5
|
+
/**
|
|
6
|
+
* The variables every run needs. The server's own secrets live in the server folder; the
|
|
7
|
+
* environment supplies them only when `deploy` creates it.
|
|
8
|
+
*/
|
|
9
|
+
const requiredEnv = (deployment) => ["FLY_API_TOKEN", ...providerEnv(deployment)];
|
|
10
|
+
/** Alchemy reads the state store's account from CLOUDFLARE_ACCOUNT_ID; the deploy file names it. */
|
|
11
|
+
const stateAccountEnv = ({ state }) => state === "local" ? {} : { CLOUDFLARE_ACCOUNT_ID: state.accountId };
|
|
12
|
+
/** The variables `env` lacks, once the CLI has added what the deploy file supplies. */
|
|
13
|
+
const missingEnv = (deployment, env) => {
|
|
14
|
+
const full = {
|
|
15
|
+
...env,
|
|
16
|
+
...stateAccountEnv(deployment)
|
|
17
|
+
};
|
|
18
|
+
return requiredEnv(deployment).filter((name) => (full[name] ?? "") === "");
|
|
19
|
+
};
|
|
20
|
+
const checkEnv = (deployment, env) => {
|
|
21
|
+
const missing = missingEnv(deployment, env);
|
|
22
|
+
return missing.length === 0 ? Effect.void : Effect.fail(new InfraError({ message: `set ${missing.join(", ")} in the environment (\`wt-tunnel init\` explains each)` }));
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* The environment for the alchemy process: the caller's, plus the state account, the deployment and
|
|
26
|
+
* the server folder's files.
|
|
27
|
+
*/
|
|
28
|
+
const stackEnv = (deployment, files, env) => ({
|
|
29
|
+
...env,
|
|
30
|
+
...stateAccountEnv(deployment),
|
|
31
|
+
[deploymentEnv]: JSON.stringify(deployment),
|
|
32
|
+
[serverFilesEnv]: JSON.stringify(files.map(({ base64, name }) => ({
|
|
33
|
+
base64,
|
|
34
|
+
name
|
|
35
|
+
})))
|
|
36
|
+
});
|
|
37
|
+
export { checkEnv, missingEnv, stackEnv };
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=secrets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"secrets.js","names":[],"sources":["../src/secrets.ts"],"sourcesContent":["import { Effect } from 'effect';\n\nimport { deploymentEnv, providerEnv, serverFilesEnv } from './deployment.ts';\nimport type { Deployment } from './deployment.ts';\nimport { InfraError } from './errors.ts';\nimport type { ServerFile } from './server-dir.ts';\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/**\n * The variables every run needs. The server's own secrets live in the server folder; the\n * environment supplies them only when `deploy` creates it.\n */\nconst requiredEnv = (deployment: Pick<Deployment, 'dns' | 'state'>): readonly string[] => [\n 'FLY_API_TOKEN',\n ...providerEnv(deployment),\n];\n\n/** Alchemy reads the state store's account from CLOUDFLARE_ACCOUNT_ID; the deploy file names it. */\nconst stateAccountEnv = ({ state }: Pick<Deployment, 'state'>): Env =>\n state === 'local' ? {} : { CLOUDFLARE_ACCOUNT_ID: state.accountId };\n\n/** The variables `env` lacks, once the CLI has added what the deploy file supplies. */\nconst missingEnv = (deployment: Pick<Deployment, 'dns' | 'state'>, env: Env): readonly string[] => {\n const full = { ...env, ...stateAccountEnv(deployment) };\n return requiredEnv(deployment).filter((name) => (full[name] ?? '') === '');\n};\n\nconst checkEnv = (deployment: Pick<Deployment, 'dns' | 'state'>, env: Env) => {\n const missing = missingEnv(deployment, env);\n return missing.length === 0\n ? Effect.void\n : Effect.fail(\n new InfraError({\n message: `set ${missing.join(', ')} in the environment (\\`wt-tunnel init\\` explains each)`,\n }),\n );\n};\n\n/**\n * The environment for the alchemy process: the caller's, plus the state account, the deployment and\n * the server folder's files.\n */\nconst stackEnv = (deployment: Deployment, files: readonly ServerFile[], env: Env): Env => ({\n ...env,\n ...stateAccountEnv(deployment),\n [deploymentEnv]: JSON.stringify(deployment),\n [serverFilesEnv]: JSON.stringify(files.map(({ base64, name }) => ({ base64, name }))),\n});\n\nexport { checkEnv, missingEnv, stackEnv };\nexport type { Env };\n"],"mappings":";;;;;;;;AAaA,MAAM,eAAe,eAAqE,CACxF,iBACA,GAAG,YAAY,UAAU,CAC3B;;AAGA,MAAM,mBAAmB,EAAE,YACzB,UAAU,UAAU,CAAC,IAAI,EAAE,uBAAuB,MAAM,UAAU;;AAGpE,MAAM,cAAc,YAA+C,QAAgC;CACjG,MAAM,OAAO;EAAE,GAAG;EAAK,GAAG,gBAAgB,UAAU;CAAE;CACtD,OAAO,YAAY,UAAU,CAAC,CAAC,QAAQ,UAAU,KAAK,SAAS,QAAQ,EAAE;AAC3E;AAEA,MAAM,YAAY,YAA+C,QAAa;CAC5E,MAAM,UAAU,WAAW,YAAY,GAAG;CAC1C,OAAO,QAAQ,WAAW,IACtB,OAAO,OACP,OAAO,KACL,IAAI,WAAW,EACb,SAAS,OAAO,QAAQ,KAAK,IAAI,EAAE,wDACrC,CAAC,CACH;AACN;;;;;AAMA,MAAM,YAAY,YAAwB,OAA8B,SAAmB;CACzF,GAAG;CACH,GAAG,gBAAgB,UAAU;EAC5B,gBAAgB,KAAK,UAAU,UAAU;EACzC,iBAAiB,KAAK,UAAU,MAAM,KAAK,EAAE,QAAQ,YAAY;EAAE;EAAQ;CAAK,EAAE,CAAC;AACtF"}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { InfraError } from "./errors.js";
|
|
2
|
+
import { uncoveredNames } from "./deployment.js";
|
|
3
|
+
import { ServerConfigFileJson, caFile, readServerConfig, serverConfigFileName } from "./packages/contract/src/server-config.js";
|
|
4
|
+
import { rootProblems } from "./packages/contract/src/root-ca.js";
|
|
5
|
+
import { secretNameOf } from "./uploads.js";
|
|
6
|
+
import { Effect, FileSystem, Path, Redacted, Schema } from "effect";
|
|
7
|
+
const groupOrOther = 63;
|
|
8
|
+
const permissionBits = 511;
|
|
9
|
+
const textOf = ({ base64 }) => Buffer.from(base64, "base64").toString("utf8");
|
|
10
|
+
/** A file for the folder, from its text. */
|
|
11
|
+
const serverFile = (name, text, mode) => ({
|
|
12
|
+
base64: Buffer.from(text).toString("base64"),
|
|
13
|
+
mode,
|
|
14
|
+
name
|
|
15
|
+
});
|
|
16
|
+
/** The folder's files by path, read the way the server reads them on the Machine. */
|
|
17
|
+
const reader = (dir, files) => (file) => {
|
|
18
|
+
const found = files.find((candidate) => `${dir}/${candidate.name}` === file);
|
|
19
|
+
return found === void 0 ? Effect.fail("missing") : Effect.succeed(textOf(found));
|
|
20
|
+
};
|
|
21
|
+
/** The domain `authHost` sits under, if any: dev hosts there belong to worktrees. */
|
|
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
|
+
const nameProblem = (file) => /^[A-Za-z0-9._-]+$/u.test(file.name) ? [] : [`${file.name}: only letters, digits, ".", "_" and "-" may name a file`];
|
|
24
|
+
/** Problems with the files themselves: names the Machine cannot take, and readable secrets. */
|
|
25
|
+
const fileProblems = (keyName, files) => {
|
|
26
|
+
const secretFiles = /* @__PURE__ */ new Set([serverConfigFileName, keyName]);
|
|
27
|
+
const secrets = files.map((file) => secretNameOf(file.name));
|
|
28
|
+
return files.flatMap((file, index) => [
|
|
29
|
+
...nameProblem(file),
|
|
30
|
+
...secretFiles.has(file.name) && (file.mode & groupOrOther) !== 0 ? [`${file.name} holds secrets but others may read it: chmod 600 it`] : [],
|
|
31
|
+
...secrets.indexOf(secretNameOf(file.name)) === index ? [] : [`${file.name} maps to the same Fly secret as another file; rename one`]
|
|
32
|
+
]);
|
|
33
|
+
};
|
|
34
|
+
/** A `ca` path the Machine can follow names a file in the folder itself. */
|
|
35
|
+
const caPathProblems = (dir, ca) => ["cert", "key"].flatMap((field) => {
|
|
36
|
+
const file = caFile(dir, ca[field]);
|
|
37
|
+
return file.startsWith(`${dir}/`) && !file.slice(dir.length + 1).includes("/") ? [] : [`ca.${field} must name a file in ${dir}, the folder uploaded to the Machine`];
|
|
38
|
+
});
|
|
39
|
+
const invalidFolder = (dir, problems) => new InfraError({ message: `${dir}/${serverConfigFileName} is not valid:\n ${problems.join("\n ")}` });
|
|
40
|
+
/**
|
|
41
|
+
* The root's file names, in the folder. When the config does not decode, readServerConfig says why,
|
|
42
|
+
* so the defaults stand in until then.
|
|
43
|
+
*/
|
|
44
|
+
const caNames = (dir, text) => Schema.decodeUnknownEffect(ServerConfigFileJson)(text).pipe(Effect.map((file) => file.ca), Effect.orElseSucceed(() => ({
|
|
45
|
+
cert: "ca.crt",
|
|
46
|
+
key: "ca.key"
|
|
47
|
+
})), Effect.filterOrFail((ca) => caPathProblems(dir, ca).length === 0, (ca) => invalidFolder(dir, caPathProblems(dir, ca))), Effect.map((ca) => ({
|
|
48
|
+
cert: caFile(dir, ca.cert).slice(dir.length + 1),
|
|
49
|
+
key: caFile(dir, ca.key).slice(dir.length + 1)
|
|
50
|
+
})));
|
|
51
|
+
/** Everything wrong with a decoded config and its folder, beyond the schema. */
|
|
52
|
+
const folderProblems = (input) => [
|
|
53
|
+
...rootProblems({
|
|
54
|
+
cert: input.config.ca.cert,
|
|
55
|
+
domains: input.config.domains,
|
|
56
|
+
key: Redacted.value(input.config.ca.key)
|
|
57
|
+
}),
|
|
58
|
+
...uncoveredNames({
|
|
59
|
+
...input.deploy,
|
|
60
|
+
...input.config
|
|
61
|
+
}),
|
|
62
|
+
...authHostProblems(input.config),
|
|
63
|
+
...fileProblems(input.keyName, input.files)
|
|
64
|
+
];
|
|
65
|
+
/**
|
|
66
|
+
* Checks a server folder, on disk or not yet written, before anything is deployed: the config
|
|
67
|
+
* decodes with the server's own schema, its root files are in the folder and hold PEM, the root
|
|
68
|
+
* covers every domain and matches its key, every DNS name sits in a zone, the sign-in host is
|
|
69
|
+
* outside the dev domains, and the secret files are private. Every problem is reported at once.
|
|
70
|
+
*/
|
|
71
|
+
const checkServerFiles = (input) => Effect.gen(function* check() {
|
|
72
|
+
const configFile = input.files.find((file) => file.name === serverConfigFileName);
|
|
73
|
+
if (configFile === void 0) return yield* invalidFolder(input.dir, ["it is missing"]);
|
|
74
|
+
const names = yield* caNames(input.dir, textOf(configFile));
|
|
75
|
+
const config = yield* readServerConfig({
|
|
76
|
+
dir: input.dir,
|
|
77
|
+
read: reader(input.dir, input.files),
|
|
78
|
+
source: `${input.dir}/${serverConfigFileName}`,
|
|
79
|
+
text: textOf(configFile)
|
|
80
|
+
}).pipe(Effect.mapError(({ message }) => new InfraError({ message })));
|
|
81
|
+
const problems = folderProblems({
|
|
82
|
+
...input,
|
|
83
|
+
config,
|
|
84
|
+
keyName: names.key
|
|
85
|
+
});
|
|
86
|
+
if (problems.length > 0) return yield* invalidFolder(input.dir, problems);
|
|
87
|
+
return {
|
|
88
|
+
config,
|
|
89
|
+
dir: input.dir,
|
|
90
|
+
files: input.files,
|
|
91
|
+
unreferenced: input.files.map(({ name }) => name).filter((name) => ![
|
|
92
|
+
serverConfigFileName,
|
|
93
|
+
names.cert,
|
|
94
|
+
names.key
|
|
95
|
+
].includes(name))
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
/** Whether the folder holds a server config yet. */
|
|
99
|
+
const hasServerConfig = (dir) => FileSystem.FileSystem.use((fs) => fs.exists(`${dir}/${serverConfigFileName}`)).pipe(Effect.orElseSucceed(() => false));
|
|
100
|
+
/** One file of the folder. Anything that is not a file fails. */
|
|
101
|
+
const readServerFile = (dir, name) => Effect.gen(function* readFile() {
|
|
102
|
+
const fs = yield* FileSystem.FileSystem;
|
|
103
|
+
const file = (yield* Path.Path).join(dir, name);
|
|
104
|
+
const cannotRead = () => new InfraError({ message: `cannot read ${file}` });
|
|
105
|
+
const info = yield* fs.stat(file).pipe(Effect.mapError(cannotRead));
|
|
106
|
+
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(Effect.mapError(cannotRead));
|
|
108
|
+
return {
|
|
109
|
+
base64: Buffer.from(content).toString("base64"),
|
|
110
|
+
mode: info.mode & permissionBits,
|
|
111
|
+
name
|
|
112
|
+
};
|
|
113
|
+
});
|
|
114
|
+
/** Reads and checks the server folder on disk. */
|
|
115
|
+
const readServerDir = (dir, deploy) => FileSystem.FileSystem.use((fs) => fs.readDirectory(dir)).pipe(Effect.mapError(() => new InfraError({ message: `cannot read the server folder ${dir}` })), Effect.flatMap((names) => Effect.forEach(names.toSorted(), (name) => readServerFile(dir, name))), Effect.flatMap((files) => checkServerFiles({
|
|
116
|
+
deploy,
|
|
117
|
+
dir,
|
|
118
|
+
files
|
|
119
|
+
})));
|
|
120
|
+
/** The config sorts last, so a run that stops halfway leaves no config and the next drafts again. */
|
|
121
|
+
const configLast = (left, right) => Number(left.name === serverConfigFileName) - Number(right.name === serverConfigFileName);
|
|
122
|
+
/** Writes a drafted folder: private, each file with its mode, the config last. Never overwrites. */
|
|
123
|
+
const writeServerDir = (dir, files) => Effect.gen(function* write() {
|
|
124
|
+
const fs = yield* FileSystem.FileSystem;
|
|
125
|
+
const path = yield* Path.Path;
|
|
126
|
+
yield* fs.makeDirectory(dir, {
|
|
127
|
+
mode: 448,
|
|
128
|
+
recursive: true
|
|
129
|
+
}).pipe(Effect.orDie);
|
|
130
|
+
yield* fs.chmod(dir, 448).pipe(Effect.orDie);
|
|
131
|
+
for (const file of files.toSorted(configLast)) {
|
|
132
|
+
const target = path.join(dir, file.name);
|
|
133
|
+
if (!(yield* fs.exists(target).pipe(Effect.orDie))) yield* fs.writeFile(target, Buffer.from(file.base64, "base64"), {
|
|
134
|
+
flag: "wx",
|
|
135
|
+
mode: file.mode
|
|
136
|
+
}).pipe(Effect.orDie);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
export { checkServerFiles, hasServerConfig, readServerDir, serverFile, writeServerDir };
|
|
140
|
+
|
|
141
|
+
//# sourceMappingURL=server-dir.js.map
|
|
@@ -0,0 +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;AA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AAM,KAAK;EAAK,CAAC,CAAC,CACtF,KAAK,OAAO,KAAK;CAExB;AACF,CAAC"}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { deploymentPolicy } from "@alchemy.run/fly/Deployment";
|
|
3
|
+
import { MachineProvider } from "@alchemy.run/fly/Machine";
|
|
4
|
+
import { createFlyResourceName, sanitizeFlyAppName } from "@alchemy.run/fly/Metadata";
|
|
5
|
+
import { reconcileReplicas, sameServices, toFlyService } from "@alchemy.run/fly/replicas";
|
|
6
|
+
import { deepEqual } from "alchemy/Diff";
|
|
7
|
+
import { Provider, effect } from "alchemy/Provider";
|
|
8
|
+
import { Resource } from "alchemy/Resource";
|
|
9
|
+
// src/server-machine.ts
|
|
10
|
+
/** What Alchemy's Machine assumes for what its props leave out. */
|
|
11
|
+
const alchemyDefaults = {
|
|
12
|
+
memoryMb: 256,
|
|
13
|
+
region: "iad",
|
|
14
|
+
restart: {
|
|
15
|
+
max_retries: 10,
|
|
16
|
+
policy: "on-failure"
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Alchemy's Fly.Machine with `files`, which Alchemy's own Machine lacks. It keeps the Fly.Machine
|
|
21
|
+
* type, so the state of a Machine deployed before carries over and an update changes it in place.
|
|
22
|
+
* Its provider takes Alchemy's for this stack, because a provider registered on its own wins over
|
|
23
|
+
* one in a collection. Read, diff, list and delete are Alchemy's; only reconcile differs: it sends
|
|
24
|
+
* the files and treats a change to them as drift.
|
|
25
|
+
*/
|
|
26
|
+
const ServerMachine = Resource("Fly.Machine");
|
|
27
|
+
const flyFiles = (files) => files.map((file) => ({
|
|
28
|
+
guest_path: file.guestPath,
|
|
29
|
+
mode: file.mode,
|
|
30
|
+
secret_name: file.secretName
|
|
31
|
+
}));
|
|
32
|
+
const fileKey = (file) => `${file.guest_path ?? ""}:${String(file.mode ?? "")}:${file.secret_name ?? ""}`;
|
|
33
|
+
const sameFiles = (observed, desired) => deepEqual((observed ?? []).map((file) => fileKey(file)).toSorted(), (desired ?? []).map((file) => fileKey(file)).toSorted());
|
|
34
|
+
const appNameOf = (app) => typeof app === "object" && app !== null && "appName" in app && typeof app.appName === "string" ? app.appName : void 0;
|
|
35
|
+
/** The Machine config for one replica, the way Alchemy's Machine builds it, plus the files. */
|
|
36
|
+
const desiredConfig = (props, metadata) => ({
|
|
37
|
+
...props.env === void 0 ? {} : { env: props.env },
|
|
38
|
+
files: flyFiles(props.files),
|
|
39
|
+
guest: {
|
|
40
|
+
cpu_kind: props.guest?.cpuKind ?? "shared",
|
|
41
|
+
cpus: props.guest?.cpus ?? 1,
|
|
42
|
+
memory_mb: props.guest?.memoryMb ?? alchemyDefaults.memoryMb
|
|
43
|
+
},
|
|
44
|
+
image: props.image,
|
|
45
|
+
...props.init?.cmd === void 0 ? {} : { init: { cmd: props.init.cmd } },
|
|
46
|
+
metadata: {
|
|
47
|
+
...props.metadata,
|
|
48
|
+
...metadata
|
|
49
|
+
},
|
|
50
|
+
...props.restart?.policy === void 0 ? {} : { restart: { policy: props.restart.policy } },
|
|
51
|
+
...props.services === void 0 ? {} : { services: props.services.map(toFlyService) }
|
|
52
|
+
});
|
|
53
|
+
/** The repository and tag of an image reference, as Fly reports them in `image_ref`. */
|
|
54
|
+
const imageParts = (image) => {
|
|
55
|
+
const colon = image.lastIndexOf(":");
|
|
56
|
+
return colon > image.lastIndexOf("/") ? {
|
|
57
|
+
repository: image.slice(0, colon),
|
|
58
|
+
tag: image.slice(colon + 1)
|
|
59
|
+
} : {
|
|
60
|
+
repository: image,
|
|
61
|
+
tag: "latest"
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
/** Fly may report the image resolved to a digest; Alchemy then compares the repository and tag. */
|
|
65
|
+
const sameImage = (machine, image) => {
|
|
66
|
+
const { repository, tag } = imageParts(image);
|
|
67
|
+
const observed = machine.image_ref?.repository ?? "";
|
|
68
|
+
return machine.config?.image === image || machine.image_ref?.tag === tag && (observed === repository || observed.endsWith(`/${repository}`));
|
|
69
|
+
};
|
|
70
|
+
/** Drops the keys whose value is null or undefined. */
|
|
71
|
+
const compact = (record) => Object.fromEntries(Object.entries(record ?? {}).filter(([, value]) => value !== null && value !== void 0));
|
|
72
|
+
const guestOf = (guest) => ({
|
|
73
|
+
cpu_kind: guest?.cpu_kind,
|
|
74
|
+
cpus: guest?.cpus,
|
|
75
|
+
memory_mb: guest?.memory_mb
|
|
76
|
+
});
|
|
77
|
+
const restartOf = (restart) => ({
|
|
78
|
+
...alchemyDefaults.restart,
|
|
79
|
+
...compact(restart)
|
|
80
|
+
});
|
|
81
|
+
/**
|
|
82
|
+
* Whether the running Machine differs from the props, as Alchemy's Machine judges it, or in its
|
|
83
|
+
* files.
|
|
84
|
+
*/
|
|
85
|
+
const drifted = (machine, desired) => {
|
|
86
|
+
const config = machine.config ?? {};
|
|
87
|
+
return [
|
|
88
|
+
sameImage(machine, desired.image ?? ""),
|
|
89
|
+
deepEqual(guestOf(config.guest), guestOf(desired.guest)),
|
|
90
|
+
deepEqual(compact(config.env), desired.env ?? {}),
|
|
91
|
+
sameServices(config.services, desired.services),
|
|
92
|
+
deepEqual(restartOf(config.restart), restartOf(desired.restart)),
|
|
93
|
+
deepEqual(config.init ?? {}, desired.init ?? {}, { stripNullish: true }),
|
|
94
|
+
sameFiles(config.files, desired.files),
|
|
95
|
+
Object.entries(desired.metadata ?? {}).every(([key, value]) => config.metadata?.[key] === value)
|
|
96
|
+
].includes(false);
|
|
97
|
+
};
|
|
98
|
+
/** The Machine's name: the props', else the one it has, else one Alchemy makes up. */
|
|
99
|
+
const baseNameOf = (id, name, output) => name === void 0 ? Effect.succeed(output?.baseName ?? output?.name).pipe(Effect.flatMap((existing) => existing === void 0 ? createFlyResourceName(id) : Effect.succeed(existing))) : Effect.succeed(sanitizeFlyAppName(name));
|
|
100
|
+
const reconcile = Effect.fn(function* reconcileServerMachine({ fqn, id, instanceId, news, output }) {
|
|
101
|
+
const { regions: _regions, services: _services, ...attributes } = yield* reconcileReplicas({
|
|
102
|
+
appName: appNameOf(news.app) ?? output?.appName ?? "",
|
|
103
|
+
baseName: yield* baseNameOf(id, news.name, output),
|
|
104
|
+
buildConfig: ({ metadata }) => desiredConfig(news, metadata),
|
|
105
|
+
configDrifted: (machine, { metadata }) => drifted(machine, desiredConfig(news, metadata)),
|
|
106
|
+
count: 1,
|
|
107
|
+
disks: [],
|
|
108
|
+
fqn,
|
|
109
|
+
id,
|
|
110
|
+
outputMachineIds: output?.machineIds ?? [],
|
|
111
|
+
policy: yield* deploymentPolicy(news.deploy, news.shutdown),
|
|
112
|
+
regions: [news.region ?? alchemyDefaults.region],
|
|
113
|
+
resourceInstanceId: instanceId,
|
|
114
|
+
type: "Fly.Machine"
|
|
115
|
+
});
|
|
116
|
+
return attributes;
|
|
117
|
+
});
|
|
118
|
+
/** Alchemy's own Machine provider, whose read, diff, list and delete this one keeps. */
|
|
119
|
+
const alchemyMachineProvider = Effect.gen(function* alchemyMachine() {
|
|
120
|
+
return yield* Provider("Fly.Machine");
|
|
121
|
+
}).pipe(Effect.provide(MachineProvider()));
|
|
122
|
+
const serverMachineProvider = () => effect(ServerMachine, Effect.gen(function* serverMachine() {
|
|
123
|
+
const alchemy = yield* alchemyMachineProvider;
|
|
124
|
+
const missing = Effect.die("Alchemy's Fly.Machine provider lacks an operation");
|
|
125
|
+
return {
|
|
126
|
+
delete: (input) => alchemy.delete(input),
|
|
127
|
+
diff: (input) => alchemy.diff === void 0 ? missing : alchemy.diff(input),
|
|
128
|
+
list: () => alchemy.list === void 0 ? missing : alchemy.list(),
|
|
129
|
+
read: (input) => alchemy.read === void 0 ? missing : alchemy.read(input),
|
|
130
|
+
reconcile,
|
|
131
|
+
...alchemy.stables === void 0 ? {} : { stables: alchemy.stables }
|
|
132
|
+
};
|
|
133
|
+
}));
|
|
134
|
+
export { ServerMachine, desiredConfig, drifted, serverMachineProvider };
|
|
135
|
+
|
|
136
|
+
//# sourceMappingURL=server-machine.js.map
|
|
@@ -0,0 +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,GA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KAAK;EAC3D;EACA,GAAI,QAAQ,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;CACtE;AACF,CAAC,CACH"}
|
package/dist/stack.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { tunnelPort } from "./packages/contract/src/index.js";
|
|
2
|
+
import { DeploymentJson, deploymentEnv, placeHosts, serverFilesEnv } from "./deployment.js";
|
|
3
|
+
import { UploadsJson, machineFileOf, serverArgs } from "./uploads.js";
|
|
4
|
+
import { ServerMachine, serverMachineProvider } from "./server-machine.js";
|
|
5
|
+
import { Effect, Layer, Redacted, Schema } from "effect";
|
|
6
|
+
import { DNS, providers, state } from "@alchemy.run/cloudflare";
|
|
7
|
+
import { App, IpAssignment, Secret, providers as providers$1 } from "@alchemy.run/fly";
|
|
8
|
+
import { Stack } from "alchemy";
|
|
9
|
+
import { map } from "alchemy/Output";
|
|
10
|
+
import { localState } from "alchemy/State";
|
|
11
|
+
// src/stack.ts
|
|
12
|
+
const deployment = await Effect.runPromise(Schema.decodeUnknownEffect(DeploymentJson)(process.env[deploymentEnv]));
|
|
13
|
+
const uploads = await Effect.runPromise(Schema.decodeUnknownEffect(UploadsJson)(process.env[serverFilesEnv]));
|
|
14
|
+
/** Raw TCP on every port: Caddy and frps terminate TLS themselves, with the deployment's CA. */
|
|
15
|
+
const tcpPassthrough = (port) => ({
|
|
16
|
+
autostop: "off",
|
|
17
|
+
internalPort: port,
|
|
18
|
+
ports: [{ port }],
|
|
19
|
+
protocol: "tcp"
|
|
20
|
+
});
|
|
21
|
+
const publicPorts = [
|
|
22
|
+
443,
|
|
23
|
+
80,
|
|
24
|
+
tunnelPort
|
|
25
|
+
];
|
|
26
|
+
const cloudflareRecords = (host, { ipv4, ipv6 }) => Effect.all(["A", "AAAA"].map((type) => DNS.Record(`${host.id}-${type}`, {
|
|
27
|
+
content: type === "A" ? ipv4 : ipv6,
|
|
28
|
+
name: host.name,
|
|
29
|
+
proxied: false,
|
|
30
|
+
ttl: "1",
|
|
31
|
+
type,
|
|
32
|
+
zoneId: host.zone.zoneId
|
|
33
|
+
})));
|
|
34
|
+
/**
|
|
35
|
+
* How each DNS provider creates a host's A and AAAA records in its zone. The error and services
|
|
36
|
+
* types are the union of every provider's; a provider besides Cloudflare adds its own to them.
|
|
37
|
+
*/
|
|
38
|
+
const recordCreators = {
|
|
39
|
+
cloudflare: cloudflareRecords,
|
|
40
|
+
manual: () => Effect.void
|
|
41
|
+
};
|
|
42
|
+
const createRecords = (provider, host, ips) => recordCreators[provider](host, ips);
|
|
43
|
+
/** Fly's providers, with the server Machine's in place of Alchemy's Machine provider. */
|
|
44
|
+
const flyWithServerMachine = serverMachineProvider().pipe(Layer.provideMerge(providers$1()));
|
|
45
|
+
const stack = Stack(deployment.stack, {
|
|
46
|
+
providers: Layer.mergeAll(flyWithServerMachine, providers()),
|
|
47
|
+
state: deployment.state === "local" ? localState() : state()
|
|
48
|
+
}, Effect.gen(function* server() {
|
|
49
|
+
const { fly } = deployment;
|
|
50
|
+
const app = yield* App("App", {
|
|
51
|
+
name: fly.app,
|
|
52
|
+
orgSlug: fly.org
|
|
53
|
+
});
|
|
54
|
+
const ipv4 = yield* IpAssignment("IPv4", {
|
|
55
|
+
app,
|
|
56
|
+
region: fly.region,
|
|
57
|
+
type: "v4"
|
|
58
|
+
});
|
|
59
|
+
const ipv6 = yield* IpAssignment("IPv6", {
|
|
60
|
+
app,
|
|
61
|
+
region: fly.region,
|
|
62
|
+
type: "v6"
|
|
63
|
+
});
|
|
64
|
+
const files = yield* Effect.all(uploads.map((upload) => {
|
|
65
|
+
const file = machineFileOf(upload.name);
|
|
66
|
+
return Secret(file.secretName, {
|
|
67
|
+
app,
|
|
68
|
+
name: file.secretName,
|
|
69
|
+
value: Redacted.make(upload.base64)
|
|
70
|
+
}).pipe(Effect.map((secret) => ({
|
|
71
|
+
file,
|
|
72
|
+
secret
|
|
73
|
+
})));
|
|
74
|
+
}));
|
|
75
|
+
yield* ServerMachine("Server", {
|
|
76
|
+
app,
|
|
77
|
+
env: Object.fromEntries(files.map(({ file, secret }) => [`${file.secretName}_DIGEST`, map(secret.digest, (digest) => digest ?? "")])),
|
|
78
|
+
files: files.map(({ file }) => file),
|
|
79
|
+
guest: {
|
|
80
|
+
cpuKind: "shared",
|
|
81
|
+
cpus: 1,
|
|
82
|
+
memoryMb: fly.memoryMb
|
|
83
|
+
},
|
|
84
|
+
image: deployment.image,
|
|
85
|
+
init: { cmd: serverArgs },
|
|
86
|
+
region: fly.region,
|
|
87
|
+
restart: { policy: "always" },
|
|
88
|
+
services: publicPorts.map((port) => tcpPassthrough(port))
|
|
89
|
+
});
|
|
90
|
+
const ips = {
|
|
91
|
+
ipv4: ipv4.ip,
|
|
92
|
+
ipv6: ipv6.ip
|
|
93
|
+
};
|
|
94
|
+
yield* Effect.all(placeHosts(deployment).placed.map((host) => createRecords(host.zone.provider, host, ips)));
|
|
95
|
+
return {
|
|
96
|
+
app: app.appName,
|
|
97
|
+
ipv4: ipv4.ip,
|
|
98
|
+
ipv6: ipv6.ip,
|
|
99
|
+
tunnelHost: deployment.tunnelHost
|
|
100
|
+
};
|
|
101
|
+
}));
|
|
102
|
+
export { stack as default };
|
|
103
|
+
|
|
104
|
+
//# sourceMappingURL=stack.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stack.js","names":["flyProviders","cloudflareProviders","cloudflareState","mapOutput"],"sources":["../src/stack.ts"],"sourcesContent":["import {\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 { DeploymentJson, deploymentEnv, placeHosts, serverFilesEnv } 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: deployment.state === 'local' ? localState() : cloudflareState(),\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":";;;;;;;;;;;AAuBA,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,WAAW,OACX;CAKE,WAAW,MAAM,SAAS,sBAAsBC,UAAoB,CAAC;CACrE,OAAO,WAAW,UAAU,UAAU,WAAW,IAAIC,MAAgB;AACvE,GACA,OAAO,IAAI,UAAU,SAAS;CAC5B,MAAM,EAAE,QAAQ;CAChB,MAAM,M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AC,CACH"}
|
package/dist/uploads.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { serverConfigFileName } from "./packages/contract/src/server-config.js";
|
|
2
|
+
import { Schema } from "effect";
|
|
3
|
+
// src/uploads.ts
|
|
4
|
+
/** Where the Machine finds the server folder's files. */
|
|
5
|
+
const guestDir = "/etc/wt-tunnel-server";
|
|
6
|
+
/** The arguments the stack appends to the image's `wt-tunnel-server start` entrypoint. */
|
|
7
|
+
const serverArgs = ["--config", `${guestDir}/${serverConfigFileName}`];
|
|
8
|
+
/** The Fly secret that holds a file's base64 content: a valid environment variable name. */
|
|
9
|
+
const secretNameOf = (name) => `WT_TUNNEL_FILE_${name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_")}`;
|
|
10
|
+
/** A server folder file as the CLI hands it to the stack. */
|
|
11
|
+
const Upload = Schema.Struct({
|
|
12
|
+
base64: Schema.String,
|
|
13
|
+
name: Schema.String
|
|
14
|
+
});
|
|
15
|
+
const UploadsJson = Schema.fromJsonString(Schema.Array(Upload));
|
|
16
|
+
/** Where Fly writes a file in the Machine, and from which secret. */
|
|
17
|
+
const machineFileOf = (name) => ({
|
|
18
|
+
guestPath: `${guestDir}/${name}`,
|
|
19
|
+
mode: 292,
|
|
20
|
+
secretName: secretNameOf(name)
|
|
21
|
+
});
|
|
22
|
+
export { UploadsJson, machineFileOf, secretNameOf, serverArgs };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=uploads.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uploads.js","names":[],"sources":["../src/uploads.ts"],"sourcesContent":["import { serverConfigFileName } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Schema } from 'effect';\n\n/** Where the Machine finds the server folder's files. */\nconst guestDir = '/etc/wt-tunnel-server';\n\n/**\n * Every uploaded file is readable by every user in the Machine. Fly's docs do not say who owns the\n * files it writes, and the server runs as the image's unprivileged `node` user, so 0600 could leave\n * them unreadable. A tighter mode would hide nothing anyway: Fly also puts every app secret, these\n * files' contents included, in the environment of the Machine's processes.\n */\nconst guestMode = 0o444;\n\n/** The arguments the stack appends to the image's `wt-tunnel-server start` entrypoint. */\nconst serverArgs = ['--config', `${guestDir}/${serverConfigFileName}`];\n\n/** The Fly secret that holds a file's base64 content: a valid environment variable name. */\nconst secretNameOf = (name: string) =>\n `WT_TUNNEL_FILE_${name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, '_')}`;\n\n/** A server folder file as the CLI hands it to the stack. */\nconst Upload = Schema.Struct({ base64: Schema.String, name: Schema.String });\ntype Upload = typeof Upload.Type;\n\nconst UploadsJson = Schema.fromJsonString(Schema.Array(Upload));\n\n/** Where Fly writes a file in the Machine, and from which secret. */\nconst machineFileOf = (name: string) => ({\n guestPath: `${guestDir}/${name}`,\n mode: guestMode,\n secretName: secretNameOf(name),\n});\n\nexport { UploadsJson, guestMode, machineFileOf, secretNameOf, serverArgs };\n"],"mappings":";;;;AAIA,MAAM,WAAW;;AAWjB,MAAM,aAAa,CAAC,YAAY,GAAG,SAAS,GAAG,sBAAsB;;AAGrE,MAAM,gBAAgB,SACpB,kBAAkB,KAAK,YAAY,CAAC,CAAC,WAAW,eAAe,GAAG;;AAGpE,MAAM,SAAS,OAAO,OAAO;CAAE,QAAQ,OAAO;CAAQ,MAAM,OAAO;AAAO,CAAC;AAG3E,MAAM,cAAc,OAAO,eAAe,OAAO,MAAM,MAAM,CAAC;;AAG9D,MAAM,iBAAiB,UAAkB;CACvC,WAAW,GAAG,SAAS,GAAG;CAC1B,MAAA;CACA,YAAY,aAAa,IAAI;AAC/B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tafrahq/wt-tunnel",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Sets up the recommended wt-tunnel server on Fly.io, with optional Cloudflare DNS: one config file, secrets from the environment, and an Alchemy stack shipped inside.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"alchemy",
|
|
7
|
+
"cli",
|
|
8
|
+
"cloudflare",
|
|
9
|
+
"deploy",
|
|
10
|
+
"fly",
|
|
11
|
+
"fly.io",
|
|
12
|
+
"frp",
|
|
13
|
+
"git-worktree",
|
|
14
|
+
"infrastructure",
|
|
15
|
+
"self-hosted",
|
|
16
|
+
"tunnel",
|
|
17
|
+
"wt-tunnel"
|
|
18
|
+
],
|
|
19
|
+
"homepage": "https://github.com/tafrahq/wt-tunnel/tree/main/apps/cli#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/tafrahq/wt-tunnel/issues"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"author": "Tafra (https://github.com/tafrahq)",
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/tafrahq/wt-tunnel.git",
|
|
28
|
+
"directory": "apps/cli"
|
|
29
|
+
},
|
|
30
|
+
"bin": {
|
|
31
|
+
"wt-tunnel": "dist/bin.js"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"type": "module",
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@alchemy.run/cloudflare": "2.0.0-beta.84",
|
|
42
|
+
"@alchemy.run/fly": "2.0.0-beta.84",
|
|
43
|
+
"@effect/platform-node": "4.0.6",
|
|
44
|
+
"alchemy": "2.0.0-beta.84",
|
|
45
|
+
"effect": "4.0.6"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@effect/vitest": "^4.0.6",
|
|
49
|
+
"@tafrahq/wt-tunnel-contract": "0.0.0",
|
|
50
|
+
"@types/node": "^22.20.5",
|
|
51
|
+
"tsdown": "0.23.2",
|
|
52
|
+
"vitest": "^5.0.5"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=22.22.3"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "tsdown && node dist/bin.js --version",
|
|
59
|
+
"typecheck": "tsc --noEmit",
|
|
60
|
+
"test": "vitest run"
|
|
61
|
+
}
|
|
6
62
|
}
|