@tafrahq/wt-tunnel-server 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 +11 -8
- package/dist/bin.js +8 -14
- package/dist/bin.js.map +1 -1
- package/dist/cli.js +8 -7
- package/dist/cli.js.map +1 -1
- package/dist/packages/binaries/src/caddy.js +2 -2
- package/dist/packages/binaries/src/caddy.js.map +1 -1
- package/dist/packages/binaries/src/install.js +1 -1
- package/dist/packages/binaries/src/install.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/packages/contract/src/temp-dir.js +12 -0
- package/dist/packages/contract/src/temp-dir.js.map +1 -0
- package/dist/runtime.js +3 -7
- package/dist/runtime.js.map +1 -1
- package/dist/session.js +4 -2
- package/dist/session.js.map +1 -1
- package/package.json +9 -8
- package/src/bin.ts +7 -22
- package/src/cli.ts +39 -26
- package/src/runtime.ts +17 -17
- package/src/session.ts +10 -9
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ The server half of [server mode](../../docs/server-mode.md). `wt-tunnel-server s
|
|
|
8
8
|
|
|
9
9
|
The supervisor writes the Caddyfile and frps.toml from the config into a private temporary directory, starts Caddy and frps, and prefixes their output with `[caddy]` or `[frps]`. Once every port accepts connections it prints `ready`. If Caddy or frps exits, the supervisor stops the other and exits with code 1, so a platform restarts it. SIGTERM or SIGINT stops both and exits 0.
|
|
10
10
|
|
|
11
|
-
The same CLI runs directly on a host and in the published Docker image, which installs
|
|
11
|
+
The same CLI runs directly on a host and in the published Docker image, which installs the same package that is published to npm.
|
|
12
12
|
|
|
13
13
|
## Run the image
|
|
14
14
|
|
|
@@ -32,6 +32,8 @@ For the recommended setup on Fly.io, use [`wt-tunnel`](../cli/README.md). It cre
|
|
|
32
32
|
|
|
33
33
|
## Run without Docker
|
|
34
34
|
|
|
35
|
+
The CLI is published to npm. Install it, or build it from a checkout as the [root README](../../README.md#install) shows:
|
|
36
|
+
|
|
35
37
|
```sh
|
|
36
38
|
npm install --global @tafrahq/wt-tunnel-server
|
|
37
39
|
cd my-wt-tunnel/.server
|
|
@@ -39,7 +41,7 @@ wt-tunnel-server check
|
|
|
39
41
|
wt-tunnel-server start --detach
|
|
40
42
|
```
|
|
41
43
|
|
|
42
|
-
It needs Node.js
|
|
44
|
+
It needs Node.js 26 or later, on Linux or macOS.
|
|
43
45
|
|
|
44
46
|
### Commands
|
|
45
47
|
|
|
@@ -79,7 +81,7 @@ Caddy binds 443 and 80. Outside Docker, only root may bind ports below 1024 by d
|
|
|
79
81
|
|
|
80
82
|
[docs/server-mode.md](../../docs/server-mode.md#server-config) lists the config's fields. `ca.cert` and `ca.key` name the root CA's PEM files, relative to the config file's directory. With the config in `WT_TUNNEL_SERVER_CONFIG`, they are relative to the current directory. `wt-tunnel deploy` writes all three files into one folder, `.server/`.
|
|
81
83
|
|
|
82
|
-
`wt-tunnel ca create
|
|
84
|
+
`wt-tunnel ca create` creates a root: an EC P-256 root, valid for 10 years and name-constrained to the server config's domains, or the deploy file's for a new folder, and every name under them. Keep `ca.key` secret.
|
|
83
85
|
|
|
84
86
|
Each device that opens dev URLs must trust the root once. The sign-in service serves it on the sign-in host, the one name with a publicly trusted certificate:
|
|
85
87
|
|
|
@@ -95,15 +97,16 @@ Each sign-in provider's redirect URI is `https://<authHost>/api/auth/callback/<p
|
|
|
95
97
|
|
|
96
98
|
## Build the image
|
|
97
99
|
|
|
98
|
-
The image installs a
|
|
100
|
+
The image ([`docker/Dockerfile`](../../docker/Dockerfile)) installs a packed `@tafrahq/wt-tunnel-server` from its build context with `npm install --global`; its dependencies come from the public npm registry. Caddy comes from the official `caddy:2.11.7` image and frps from the checksum-verified frp release. From the repository root:
|
|
99
101
|
|
|
100
102
|
```sh
|
|
101
|
-
|
|
102
|
-
|
|
103
|
+
pnpm install
|
|
104
|
+
pnpm --dir apps/server pack --out "$PWD/docker/wt-tunnel-server.tgz"
|
|
105
|
+
docker build --platform linux/amd64 -f docker/Dockerfile -t wt-tunnel-server docker
|
|
103
106
|
```
|
|
104
107
|
|
|
105
|
-
The
|
|
108
|
+
The release workflow builds the published image the same way, from the very tarball it stages on npm.
|
|
106
109
|
|
|
107
110
|
## Develop
|
|
108
111
|
|
|
109
|
-
`
|
|
112
|
+
`nub run check:quality` and `nub run test` at the repository root format, lint, type-check and test this package with the rest of the monorepo. `nubx turbo run build --filter @tafrahq/wt-tunnel-server` builds `apps/server/dist`. tsdown compiles the workspace-only packages into it: `@tafrahq/wt-tunnel-contract`, which holds the config schema that this server and `wt-tunnel` both decode, and `@tafrahq/wt-tunnel-binaries`, which pins and installs Caddy and frps. The published package depends on neither.
|
package/dist/bin.js
CHANGED
|
@@ -1,20 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { binProgram } from "./packages/contract/src/bin.js";
|
|
2
3
|
import { run } from "./cli.js";
|
|
3
|
-
import { createRequire } from "node:module";
|
|
4
4
|
import { NodeRuntime, NodeServices } from "@effect/platform-node";
|
|
5
|
-
import { Cause,
|
|
5
|
+
import { Cause, Effect, Exit, Runtime } from "effect";
|
|
6
6
|
// src/bin.ts
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
process.exitCode = 1;
|
|
13
|
-
});
|
|
14
|
-
const program = Effect.gen(function* main() {
|
|
15
|
-
const { version } = yield* Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(Effect.orDie);
|
|
16
|
-
yield* run(version);
|
|
17
|
-
}).pipe(Effect.catchTag("ServerError", ({ message }) => report(message)), Effect.provide(NodeServices.layer));
|
|
7
|
+
const program = binProgram({
|
|
8
|
+
expected: "ServerError",
|
|
9
|
+
name: "wt-tunnel-server",
|
|
10
|
+
url: import.meta.url
|
|
11
|
+
}, run);
|
|
18
12
|
/**
|
|
19
13
|
* SIGTERM and SIGINT interrupt the program, which stops Caddy and frps. That is a clean stop, so it
|
|
20
14
|
* exits 0 rather than 130, unless a child had already died.
|
|
@@ -26,7 +20,7 @@ const teardown = (exit, onExit) => {
|
|
|
26
20
|
}
|
|
27
21
|
Runtime.defaultTeardown(exit, onExit);
|
|
28
22
|
};
|
|
29
|
-
NodeRuntime.runMain(program, { teardown });
|
|
23
|
+
NodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)), { teardown });
|
|
30
24
|
export {};
|
|
31
25
|
|
|
32
26
|
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\
|
|
1
|
+
{"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\n// fallow-ignore-file coverage-gaps -- it runs the CLI on import, so cli.test.ts runs it as a subprocess, which fallow cannot follow; 'exits 0 when SIGTERM stops it' tests the teardown\nimport { NodeRuntime, NodeServices } from '@effect/platform-node';\nimport { binProgram } from '@tafrahq/wt-tunnel-contract/bin';\nimport { Cause, Effect, Exit, Runtime } from 'effect';\n\nimport { run } from './cli.ts';\n\nconst program = binProgram(\n { expected: 'ServerError', name: 'wt-tunnel-server', url: import.meta.url },\n run,\n);\n\n/**\n * SIGTERM and SIGINT interrupt the program, which stops Caddy and frps. That is a clean stop, so it\n * exits 0 rather than 130, unless a child had already died.\n */\nconst teardown: Runtime.Teardown = (exit, onExit) => {\n if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {\n onExit(Number(process.exitCode ?? 0));\n return;\n }\n Runtime.defaultTeardown(exit, onExit);\n};\n\nNodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)), { teardown });\n"],"mappings":";;;;;;AAQA,MAAM,UAAU,WACd;CAAE,UAAU;CAAe,MAAM;CAAoB,KAAK,YAAY;AAAI,GAC1E,GACF;;;;;AAMA,MAAM,YAA8B,MAAM,WAAW;CACnD,IAAI,KAAK,UAAU,IAAI,KAAK,MAAM,kBAAkB,KAAK,KAAK,GAAG;EAC/D,OAAO,OAAO,QAAQ,YAAY,CAAC,CAAC;EACpC;CACF;CACA,QAAQ,gBAAgB,MAAM,MAAM;AACtC;AAEA,YAAY,QAAQ,QAAQ,KAAK,OAAO,QAAQ,aAAa,KAAK,CAAC,GAAG,EAAE,SAAS,CAAC"}
|
package/dist/cli.js
CHANGED
|
@@ -79,12 +79,13 @@ const start = Command.make("start", {
|
|
|
79
79
|
};
|
|
80
80
|
yield* input.detach ? runDetached(checked, input.stateDir) : runForeground(checked);
|
|
81
81
|
})).pipe(Command.withDescription("Run Caddy, frps and the sign-in service; in the foreground unless --detach"));
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
/** A command that acts on the detached server that --state-dir names. */
|
|
83
|
+
const stateDirCommand = (name, description, act) => Command.make(name, { stateDir: stateDirFlag }, ({ stateDir }) => act(stateDirFrom(stateDir))).pipe(Command.withDescription(description));
|
|
84
|
+
const stop = stateDirCommand("stop", "Stop the detached server and wait until Caddy and frps exit", (state) => Effect.gen(function* stopDetached() {
|
|
85
|
+
const previous = yield* stopServer(state);
|
|
84
86
|
yield* Console.log(previous._tag === "running" ? `Stopped (pid ${previous.pid}).` : "Not running.");
|
|
85
|
-
}))
|
|
86
|
-
const status =
|
|
87
|
-
const state = stateDirFrom(stateDir);
|
|
87
|
+
}));
|
|
88
|
+
const status = stateDirCommand("status", "Show whether the detached server runs: exit 0 if it does, 3 if not", (state) => Effect.gen(function* printStatus() {
|
|
88
89
|
const current = yield* serverStatus(state);
|
|
89
90
|
if (current._tag === "running") {
|
|
90
91
|
yield* Console.log(`running: pid ${current.pid}, since ${current.since.toISOString()}, log ${state.log}`);
|
|
@@ -92,13 +93,13 @@ const status = Command.make("status", { stateDir: stateDirFlag }, ({ stateDir })
|
|
|
92
93
|
}
|
|
93
94
|
yield* Console.log(current._tag === "stale" ? `stopped (pid ${current.pid} in ${state.pid} is not this server)` : "stopped");
|
|
94
95
|
process.exitCode = stoppedExitCode;
|
|
95
|
-
}))
|
|
96
|
+
}));
|
|
96
97
|
const check = Command.make("check", { config: configFlag }, ({ config }) => Effect.gen(function* checkConfig() {
|
|
97
98
|
const file = yield* configFileOf(Option.getOrUndefined(config), process.env);
|
|
98
99
|
yield* loadServerConfig(file, process.env);
|
|
99
100
|
yield* Console.log(`${file ?? "WT_TUNNEL_SERVER_CONFIG"} is a valid server config`);
|
|
100
101
|
})).pipe(Command.withDescription("Check the server config without starting anything"));
|
|
101
|
-
const cli = Command.make("wt-tunnel-server").pipe(Command.withDescription("The wt-tunnel server: Caddy, frps and
|
|
102
|
+
const cli = Command.make("wt-tunnel-server").pipe(Command.withDescription("The wt-tunnel server: Caddy, frps and the sign-in service under one supervisor"), Command.withSubcommands([
|
|
102
103
|
start,
|
|
103
104
|
stop,
|
|
104
105
|
status,
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { resolve } from 'node:path';\n\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Console, Effect, Option, Schema } from 'effect';\nimport { Command, Flag } from 'effect/cli';\n\nimport { resolveBinaries } from './binaries.ts';\nimport type { Binaries } from './binaries.ts';\nimport { configFileOf, loadServerConfig } from './config.ts';\nimport { refuseIfRunning, serverStatus, startDetached, stateDirOf, stopServer } from './daemon.ts';\nimport type { StateDir } from './daemon.ts';\nimport { defaultPorts } from './render.ts';\nimport type { Ports } from './render.ts';\n\n/** `status` exits with 3 when no server runs, as LSB init scripts do. */\nconst stoppedExitCode = 3;\nconst maxPort = 65_535;\n\nconst configFlag = Flag.String('config').pipe(\n Flag.withDescription(\n 'The server config file. Default: the JSON in WT_TUNNEL_SERVER_CONFIG, else ./wt-tunnel-server.json.',\n ),\n Flag.optional,\n);\n\nconst stateDirFlag = Flag.String('state-dir').pipe(\n Flag.withDescription(\n 'Where a detached server keeps server.pid and server.log. Default: WT_TUNNEL_SERVER_STATE_DIR, else $XDG_STATE_HOME/wt-tunnel-server, else ~/.local/state/wt-tunnel-server.',\n ),\n Flag.optional,\n);\n\nconst Port = Schema.Int.check(Schema.isBetween({ maximum: maxPort, minimum: 1 }));\n\nconst portFlag = (name: string, fallback: number, description: string) =>\n Flag.Int(name).pipe(\n Flag.withSchema(Port),\n Flag.withDescription(`${description} (default ${fallback})`),\n Flag.withDefault(fallback),\n );\n\nconst binaryFlag = (name: string) =>\n Flag.String(name).pipe(\n Flag.withDescription(\n `Run this ${name} executable. Default: ${name} on PATH, else the pinned release, downloaded to the user cache on first use.`,\n ),\n Flag.optional,\n );\n\nconst stateDirFrom = (flag: Option.Option<string>) =>\n stateDirOf(Option.getOrUndefined(flag), process.env);\n\n/** What `start` needs once the flags are checked. */\ninterface Start {\n readonly binaries: Binaries;\n readonly config: ServerConfig;\n /** The config file as an absolute path, so a detached server finds it from any directory. */\n readonly configFile: string | undefined;\n readonly ports: Ports;\n readonly state: StateDir;\n}\n\n/**\n * The arguments a detached server is started with: the resolved binaries, so it never downloads,\n * and the state dir, which is how `status` and `stop` recognise it.\n */\nconst foregroundArgs = ({ binaries, configFile, ports, state }: Start) => [\n 'start',\n ...(configFile === undefined ? [] : ['--config', configFile]),\n '--state-dir',\n state.dir,\n '--caddy',\n binaries.caddy,\n '--frps',\n binaries.frps,\n '--https-port',\n String(ports.https),\n '--http-port',\n String(ports.http),\n '--tunnel-port',\n String(ports.tunnel),\n];\n\nconst runForeground = ({ binaries, config, ports }: Start) =>\n Effect.gen(function* loadThenSupervise() {\n // Loaded here, so stop, status and check skip loading Better Auth.\n const supervise = yield* Effect.promise(async () => {\n const module = await import('./supervise.ts');\n return module.supervise;\n });\n yield* supervise(config, { binaries, ports });\n });\n\n/** `stop` finds the server only in the state dir it was started with, so the hint names a flag. */\nconst runDetached = (start: Start, stateDirGiven: Option.Option<string>) =>\n startDetached(start.state, foregroundArgs(start)).pipe(\n Effect.flatMap((pid) =>\n Console.log(\n `wt-tunnel-server is running (pid ${pid}). Log: ${start.state.log}. Stop it with wt-tunnel-server stop${Option.isSome(stateDirGiven) ? ` --state-dir ${start.state.dir}` : ''}.`,\n ),\n ),\n );\n\nconst start = Command.make(\n 'start',\n {\n caddy: binaryFlag('caddy'),\n config: configFlag,\n detach: Flag.Boolean('detach').pipe(\n Flag.withDescription(\n 'Run in the background: return once the server listens, with its output in server.log',\n ),\n Flag.withDefault(false),\n ),\n frps: binaryFlag('frps'),\n http: portFlag('http-port', defaultPorts.http, 'The port Caddy redirects to https on'),\n https: portFlag('https-port', defaultPorts.https, 'The port Caddy serves dev hosts on'),\n stateDir: stateDirFlag,\n tunnel: portFlag('tunnel-port', defaultPorts.tunnel, 'The port frps accepts frpc on'),\n },\n (input) =>\n Effect.gen(function* startServer() {\n const state = stateDirFrom(input.stateDir);\n yield* refuseIfRunning(state);\n const file = yield* configFileOf(Option.getOrUndefined(input.config), process.env);\n const configFile = file === undefined ? undefined : resolve(file);\n // The config is checked before anything is downloaded.\n const config = yield* loadServerConfig(configFile, process.env);\n const binaries = yield* resolveBinaries({\n caddy: Option.getOrUndefined(input.caddy),\n frps: Option.getOrUndefined(input.frps),\n });\n const checked: Start = {\n binaries,\n config,\n configFile,\n ports: { http: input.http, https: input.https, tunnel: input.tunnel },\n state,\n };\n yield* input.detach ? runDetached(checked, input.stateDir) : runForeground(checked);\n }),\n).pipe(\n Command.withDescription(\n 'Run Caddy, frps and the sign-in service; in the foreground unless --detach',\n ),\n);\n\nconst stop = Command.make('stop', { stateDir: stateDirFlag }, ({ stateDir }) =>\n Effect.gen(function* stopDetached() {\n const previous = yield* stopServer(stateDirFrom(stateDir));\n yield* Console.log(\n previous._tag === 'running' ? `Stopped (pid ${previous.pid}).` : 'Not running.',\n );\n }),\n).pipe(Command.withDescription('Stop the detached server and wait until Caddy and frps exit'));\n\nconst status = Command.make('status', { stateDir: stateDirFlag }, ({ stateDir }) =>\n Effect.gen(function* printStatus() {\n const state = stateDirFrom(stateDir);\n const current = yield* serverStatus(state);\n if (current._tag === 'running') {\n yield* Console.log(\n `running: pid ${current.pid}, since ${current.since.toISOString()}, log ${state.log}`,\n );\n return;\n }\n yield* Console.log(\n current._tag === 'stale'\n ? `stopped (pid ${current.pid} in ${state.pid} is not this server)`\n : 'stopped',\n );\n process.exitCode = stoppedExitCode;\n }),\n).pipe(\n Command.withDescription('Show whether the detached server runs: exit 0 if it does, 3 if not'),\n);\n\nconst check = Command.make('check', { config: configFlag }, ({ config }) =>\n Effect.gen(function* checkConfig() {\n const file = yield* configFileOf(Option.getOrUndefined(config), process.env);\n yield* loadServerConfig(file, process.env);\n yield* Console.log(`${file ?? 'WT_TUNNEL_SERVER_CONFIG'} is a valid server config`);\n }),\n).pipe(Command.withDescription('Check the server config without starting anything'));\n\nconst cli = Command.make('wt-tunnel-server').pipe(\n Command.withDescription(\n 'The wt-tunnel server: Caddy, frps and a Google sign-in service under one supervisor',\n ),\n Command.withSubcommands([start, stop, status, check]),\n);\n\nconst run = (version: string) => Command.run(cli, { version });\n\nexport { run };\n"],"mappings":";;;;;;;;;AAeA,MAAM,kBAAkB;AACxB,MAAM,UAAU;AAEhB,MAAM,aAAa,KAAK,OAAO,QAAQ,CAAC,CAAC,KACvC,KAAK,gBACH,qGACF,GACA,KAAK,QACP;AAEA,MAAM,eAAe,KAAK,OAAO,WAAW,CAAC,CAAC,KAC5C,KAAK,gBACH,4KACF,GACA,KAAK,QACP;AAEA,MAAM,OAAO,OAAO,IAAI,MAAM,OAAO,UAAU;CAAE,SAAS;CAAS,SAAS;AAAE,CAAC,CAAC;AAEhF,MAAM,YAAY,MAAc,UAAkB,gBAChD,KAAK,IAAI,IAAI,CAAC,CAAC,KACb,KAAK,WAAW,IAAI,GACpB,KAAK,gBAAgB,GAAG,YAAY,YAAY,SAAS,EAAE,GAC3D,KAA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M,YAAY,EAAE,QAAQ,MAAM,KAClF;EACA;CACF;CACA,OAAO,QAAQ,IACb,QAAQ,SAAS,UACb,gBAAgB,QAAQ,IAAI,MAAM,MAAM,IAAI,wBAC5C,SACN;CACA,QAAQ,WAAW;AACrB,CAAC,CACH,CAAC,CAAC,KACA,QAAQ,gBAAgB,oEAAoE,CAC9F;AAEA,MAAM,QAAQ,QAAQ,KAAK,SAAS,EAAE,QAAQ,WAAW,IAAI,EAAE,aAC7D,OAAO,IAAI,UAAU,cAAc;CACjC,MAAM,OAAO,OAAO,aAAa,OAAO,eAAe,MAAM,GAAG,QAAQ,GAAG;CAC3E,OAAO,iBAAiB,MAAM,QAAQ,GAAG;CACzC,OAAO,QAAQ,IAAI,GAAG,QAAQ,0BAA0B,0BAA0B;AACpF,CAAC,CACH,CAAC,CAAC,KAAK,QAAQ,gBAAgB,mDAAmD,CAAC;AAEnF,MAAM,MAAM,QAAQ,KAAK,kBAAkB,CAAC,CAAC,KAC3C,QAAQ,gBACN,qFACF,GACA,QAAQ,gBAAgB;CAAC;CAAO;CAAM;CAAQ;AAAK,CAAC,CACtD;AAEA,MAAM,OAAO,YAAoB,QAAQ,IAAI,KAAK,EAAE,QAAQ,CAAC"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { resolve } from 'node:path';\n\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Console, Effect, Option, Schema } from 'effect';\nimport { Command, Flag } from 'effect/cli';\n\nimport { resolveBinaries } from './binaries.ts';\nimport type { Binaries } from './binaries.ts';\nimport { configFileOf, loadServerConfig } from './config.ts';\nimport { refuseIfRunning, serverStatus, startDetached, stateDirOf, stopServer } from './daemon.ts';\nimport type { StateDir } from './daemon.ts';\nimport { defaultPorts } from './render.ts';\nimport type { Ports } from './render.ts';\n\n/** `status` exits with 3 when no server runs, as LSB init scripts do. */\nconst stoppedExitCode = 3;\nconst maxPort = 65_535;\n\nconst configFlag = Flag.String('config').pipe(\n Flag.withDescription(\n 'The server config file. Default: the JSON in WT_TUNNEL_SERVER_CONFIG, else ./wt-tunnel-server.json.',\n ),\n Flag.optional,\n);\n\nconst stateDirFlag = Flag.String('state-dir').pipe(\n Flag.withDescription(\n 'Where a detached server keeps server.pid and server.log. Default: WT_TUNNEL_SERVER_STATE_DIR, else $XDG_STATE_HOME/wt-tunnel-server, else ~/.local/state/wt-tunnel-server.',\n ),\n Flag.optional,\n);\n\nconst Port = Schema.Int.check(Schema.isBetween({ maximum: maxPort, minimum: 1 }));\n\nconst portFlag = (name: string, fallback: number, description: string) =>\n Flag.Int(name).pipe(\n Flag.withSchema(Port),\n Flag.withDescription(`${description} (default ${fallback})`),\n Flag.withDefault(fallback),\n );\n\nconst binaryFlag = (name: string) =>\n Flag.String(name).pipe(\n Flag.withDescription(\n `Run this ${name} executable. Default: ${name} on PATH, else the pinned release, downloaded to the user cache on first use.`,\n ),\n Flag.optional,\n );\n\nconst stateDirFrom = (flag: Option.Option<string>) =>\n stateDirOf(Option.getOrUndefined(flag), process.env);\n\n/** What `start` needs once the flags are checked. */\ninterface Start {\n readonly binaries: Binaries;\n readonly config: ServerConfig;\n /** The config file as an absolute path, so a detached server finds it from any directory. */\n readonly configFile: string | undefined;\n readonly ports: Ports;\n readonly state: StateDir;\n}\n\n/**\n * The arguments a detached server is started with: the resolved binaries, so it never downloads,\n * and the state dir, which is how `status` and `stop` recognise it.\n */\nconst foregroundArgs = ({ binaries, configFile, ports, state }: Start) => [\n 'start',\n ...(configFile === undefined ? [] : ['--config', configFile]),\n '--state-dir',\n state.dir,\n '--caddy',\n binaries.caddy,\n '--frps',\n binaries.frps,\n '--https-port',\n String(ports.https),\n '--http-port',\n String(ports.http),\n '--tunnel-port',\n String(ports.tunnel),\n];\n\nconst runForeground = ({ binaries, config, ports }: Start) =>\n Effect.gen(function* loadThenSupervise() {\n // Loaded here, so stop, status and check skip loading Better Auth.\n const supervise = yield* Effect.promise(async () => {\n const module = await import('./supervise.ts');\n return module.supervise;\n });\n yield* supervise(config, { binaries, ports });\n });\n\n/** `stop` finds the server only in the state dir it was started with, so the hint names a flag. */\nconst runDetached = (start: Start, stateDirGiven: Option.Option<string>) =>\n startDetached(start.state, foregroundArgs(start)).pipe(\n Effect.flatMap((pid) =>\n Console.log(\n `wt-tunnel-server is running (pid ${pid}). Log: ${start.state.log}. Stop it with wt-tunnel-server stop${Option.isSome(stateDirGiven) ? ` --state-dir ${start.state.dir}` : ''}.`,\n ),\n ),\n );\n\nconst start = Command.make(\n 'start',\n {\n caddy: binaryFlag('caddy'),\n config: configFlag,\n detach: Flag.Boolean('detach').pipe(\n Flag.withDescription(\n 'Run in the background: return once the server listens, with its output in server.log',\n ),\n Flag.withDefault(false),\n ),\n frps: binaryFlag('frps'),\n http: portFlag('http-port', defaultPorts.http, 'The port Caddy redirects to https on'),\n https: portFlag('https-port', defaultPorts.https, 'The port Caddy serves dev hosts on'),\n stateDir: stateDirFlag,\n tunnel: portFlag('tunnel-port', defaultPorts.tunnel, 'The port frps accepts frpc on'),\n },\n (input) =>\n Effect.gen(function* startServer() {\n const state = stateDirFrom(input.stateDir);\n yield* refuseIfRunning(state);\n const file = yield* configFileOf(Option.getOrUndefined(input.config), process.env);\n const configFile = file === undefined ? undefined : resolve(file);\n // The config is checked before anything is downloaded.\n const config = yield* loadServerConfig(configFile, process.env);\n const binaries = yield* resolveBinaries({\n caddy: Option.getOrUndefined(input.caddy),\n frps: Option.getOrUndefined(input.frps),\n });\n const checked: Start = {\n binaries,\n config,\n configFile,\n ports: { http: input.http, https: input.https, tunnel: input.tunnel },\n state,\n };\n yield* input.detach ? runDetached(checked, input.stateDir) : runForeground(checked);\n }),\n).pipe(\n Command.withDescription(\n 'Run Caddy, frps and the sign-in service; in the foreground unless --detach',\n ),\n);\n\n/** A command that acts on the detached server that --state-dir names. */\nconst stateDirCommand = <Failure, Requirements>(\n name: string,\n description: string,\n act: (state: StateDir) => Effect.Effect<void, Failure, Requirements>,\n) =>\n Command.make(name, { stateDir: stateDirFlag }, ({ stateDir }) =>\n act(stateDirFrom(stateDir)),\n ).pipe(Command.withDescription(description));\n\nconst stop = stateDirCommand(\n 'stop',\n 'Stop the detached server and wait until Caddy and frps exit',\n (state) =>\n Effect.gen(function* stopDetached() {\n const previous = yield* stopServer(state);\n yield* Console.log(\n previous._tag === 'running' ? `Stopped (pid ${previous.pid}).` : 'Not running.',\n );\n }),\n);\n\nconst status = stateDirCommand(\n 'status',\n 'Show whether the detached server runs: exit 0 if it does, 3 if not',\n (state) =>\n Effect.gen(function* printStatus() {\n const current = yield* serverStatus(state);\n if (current._tag === 'running') {\n yield* Console.log(\n `running: pid ${current.pid}, since ${current.since.toISOString()}, log ${state.log}`,\n );\n return;\n }\n yield* Console.log(\n current._tag === 'stale'\n ? `stopped (pid ${current.pid} in ${state.pid} is not this server)`\n : 'stopped',\n );\n process.exitCode = stoppedExitCode;\n }),\n);\n\nconst check = Command.make('check', { config: configFlag }, ({ config }) =>\n Effect.gen(function* checkConfig() {\n const file = yield* configFileOf(Option.getOrUndefined(config), process.env);\n yield* loadServerConfig(file, process.env);\n yield* Console.log(`${file ?? 'WT_TUNNEL_SERVER_CONFIG'} is a valid server config`);\n }),\n).pipe(Command.withDescription('Check the server config without starting anything'));\n\nconst cli = Command.make('wt-tunnel-server').pipe(\n Command.withDescription(\n 'The wt-tunnel server: Caddy, frps and the sign-in service under one supervisor',\n ),\n Command.withSubcommands([start, stop, status, check]),\n);\n\nconst run = (version: string) => Command.run(cli, { version });\n\nexport { run };\n"],"mappings":";;;;;;;;;AAeA,MAAM,kBAAkB;AACxB,MAAM,UAAU;AAEhB,MAAM,aAAa,KAAK,OAAO,QAAQ,CAAC,CAAC,KACvC,KAAK,gBACH,qGACF,GACA,KAAK,QACP;AAEA,MAAM,eAAe,KAAK,OAAO,WAAW,CAAC,CAAC,KAC5C,KAAK,gBACH,4KACF,GACA,KAAK,QACP;AAEA,MAAM,OAAO,OAAO,IAAI,MAA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cACnE;AACF,CAAC,CACL;AAEA,MAAM,SAAS,gBACb,UACA,uEACC,UACC,OAAO,IAAI,UAAU,cAAc;CACjC,MAAM,UAAU,OAAO,aAAa,KAAK;CACzC,IAAI,QAAQ,SAAS,WAAW;EAC9B,OAAO,QAAQ,IACb,gBAAgB,QAAQ,IAAI,UAAU,QAAQ,MAAM,YAAY,EAAE,QAAQ,MAAM,KAClF;EACA;CACF;CACA,OAAO,QAAQ,IACb,QAAQ,SAAS,UACb,gBAAgB,QAAQ,IAAI,MAAM,MAAM,IAAI,wBAC5C,SACN;CACA,QAAQ,WAAW;AACrB,CAAC,CACL;AAEA,MAAM,QAAQ,QAAQ,KAAK,SAAS,EAAE,QAAQ,WAAW,IAAI,EAAE,aAC7D,OAAO,IAAI,UAAU,cAAc;CACjC,MAAM,OAAO,OAAO,aAAa,OAAO,eAAe,MAAM,GAAG,QAAQ,GAAG;CAC3E,OAAO,iBAAiB,MAAM,QAAQ,GAAG;CACzC,OAAO,QAAQ,IAAI,GAAG,QAAQ,0BAA0B,0BAA0B;AACpF,CAAC,CACH,CAAC,CAAC,KAAK,QAAQ,gBAAgB,mDAAmD,CAAC;AAEnF,MAAM,MAAM,QAAQ,KAAK,kBAAkB,CAAC,CAAC,KAC3C,QAAQ,gBACN,gFACF,GACA,QAAQ,gBAAgB;CAAC;CAAO;CAAM;CAAQ;AAAK,CAAC,CACtD;AAEA,MAAM,OAAO,YAAoB,QAAQ,IAAI,KAAK,EAAE,QAAQ,CAAC"}
|
|
@@ -6,8 +6,8 @@ const caddyTarball = (target, sha256) => ({
|
|
|
6
6
|
});
|
|
7
7
|
/**
|
|
8
8
|
* SHA-256 of each tarball, computed after it matched the SHA-512 in the release's
|
|
9
|
-
* caddy_2.11.7_checksums.txt. The
|
|
10
|
-
* version.
|
|
9
|
+
* caddy_2.11.7_checksums.txt. The image's Dockerfile (docker/Dockerfile) copies Caddy from the
|
|
10
|
+
* image of the same version.
|
|
11
11
|
*/
|
|
12
12
|
const caddyPin = {
|
|
13
13
|
name: "caddy",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caddy.js","names":[],"sources":["../../../../../../packages/binaries/src/caddy.ts"],"sourcesContent":["import type { Pin } from './install.ts';\n\nconst caddyVersion = '2.11.7';\n\nconst caddyTarball = (target: string, sha256: string) => ({\n sha256,\n url: `https://github.com/caddyserver/caddy/releases/download/v${caddyVersion}/caddy_${caddyVersion}_${target}.tar.gz`,\n});\n\n/**\n * SHA-256 of each tarball, computed after it matched the SHA-512 in the release's\n * caddy_2.11.7_checksums.txt. The
|
|
1
|
+
{"version":3,"file":"caddy.js","names":[],"sources":["../../../../../../packages/binaries/src/caddy.ts"],"sourcesContent":["import type { Pin } from './install.ts';\n\nconst caddyVersion = '2.11.7';\n\nconst caddyTarball = (target: string, sha256: string) => ({\n sha256,\n url: `https://github.com/caddyserver/caddy/releases/download/v${caddyVersion}/caddy_${caddyVersion}_${target}.tar.gz`,\n});\n\n/**\n * SHA-256 of each tarball, computed after it matched the SHA-512 in the release's\n * caddy_2.11.7_checksums.txt. The image's Dockerfile (docker/Dockerfile) copies Caddy from the\n * image of the same version.\n */\nconst caddyPin: Pin = {\n name: 'caddy',\n tarballs: {\n 'darwin-arm64': caddyTarball(\n 'mac_arm64',\n 'cda3030e5d5b13eb9f0b6fb541037f633bddd958c070c5f561d7a5cccb581665',\n ),\n 'darwin-x64': caddyTarball(\n 'mac_amd64',\n '110c53e5c093e4cfce6eda787f94f23bef913c309f620fab26b4f678031841ad',\n ),\n 'linux-arm64': caddyTarball(\n 'linux_arm64',\n 'd8fc6d179a5d283028a472a5618564f6ad8a86fed513e64f032b3b0b7cc45e42',\n ),\n 'linux-x64': caddyTarball(\n 'linux_amd64',\n '727b91701a392de6ebc5027509f548bf39979e5216340d0faed8fa5e69c84f8b',\n ),\n },\n version: caddyVersion,\n};\n\nexport { caddyPin };\n"],"mappings":";AAEA,MAAM,eAAe;AAErB,MAAM,gBAAgB,QAAgB,YAAoB;CACxD;CACA,KAAK,2DAA2D,aAAa,SAAS,aAAa,GAAG,OAAO;AAC/G;;;;;;AAOA,MAAM,WAAgB;CACpB,MAAM;CACN,UAAU;EACR,gBAAgB,aACd,aACA,kEACF;EACA,cAAc,aACZ,aACA,kEACF;EACA,eAAe,aACb,eACA,kEACF;EACA,aAAa,aACX,eACA,kEACF;CACF;CACA,SAAS;AACX"}
|
|
@@ -105,6 +105,6 @@ const pinnedBinary = (pin, destination) => Effect.gen(function* cachedOrDownload
|
|
|
105
105
|
tarball
|
|
106
106
|
});
|
|
107
107
|
});
|
|
108
|
-
export {
|
|
108
|
+
export { cacheHome, installTarballEntry, pinnedBinary, tarballFor };
|
|
109
109
|
|
|
110
110
|
//# sourceMappingURL=install.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"install.js","names":[],"sources":["../../../../../../packages/binaries/src/install.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { access, chmod, mkdir, rename, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { gunzip } from 'node:zlib';\n\nimport { Console, Effect, Schema } from 'effect';\n\n/*\n * The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in\n * `Error`, as an error thrown without `new`.\n */\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass InstallError extends taggedErrorClass<InstallError>()('InstallError', {\n message: Schema.String,\n}) {}\n\n/** A release tarball and the SHA-256 it must have. */\ninterface Tarball {\n readonly sha256: string;\n readonly url: string;\n}\n\n/** One executable at one version, with a tarball per `<process.platform>-<process.arch>`. */\ninterface Pin {\n readonly name: string;\n readonly tarballs: Readonly<Partial<Record<string, Tarball>>>;\n readonly version: string;\n}\n\nconst executableMode = 0o755;\n\nconst tarBlock = 512;\nconst tarName = { end: 100, start: 0 } as const;\nconst tarSize = { end: 136, start: 124 } as const;\nconst tarType = { end: 157, start: 156 } as const;\nconst octal = 8;\n/** Old tar writes NUL, ustar writes '0', for a regular file. */\nconst regularFileTypes: ReadonlySet<string> = new Set(['0', '\\0']);\n\n/** A header block's fields; undefined for the zero block that ends the archive. */\nconst tarHeader = (\n block: Buffer,\n): { readonly path: string; readonly regularFile: boolean; readonly size: number } | undefined => {\n const path = block.toString('utf8', tarName.start, tarName.end).replace(/\\0.*$/su, '');\n const size = Number.parseInt(block.toString('ascii', tarSize.start, tarSize.end).trim(), octal);\n if (path === '' || Number.isNaN(size)) {\n return undefined;\n }\n const regularFile = regularFileTypes.has(block.toString('ascii', tarType.start, tarType.end));\n return { path, regularFile, size };\n};\n\n/**\n * The bytes of the regular file named `name` (in any directory) in a tar archive. Reading the one\n * entry in process means nothing in the archive decides which paths get written.\n */\nconst tarEntry = (archive: Buffer, name: string): Buffer | undefined => {\n let offset = 0;\n while (offset + tarBlock <= archive.length) {\n const header = tarHeader(archive.subarray(offset, offset + tarBlock));\n if (header === undefined) {\n return undefined;\n }\n const data = offset + tarBlock;\n if (header.regularFile && basename(header.path) === name) {\n return archive.subarray(data, data + header.size);\n }\n offset = data + Math.ceil(header.size / tarBlock) * tarBlock;\n }\n return undefined;\n};\n\ntype FetchBytes = (url: string) => Promise<Uint8Array>;\n\nconst fetchBytes: FetchBytes = async (url) => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return new Uint8Array(await response.arrayBuffer());\n};\n\nconst installFailed = (pin: Pin, message: string) =>\n new InstallError({ message: `Could not install ${pin.name}: ${message}` });\n\n/** The rename is atomic, so a concurrent install sees no file or a complete one. */\nconst placeExecutable = async (destination: string, bytes: Buffer) => {\n await mkdir(dirname(destination), { recursive: true });\n const temp = `${destination}.${process.pid}.tmp`;\n await writeFile(temp, bytes);\n await chmod(temp, executableMode);\n await rename(temp, destination);\n};\n\nconst verifiedDownload = (pin: Pin, tarball: Tarball, download: FetchBytes) =>\n Effect.gen(function* downloadThenHash() {\n yield* Console.log(`Downloading ${pin.name} ${pin.version} from ${tarball.url}`);\n const bytes = yield* Effect.tryPromise({\n catch: (cause) => installFailed(pin, `${tarball.url}: ${String(cause)}`),\n try: () => download(tarball.url),\n });\n const actual = createHash('sha256').update(bytes).digest('hex');\n if (actual !== tarball.sha256) {\n return yield* installFailed(\n pin,\n `${tarball.url} has SHA-256 ${actual}, expected ${tarball.sha256}. Nothing was installed.`,\n );\n }\n return bytes;\n });\n\n/** Where to install from and to. */\ninterface Install {\n readonly destination: string;\n readonly download: FetchBytes;\n readonly tarball: Tarball;\n}\n\n/** Downloads the tarball, checks its SHA-256, and moves only the pinned executable into place. */\nconst installTarballEntry = (pin: Pin, { destination, download, tarball }: Install) =>\n Effect.gen(function* downloadVerifyExtract() {\n const bytes = yield* verifiedDownload(pin, tarball, download);\n const archive = yield* Effect.promise(() => promisify(gunzip)(bytes));\n const executable = tarEntry(archive, pin.name);\n if (executable === undefined) {\n return yield* installFailed(pin, `${tarball.url} holds no ${pin.name}.`);\n }\n yield* Effect.promise(() => placeExecutable(destination, executable));\n return destination;\n });\n\nconst tarballFor = (pin: Pin, platform: string, arch: string) =>\n pin.tarballs[`${platform}-${arch}`];\n\n/** The user's cache directory: `$XDG_CACHE_HOME`, else the platform's usual place. */\nconst cacheHome = () =>\n process.env.XDG_CACHE_HOME ??\n (process.platform === 'darwin'\n ? join(homedir(), 'Library', 'Caches')\n : join(homedir(), '.cache'));\n\nconst exists = (path: string) =>\n Effect.promise(async () => {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n });\n\n/** The executable at `destination`, downloaded there on first use. */\nconst pinnedBinary = (pin: Pin, destination: string) =>\n Effect.gen(function* cachedOrDownload() {\n if (yield* exists(destination)) {\n return destination;\n }\n const tarball = tarballFor(pin, process.platform, process.arch);\n if (tarball === undefined) {\n return yield* installFailed(\n pin,\n `no pinned ${pin.version} build for ${process.platform} ${process.arch}.`,\n );\n }\n return yield* installTarballEntry(pin, { destination, download: fetchBytes, tarball });\n });\n\nexport { cacheHome,
|
|
1
|
+
{"version":3,"file":"install.js","names":[],"sources":["../../../../../../packages/binaries/src/install.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { access, chmod, mkdir, rename, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { gunzip } from 'node:zlib';\n\nimport { Console, Effect, Schema } from 'effect';\n\n/*\n * The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in\n * `Error`, as an error thrown without `new`.\n */\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass InstallError extends taggedErrorClass<InstallError>()('InstallError', {\n message: Schema.String,\n}) {}\n\n/** A release tarball and the SHA-256 it must have. */\ninterface Tarball {\n readonly sha256: string;\n readonly url: string;\n}\n\n/** One executable at one version, with a tarball per `<process.platform>-<process.arch>`. */\ninterface Pin {\n readonly name: string;\n readonly tarballs: Readonly<Partial<Record<string, Tarball>>>;\n readonly version: string;\n}\n\nconst executableMode = 0o755;\n\nconst tarBlock = 512;\nconst tarName = { end: 100, start: 0 } as const;\nconst tarSize = { end: 136, start: 124 } as const;\nconst tarType = { end: 157, start: 156 } as const;\nconst octal = 8;\n/** Old tar writes NUL, ustar writes '0', for a regular file. */\nconst regularFileTypes: ReadonlySet<string> = new Set(['0', '\\0']);\n\n/** A header block's fields; undefined for the zero block that ends the archive. */\nconst tarHeader = (\n block: Buffer,\n): { readonly path: string; readonly regularFile: boolean; readonly size: number } | undefined => {\n const path = block.toString('utf8', tarName.start, tarName.end).replace(/\\0.*$/su, '');\n const size = Number.parseInt(block.toString('ascii', tarSize.start, tarSize.end).trim(), octal);\n if (path === '' || Number.isNaN(size)) {\n return undefined;\n }\n const regularFile = regularFileTypes.has(block.toString('ascii', tarType.start, tarType.end));\n return { path, regularFile, size };\n};\n\n/**\n * The bytes of the regular file named `name` (in any directory) in a tar archive. Reading the one\n * entry in process means nothing in the archive decides which paths get written.\n */\nconst tarEntry = (archive: Buffer, name: string): Buffer | undefined => {\n let offset = 0;\n while (offset + tarBlock <= archive.length) {\n const header = tarHeader(archive.subarray(offset, offset + tarBlock));\n if (header === undefined) {\n return undefined;\n }\n const data = offset + tarBlock;\n if (header.regularFile && basename(header.path) === name) {\n return archive.subarray(data, data + header.size);\n }\n offset = data + Math.ceil(header.size / tarBlock) * tarBlock;\n }\n return undefined;\n};\n\ntype FetchBytes = (url: string) => Promise<Uint8Array>;\n\nconst fetchBytes: FetchBytes = async (url) => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return new Uint8Array(await response.arrayBuffer());\n};\n\nconst installFailed = (pin: Pin, message: string) =>\n new InstallError({ message: `Could not install ${pin.name}: ${message}` });\n\n/** The rename is atomic, so a concurrent install sees no file or a complete one. */\nconst placeExecutable = async (destination: string, bytes: Buffer) => {\n await mkdir(dirname(destination), { recursive: true });\n const temp = `${destination}.${process.pid}.tmp`;\n await writeFile(temp, bytes);\n await chmod(temp, executableMode);\n await rename(temp, destination);\n};\n\nconst verifiedDownload = (pin: Pin, tarball: Tarball, download: FetchBytes) =>\n Effect.gen(function* downloadThenHash() {\n yield* Console.log(`Downloading ${pin.name} ${pin.version} from ${tarball.url}`);\n const bytes = yield* Effect.tryPromise({\n catch: (cause) => installFailed(pin, `${tarball.url}: ${String(cause)}`),\n try: () => download(tarball.url),\n });\n const actual = createHash('sha256').update(bytes).digest('hex');\n if (actual !== tarball.sha256) {\n return yield* installFailed(\n pin,\n `${tarball.url} has SHA-256 ${actual}, expected ${tarball.sha256}. Nothing was installed.`,\n );\n }\n return bytes;\n });\n\n/** Where to install from and to. */\ninterface Install {\n readonly destination: string;\n readonly download: FetchBytes;\n readonly tarball: Tarball;\n}\n\n/** Downloads the tarball, checks its SHA-256, and moves only the pinned executable into place. */\nconst installTarballEntry = (pin: Pin, { destination, download, tarball }: Install) =>\n Effect.gen(function* downloadVerifyExtract() {\n const bytes = yield* verifiedDownload(pin, tarball, download);\n const archive = yield* Effect.promise(() => promisify(gunzip)(bytes));\n const executable = tarEntry(archive, pin.name);\n if (executable === undefined) {\n return yield* installFailed(pin, `${tarball.url} holds no ${pin.name}.`);\n }\n yield* Effect.promise(() => placeExecutable(destination, executable));\n return destination;\n });\n\nconst tarballFor = (pin: Pin, platform: string, arch: string) =>\n pin.tarballs[`${platform}-${arch}`];\n\n/** The user's cache directory: `$XDG_CACHE_HOME`, else the platform's usual place. */\nconst cacheHome = () =>\n process.env.XDG_CACHE_HOME ??\n (process.platform === 'darwin'\n ? join(homedir(), 'Library', 'Caches')\n : join(homedir(), '.cache'));\n\nconst exists = (path: string) =>\n Effect.promise(async () => {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n });\n\n/** The executable at `destination`, downloaded there on first use. */\nconst pinnedBinary = (pin: Pin, destination: string) =>\n Effect.gen(function* cachedOrDownload() {\n if (yield* exists(destination)) {\n return destination;\n }\n const tarball = tarballFor(pin, process.platform, process.arch);\n if (tarball === undefined) {\n return yield* installFailed(\n pin,\n `no pinned ${pin.version} build for ${process.platform} ${process.arch}.`,\n );\n }\n return yield* installTarballEntry(pin, { destination, download: fetchBytes, tarball });\n });\n\nexport { cacheHome, installTarballEntry, pinnedBinary, tarballFor };\nexport type { FetchBytes, Install, Pin, Tarball };\n"],"mappings":";;;;;;;;AAaA,MAAM,EAAE,aAAa,qBAAqB;AAE1C,IAAM,eAAN,cAA2B,iBAA+B,CAAC,CAAC,gBAAgB,EAC1E,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;AAeJ,MAAM,iBAAiB;AAEvB,MAAM,WAAW;AACjB,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAE;AACrC,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAI;AACvC,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAI;AACvC,MAAM,QAAQ;;AAEd,MAAM,mCAAwC,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC;;AAGjE,MAAM,aACJ,UACgG;CAChG,MAAM,OAA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,OAAO,IAAI;EACjB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF,CAAC;;AAGH,MAAM,gBAAgB,KAAU,gBAC9B,OAAO,IAAI,UAAU,mBAAmB;CACtC,IAAI,OAAO,OAAO,WAAW,GAC3B,OAAO;CAET,MAAM,UAAU,WAAW,KAAK,QAAQ,UAAU,QAAQ,IAAI;CAC9D,IAAI,YAAY,KAAA,GACd,OAAO,OAAO,cACZ,KACA,aAAa,IAAI,QAAQ,aAAa,QAAQ,SAAS,GAAG,QAAQ,KAAK,EACzE;CAEF,OAAO,OAAO,oBAAoB,KAAK;EAAE;EAAa,UAAU;EAAY;CAAQ,CAAC;AACvF,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { Console, Effect, Schema } from "effect";
|
|
3
|
+
// ../../packages/contract/src/bin.ts
|
|
4
|
+
const PackageJson = Schema.Struct({ version: Schema.String });
|
|
5
|
+
/** The version in the package.json one level above the built bin at `binUrl`. */
|
|
6
|
+
const packageVersion = (binUrl) => {
|
|
7
|
+
const packageJson = createRequire(binUrl)("../package.json");
|
|
8
|
+
return Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(Effect.map(({ version }) => version), Effect.orDie);
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Runs the CLI at the version of the package whose bin is at `url`. `name` is the name it prints.
|
|
12
|
+
* An `expected` failure carries a message written for the user, so it is printed as `<name>:
|
|
13
|
+
* <message>` without a stack trace, and the bin exits 1.
|
|
14
|
+
*/
|
|
15
|
+
const binProgram = (bin, run) => packageVersion(bin.url).pipe(Effect.flatMap(run), Effect.catchIf((failure) => failure._tag === bin.expected, ({ message }) => Console.error(`${bin.name}: ${message}`).pipe(Effect.andThen(Effect.sync(() => {
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
})))));
|
|
18
|
+
export { binProgram };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=bin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.js","names":[],"sources":["../../../../../../packages/contract/src/bin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\n\nimport { Console, Effect, Schema } from 'effect';\n\nconst PackageJson = Schema.Struct({ version: Schema.String });\n\n/** The version in the package.json one level above the built bin at `binUrl`. */\nconst packageVersion = (binUrl: string) => {\n const packageJson: unknown = createRequire(binUrl)('../package.json');\n return Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(\n Effect.map(({ version }) => version),\n Effect.orDie,\n );\n};\n\n/**\n * Runs the CLI at the version of the package whose bin is at `url`. `name` is the name it prints.\n * An `expected` failure carries a message written for the user, so it is printed as `<name>:\n * <message>` without a stack trace, and the bin exits 1.\n */\nconst binProgram = <\n Failure extends { readonly _tag: string },\n Requirements,\n Tag extends Extract<Failure, { readonly message: string }>['_tag'],\n>(\n bin: { readonly expected: Tag; readonly name: string; readonly url: string },\n run: (version: string) => Effect.Effect<void, Failure, Requirements>,\n) =>\n packageVersion(bin.url).pipe(\n Effect.flatMap(run),\n Effect.catchIf(\n (failure): failure is Extract<Failure, { readonly _tag: Tag; readonly message: string }> =>\n failure._tag === bin.expected,\n ({ message }) =>\n Console.error(`${bin.name}: ${message}`).pipe(\n Effect.andThen(\n Effect.sync(() => {\n process.exitCode = 1;\n }),\n ),\n ),\n ),\n );\n\nexport { binProgram };\n"],"mappings":";;;AAIA,MAAM,cAAc,OAAO,OAAO,EAAE,SAAS,OAAO,OAAO,CAAC;;AAG5D,MAAM,kBAAkB,WAAmB;CACzC,MAAM,cAAuB,cAAc,MAAM,CAAC,CAAC,iBAAiB;CACpE,OAAO,OAAO,oBAAoB,WAAW,CAAC,CAAC,WAAW,CAAC,CAAC,KAC1D,OAAO,KAAK,EAAE,cAAc,OAAO,GACnC,OAAO,KACT;AACF;;;;;;AAOA,MAAM,cAKJ,KACA,QAEA,eAAe,IAAI,GAAG,CAAC,CAAC,KACtB,OAAO,QAAQ,GAAG,GAClB,OAAO,SACJ,YACC,QAAQ,SAAS,IAAI,WACtB,EAAE,cACD,QAAQ,MAAM,GAAG,IAAI,KAAK,IAAI,SAAS,CAAC,CAAC,KACvC,OAAO,QACL,OAAO,WAAW;CAChB,QAAQ,WAAW;AACrB,CAAC,CACH,CACF,CACJ,CACF"}
|
|
@@ -94,6 +94,6 @@ const readServerConfig = (input) => Effect.gen(function* readConfig() {
|
|
|
94
94
|
ca
|
|
95
95
|
};
|
|
96
96
|
});
|
|
97
|
-
export { AllowList,
|
|
97
|
+
export { AllowList, ServerConfigFileJson, caFile, providerIds, readServerConfig, serverConfigFileName };
|
|
98
98
|
|
|
99
99
|
//# sourceMappingURL=server-config.js.map
|
|
@@ -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,cAAc;CAClB,UAAU,OAAO;CACjB,cAAc,OAAO,kBAAkB,OAAO,cAAc;AAC9D;;AAGA,MAAM,cAAc;CAAC;CAAU;CAAU;CAAa;AAAY;;;;;;AAQlE,MAAM,kBAAkB,OAAO,OAAO;CACpC,GAAG;CACH,UAAU,OAAO,YAAY,OAAO,cAAc;AACpD,CAAC;AAED,MAAM,YAAY,OAAO,OAAO;CAC9B,YAAY,OAAO,YAAY,OAAO,OAAO;EAAE,GAAG;EAAa,YAAY;CAAS,CAAC,CAAC;CACtF,QAAQ,OAAO,YAAY,OAAO,OAAO,WAAW,CAAC;CACrD,QAAQ,OAAO,YAAY,OAAO,OAAO,WA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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"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
4
|
+
// ../../packages/contract/src/temp-dir.ts
|
|
5
|
+
/** A fresh directory in `parent`, deleted with everything in it when the scope closes. */
|
|
6
|
+
const scopedTempDir = (parent, prefix) => Effect.acquireRelease(Effect.promise(() => mkdtemp(join(parent, prefix))), (dir) => Effect.promise(() => rm(dir, {
|
|
7
|
+
force: true,
|
|
8
|
+
recursive: true
|
|
9
|
+
})));
|
|
10
|
+
export { scopedTempDir };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=temp-dir.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"temp-dir.js","names":[],"sources":["../../../../../../packages/contract/src/temp-dir.ts"],"sourcesContent":["import { mkdtemp, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { Effect } from 'effect';\n\n/** A fresh directory in `parent`, deleted with everything in it when the scope closes. */\nconst scopedTempDir = (parent: string, prefix: string) =>\n Effect.acquireRelease(\n Effect.promise(() => mkdtemp(join(parent, prefix))),\n (dir) => Effect.promise(() => rm(dir, { force: true, recursive: true })),\n );\n\nexport { scopedTempDir };\n"],"mappings":";;;;;AAMA,MAAM,iBAAiB,QAAgB,WACrC,OAAO,eACL,OAAO,cAAc,QAAQ,KAAK,QAAQ,MAAM,CAAC,CAAC,IACjD,QAAQ,OAAO,cAAc,GAAG,KAAK;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC,CAAC,CACzE"}
|
package/dist/runtime.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { renderCaddyfile, renderFrpsToml } from "./render.js";
|
|
2
|
+
import { scopedTempDir } from "./packages/contract/src/temp-dir.js";
|
|
2
3
|
import { Effect, Redacted } from "effect";
|
|
3
4
|
import { join } from "node:path";
|
|
4
|
-
import { mkdir,
|
|
5
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
5
6
|
import { tmpdir } from "node:os";
|
|
6
7
|
// src/runtime.ts
|
|
7
8
|
/**
|
|
8
9
|
* Writes the Caddyfile, frps.toml and the CA into a fresh private directory, deleted with the scope
|
|
9
10
|
* so no copy of the CA key outlives the server.
|
|
10
11
|
*/
|
|
11
|
-
const writeRuntimeFiles = (config, ports) => Effect.
|
|
12
|
-
const dir = await mkdtemp(join(tmpdir(), "wt-tunnel-server-"));
|
|
12
|
+
const writeRuntimeFiles = (config, ports) => scopedTempDir(tmpdir(), "wt-tunnel-server-").pipe(Effect.tap((dir) => Effect.promise(async () => {
|
|
13
13
|
const paths = {
|
|
14
14
|
caCert: join(dir, "ca.crt"),
|
|
15
15
|
caKey: join(dir, "ca.key"),
|
|
@@ -20,10 +20,6 @@ const writeRuntimeFiles = (config, ports) => Effect.acquireRelease(Effect.promis
|
|
|
20
20
|
await writeFile(paths.caKey, Redacted.value(config.ca.key), { mode: 384 });
|
|
21
21
|
await writeFile(join(dir, "Caddyfile"), renderCaddyfile(config, paths, ports));
|
|
22
22
|
await writeFile(join(dir, "frps.toml"), renderFrpsToml(config, ports), { mode: 384 });
|
|
23
|
-
return dir;
|
|
24
|
-
}), (dir) => Effect.promise(() => rm(dir, {
|
|
25
|
-
force: true,
|
|
26
|
-
recursive: true
|
|
27
23
|
})));
|
|
28
24
|
const childSpecs = (dir, binaries) => {
|
|
29
25
|
const env = {
|
package/dist/runtime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["import { mkdir,
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { scopedTempDir } from '@tafrahq/wt-tunnel-contract/temp-dir';\nimport { Effect, Redacted } from 'effect';\n\nimport type { Binaries } from './binaries.ts';\nimport { renderCaddyfile, renderFrpsToml } from './render.ts';\nimport type { Ports } from './render.ts';\n\n/**\n * Writes the Caddyfile, frps.toml and the CA into a fresh private directory, deleted with the scope\n * so no copy of the CA key outlives the server.\n */\nconst writeRuntimeFiles = (config: ServerConfig, ports: Ports) =>\n scopedTempDir(tmpdir(), 'wt-tunnel-server-').pipe(\n Effect.tap((dir) =>\n Effect.promise(async () => {\n const paths = {\n caCert: join(dir, 'ca.crt'),\n caKey: join(dir, 'ca.key'),\n storage: join(dir, 'caddy'),\n };\n await mkdir(paths.storage, { mode: 0o700 });\n await writeFile(paths.caCert, config.ca.cert);\n await writeFile(paths.caKey, Redacted.value(config.ca.key), { mode: 0o600 });\n await writeFile(join(dir, 'Caddyfile'), renderCaddyfile(config, paths, ports));\n await writeFile(join(dir, 'frps.toml'), renderFrpsToml(config, ports), { mode: 0o600 });\n }),\n ),\n );\n\nconst childSpecs = (dir: string, binaries: Binaries) => {\n // Caddy keeps its local CA and autosave under XDG dirs; keep them in the runtime dir.\n const env = { XDG_CONFIG_HOME: dir, XDG_DATA_HOME: dir };\n return [\n {\n args: ['run', '--adapter', 'caddyfile', '--config', join(dir, 'Caddyfile')],\n command: binaries.caddy,\n env,\n name: 'caddy',\n },\n { args: ['-c', join(dir, 'frps.toml')], command: binaries.frps, env, name: 'frps' },\n ];\n};\n\nexport { childSpecs, writeRuntimeFiles };\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,qBAAqB,QAAsB,UAC/C,cAAc,OAAO,GAAG,mBAAmB,CAAC,CAAC,KAC3C,OAAO,KAAK,QACV,OAAO,QAAQ,YAAY;CACzB,MAAM,QAAQ;EACZ,QAAQ,KAAK,KAAK,QAAQ;EAC1B,OAAO,KAAK,KAAK,QAAQ;EACzB,SAAS,KAAK,KAAK,OAAO;CAC5B;CACA,MAAM,MAAM,MAAM,SAAS,EAAE,MAAM,IAAM,CAAC;CAC1C,MAAM,UAAU,MAAM,QAAQ,OAAO,GAAG,IAAI;CAC5C,MAAM,UAAU,MAAM,OAAO,SAAS,MAAM,OAAO,GAAG,GAAG,GAAG,EAAE,MAAM,IAAM,CAAC;CAC3E,MAAM,UAAU,KAAK,KAAK,WAAW,GAAG,gBAAgB,QAAQ,OAAO,KAAK,CAAC;CAC7E,MAAM,UAAU,KAAK,KAAK,WAAW,GAAG,eAAe,QAAQ,KAAK,GAAG,EAAE,MAAM,IAAM,CAAC;AACxF,CAAC,CACH,CACF;AAEF,MAAM,cAAc,KAAa,aAAuB;CAEtD,MAAM,MAAM;EAAE,iBAAiB;EAAK,eAAe;CAAI;CACvD,OAAO,CACL;EACE,MAAM;GAAC;GAAO;GAAa;GAAa;GAAY,KAAK,KAAK,WAAW;EAAC;EAC1E,SAAS,SAAS;EAClB;EACA,MAAM;CACR,GACA;EAAE,MAAM,CAAC,MAAM,KAAK,KAAK,WAAW,CAAC;EAAG,SAAS,SAAS;EAAM;EAAK,MAAM;CAAO,CACpF;AACF"}
|
package/dist/session.js
CHANGED
|
@@ -36,10 +36,12 @@ const verifySession = (key, value, nowMillis) => {
|
|
|
36
36
|
const cookieAttributes = (domain) => `Domain=${domain}; Path=/; HttpOnly; Secure; SameSite=Lax`;
|
|
37
37
|
const sessionSetCookie = (value, domain) => `${sessionCookieName}=${value}; Max-Age=${sessionSeconds}; ${cookieAttributes(domain)}`;
|
|
38
38
|
const sessionClearCookie = (domain) => `${sessionCookieName}=; Max-Age=0; ${cookieAttributes(domain)}`;
|
|
39
|
+
const sessionPrefix = `${sessionCookieName}=`;
|
|
40
|
+
const cookiePairs = (cookieHeader) => (cookieHeader ?? "").split(";").map((pair) => pair.trim());
|
|
39
41
|
/** A Cookie header's pairs other than `wt_session`, joined again; empty when none are left. */
|
|
40
|
-
const cookiesWithoutSession = (cookieHeader) => (cookieHeader
|
|
42
|
+
const cookiesWithoutSession = (cookieHeader) => cookiePairs(cookieHeader).filter((pair) => pair !== "" && !pair.startsWith(sessionPrefix)).join("; ");
|
|
41
43
|
/** Every `wt_session` value in a Cookie header; a stale one may sit beside a fresh one. */
|
|
42
|
-
const sessionCookieValues = (cookieHeader) => (cookieHeader
|
|
44
|
+
const sessionCookieValues = (cookieHeader) => cookiePairs(cookieHeader).filter((pair) => pair.startsWith(sessionPrefix)).map((pair) => pair.slice(sessionPrefix.length));
|
|
43
45
|
/** One-time codes in memory: random, single use, valid for 60 seconds. */
|
|
44
46
|
const createCodeStore = () => {
|
|
45
47
|
const codes = /* @__PURE__ */ new Map();
|
package/dist/session.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\n\nimport type { Hostname } from '@tafrahq/wt-tunnel-contract';\n\nconst sessionCookieName = 'wt_session';\n/** Seven days. */\nconst sessionSeconds = 604_800;\nconst codeMillis = 60_000;\nconst codeBytes = 32;\nconst cookieParts = 3;\n\n/** What a cookie is bound to: the auth secret and one dev domain. */\ninterface SessionKey {\n readonly domain: Hostname;\n readonly secret: string;\n}\n\nconst millisPerSecond = 1000;\n\n/**\n * The MAC covers the dev domain too, so a cookie minted for one dev domain does not verify on\n * another even when a browser is tricked into sending it there.\n */\nconst mac = ({ domain, secret }: SessionKey, emailPart: string, expiry: string) =>\n createHmac('sha256', secret)\n .update(`${sessionCookieName}|${domain}|${emailPart}|${expiry}`)\n .digest('base64url');\n\n/**\n * `wt_session` value: `base64url(email) \".\" expiry \".\" base64url(HMAC-SHA256(authSecret,\n * \"wt_session|\" domain \"|\" base64url(email) \"|\" expiry))`, expiry in Unix seconds.\n */\nconst mintSession = (key: SessionKey, email: string, nowMillis: number) => {\n const emailPart = Buffer.from(email, 'utf8').toString('base64url');\n const expiry = String(Math.floor(nowMillis / millisPerSecond) + sessionSeconds);\n return `${emailPart}.${expiry}.${mac(key, emailPart, expiry)}`;\n};\n\nconst sameText = (left: string, right: string) => {\n const leftBytes = Buffer.from(left);\n const rightBytes = Buffer.from(right);\n return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);\n};\n\n/** The email the cookie was minted for, when its MAC matches this key and it has not expired. */\nconst verifySession = (key: SessionKey, value: string, nowMillis: number) => {\n const parts = value.split('.');\n const [emailPart = '', expiry = '', signature = ''] = parts;\n const valid =\n parts.length === cookieParts &&\n /^\\d+$/u.test(expiry) &&\n sameText(signature, mac(key, emailPart, expiry)) &&\n Number(expiry) * millisPerSecond > nowMillis;\n const email = valid ? Buffer.from(emailPart, 'base64url').toString('utf8') : '';\n return email === '' ? undefined : email;\n};\n\nconst cookieAttributes = (domain: Hostname) =>\n `Domain=${domain}; Path=/; HttpOnly; Secure; SameSite=Lax`;\n\nconst sessionSetCookie = (value: string, domain: Hostname) =>\n `${sessionCookieName}=${value}; Max-Age=${sessionSeconds}; ${cookieAttributes(domain)}`;\n\nconst sessionClearCookie = (domain: Hostname) =>\n `${sessionCookieName}=; Max-Age=0; ${cookieAttributes(domain)}`;\n\n/** A Cookie header's pairs other than `wt_session`, joined again; empty when none are left. */\nconst cookiesWithoutSession = (cookieHeader: string | undefined) =>\n (cookieHeader
|
|
1
|
+
{"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\n\nimport type { Hostname } from '@tafrahq/wt-tunnel-contract';\n\nconst sessionCookieName = 'wt_session';\n/** Seven days. */\nconst sessionSeconds = 604_800;\nconst codeMillis = 60_000;\nconst codeBytes = 32;\nconst cookieParts = 3;\n\n/** What a cookie is bound to: the auth secret and one dev domain. */\ninterface SessionKey {\n readonly domain: Hostname;\n readonly secret: string;\n}\n\nconst millisPerSecond = 1000;\n\n/**\n * The MAC covers the dev domain too, so a cookie minted for one dev domain does not verify on\n * another even when a browser is tricked into sending it there.\n */\nconst mac = ({ domain, secret }: SessionKey, emailPart: string, expiry: string) =>\n createHmac('sha256', secret)\n .update(`${sessionCookieName}|${domain}|${emailPart}|${expiry}`)\n .digest('base64url');\n\n/**\n * `wt_session` value: `base64url(email) \".\" expiry \".\" base64url(HMAC-SHA256(authSecret,\n * \"wt_session|\" domain \"|\" base64url(email) \"|\" expiry))`, expiry in Unix seconds.\n */\nconst mintSession = (key: SessionKey, email: string, nowMillis: number) => {\n const emailPart = Buffer.from(email, 'utf8').toString('base64url');\n const expiry = String(Math.floor(nowMillis / millisPerSecond) + sessionSeconds);\n return `${emailPart}.${expiry}.${mac(key, emailPart, expiry)}`;\n};\n\nconst sameText = (left: string, right: string) => {\n const leftBytes = Buffer.from(left);\n const rightBytes = Buffer.from(right);\n return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);\n};\n\n/** The email the cookie was minted for, when its MAC matches this key and it has not expired. */\nconst verifySession = (key: SessionKey, value: string, nowMillis: number) => {\n const parts = value.split('.');\n const [emailPart = '', expiry = '', signature = ''] = parts;\n const valid =\n parts.length === cookieParts &&\n /^\\d+$/u.test(expiry) &&\n sameText(signature, mac(key, emailPart, expiry)) &&\n Number(expiry) * millisPerSecond > nowMillis;\n const email = valid ? Buffer.from(emailPart, 'base64url').toString('utf8') : '';\n return email === '' ? undefined : email;\n};\n\nconst cookieAttributes = (domain: Hostname) =>\n `Domain=${domain}; Path=/; HttpOnly; Secure; SameSite=Lax`;\n\nconst sessionSetCookie = (value: string, domain: Hostname) =>\n `${sessionCookieName}=${value}; Max-Age=${sessionSeconds}; ${cookieAttributes(domain)}`;\n\nconst sessionClearCookie = (domain: Hostname) =>\n `${sessionCookieName}=; Max-Age=0; ${cookieAttributes(domain)}`;\n\nconst sessionPrefix = `${sessionCookieName}=`;\n\nconst cookiePairs = (cookieHeader: string | undefined) =>\n (cookieHeader ?? '').split(';').map((pair) => pair.trim());\n\n/** A Cookie header's pairs other than `wt_session`, joined again; empty when none are left. */\nconst cookiesWithoutSession = (cookieHeader: string | undefined) =>\n cookiePairs(cookieHeader)\n .filter((pair) => pair !== '' && !pair.startsWith(sessionPrefix))\n .join('; ');\n\n/** Every `wt_session` value in a Cookie header; a stale one may sit beside a fresh one. */\nconst sessionCookieValues = (cookieHeader: string | undefined) =>\n cookiePairs(cookieHeader)\n .filter((pair) => pair.startsWith(sessionPrefix))\n .map((pair) => pair.slice(sessionPrefix.length));\n\ninterface Grant {\n readonly domain: Hostname;\n readonly email: string;\n readonly host: Hostname;\n /** Where `/_wt/callback` sends the browser once the cookie is set. */\n readonly url: string;\n}\n\ninterface CodeStore {\n readonly issue: (grant: Grant, nowMillis: number) => string;\n /** The grant behind an unexpired code; the code is gone afterwards either way. */\n readonly redeem: (code: string, nowMillis: number) => Grant | undefined;\n}\n\n/** One-time codes in memory: random, single use, valid for 60 seconds. */\nconst createCodeStore = (): CodeStore => {\n const codes = new Map<string, Grant & { readonly expiresAt: number }>();\n return {\n issue: (grant, nowMillis) => {\n for (const [code, entry] of codes) {\n if (entry.expiresAt <= nowMillis) {\n codes.delete(code);\n }\n }\n const code = randomBytes(codeBytes).toString('base64url');\n codes.set(code, { ...grant, expiresAt: nowMillis + codeMillis });\n return code;\n },\n redeem: (code, nowMillis) => {\n const entry = codes.get(code);\n codes.delete(code);\n return entry === undefined || entry.expiresAt <= nowMillis ? undefined : entry;\n },\n };\n};\n\nexport {\n cookiesWithoutSession,\n createCodeStore,\n mintSession,\n sessionClearCookie,\n sessionCookieValues,\n sessionSeconds,\n sessionSetCookie,\n verifySession,\n};\nexport type { CodeStore, Grant, SessionKey };\n"],"mappings":";;AAIA,MAAM,oBAAoB;;AAE1B,MAAM,iBAAiB;AACvB,MAAM,aAAa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AAgB,GAAG,kBAAkB;AAE3C,MAAM,eAAe,kBAClB,gBAAgB,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,KAAK,SAAS,KAAK,KAAK,CAAC;;AAG3D,MAAM,yBAAyB,iBAC7B,YAAY,YAAY,CAAC,CACtB,QAAQ,SAAS,SAAS,MAAM,CAAC,KAAK,WAAW,aAAa,CAAC,CAAC,CAChE,KAAK,IAAI;;AAGd,MAAM,uBAAuB,iBAC3B,YAAY,YAAY,CAAC,CACtB,QAAQ,SAAS,KAAK,WAAW,aAAa,CAAC,CAAC,CAChD,KAAK,SAAS,KAAK,MAAM,cAAc,MAAM,CAAC;;AAiBnD,MAAM,wBAAmC;CACvC,MAAM,wBAAQ,IAAI,IAAoD;CACtE,OAAO;EACL,QAAQ,OAAO,cAAc;GAC3B,KAAK,MAAM,CAAC,MAAM,UAAU,OAC1B,IAAI,MAAM,aAAa,WACrB,MAAM,OAAO,IAAI;GAGrB,MAAM,OAAO,YAAY,SAAS,CAAC,CAAC,SAAS,WAAW;GACxD,MAAM,IAAI,MAAM;IAAE,GAAG;IAAO,WAAW,YAAY;GAAW,CAAC;GAC/D,OAAO;EACT;EACA,SAAS,MAAM,cAAc;GAC3B,MAAM,QAAQ,MAAM,IAAI,IAAI;GAC5B,MAAM,OAAO,IAAI;GACjB,OAAO,UAAU,KAAA,KAAa,MAAM,aAAa,YAAY,KAAA,IAAY;EAC3E;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tafrahq/wt-tunnel-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Runs the wt-tunnel server: Caddy, frps and a sign-in service (Google, GitHub, Microsoft, Cloudflare Access) under one supervisor, in the foreground or detached. Downloads pinned, checksum-verified Caddy and frps when you have none.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"caddy",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"tunnel",
|
|
20
20
|
"wt-tunnel"
|
|
21
21
|
],
|
|
22
|
-
"homepage": "https://
|
|
22
|
+
"homepage": "https://wt.tafrahq.com",
|
|
23
23
|
"bugs": {
|
|
24
24
|
"url": "https://github.com/tafrahq/wt-tunnel/issues"
|
|
25
25
|
},
|
|
@@ -43,25 +43,26 @@
|
|
|
43
43
|
"access": "public"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@effect/platform-node": "4.0.
|
|
46
|
+
"@effect/platform-node": "4.0.7",
|
|
47
|
+
"@effect/platform-node-shared": "4.0.7",
|
|
47
48
|
"better-auth": "1.7.14",
|
|
48
|
-
"effect": "4.0.
|
|
49
|
+
"effect": "4.0.7"
|
|
49
50
|
},
|
|
50
51
|
"devDependencies": {
|
|
51
|
-
"@effect/vitest": "
|
|
52
|
+
"@effect/vitest": "4.0.7",
|
|
52
53
|
"@tafrahq/wt-tunnel-binaries": "0.0.0",
|
|
53
54
|
"@tafrahq/wt-tunnel-contract": "0.0.0",
|
|
54
|
-
"@types/node": "^
|
|
55
|
+
"@types/node": "^26.6.6",
|
|
55
56
|
"@types/plist": "^3.0.5",
|
|
56
57
|
"plist": "^5.0.0",
|
|
57
58
|
"tsdown": "0.23.2",
|
|
58
59
|
"vitest": "^5.0.5"
|
|
59
60
|
},
|
|
60
61
|
"engines": {
|
|
61
|
-
"node": ">=
|
|
62
|
+
"node": ">=26"
|
|
62
63
|
},
|
|
63
64
|
"scripts": {
|
|
64
|
-
"build": "tsdown &&
|
|
65
|
+
"build": "tsdown && nub dist/bin.js --version",
|
|
65
66
|
"typecheck": "tsc --noEmit",
|
|
66
67
|
"test": "vitest run"
|
|
67
68
|
}
|
package/src/bin.ts
CHANGED
|
@@ -1,29 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
|
|
2
|
+
// fallow-ignore-file coverage-gaps -- it runs the CLI on import, so cli.test.ts runs it as a subprocess, which fallow cannot follow; 'exits 0 when SIGTERM stops it' tests the teardown
|
|
4
3
|
import { NodeRuntime, NodeServices } from '@effect/platform-node';
|
|
5
|
-
import {
|
|
4
|
+
import { binProgram } from '@tafrahq/wt-tunnel-contract/bin';
|
|
5
|
+
import { Cause, Effect, Exit, Runtime } from 'effect';
|
|
6
6
|
|
|
7
7
|
import { run } from './cli.ts';
|
|
8
8
|
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
/** Expected failures carry a message written for the user; skip the stack trace. */
|
|
13
|
-
const report = (message: string) =>
|
|
14
|
-
Effect.gen(function* reportFailure() {
|
|
15
|
-
yield* Console.error(`wt-tunnel-server: ${message}`);
|
|
16
|
-
process.exitCode = 1;
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
const program = Effect.gen(function* main() {
|
|
20
|
-
const { version } = yield* Schema.decodeUnknownEffect(PackageJson)(packageJson).pipe(
|
|
21
|
-
Effect.orDie,
|
|
22
|
-
);
|
|
23
|
-
yield* run(version);
|
|
24
|
-
}).pipe(
|
|
25
|
-
Effect.catchTag('ServerError', ({ message }: { readonly message: string }) => report(message)),
|
|
26
|
-
Effect.provide(NodeServices.layer),
|
|
9
|
+
const program = binProgram(
|
|
10
|
+
{ expected: 'ServerError', name: 'wt-tunnel-server', url: import.meta.url },
|
|
11
|
+
run,
|
|
27
12
|
);
|
|
28
13
|
|
|
29
14
|
/**
|
|
@@ -38,4 +23,4 @@ const teardown: Runtime.Teardown = (exit, onExit) => {
|
|
|
38
23
|
Runtime.defaultTeardown(exit, onExit);
|
|
39
24
|
};
|
|
40
25
|
|
|
41
|
-
NodeRuntime.runMain(program, { teardown });
|
|
26
|
+
NodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)), { teardown });
|
package/src/cli.ts
CHANGED
|
@@ -145,34 +145,47 @@ const start = Command.make(
|
|
|
145
145
|
),
|
|
146
146
|
);
|
|
147
147
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
})
|
|
155
|
-
|
|
148
|
+
/** A command that acts on the detached server that --state-dir names. */
|
|
149
|
+
const stateDirCommand = <Failure, Requirements>(
|
|
150
|
+
name: string,
|
|
151
|
+
description: string,
|
|
152
|
+
act: (state: StateDir) => Effect.Effect<void, Failure, Requirements>,
|
|
153
|
+
) =>
|
|
154
|
+
Command.make(name, { stateDir: stateDirFlag }, ({ stateDir }) =>
|
|
155
|
+
act(stateDirFrom(stateDir)),
|
|
156
|
+
).pipe(Command.withDescription(description));
|
|
157
|
+
|
|
158
|
+
const stop = stateDirCommand(
|
|
159
|
+
'stop',
|
|
160
|
+
'Stop the detached server and wait until Caddy and frps exit',
|
|
161
|
+
(state) =>
|
|
162
|
+
Effect.gen(function* stopDetached() {
|
|
163
|
+
const previous = yield* stopServer(state);
|
|
164
|
+
yield* Console.log(
|
|
165
|
+
previous._tag === 'running' ? `Stopped (pid ${previous.pid}).` : 'Not running.',
|
|
166
|
+
);
|
|
167
|
+
}),
|
|
168
|
+
);
|
|
156
169
|
|
|
157
|
-
const status =
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
170
|
+
const status = stateDirCommand(
|
|
171
|
+
'status',
|
|
172
|
+
'Show whether the detached server runs: exit 0 if it does, 3 if not',
|
|
173
|
+
(state) =>
|
|
174
|
+
Effect.gen(function* printStatus() {
|
|
175
|
+
const current = yield* serverStatus(state);
|
|
176
|
+
if (current._tag === 'running') {
|
|
177
|
+
yield* Console.log(
|
|
178
|
+
`running: pid ${current.pid}, since ${current.since.toISOString()}, log ${state.log}`,
|
|
179
|
+
);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
162
182
|
yield* Console.log(
|
|
163
|
-
|
|
183
|
+
current._tag === 'stale'
|
|
184
|
+
? `stopped (pid ${current.pid} in ${state.pid} is not this server)`
|
|
185
|
+
: 'stopped',
|
|
164
186
|
);
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
yield* Console.log(
|
|
168
|
-
current._tag === 'stale'
|
|
169
|
-
? `stopped (pid ${current.pid} in ${state.pid} is not this server)`
|
|
170
|
-
: 'stopped',
|
|
171
|
-
);
|
|
172
|
-
process.exitCode = stoppedExitCode;
|
|
173
|
-
}),
|
|
174
|
-
).pipe(
|
|
175
|
-
Command.withDescription('Show whether the detached server runs: exit 0 if it does, 3 if not'),
|
|
187
|
+
process.exitCode = stoppedExitCode;
|
|
188
|
+
}),
|
|
176
189
|
);
|
|
177
190
|
|
|
178
191
|
const check = Command.make('check', { config: configFlag }, ({ config }) =>
|
|
@@ -185,7 +198,7 @@ const check = Command.make('check', { config: configFlag }, ({ config }) =>
|
|
|
185
198
|
|
|
186
199
|
const cli = Command.make('wt-tunnel-server').pipe(
|
|
187
200
|
Command.withDescription(
|
|
188
|
-
'The wt-tunnel server: Caddy, frps and
|
|
201
|
+
'The wt-tunnel server: Caddy, frps and the sign-in service under one supervisor',
|
|
189
202
|
),
|
|
190
203
|
Command.withSubcommands([start, stop, status, check]),
|
|
191
204
|
);
|
package/src/runtime.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { mkdir,
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { tmpdir } from 'node:os';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
|
|
5
5
|
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
6
|
+
import { scopedTempDir } from '@tafrahq/wt-tunnel-contract/temp-dir';
|
|
6
7
|
import { Effect, Redacted } from 'effect';
|
|
7
8
|
|
|
8
9
|
import type { Binaries } from './binaries.ts';
|
|
@@ -14,22 +15,21 @@ import type { Ports } from './render.ts';
|
|
|
14
15
|
* so no copy of the CA key outlives the server.
|
|
15
16
|
*/
|
|
16
17
|
const writeRuntimeFiles = (config: ServerConfig, ports: Ports) =>
|
|
17
|
-
|
|
18
|
-
Effect.
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
(dir) => Effect.promise(() => rm(dir, { force: true, recursive: true })),
|
|
18
|
+
scopedTempDir(tmpdir(), 'wt-tunnel-server-').pipe(
|
|
19
|
+
Effect.tap((dir) =>
|
|
20
|
+
Effect.promise(async () => {
|
|
21
|
+
const paths = {
|
|
22
|
+
caCert: join(dir, 'ca.crt'),
|
|
23
|
+
caKey: join(dir, 'ca.key'),
|
|
24
|
+
storage: join(dir, 'caddy'),
|
|
25
|
+
};
|
|
26
|
+
await mkdir(paths.storage, { mode: 0o700 });
|
|
27
|
+
await writeFile(paths.caCert, config.ca.cert);
|
|
28
|
+
await writeFile(paths.caKey, Redacted.value(config.ca.key), { mode: 0o600 });
|
|
29
|
+
await writeFile(join(dir, 'Caddyfile'), renderCaddyfile(config, paths, ports));
|
|
30
|
+
await writeFile(join(dir, 'frps.toml'), renderFrpsToml(config, ports), { mode: 0o600 });
|
|
31
|
+
}),
|
|
32
|
+
),
|
|
33
33
|
);
|
|
34
34
|
|
|
35
35
|
const childSpecs = (dir: string, binaries: Binaries) => {
|
package/src/session.ts
CHANGED
|
@@ -64,21 +64,22 @@ const sessionSetCookie = (value: string, domain: Hostname) =>
|
|
|
64
64
|
const sessionClearCookie = (domain: Hostname) =>
|
|
65
65
|
`${sessionCookieName}=; Max-Age=0; ${cookieAttributes(domain)}`;
|
|
66
66
|
|
|
67
|
+
const sessionPrefix = `${sessionCookieName}=`;
|
|
68
|
+
|
|
69
|
+
const cookiePairs = (cookieHeader: string | undefined) =>
|
|
70
|
+
(cookieHeader ?? '').split(';').map((pair) => pair.trim());
|
|
71
|
+
|
|
67
72
|
/** A Cookie header's pairs other than `wt_session`, joined again; empty when none are left. */
|
|
68
73
|
const cookiesWithoutSession = (cookieHeader: string | undefined) =>
|
|
69
|
-
(cookieHeader
|
|
70
|
-
.
|
|
71
|
-
.map((pair) => pair.trim())
|
|
72
|
-
.filter((pair) => pair !== '' && !pair.startsWith(`${sessionCookieName}=`))
|
|
74
|
+
cookiePairs(cookieHeader)
|
|
75
|
+
.filter((pair) => pair !== '' && !pair.startsWith(sessionPrefix))
|
|
73
76
|
.join('; ');
|
|
74
77
|
|
|
75
78
|
/** Every `wt_session` value in a Cookie header; a stale one may sit beside a fresh one. */
|
|
76
79
|
const sessionCookieValues = (cookieHeader: string | undefined) =>
|
|
77
|
-
(cookieHeader
|
|
78
|
-
.
|
|
79
|
-
.map((pair) => pair.
|
|
80
|
-
.filter((pair) => pair.startsWith(`${sessionCookieName}=`))
|
|
81
|
-
.map((pair) => pair.slice(sessionCookieName.length + 1));
|
|
80
|
+
cookiePairs(cookieHeader)
|
|
81
|
+
.filter((pair) => pair.startsWith(sessionPrefix))
|
|
82
|
+
.map((pair) => pair.slice(sessionPrefix.length));
|
|
82
83
|
|
|
83
84
|
interface Grant {
|
|
84
85
|
readonly domain: Hostname;
|