@tafrahq/wt-tunnel-server 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +111 -2
- package/dist/auth.js +121 -0
- package/dist/auth.js.map +1 -0
- package/dist/bin.js +26 -0
- package/dist/bin.js.map +1 -0
- package/dist/binaries.js +51 -0
- package/dist/binaries.js.map +1 -0
- package/dist/brand.js +10 -0
- package/dist/brand.js.map +1 -0
- package/dist/ca-page.js +112 -0
- package/dist/ca-page.js.map +1 -0
- package/dist/children.js +72 -0
- package/dist/children.js.map +1 -0
- package/dist/cli.js +111 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.js +55 -0
- package/dist/config.js.map +1 -0
- package/dist/context.js +5 -0
- package/dist/context.js.map +1 -0
- package/dist/daemon.js +176 -0
- package/dist/daemon.js.map +1 -0
- package/dist/dev-host.js +71 -0
- package/dist/dev-host.js.map +1 -0
- package/dist/errors.js +8 -0
- package/dist/errors.js.map +1 -0
- package/dist/hosts.js +32 -0
- package/dist/hosts.js.map +1 -0
- package/dist/internal.js +62 -0
- package/dist/internal.js.map +1 -0
- package/dist/listen.js +31 -0
- package/dist/listen.js.map +1 -0
- package/dist/packages/binaries/src/caddy.js +24 -0
- package/dist/packages/binaries/src/caddy.js.map +1 -0
- package/dist/packages/binaries/src/frp.js +45 -0
- package/dist/packages/binaries/src/frp.js.map +1 -0
- package/dist/packages/binaries/src/install.js +110 -0
- package/dist/packages/binaries/src/install.js.map +1 -0
- package/dist/packages/contract/src/bin.js +20 -0
- package/dist/packages/contract/src/bin.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 +61 -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/packages/contract/src/temp-dir.js +12 -0
- package/dist/packages/contract/src/temp-dir.js.map +1 -0
- package/dist/ready.js +36 -0
- package/dist/ready.js.map +1 -0
- package/dist/render.js +101 -0
- package/dist/render.js.map +1 -0
- package/dist/reply.js +46 -0
- package/dist/reply.js.map +1 -0
- package/dist/root-ca.js +85 -0
- package/dist/root-ca.js.map +1 -0
- package/dist/runtime.js +49 -0
- package/dist/runtime.js.map +1 -0
- package/dist/service.js +59 -0
- package/dist/service.js.map +1 -0
- package/dist/session.js +67 -0
- package/dist/session.js.map +1 -0
- package/dist/sign-in.js +103 -0
- package/dist/sign-in.js.map +1 -0
- package/dist/supervise.js +33 -0
- package/dist/supervise.js.map +1 -0
- package/package.json +66 -3
- package/src/auth.ts +153 -0
- package/src/bin.ts +26 -0
- package/src/binaries.ts +82 -0
- package/src/brand.ts +10 -0
- package/src/ca-page.ts +166 -0
- package/src/children.ts +98 -0
- package/src/cli.ts +208 -0
- package/src/config.ts +92 -0
- package/src/context.ts +23 -0
- package/src/daemon.ts +254 -0
- package/src/dev-host.ts +101 -0
- package/src/errors.ts +14 -0
- package/src/hosts.ts +49 -0
- package/src/internal.ts +89 -0
- package/src/listen.ts +43 -0
- package/src/ready.ts +50 -0
- package/src/render.ts +121 -0
- package/src/reply.ts +60 -0
- package/src/root-ca.ts +116 -0
- package/src/runtime.ts +49 -0
- package/src/service.ts +90 -0
- package/src/session.ts +130 -0
- package/src/sign-in.ts +147 -0
- package/src/supervise.ts +51 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { resolveBinaries } from "./binaries.js";
|
|
2
|
+
import { configFileOf, loadServerConfig } from "./config.js";
|
|
3
|
+
import { refuseIfRunning, serverStatus, startDetached, stateDirOf, stopServer } from "./daemon.js";
|
|
4
|
+
import { defaultPorts } from "./render.js";
|
|
5
|
+
import { Console, Effect, Option, Schema } from "effect";
|
|
6
|
+
import { resolve } from "node:path";
|
|
7
|
+
import { Command, Flag } from "effect/cli";
|
|
8
|
+
// src/cli.ts
|
|
9
|
+
/** `status` exits with 3 when no server runs, as LSB init scripts do. */
|
|
10
|
+
const stoppedExitCode = 3;
|
|
11
|
+
const maxPort = 65535;
|
|
12
|
+
const configFlag = Flag.String("config").pipe(Flag.withDescription("The server config file. Default: the JSON in WT_TUNNEL_SERVER_CONFIG, else ./wt-tunnel-server.json."), Flag.optional);
|
|
13
|
+
const stateDirFlag = Flag.String("state-dir").pipe(Flag.withDescription("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."), Flag.optional);
|
|
14
|
+
const Port = Schema.Int.check(Schema.isBetween({
|
|
15
|
+
maximum: maxPort,
|
|
16
|
+
minimum: 1
|
|
17
|
+
}));
|
|
18
|
+
const portFlag = (name, fallback, description) => Flag.Int(name).pipe(Flag.withSchema(Port), Flag.withDescription(`${description} (default ${fallback})`), Flag.withDefault(fallback));
|
|
19
|
+
const binaryFlag = (name) => Flag.String(name).pipe(Flag.withDescription(`Run this ${name} executable. Default: ${name} on PATH, else the pinned release, downloaded to the user cache on first use.`), Flag.optional);
|
|
20
|
+
const stateDirFrom = (flag) => stateDirOf(Option.getOrUndefined(flag), process.env);
|
|
21
|
+
/**
|
|
22
|
+
* The arguments a detached server is started with: the resolved binaries, so it never downloads,
|
|
23
|
+
* and the state dir, which is how `status` and `stop` recognise it.
|
|
24
|
+
*/
|
|
25
|
+
const foregroundArgs = ({ binaries, configFile, ports, state }) => [
|
|
26
|
+
"start",
|
|
27
|
+
...configFile === void 0 ? [] : ["--config", configFile],
|
|
28
|
+
"--state-dir",
|
|
29
|
+
state.dir,
|
|
30
|
+
"--caddy",
|
|
31
|
+
binaries.caddy,
|
|
32
|
+
"--frps",
|
|
33
|
+
binaries.frps,
|
|
34
|
+
"--https-port",
|
|
35
|
+
String(ports.https),
|
|
36
|
+
"--http-port",
|
|
37
|
+
String(ports.http),
|
|
38
|
+
"--tunnel-port",
|
|
39
|
+
String(ports.tunnel)
|
|
40
|
+
];
|
|
41
|
+
const runForeground = ({ binaries, config, ports }) => Effect.gen(function* loadThenSupervise() {
|
|
42
|
+
yield* (yield* Effect.promise(async () => {
|
|
43
|
+
return (await import("./supervise.js")).supervise;
|
|
44
|
+
}))(config, {
|
|
45
|
+
binaries,
|
|
46
|
+
ports
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
/** `stop` finds the server only in the state dir it was started with, so the hint names a flag. */
|
|
50
|
+
const runDetached = (start, stateDirGiven) => startDetached(start.state, foregroundArgs(start)).pipe(Effect.flatMap((pid) => Console.log(`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}` : ""}.`)));
|
|
51
|
+
const start = Command.make("start", {
|
|
52
|
+
caddy: binaryFlag("caddy"),
|
|
53
|
+
config: configFlag,
|
|
54
|
+
detach: Flag.Boolean("detach").pipe(Flag.withDescription("Run in the background: return once the server listens, with its output in server.log"), Flag.withDefault(false)),
|
|
55
|
+
frps: binaryFlag("frps"),
|
|
56
|
+
http: portFlag("http-port", defaultPorts.http, "The port Caddy redirects to https on"),
|
|
57
|
+
https: portFlag("https-port", defaultPorts.https, "The port Caddy serves dev hosts on"),
|
|
58
|
+
stateDir: stateDirFlag,
|
|
59
|
+
tunnel: portFlag("tunnel-port", defaultPorts.tunnel, "The port frps accepts frpc on")
|
|
60
|
+
}, (input) => Effect.gen(function* startServer() {
|
|
61
|
+
const state = stateDirFrom(input.stateDir);
|
|
62
|
+
yield* refuseIfRunning(state);
|
|
63
|
+
const file = yield* configFileOf(Option.getOrUndefined(input.config), process.env);
|
|
64
|
+
const configFile = file === void 0 ? void 0 : resolve(file);
|
|
65
|
+
const config = yield* loadServerConfig(configFile, process.env);
|
|
66
|
+
const checked = {
|
|
67
|
+
binaries: yield* resolveBinaries({
|
|
68
|
+
caddy: Option.getOrUndefined(input.caddy),
|
|
69
|
+
frps: Option.getOrUndefined(input.frps)
|
|
70
|
+
}),
|
|
71
|
+
config,
|
|
72
|
+
configFile,
|
|
73
|
+
ports: {
|
|
74
|
+
http: input.http,
|
|
75
|
+
https: input.https,
|
|
76
|
+
tunnel: input.tunnel
|
|
77
|
+
},
|
|
78
|
+
state
|
|
79
|
+
};
|
|
80
|
+
yield* input.detach ? runDetached(checked, input.stateDir) : runForeground(checked);
|
|
81
|
+
})).pipe(Command.withDescription("Run Caddy, frps and the sign-in service; in the foreground unless --detach"));
|
|
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);
|
|
86
|
+
yield* Console.log(previous._tag === "running" ? `Stopped (pid ${previous.pid}).` : "Not running.");
|
|
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() {
|
|
89
|
+
const current = yield* serverStatus(state);
|
|
90
|
+
if (current._tag === "running") {
|
|
91
|
+
yield* Console.log(`running: pid ${current.pid}, since ${current.since.toISOString()}, log ${state.log}`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
yield* Console.log(current._tag === "stale" ? `stopped (pid ${current.pid} in ${state.pid} is not this server)` : "stopped");
|
|
95
|
+
process.exitCode = stoppedExitCode;
|
|
96
|
+
}));
|
|
97
|
+
const check = Command.make("check", { config: configFlag }, ({ config }) => Effect.gen(function* checkConfig() {
|
|
98
|
+
const file = yield* configFileOf(Option.getOrUndefined(config), process.env);
|
|
99
|
+
yield* loadServerConfig(file, process.env);
|
|
100
|
+
yield* Console.log(`${file ?? "WT_TUNNEL_SERVER_CONFIG"} is a valid server config`);
|
|
101
|
+
})).pipe(Command.withDescription("Check the server config without starting anything"));
|
|
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([
|
|
103
|
+
start,
|
|
104
|
+
stop,
|
|
105
|
+
status,
|
|
106
|
+
check
|
|
107
|
+
]));
|
|
108
|
+
const run = (version) => Command.run(cli, { version });
|
|
109
|
+
export { run };
|
|
110
|
+
|
|
111
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +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\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,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,KAAK,YAAY,QAAQ,CAC3B;AAEF,MAAM,cAAc,SAClB,KAAK,OAAO,IAAI,CAAC,CAAC,KAChB,KAAK,gBACH,YAAY,KAAK,wBAAwB,KAAK,8EAChD,GACA,KAAK,QACP;AAEF,MAAM,gBAAgB,SACpB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AC,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"}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { ServerError } from "./errors.js";
|
|
2
|
+
import { readServerConfig, serverConfigFileName } from "./packages/contract/src/server-config.js";
|
|
3
|
+
import { readRootCa } from "./root-ca.js";
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { readFile, stat } from "node:fs/promises";
|
|
7
|
+
// src/config.ts
|
|
8
|
+
const readText = (file) => Effect.tryPromise(() => readFile(file, "utf8"));
|
|
9
|
+
/** Decodes a config's text; `dir` is where its `ca` paths are relative to. */
|
|
10
|
+
const decodeServerConfig = (text, source, dir) => readServerConfig({
|
|
11
|
+
dir,
|
|
12
|
+
read: readText,
|
|
13
|
+
source,
|
|
14
|
+
text
|
|
15
|
+
}).pipe(Effect.mapError(({ message }) => new ServerError({ message })), Effect.tap((config) => Effect.try({
|
|
16
|
+
catch: () => new ServerError({ message: `${source}: ca.cert is not a readable certificate` }),
|
|
17
|
+
try: () => readRootCa(config)
|
|
18
|
+
})));
|
|
19
|
+
const configEnv = "WT_TUNNEL_SERVER_CONFIG";
|
|
20
|
+
const isDirectory = (path) => Effect.tryPromise(async () => {
|
|
21
|
+
return (await stat(path)).isDirectory();
|
|
22
|
+
}).pipe(Effect.orElseSucceed(() => false));
|
|
23
|
+
const exists = (path) => Effect.tryPromise(() => stat(path)).pipe(Effect.as(true), Effect.orElseSucceed(() => false));
|
|
24
|
+
/**
|
|
25
|
+
* `--config` wins: a file, or a directory that holds wt-tunnel-server.json. Then
|
|
26
|
+
* WT_TUNNEL_SERVER_CONFIG, then ./wt-tunnel-server.json if it exists. Undefined means the JSON
|
|
27
|
+
* comes from the environment.
|
|
28
|
+
*/
|
|
29
|
+
const configFileOf = (flag, env) => Effect.gen(function* findConfig() {
|
|
30
|
+
if (flag !== void 0) return (yield* isDirectory(flag)) ? join(flag, serverConfigFileName) : flag;
|
|
31
|
+
return !((env[configEnv] ?? "") !== "") && (yield* exists("wt-tunnel-server.json")) ? serverConfigFileName : flag;
|
|
32
|
+
});
|
|
33
|
+
const readConfigFile = (file) => Effect.tryPromise({
|
|
34
|
+
catch: (cause) => new ServerError({ message: `cannot read ${file}: ${String(cause)}` }),
|
|
35
|
+
try: () => readFile(file, "utf8")
|
|
36
|
+
}).pipe(Effect.flatMap((text) => decodeServerConfig(text, file, dirname(file))));
|
|
37
|
+
/**
|
|
38
|
+
* Reads `file`, or without one the JSON in WT_TUNNEL_SERVER_CONFIG, whose `ca` paths are relative
|
|
39
|
+
* to the current directory.
|
|
40
|
+
*/
|
|
41
|
+
const loadServerConfig = (file, env) => {
|
|
42
|
+
if (file !== void 0) return readConfigFile(file);
|
|
43
|
+
const text = env[configEnv];
|
|
44
|
+
return text === void 0 || text === "" ? Effect.fail(new ServerError({ message: `pass --config <file or directory>, set ${configEnv}, or run in a directory that holds ${serverConfigFileName}` })) : decodeServerConfig(text, configEnv, process.cwd());
|
|
45
|
+
};
|
|
46
|
+
/** An email passes when Google verified it and it, or its domain, is listed. */
|
|
47
|
+
const isAllowed = (allow, email, emailVerified) => {
|
|
48
|
+
if (!emailVerified) return false;
|
|
49
|
+
const address = email.toLowerCase();
|
|
50
|
+
const domain = address.slice(address.lastIndexOf("@") + 1);
|
|
51
|
+
return (allow.emails ?? []).some((listed) => listed.toLowerCase() === address) || (allow.emailDomains ?? []).some((listed) => listed === domain);
|
|
52
|
+
};
|
|
53
|
+
export { configFileOf, decodeServerConfig, isAllowed, loadServerConfig };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\n\nimport { readServerConfig, serverConfigFileName } from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect } from 'effect';\n\nimport { ServerError } from './errors.ts';\nimport { readRootCa } from './root-ca.ts';\n\nconst readText = (file: string) => Effect.tryPromise(() => readFile(file, 'utf8'));\n\n/** Decodes a config's text; `dir` is where its `ca` paths are relative to. */\nconst decodeServerConfig = (text: string, source: string, dir: string) =>\n readServerConfig({ dir, read: readText, source, text }).pipe(\n Effect.mapError(({ message }: { readonly message: string }) => new ServerError({ message })),\n Effect.tap((config) =>\n Effect.try({\n catch: () =>\n new ServerError({ message: `${source}: ca.cert is not a readable certificate` }),\n try: () => readRootCa(config),\n }),\n ),\n );\nconst configEnv = 'WT_TUNNEL_SERVER_CONFIG';\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\nconst isDirectory = (path: string) =>\n Effect.tryPromise(async () => {\n const stats = await stat(path);\n return stats.isDirectory();\n }).pipe(Effect.orElseSucceed(() => false));\n\nconst exists = (path: string) =>\n Effect.tryPromise(() => stat(path)).pipe(\n Effect.as(true),\n Effect.orElseSucceed(() => false),\n );\n\n/**\n * `--config` wins: a file, or a directory that holds wt-tunnel-server.json. Then\n * WT_TUNNEL_SERVER_CONFIG, then ./wt-tunnel-server.json if it exists. Undefined means the JSON\n * comes from the environment.\n */\nconst configFileOf = (flag: string | undefined, env: Env) =>\n Effect.gen(function* findConfig() {\n if (flag !== undefined) {\n return (yield* isDirectory(flag)) ? join(flag, serverConfigFileName) : flag;\n }\n const fromEnv = (env[configEnv] ?? '') !== '';\n return !fromEnv && (yield* exists(serverConfigFileName)) ? serverConfigFileName : flag;\n });\n\nconst readConfigFile = (file: string) =>\n Effect.tryPromise({\n catch: (cause) => new ServerError({ message: `cannot read ${file}: ${String(cause)}` }),\n try: () => readFile(file, 'utf8'),\n }).pipe(Effect.flatMap((text) => decodeServerConfig(text, file, dirname(file))));\n\n/**\n * Reads `file`, or without one the JSON in WT_TUNNEL_SERVER_CONFIG, whose `ca` paths are relative\n * to the current directory.\n */\nconst loadServerConfig = (file: string | undefined, env: Env) => {\n if (file !== undefined) {\n return readConfigFile(file);\n }\n const text = env[configEnv];\n return text === undefined || text === ''\n ? Effect.fail(\n new ServerError({\n message: `pass --config <file or directory>, set ${configEnv}, or run in a directory that holds ${serverConfigFileName}`,\n }),\n )\n : decodeServerConfig(text, configEnv, process.cwd());\n};\n\n/** An email passes when Google verified it and it, or its domain, is listed. */\nconst isAllowed = (allow: ServerConfig['allow'], email: string, emailVerified: boolean) => {\n if (!emailVerified) {\n return false;\n }\n const address = email.toLowerCase();\n const domain = address.slice(address.lastIndexOf('@') + 1);\n return (\n (allow.emails ?? []).some((listed) => listed.toLowerCase() === address) ||\n (allow.emailDomains ?? []).some((listed) => listed === domain)\n );\n};\n\nexport { configFileOf, decodeServerConfig, isAllowed, loadServerConfig };\n"],"mappings":";;;;;;;AAUA,MAAM,YAAY,SAAiB,OAAO,iBAAiB,SAAS,MAAM,MAAM,CAAC;;AAGjF,MAAM,sBAAsB,MAAc,QAAgB,QACxD,iBAAiB;CAAE;CAAK,MAAM;CAAU;CAAQ;AAAK,CAAC,CAAC,CAAC,KACtD,OAAO,UAAU,EAAE,cAA4C,IAAI,YAAY,EAAE,QAA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MAAM,aAAa,OAA8B,OAAe,kBAA2B;CACzF,IAAI,CAAC,eACH,OAAO;CAET,MAAM,UAAU,MAAM,YAAY;CAClC,MAAM,SAAS,QAAQ,MAAM,QAAQ,YAAY,GAAG,IAAI,CAAC;CACzD,QACG,MAAM,UAAU,CAAC,EAAA,CAAG,MAAM,WAAW,OAAO,YAAY,MAAM,OAAO,MACrE,MAAM,gBAAgB,CAAC,EAAA,CAAG,MAAM,WAAW,WAAW,MAAM;AAEjE"}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\n\nimport type { SignIn } from './auth.ts';\nimport type { RootCa } from './root-ca.ts';\nimport type { CodeStore } from './session.ts';\n\n/** Everything a route reads besides the request itself. */\ninterface ServiceContext {\n readonly codes: CodeStore;\n readonly config: ServerConfig;\n readonly now: () => number;\n readonly rootCa: RootCa;\n readonly signIn: SignIn;\n}\n\n/** The request's query string, parsed once. */\ntype Query = Readonly<Record<string, string>>;\n\nconst loginUrl = (context: ServiceContext, returnUrl: string) =>\n `https://${context.config.authHost}/login?rd=${encodeURIComponent(returnUrl)}`;\n\nexport { loginUrl };\nexport type { Query, ServiceContext };\n"],"mappings":";AAkBA,MAAM,YAAY,SAAyB,cACzC,WAAW,QAAQ,OAAO,SAAS,YAAY,mBAAmB,SAAS"}
|
package/dist/daemon.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { ServerError } from "./errors.js";
|
|
2
|
+
import { Effect, Option } from "effect";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { execFile, spawn } from "node:child_process";
|
|
7
|
+
// src/daemon.ts
|
|
8
|
+
/** Signal 0 checks that a process exists without touching it. */
|
|
9
|
+
const probeSignal = 0;
|
|
10
|
+
const firstPid = 1;
|
|
11
|
+
const startupTimeout = "60 seconds";
|
|
12
|
+
const stopPollInterval = "100 millis";
|
|
13
|
+
/** Longer than the supervisor's own 10 s grace for its children. */
|
|
14
|
+
const stopPolls = 150;
|
|
15
|
+
const killPolls = 20;
|
|
16
|
+
/** The message a detached server sends its parent over IPC once every port accepts connections. */
|
|
17
|
+
const readyMessage = "ready";
|
|
18
|
+
/** `--state-dir`, else WT_TUNNEL_SERVER_STATE_DIR, else `$XDG_STATE_HOME/wt-tunnel-server`. */
|
|
19
|
+
const stateDirOf = (flag, env) => {
|
|
20
|
+
const stateHome = env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
|
|
21
|
+
const dir = resolve(flag ?? env.WT_TUNNEL_SERVER_STATE_DIR ?? join(stateHome, "wt-tunnel-server"));
|
|
22
|
+
return {
|
|
23
|
+
dir,
|
|
24
|
+
log: join(dir, "server.log"),
|
|
25
|
+
pid: join(dir, "server.pid")
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
const errorCode = (error) => error instanceof Error && "code" in error ? error.code : void 0;
|
|
29
|
+
/** EPERM means the process exists but belongs to someone else. */
|
|
30
|
+
const exists = (pid) => {
|
|
31
|
+
try {
|
|
32
|
+
process.kill(pid, probeSignal);
|
|
33
|
+
return true;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
return errorCode(error) === "EPERM";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const psArgs = (pid) => Effect.callback((resume) => {
|
|
39
|
+
execFile("ps", [
|
|
40
|
+
"-o",
|
|
41
|
+
"args=",
|
|
42
|
+
"-p",
|
|
43
|
+
String(pid)
|
|
44
|
+
], (failure, stdout) => {
|
|
45
|
+
resume(Effect.succeed(failure === null ? stdout : ""));
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* A pid file can outlive its process and the pid can be reused, so a pid only counts as ours while
|
|
50
|
+
* its argv still names this state dir. The detached server is started with `--state-dir <dir>`.
|
|
51
|
+
*/
|
|
52
|
+
const ownedBy = (pid, state) => psArgs(pid).pipe(Effect.map((args) => `${args.trimEnd()} `.includes(`--state-dir ${state.dir} `)));
|
|
53
|
+
/** The file's text, or '' if it cannot be read. */
|
|
54
|
+
const readOrEmpty = (file) => Effect.tryPromise(() => readFile(file, "utf8")).pipe(Effect.orElseSucceed(() => ""));
|
|
55
|
+
/** The pid a pid file names, if it names one. */
|
|
56
|
+
const parsePid = (text) => {
|
|
57
|
+
const pid = Number(text.trim());
|
|
58
|
+
return Number.isInteger(pid) && pid >= firstPid ? pid : void 0;
|
|
59
|
+
};
|
|
60
|
+
const serverStatus = (state) => Effect.gen(function* readPidFile() {
|
|
61
|
+
const pid = parsePid(yield* readOrEmpty(state.pid));
|
|
62
|
+
if (pid === void 0) return { _tag: "stopped" };
|
|
63
|
+
if (!exists(pid) || !(yield* ownedBy(pid, state))) return {
|
|
64
|
+
_tag: "stale",
|
|
65
|
+
pid
|
|
66
|
+
};
|
|
67
|
+
const { mtime } = yield* Effect.promise(() => stat(state.pid));
|
|
68
|
+
return {
|
|
69
|
+
_tag: "running",
|
|
70
|
+
pid,
|
|
71
|
+
since: mtime
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
/** Fails when another server already runs from this state dir; the caller itself does not count. */
|
|
75
|
+
const refuseIfRunning = (state) => Effect.gen(function* checkPidFile() {
|
|
76
|
+
const current = yield* serverStatus(state);
|
|
77
|
+
if (current._tag === "running" && current.pid !== process.pid) yield* new ServerError({ message: `already running (pid ${current.pid}, log ${state.log}). Run wt-tunnel-server stop first.` });
|
|
78
|
+
});
|
|
79
|
+
const logSize = (log) => Effect.tryPromise(() => stat(log)).pipe(Effect.map(({ size }) => size), Effect.orElseSucceed(() => 0));
|
|
80
|
+
/** The log's last lines written since byte `from`, so an earlier run's lines are left out. */
|
|
81
|
+
const logTail = (log, from) => readOrEmpty(log).pipe(Effect.map((text) => Buffer.from(text).subarray(from).toString().trimEnd().split("\n").slice(-30).join("\n")));
|
|
82
|
+
/**
|
|
83
|
+
* Runs this CLI again with `args` in a new session, its output appended to the log. The child holds
|
|
84
|
+
* its own copy of the log descriptor, so ours is closed right away.
|
|
85
|
+
*/
|
|
86
|
+
const spawnServer = (state, args) => Effect.acquireUseRelease(Effect.promise(() => open(state.log, "a")), (handle) => Effect.promise(async () => {
|
|
87
|
+
await handle.write(`--- wt-tunnel-server start, ${(/* @__PURE__ */ new Date()).toISOString()} ---\n`);
|
|
88
|
+
const [script = ""] = process.argv.slice(1);
|
|
89
|
+
return spawn(process.execPath, [
|
|
90
|
+
...process.execArgv,
|
|
91
|
+
script,
|
|
92
|
+
...args
|
|
93
|
+
], {
|
|
94
|
+
detached: true,
|
|
95
|
+
stdio: [
|
|
96
|
+
"ignore",
|
|
97
|
+
handle.fd,
|
|
98
|
+
handle.fd,
|
|
99
|
+
"ipc"
|
|
100
|
+
]
|
|
101
|
+
});
|
|
102
|
+
}), (handle) => Effect.promise(() => handle.close()));
|
|
103
|
+
/** Waits for the child's ready message, or for it to exit first. */
|
|
104
|
+
const startup = (child) => Effect.callback((resume) => {
|
|
105
|
+
child.on("message", (message) => {
|
|
106
|
+
if (message === "ready") resume(Effect.succeed({ _tag: "ready" }));
|
|
107
|
+
});
|
|
108
|
+
child.once("error", (error) => {
|
|
109
|
+
resume(Effect.succeed({
|
|
110
|
+
_tag: "exited",
|
|
111
|
+
reason: error.message
|
|
112
|
+
}));
|
|
113
|
+
});
|
|
114
|
+
child.once("exit", (code, signal) => {
|
|
115
|
+
resume(Effect.succeed({
|
|
116
|
+
_tag: "exited",
|
|
117
|
+
reason: `code ${code} signal ${signal}`
|
|
118
|
+
}));
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
/** The detached server leads its own process group, which holds Caddy and frps too. */
|
|
122
|
+
const groupExists = (pid) => exists(-pid);
|
|
123
|
+
const waitForGroupExit = (pid, polls) => Effect.gen(function* poll() {
|
|
124
|
+
for (let count = 0; count < polls && groupExists(pid); count++) yield* Effect.sleep(stopPollInterval);
|
|
125
|
+
return !groupExists(pid);
|
|
126
|
+
});
|
|
127
|
+
/** SIGTERM to the server, then SIGKILL to its whole group if any of it outlives the grace period. */
|
|
128
|
+
const terminate = (pid) => Effect.gen(function* termThenKill() {
|
|
129
|
+
process.kill(pid, "SIGTERM");
|
|
130
|
+
if (yield* waitForGroupExit(pid, stopPolls)) return;
|
|
131
|
+
process.kill(-pid, "SIGKILL");
|
|
132
|
+
if (!(yield* waitForGroupExit(pid, killPolls))) yield* new ServerError({ message: `process group ${pid} survived SIGKILL` });
|
|
133
|
+
});
|
|
134
|
+
const startFailed = (state, from, reason) => Effect.gen(function* removePidFileAndReport() {
|
|
135
|
+
yield* Effect.promise(() => rm(state.pid, { force: true }));
|
|
136
|
+
const tail = yield* logTail(state.log, from);
|
|
137
|
+
return yield* new ServerError({ message: `the server did not start (${reason}). Last log lines (${state.log}):\n${tail}` });
|
|
138
|
+
});
|
|
139
|
+
/**
|
|
140
|
+
* Waits for the ready message, and yields why the server did not start if it does not arrive. A
|
|
141
|
+
* server that is not ready in time is stopped.
|
|
142
|
+
*/
|
|
143
|
+
const awaitReady = (child, pid) => Effect.gen(function* readyExitedOrTimedOut() {
|
|
144
|
+
const outcome = yield* Effect.timeoutOption(startup(child), startupTimeout);
|
|
145
|
+
if (Option.isNone(outcome)) {
|
|
146
|
+
yield* terminate(pid);
|
|
147
|
+
return Option.some(`not ready after ${startupTimeout}`);
|
|
148
|
+
}
|
|
149
|
+
if (outcome.value._tag === "exited") return Option.some(`it exited with ${outcome.value.reason}`);
|
|
150
|
+
child.disconnect();
|
|
151
|
+
child.unref();
|
|
152
|
+
return Option.none();
|
|
153
|
+
});
|
|
154
|
+
/**
|
|
155
|
+
* Starts the server in the background with `args`, and returns its pid once Caddy, frps and the
|
|
156
|
+
* auth service all listen. The caller has checked that none runs already.
|
|
157
|
+
*/
|
|
158
|
+
const startDetached = (state, args) => Effect.gen(function* spawnAndAwaitReady() {
|
|
159
|
+
const from = yield* Effect.promise(() => mkdir(state.dir, { recursive: true })).pipe(Effect.andThen(logSize(state.log)));
|
|
160
|
+
const child = yield* spawnServer(state, args);
|
|
161
|
+
const { pid } = child;
|
|
162
|
+
if (pid === void 0) return yield* startFailed(state, from, "it could not be spawned");
|
|
163
|
+
yield* Effect.promise(() => writeFile(state.pid, `${pid}\n`));
|
|
164
|
+
const failure = yield* awaitReady(child, pid);
|
|
165
|
+
if (Option.isSome(failure)) return yield* startFailed(state, from, failure.value);
|
|
166
|
+
return pid;
|
|
167
|
+
});
|
|
168
|
+
const stopServer = (state) => Effect.gen(function* terminateAndForget() {
|
|
169
|
+
const current = yield* serverStatus(state);
|
|
170
|
+
if (current._tag === "running") yield* terminate(current.pid);
|
|
171
|
+
yield* Effect.promise(() => rm(state.pid, { force: true }));
|
|
172
|
+
return current;
|
|
173
|
+
});
|
|
174
|
+
export { readyMessage, refuseIfRunning, serverStatus, startDetached, stateDirOf, stopServer };
|
|
175
|
+
|
|
176
|
+
//# sourceMappingURL=daemon.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemon.js","names":[],"sources":["../src/daemon.ts"],"sourcesContent":["import { execFile, spawn } from 'node:child_process';\nimport type { ChildProcess } from 'node:child_process';\nimport { mkdir, open, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\nimport { Effect, Option } from 'effect';\n\nimport { ServerError } from './errors.ts';\n\n/** Signal 0 checks that a process exists without touching it. */\nconst probeSignal = 0;\nconst firstPid = 1;\nconst logTailLines = 30;\nconst startupTimeout = '60 seconds';\nconst stopPollInterval = '100 millis';\n/** Longer than the supervisor's own 10 s grace for its children. */\nconst stopPolls = 150;\nconst killPolls = 20;\n\n/** The message a detached server sends its parent over IPC once every port accepts connections. */\nconst readyMessage = 'ready';\n\n/** Where a detached server keeps its pid file and log. */\ninterface StateDir {\n readonly dir: string;\n readonly log: string;\n readonly pid: string;\n}\n\ntype ServerStatus =\n | { readonly _tag: 'running'; readonly pid: number; readonly since: Date }\n | { readonly _tag: 'stale'; readonly pid: number }\n | { readonly _tag: 'stopped' };\n\n/** `--state-dir`, else WT_TUNNEL_SERVER_STATE_DIR, else `$XDG_STATE_HOME/wt-tunnel-server`. */\nconst stateDirOf = (\n flag: string | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): StateDir => {\n const stateHome = env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state');\n const dir = resolve(\n flag ?? env.WT_TUNNEL_SERVER_STATE_DIR ?? join(stateHome, 'wt-tunnel-server'),\n );\n return { dir, log: join(dir, 'server.log'), pid: join(dir, 'server.pid') };\n};\n\nconst errorCode = (error: unknown): unknown =>\n error instanceof Error && 'code' in error ? error.code : undefined;\n\n/** EPERM means the process exists but belongs to someone else. */\nconst exists = (pid: number) => {\n try {\n process.kill(pid, probeSignal);\n return true;\n } catch (error) {\n return errorCode(error) === 'EPERM';\n }\n};\n\nconst psArgs = (pid: number) =>\n Effect.callback<string>((resume) => {\n execFile('ps', ['-o', 'args=', '-p', String(pid)], (failure: unknown, stdout) => {\n resume(Effect.succeed(failure === null ? stdout : ''));\n });\n });\n\n/**\n * A pid file can outlive its process and the pid can be reused, so a pid only counts as ours while\n * its argv still names this state dir. The detached server is started with `--state-dir <dir>`.\n */\nconst ownedBy = (pid: number, state: StateDir) =>\n psArgs(pid).pipe(\n Effect.map((args) => `${args.trimEnd()} `.includes(`--state-dir ${state.dir} `)),\n );\n\n/** The file's text, or '' if it cannot be read. */\nconst readOrEmpty = (file: string) =>\n Effect.tryPromise(() => readFile(file, 'utf8')).pipe(Effect.orElseSucceed(() => ''));\n\n/** The pid a pid file names, if it names one. */\nconst parsePid = (text: string) => {\n const pid = Number(text.trim());\n return Number.isInteger(pid) && pid >= firstPid ? pid : undefined;\n};\n\nconst serverStatus = (state: StateDir): Effect.Effect<ServerStatus> =>\n Effect.gen(function* readPidFile() {\n const pid = parsePid(yield* readOrEmpty(state.pid));\n if (pid === undefined) {\n return { _tag: 'stopped' };\n }\n if (!exists(pid) || !(yield* ownedBy(pid, state))) {\n return { _tag: 'stale', pid };\n }\n const { mtime } = yield* Effect.promise(() => stat(state.pid));\n return { _tag: 'running', pid, since: mtime };\n });\n\n/** Fails when another server already runs from this state dir; the caller itself does not count. */\nconst refuseIfRunning = (state: StateDir) =>\n Effect.gen(function* checkPidFile() {\n const current = yield* serverStatus(state);\n if (current._tag === 'running' && current.pid !== process.pid) {\n yield* new ServerError({\n message: `already running (pid ${current.pid}, log ${state.log}). Run wt-tunnel-server stop first.`,\n });\n }\n });\n\nconst logSize = (log: string) =>\n Effect.tryPromise(() => stat(log)).pipe(\n Effect.map(({ size }: { readonly size: number }) => size),\n Effect.orElseSucceed(() => 0),\n );\n\n/** The log's last lines written since byte `from`, so an earlier run's lines are left out. */\nconst logTail = (log: string, from: number) =>\n readOrEmpty(log).pipe(\n Effect.map((text) =>\n Buffer.from(text)\n .subarray(from)\n .toString()\n .trimEnd()\n .split('\\n')\n .slice(-logTailLines)\n .join('\\n'),\n ),\n );\n\n/**\n * Runs this CLI again with `args` in a new session, its output appended to the log. The child holds\n * its own copy of the log descriptor, so ours is closed right away.\n */\nconst spawnServer = (state: StateDir, args: readonly string[]) =>\n Effect.acquireUseRelease(\n Effect.promise(() => open(state.log, 'a')),\n (handle: Readonly<FileHandle>) =>\n Effect.promise(async () => {\n await handle.write(`--- wt-tunnel-server start, ${new Date().toISOString()} ---\\n`);\n const [script = ''] = process.argv.slice(1);\n return spawn(process.execPath, [...process.execArgv, script, ...args], {\n detached: true,\n stdio: ['ignore', handle.fd, handle.fd, 'ipc'],\n });\n }),\n (handle: Readonly<FileHandle>) => Effect.promise(() => handle.close()),\n );\n\ntype Startup = { readonly _tag: 'exited'; readonly reason: string } | { readonly _tag: 'ready' };\n\n/** Waits for the child's ready message, or for it to exit first. */\nconst startup = (child: ChildProcess) =>\n Effect.callback<Startup>((resume) => {\n child.on('message', (message) => {\n if (message === readyMessage) {\n resume(Effect.succeed({ _tag: 'ready' }));\n }\n });\n child.once('error', (error: Readonly<Error>) => {\n resume(Effect.succeed({ _tag: 'exited', reason: error.message }));\n });\n child.once('exit', (code, signal) => {\n resume(Effect.succeed({ _tag: 'exited', reason: `code ${code} signal ${signal}` }));\n });\n });\n\n/** The detached server leads its own process group, which holds Caddy and frps too. */\nconst groupExists = (pid: number) => exists(-pid);\n\nconst waitForGroupExit = (pid: number, polls: number) =>\n Effect.gen(function* poll() {\n for (let count = 0; count < polls && groupExists(pid); count++) {\n yield* Effect.sleep(stopPollInterval);\n }\n return !groupExists(pid);\n });\n\n/** SIGTERM to the server, then SIGKILL to its whole group if any of it outlives the grace period. */\nconst terminate = (pid: number) =>\n Effect.gen(function* termThenKill() {\n process.kill(pid, 'SIGTERM');\n if (yield* waitForGroupExit(pid, stopPolls)) {\n return;\n }\n process.kill(-pid, 'SIGKILL');\n if (!(yield* waitForGroupExit(pid, killPolls))) {\n yield* new ServerError({ message: `process group ${pid} survived SIGKILL` });\n }\n });\n\nconst startFailed = (state: StateDir, from: number, reason: string) =>\n Effect.gen(function* removePidFileAndReport() {\n yield* Effect.promise(() => rm(state.pid, { force: true }));\n const tail = yield* logTail(state.log, from);\n return yield* new ServerError({\n message: `the server did not start (${reason}). Last log lines (${state.log}):\\n${tail}`,\n });\n });\n\n/**\n * Waits for the ready message, and yields why the server did not start if it does not arrive. A\n * server that is not ready in time is stopped.\n */\nconst awaitReady = (child: ChildProcess, pid: number) =>\n Effect.gen(function* readyExitedOrTimedOut() {\n const outcome = yield* Effect.timeoutOption(startup(child), startupTimeout);\n if (Option.isNone(outcome)) {\n yield* terminate(pid);\n return Option.some(`not ready after ${startupTimeout}`);\n }\n if (outcome.value._tag === 'exited') {\n return Option.some(`it exited with ${outcome.value.reason}`);\n }\n child.disconnect();\n child.unref();\n return Option.none();\n });\n\n/**\n * Starts the server in the background with `args`, and returns its pid once Caddy, frps and the\n * auth service all listen. The caller has checked that none runs already.\n */\nconst startDetached = (state: StateDir, args: readonly string[]) =>\n Effect.gen(function* spawnAndAwaitReady() {\n const from = yield* Effect.promise(() => mkdir(state.dir, { recursive: true })).pipe(\n Effect.andThen(logSize(state.log)),\n );\n const child = yield* spawnServer(state, args);\n const { pid } = child;\n if (pid === undefined) {\n return yield* startFailed(state, from, 'it could not be spawned');\n }\n yield* Effect.promise(() => writeFile(state.pid, `${pid}\\n`));\n const failure = yield* awaitReady(child, pid);\n if (Option.isSome(failure)) {\n return yield* startFailed(state, from, failure.value);\n }\n return pid;\n });\n\nconst stopServer = (state: StateDir) =>\n Effect.gen(function* terminateAndForget() {\n const current = yield* serverStatus(state);\n if (current._tag === 'running') {\n yield* terminate(current.pid);\n }\n yield* Effect.promise(() => rm(state.pid, { force: true }));\n return current;\n });\n\nexport { readyMessage, refuseIfRunning, serverStatus, startDetached, stateDirOf, stopServer };\nexport type { StateDir };\n"],"mappings":";;;;;;;;AAYA,MAAM,cAAc;AACpB,MAAM,WAAW;AAEjB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;;AAEzB,MAAM,YAAY;AAClB,MAAM,YAAY;;AAGlB,MAAM,eAAe;;AAerB,MAAM,cACJ,MACA,QACa;CACb,MAAM,YAAY,IAAI,kBAAkB,KAAK,QAAQ,GAAG,UAAU,OAAO;CACzE,MAAM,MAAM,QACV,QAAQ,IAAI,8BAA8B,KAAK,WAAW,kBAAkB,CAC9E;CACA,OAAO;EAAE;EAAK,KAAK,KAAK,KAAK,YAAY;EAAG,KAAK,KAAK,KAAK,YAAY;CAAE;AAC3E;AAEA,MAAM,aAAa,UACjB,iBAAiB,SAAS,UAAU,QAAQ,MAAM,OAAO,KAAA;;AAG3D,MAAM,UAAU,QAAgB;CAC9B,IAAI;EACF,QAAQ,KAAK,KAAK,WAAW;EAC7B,OAAO;CACT,SAAS,OAAO;EACd,OAAO,UAAU,KAAK,MAAM;CAC9B;AACF;AAEA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O,OAAO,KAAK;AACrB,CAAC;;;;;AAMH,MAAM,iBAAiB,OAAiB,SACtC,OAAO,IAAI,UAAU,qBAAqB;CACxC,MAAM,OAAO,OAAO,OAAO,cAAc,MAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,KAC9E,OAAO,QAAQ,QAAQ,MAAM,GAAG,CAAC,CACnC;CACA,MAAM,QAAQ,OAAO,YAAY,OAAO,IAAI;CAC5C,MAAM,EAAE,QAAQ;CAChB,IAAI,QAAQ,KAAA,GACV,OAAO,OAAO,YAAY,OAAO,MAAM,yBAAyB;CAElE,OAAO,OAAO,cAAc,UAAU,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC;CAC5D,MAAM,UAAU,OAAO,WAAW,OAAO,GAAG;CAC5C,IAAI,OAAO,OAAO,OAAO,GACvB,OAAO,OAAO,YAAY,OAAO,MAAM,QAAQ,KAAK;CAEtD,OAAO;AACT,CAAC;AAEH,MAAM,cAAc,UAClB,OAAO,IAAI,UAAU,qBAAqB;CACxC,MAAM,UAAU,OAAO,aAAa,KAAK;CACzC,IAAI,QAAQ,SAAS,WACnB,OAAO,UAAU,QAAQ,GAAG;CAE9B,OAAO,OAAO,cAAc,GAAG,MAAM,KAAK,EAAE,OAAO,KAAK,CAAC,CAAC;CAC1D,OAAO;AACT,CAAC"}
|
package/dist/dev-host.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { isAllowed } from "./config.js";
|
|
2
|
+
import { loginUrl } from "./context.js";
|
|
3
|
+
import { hostWithoutPort } from "./hosts.js";
|
|
4
|
+
import { header, notFound, page, redirect, status } from "./reply.js";
|
|
5
|
+
import { cookiesWithoutSession, mintSession, sessionClearCookie, sessionCookieValues, sessionSetCookie, verifySession } from "./session.js";
|
|
6
|
+
import { Redacted } from "effect";
|
|
7
|
+
// src/dev-host.ts
|
|
8
|
+
/** Forward-auth sends the original method; a browser loading a page gets a redirect, not a 401. */
|
|
9
|
+
const isNavigation = (request) => (header(request, "x-forwarded-method") ?? request.method) === "GET" && (header(request, "sec-fetch-mode") === "navigate" || (header(request, "accept") ?? "").includes("text/html"));
|
|
10
|
+
/** The URL the browser asked for, rebuilt from what Caddy's forward_auth sends. */
|
|
11
|
+
const originalUrl = (request) => {
|
|
12
|
+
const host = header(request, "x-forwarded-host") ?? header(request, "host") ?? "";
|
|
13
|
+
return `https://${hostWithoutPort(host)}${header(request, "x-forwarded-uri") ?? "/"}`;
|
|
14
|
+
};
|
|
15
|
+
/** Allow-list changes take effect on the next request, not when old cookies expire. */
|
|
16
|
+
const signedIn = (request, { context, domain }) => {
|
|
17
|
+
const { config } = context;
|
|
18
|
+
const key = {
|
|
19
|
+
domain,
|
|
20
|
+
secret: Redacted.value(config.authSecret)
|
|
21
|
+
};
|
|
22
|
+
return sessionCookieValues(header(request, "cookie")).some((value) => {
|
|
23
|
+
const email = verifySession(key, value, context.now());
|
|
24
|
+
return email !== void 0 && isAllowed(config.allow, email, true);
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Caddy copies this header of a successful check over the request's Cookie, and drops Cookie when
|
|
29
|
+
* the header is absent. So the app never sees `wt_session`, which is valid on every host of the dev
|
|
30
|
+
* domain and would let whoever runs one app act as its visitors on every other.
|
|
31
|
+
*/
|
|
32
|
+
const appCookieHeader = "x-wt-app-cookie";
|
|
33
|
+
const verify = (request, dev) => {
|
|
34
|
+
if (signedIn(request, dev)) {
|
|
35
|
+
const cookies = cookiesWithoutSession(header(request, "cookie"));
|
|
36
|
+
return {
|
|
37
|
+
headers: cookies === "" ? {} : { [appCookieHeader]: cookies },
|
|
38
|
+
status: status.ok
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
return isNavigation(request) ? redirect(loginUrl(dev.context, originalUrl(request))) : {
|
|
42
|
+
body: "sign-in required\n",
|
|
43
|
+
status: status.unauthorized
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
const exchangeCode = (request, { context, query }) => {
|
|
47
|
+
const grant = context.codes.redeem(query.code ?? "", context.now());
|
|
48
|
+
if (grant === void 0 || grant.host !== hostWithoutPort(header(request, "host") ?? "")) return page(status.badRequest, {
|
|
49
|
+
html: "Open the page again to sign in.",
|
|
50
|
+
title: "Sign-in link expired"
|
|
51
|
+
});
|
|
52
|
+
const key = {
|
|
53
|
+
domain: grant.domain,
|
|
54
|
+
secret: Redacted.value(context.config.authSecret)
|
|
55
|
+
};
|
|
56
|
+
const value = mintSession(key, grant.email, context.now());
|
|
57
|
+
return redirect(grant.url, [sessionSetCookie(value, grant.domain)]);
|
|
58
|
+
};
|
|
59
|
+
/** Also ends the sign-in host's session, or the next visit would sign straight back in. */
|
|
60
|
+
const logout = ({ context, domain }) => redirect(`https://${context.config.authHost}/logout`, [sessionClearCookie(domain)]);
|
|
61
|
+
const devHostRoute = (request, path, dev) => {
|
|
62
|
+
switch (path) {
|
|
63
|
+
case "/_wt/verify": return verify(request, dev);
|
|
64
|
+
case "/_wt/callback": return exchangeCode(request, dev);
|
|
65
|
+
case "/_wt/logout": return logout(dev);
|
|
66
|
+
default: return notFound;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
export { appCookieHeader, devHostRoute };
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=dev-host.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dev-host.js","names":[],"sources":["../src/dev-host.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\n\nimport type { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { Redacted } from 'effect';\n\nimport { isAllowed } from './config.ts';\nimport { loginUrl } from './context.ts';\nimport type { Query, ServiceContext } from './context.ts';\nimport { hostWithoutPort } from './hosts.ts';\nimport { header, notFound, page, redirect, status } from './reply.ts';\nimport type { Reply } from './reply.ts';\nimport {\n cookiesWithoutSession,\n mintSession,\n sessionClearCookie,\n sessionCookieValues,\n sessionSetCookie,\n verifySession,\n} from './session.ts';\n\n/** A request to `/_wt/*` on a dev host, with the configured domain that covers the host. */\ninterface DevRequest {\n readonly context: ServiceContext;\n readonly domain: Hostname;\n readonly query: Query;\n}\n\n/** Forward-auth sends the original method; a browser loading a page gets a redirect, not a 401. */\nconst isNavigation = (request: IncomingMessage) =>\n (header(request, 'x-forwarded-method') ?? request.method) === 'GET' &&\n (header(request, 'sec-fetch-mode') === 'navigate' ||\n (header(request, 'accept') ?? '').includes('text/html'));\n\n/** The URL the browser asked for, rebuilt from what Caddy's forward_auth sends. */\nconst originalUrl = (request: IncomingMessage) => {\n const host = header(request, 'x-forwarded-host') ?? header(request, 'host') ?? '';\n return `https://${hostWithoutPort(host)}${header(request, 'x-forwarded-uri') ?? '/'}`;\n};\n\n/** Allow-list changes take effect on the next request, not when old cookies expire. */\nconst signedIn = (request: IncomingMessage, { context, domain }: DevRequest) => {\n const { config } = context;\n const key = { domain, secret: Redacted.value(config.authSecret) };\n return sessionCookieValues(header(request, 'cookie')).some((value) => {\n const email = verifySession(key, value, context.now());\n return email !== undefined && isAllowed(config.allow, email, true);\n });\n};\n\n/**\n * Caddy copies this header of a successful check over the request's Cookie, and drops Cookie when\n * the header is absent. So the app never sees `wt_session`, which is valid on every host of the dev\n * domain and would let whoever runs one app act as its visitors on every other.\n */\nconst appCookieHeader = 'x-wt-app-cookie';\n\nconst verify = (request: IncomingMessage, dev: DevRequest): Reply => {\n if (signedIn(request, dev)) {\n const cookies = cookiesWithoutSession(header(request, 'cookie'));\n return { headers: cookies === '' ? {} : { [appCookieHeader]: cookies }, status: status.ok };\n }\n return isNavigation(request)\n ? redirect(loginUrl(dev.context, originalUrl(request)))\n : { body: 'sign-in required\\n', status: status.unauthorized };\n};\n\nconst exchangeCode = (request: IncomingMessage, { context, query }: DevRequest): Reply => {\n const grant = context.codes.redeem(query.code ?? '', context.now());\n if (grant === undefined || grant.host !== hostWithoutPort(header(request, 'host') ?? '')) {\n return page(status.badRequest, {\n html: 'Open the page again to sign in.',\n title: 'Sign-in link expired',\n });\n }\n const key = { domain: grant.domain, secret: Redacted.value(context.config.authSecret) };\n const value = mintSession(key, grant.email, context.now());\n return redirect(grant.url, [sessionSetCookie(value, grant.domain)]);\n};\n\n/** Also ends the sign-in host's session, or the next visit would sign straight back in. */\nconst logout = ({ context, domain }: DevRequest): Reply =>\n redirect(`https://${context.config.authHost}/logout`, [sessionClearCookie(domain)]);\n\nconst devHostRoute = (request: IncomingMessage, path: string, dev: DevRequest): Reply => {\n switch (path) {\n case '/_wt/verify': {\n return verify(request, dev);\n }\n case '/_wt/callback': {\n return exchangeCode(request, dev);\n }\n case '/_wt/logout': {\n return logout(dev);\n }\n default: {\n return notFound;\n }\n }\n};\n\nexport { appCookieHeader, devHostRoute };\n"],"mappings":";;;;;;;;AA4BA,MAAM,gBAAgB,aACnB,OAAO,SAAS,oBAAoB,KAAK,QAAQ,YAAY,UAC7D,OAAO,SAAS,gBAAgB,MAAM,eACpC,OAAO,SAAS,QAAQ,KAAK,GAAA,CAAI,SAAS,WAAW;;AAG1D,MAAM,eAAe,YAA6B;CAChD,MAAM,OAAO,OAAO,SAAS,kBAAkB,KAAK,OAAO,SAAS,MAAM,KAAK;CAC/E,OAAO,WAAW,gBAAgB,IAAI,IAAI,OAAO,SAAS,iBAAiB,KAAK;AAClF;;AAGA,MAAM,YAAY,SAA0B,EAAE,SAAS,aAAyB;CAC9E,MAAM,EAAE,WAAW;CACnB,MAAM,MAAM;EAAE;EAAQ,QAAQ,SAAS,MAAM,OAAO,UAAU;CAAE;CAChE,OAAO,oBAAoB,OAAO,SAAS,QAAQ,CAAC,CAAC,CAAC,MAAM,UAAU;EACpE,MAAM,QAAQ,cAAc,KAAK,OAAO,QAAQ,IAAI,CAAC;EACrD,OAAO,UAAU,KAAA,KAAa,UAAU,OAAO,OAAO,OAAO,IAAI;CACnE,CAAC;AACH;;;;;;AAOA,MAAM,kBAAkB;AAExB,MAAM,UAAU,SAA0B,QAA2B;CACnE,IAAI,SAAS,SAAS,GAAG,GAAG;EAC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
|
|
4
|
+
/** An expected failure, with a message written for the person at the terminal. */
|
|
5
|
+
var ServerError = class extends taggedErrorClass()("ServerError", { message: Schema.String }) {};
|
|
6
|
+
export { ServerError };
|
|
7
|
+
|
|
8
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { Schema } from 'effect';\n\n/*\n * The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in\n * `Error`, as an error thrown without `new`.\n */\nconst { TaggedError: taggedErrorClass } = Schema;\n\n/** An expected failure, with a message written for the person at the terminal. */\nclass ServerError extends taggedErrorClass<ServerError>()('ServerError', {\n message: Schema.String,\n}) {}\n\nexport { ServerError };\n"],"mappings":";;AAMA,MAAM,EAAE,aAAa,qBAAqB;;AAG1C,IAAM,cAAN,cAA0B,iBAA8B,CAAC,CAAC,eAAe,EACvE,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC"}
|
package/dist/hosts.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Brand } from "effect";
|
|
2
|
+
// src/hosts.ts
|
|
3
|
+
const trustedHostname = Brand.nominal();
|
|
4
|
+
/** Strips the port and lowercases, as browsers send Host case-insensitively. */
|
|
5
|
+
const hostWithoutPort = (host) => host.replace(/:\d+$/u, "").toLowerCase();
|
|
6
|
+
/**
|
|
7
|
+
* The configured domain that serves `host`: the host equals it or ends with `.<domain>`. The
|
|
8
|
+
* longest match wins, so `a.dev.x.com` belongs to `dev.x.com` even when `x.com` is configured too.
|
|
9
|
+
*/
|
|
10
|
+
const domainOf = (host, domains) => {
|
|
11
|
+
const name = hostWithoutPort(host);
|
|
12
|
+
let match = void 0;
|
|
13
|
+
for (const domain of domains) if ((name === domain || name.endsWith(`.${domain}`)) && (match === void 0 || domain.length > match.length)) match = domain;
|
|
14
|
+
return match;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Validates a sign-in return URL (`rd`): https on the default port, no credentials, and a host
|
|
18
|
+
* under a configured domain. Anything else could turn the sign-in host into an open redirect.
|
|
19
|
+
*/
|
|
20
|
+
const parseReturnTarget = (rd, domains) => {
|
|
21
|
+
const url = rd !== void 0 && URL.canParse(rd) ? new URL(rd) : void 0;
|
|
22
|
+
const plain = url?.protocol === "https:" && url.port === "" && url.username === "" && url.password === "";
|
|
23
|
+
const domain = plain ? domainOf(url.hostname, domains) : void 0;
|
|
24
|
+
return plain && domain !== void 0 ? {
|
|
25
|
+
domain,
|
|
26
|
+
host: trustedHostname(url.hostname),
|
|
27
|
+
url: url.href
|
|
28
|
+
} : void 0;
|
|
29
|
+
};
|
|
30
|
+
export { domainOf, hostWithoutPort, parseReturnTarget };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=hosts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hosts.js","names":[],"sources":["../src/hosts.ts"],"sourcesContent":["import type { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { Brand } from 'effect';\n\nconst trustedHostname = Brand.nominal<Hostname>();\n\n/** Strips the port and lowercases, as browsers send Host case-insensitively. */\nconst hostWithoutPort = (host: string) => host.replace(/:\\d+$/u, '').toLowerCase();\n\n/**\n * The configured domain that serves `host`: the host equals it or ends with `.<domain>`. The\n * longest match wins, so `a.dev.x.com` belongs to `dev.x.com` even when `x.com` is configured too.\n */\nconst domainOf = (host: string, domains: readonly Hostname[]): Hostname | undefined => {\n const name = hostWithoutPort(host);\n let match: Hostname | undefined = undefined;\n for (const domain of domains) {\n const covers = name === domain || name.endsWith(`.${domain}`);\n if (covers && (match === undefined || domain.length > match.length)) {\n match = domain;\n }\n }\n return match;\n};\n\ninterface ReturnTarget {\n readonly domain: Hostname;\n readonly host: Hostname;\n readonly url: string;\n}\n\n/**\n * Validates a sign-in return URL (`rd`): https on the default port, no credentials, and a host\n * under a configured domain. Anything else could turn the sign-in host into an open redirect.\n */\nconst parseReturnTarget = (\n rd: string | undefined,\n domains: readonly Hostname[],\n): ReturnTarget | undefined => {\n const url = rd !== undefined && URL.canParse(rd) ? new URL(rd) : undefined;\n const plain =\n url?.protocol === 'https:' && url.port === '' && url.username === '' && url.password === '';\n const domain = plain ? domainOf(url.hostname, domains) : undefined;\n return plain && domain !== undefined\n ? { domain, host: trustedHostname(url.hostname), url: url.href }\n : undefined;\n};\n\nexport { domainOf, hostWithoutPort, parseReturnTarget };\nexport type { ReturnTarget };\n"],"mappings":";;AAGA,MAAM,kBAAkB,MAAM,QAAkB;;AAGhD,MAAM,mBAAmB,SAAiB,KAAK,QAAQ,UAAU,EAAE,CAAC,CAAC,YAAY;;;;;AAMjF,MAAM,YAAY,MAAc,YAAuD;CACrF,MAAM,OAAO,gBAAgB,IAAI;CACjC,IAAI,QAA8B,KAAA;CAClC,KAAK,MAAM,UAAU,SAEnB,KADe,SAAS,UAAU,KAAK,SAAS,IAAI,QAAQ,OAC7C,UAAU,KAAA,KAAa,OAAO,SAAS,MAAM,SAC1D,QAAQ;CAGZ,OAAO;AACT;;;;;AAYA,MAAM,qBACJ,IACA,YAC6B;CAC7B,MAAM,MAAM,OAAO,KAAA,KAAa,IAAI,SAAS,EAAE,IAAI,IAAI,IAAI,EAAE,IAAI,KAAA;CACjE,MAAM,QACJ,KAAK,aAAa,YAAY,IAAI,SAAS,MAAM,IAAI,aAAa,MAAM,IAAI,aAAa;CAC3F,MAAM,SAAS,QAAQ,SAAS,IAAI,UAAU,OAAO,IAAI,KAAA;CACzD,OAAO,SAAS,WAAW,KAAA,IACvB;EAAE;EAAQ,MAAM,gBAAgB,IAAI,QAAQ;EAAG,KAAK,IAAI;CAAK,IAC7D,KAAA;AACN"}
|
package/dist/internal.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { domainOf } from "./hosts.js";
|
|
2
|
+
import { notFound, status } from "./reply.js";
|
|
3
|
+
import { Option, Schema } from "effect";
|
|
4
|
+
// src/internal.ts
|
|
5
|
+
const askPath = "/ask";
|
|
6
|
+
const newProxyPath = "/frps/new-proxy";
|
|
7
|
+
const maxBodyLength = 65536;
|
|
8
|
+
/** Caddy's on-demand TLS check: certificates only for dev hosts and the sign-in host. */
|
|
9
|
+
const ask = (query, config) => {
|
|
10
|
+
const host = query.domain ?? "";
|
|
11
|
+
return { status: host === config.authHost || domainOf(host, config.domains) !== void 0 ? status.ok : status.forbidden };
|
|
12
|
+
};
|
|
13
|
+
const CustomDomains = Schema.NullOr(Schema.Array(Schema.String));
|
|
14
|
+
/** The fields of frps's NewProxy plugin request that decide whether a proxy is allowed. */
|
|
15
|
+
const NewProxyContent = Schema.Struct({
|
|
16
|
+
custom_domains: Schema.optionalKey(CustomDomains),
|
|
17
|
+
proxy_type: Schema.String,
|
|
18
|
+
subdomain: Schema.optionalKey(Schema.String)
|
|
19
|
+
});
|
|
20
|
+
const NewProxyRequest = Schema.fromJsonString(Schema.Struct({ content: NewProxyContent }));
|
|
21
|
+
/** Why frps must refuse this proxy, or undefined for an http proxy that serves dev hosts only. */
|
|
22
|
+
const contentProblem = (content, config) => {
|
|
23
|
+
const hosts = content.custom_domains ?? [];
|
|
24
|
+
if (content.proxy_type !== "http") return `only http proxies are allowed, not ${content.proxy_type}`;
|
|
25
|
+
if ((content.subdomain ?? "") !== "" || hosts.length === 0) return "http proxies must name their dev hosts in customDomains";
|
|
26
|
+
const foreign = hosts.find((host) => domainOf(host, config.domains) === void 0);
|
|
27
|
+
return foreign === void 0 ? void 0 : `${foreign} is not under a configured domain`;
|
|
28
|
+
};
|
|
29
|
+
const proxyProblem = (body, config) => Option.match(Schema.decodeUnknownOption(NewProxyRequest)(body), {
|
|
30
|
+
onNone: () => "unreadable NewProxy request",
|
|
31
|
+
onSome: ({ content }) => contentProblem(content, config)
|
|
32
|
+
});
|
|
33
|
+
const readBody = async (request) => {
|
|
34
|
+
let body = "";
|
|
35
|
+
for await (const chunk of request) {
|
|
36
|
+
body += String(chunk);
|
|
37
|
+
if (body.length > maxBodyLength) throw new Error("request body too large");
|
|
38
|
+
}
|
|
39
|
+
return body;
|
|
40
|
+
};
|
|
41
|
+
/** Frps server plugin, NewProxy op: frps accepts the proxy only when `reject` is false. */
|
|
42
|
+
const newProxy = async (request, config) => {
|
|
43
|
+
const problem = proxyProblem(await readBody(request), config);
|
|
44
|
+
return {
|
|
45
|
+
body: JSON.stringify({
|
|
46
|
+
reject: problem !== void 0,
|
|
47
|
+
reject_reason: problem ?? "",
|
|
48
|
+
unchange: true
|
|
49
|
+
}),
|
|
50
|
+
headers: { "content-type": "application/json" },
|
|
51
|
+
status: status.ok
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/** Routes for Caddy and frps, which call on the loopback address. */
|
|
55
|
+
const internalRoute = (request, path, { config, query }) => {
|
|
56
|
+
if (path === "/ask") return Promise.resolve(ask(query, config));
|
|
57
|
+
if (path === "/frps/new-proxy" && request.method === "POST") return newProxy(request, config);
|
|
58
|
+
return Promise.resolve(notFound);
|
|
59
|
+
};
|
|
60
|
+
export { askPath, internalRoute, newProxyPath };
|
|
61
|
+
|
|
62
|
+
//# sourceMappingURL=internal.js.map
|