@tafrahq/wt-tunnel-server 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +108 -2
- package/dist/auth.js +121 -0
- package/dist/auth.js.map +1 -0
- package/dist/bin.js +32 -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 +110 -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/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/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 +53 -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 +65 -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 +65 -3
- package/src/auth.ts +153 -0
- package/src/bin.ts +41 -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 +195 -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 +129 -0
- package/src/sign-in.ts +147 -0
- package/src/supervise.ts +51 -0
package/src/cli.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
|
|
3
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
4
|
+
import { Console, Effect, Option, Schema } from 'effect';
|
|
5
|
+
import { Command, Flag } from 'effect/cli';
|
|
6
|
+
|
|
7
|
+
import { resolveBinaries } from './binaries.ts';
|
|
8
|
+
import type { Binaries } from './binaries.ts';
|
|
9
|
+
import { configFileOf, loadServerConfig } from './config.ts';
|
|
10
|
+
import { refuseIfRunning, serverStatus, startDetached, stateDirOf, stopServer } from './daemon.ts';
|
|
11
|
+
import type { StateDir } from './daemon.ts';
|
|
12
|
+
import { defaultPorts } from './render.ts';
|
|
13
|
+
import type { Ports } from './render.ts';
|
|
14
|
+
|
|
15
|
+
/** `status` exits with 3 when no server runs, as LSB init scripts do. */
|
|
16
|
+
const stoppedExitCode = 3;
|
|
17
|
+
const maxPort = 65_535;
|
|
18
|
+
|
|
19
|
+
const configFlag = Flag.String('config').pipe(
|
|
20
|
+
Flag.withDescription(
|
|
21
|
+
'The server config file. Default: the JSON in WT_TUNNEL_SERVER_CONFIG, else ./wt-tunnel-server.json.',
|
|
22
|
+
),
|
|
23
|
+
Flag.optional,
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const stateDirFlag = Flag.String('state-dir').pipe(
|
|
27
|
+
Flag.withDescription(
|
|
28
|
+
'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.',
|
|
29
|
+
),
|
|
30
|
+
Flag.optional,
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
const Port = Schema.Int.check(Schema.isBetween({ maximum: maxPort, minimum: 1 }));
|
|
34
|
+
|
|
35
|
+
const portFlag = (name: string, fallback: number, description: string) =>
|
|
36
|
+
Flag.Int(name).pipe(
|
|
37
|
+
Flag.withSchema(Port),
|
|
38
|
+
Flag.withDescription(`${description} (default ${fallback})`),
|
|
39
|
+
Flag.withDefault(fallback),
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
const binaryFlag = (name: string) =>
|
|
43
|
+
Flag.String(name).pipe(
|
|
44
|
+
Flag.withDescription(
|
|
45
|
+
`Run this ${name} executable. Default: ${name} on PATH, else the pinned release, downloaded to the user cache on first use.`,
|
|
46
|
+
),
|
|
47
|
+
Flag.optional,
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
const stateDirFrom = (flag: Option.Option<string>) =>
|
|
51
|
+
stateDirOf(Option.getOrUndefined(flag), process.env);
|
|
52
|
+
|
|
53
|
+
/** What `start` needs once the flags are checked. */
|
|
54
|
+
interface Start {
|
|
55
|
+
readonly binaries: Binaries;
|
|
56
|
+
readonly config: ServerConfig;
|
|
57
|
+
/** The config file as an absolute path, so a detached server finds it from any directory. */
|
|
58
|
+
readonly configFile: string | undefined;
|
|
59
|
+
readonly ports: Ports;
|
|
60
|
+
readonly state: StateDir;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The arguments a detached server is started with: the resolved binaries, so it never downloads,
|
|
65
|
+
* and the state dir, which is how `status` and `stop` recognise it.
|
|
66
|
+
*/
|
|
67
|
+
const foregroundArgs = ({ binaries, configFile, ports, state }: Start) => [
|
|
68
|
+
'start',
|
|
69
|
+
...(configFile === undefined ? [] : ['--config', configFile]),
|
|
70
|
+
'--state-dir',
|
|
71
|
+
state.dir,
|
|
72
|
+
'--caddy',
|
|
73
|
+
binaries.caddy,
|
|
74
|
+
'--frps',
|
|
75
|
+
binaries.frps,
|
|
76
|
+
'--https-port',
|
|
77
|
+
String(ports.https),
|
|
78
|
+
'--http-port',
|
|
79
|
+
String(ports.http),
|
|
80
|
+
'--tunnel-port',
|
|
81
|
+
String(ports.tunnel),
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
const runForeground = ({ binaries, config, ports }: Start) =>
|
|
85
|
+
Effect.gen(function* loadThenSupervise() {
|
|
86
|
+
// Loaded here, so stop, status and check skip loading Better Auth.
|
|
87
|
+
const supervise = yield* Effect.promise(async () => {
|
|
88
|
+
const module = await import('./supervise.ts');
|
|
89
|
+
return module.supervise;
|
|
90
|
+
});
|
|
91
|
+
yield* supervise(config, { binaries, ports });
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
/** `stop` finds the server only in the state dir it was started with, so the hint names a flag. */
|
|
95
|
+
const runDetached = (start: Start, stateDirGiven: Option.Option<string>) =>
|
|
96
|
+
startDetached(start.state, foregroundArgs(start)).pipe(
|
|
97
|
+
Effect.flatMap((pid) =>
|
|
98
|
+
Console.log(
|
|
99
|
+
`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}` : ''}.`,
|
|
100
|
+
),
|
|
101
|
+
),
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
const start = Command.make(
|
|
105
|
+
'start',
|
|
106
|
+
{
|
|
107
|
+
caddy: binaryFlag('caddy'),
|
|
108
|
+
config: configFlag,
|
|
109
|
+
detach: Flag.Boolean('detach').pipe(
|
|
110
|
+
Flag.withDescription(
|
|
111
|
+
'Run in the background: return once the server listens, with its output in server.log',
|
|
112
|
+
),
|
|
113
|
+
Flag.withDefault(false),
|
|
114
|
+
),
|
|
115
|
+
frps: binaryFlag('frps'),
|
|
116
|
+
http: portFlag('http-port', defaultPorts.http, 'The port Caddy redirects to https on'),
|
|
117
|
+
https: portFlag('https-port', defaultPorts.https, 'The port Caddy serves dev hosts on'),
|
|
118
|
+
stateDir: stateDirFlag,
|
|
119
|
+
tunnel: portFlag('tunnel-port', defaultPorts.tunnel, 'The port frps accepts frpc on'),
|
|
120
|
+
},
|
|
121
|
+
(input) =>
|
|
122
|
+
Effect.gen(function* startServer() {
|
|
123
|
+
const state = stateDirFrom(input.stateDir);
|
|
124
|
+
yield* refuseIfRunning(state);
|
|
125
|
+
const file = yield* configFileOf(Option.getOrUndefined(input.config), process.env);
|
|
126
|
+
const configFile = file === undefined ? undefined : resolve(file);
|
|
127
|
+
// The config is checked before anything is downloaded.
|
|
128
|
+
const config = yield* loadServerConfig(configFile, process.env);
|
|
129
|
+
const binaries = yield* resolveBinaries({
|
|
130
|
+
caddy: Option.getOrUndefined(input.caddy),
|
|
131
|
+
frps: Option.getOrUndefined(input.frps),
|
|
132
|
+
});
|
|
133
|
+
const checked: Start = {
|
|
134
|
+
binaries,
|
|
135
|
+
config,
|
|
136
|
+
configFile,
|
|
137
|
+
ports: { http: input.http, https: input.https, tunnel: input.tunnel },
|
|
138
|
+
state,
|
|
139
|
+
};
|
|
140
|
+
yield* input.detach ? runDetached(checked, input.stateDir) : runForeground(checked);
|
|
141
|
+
}),
|
|
142
|
+
).pipe(
|
|
143
|
+
Command.withDescription(
|
|
144
|
+
'Run Caddy, frps and the sign-in service; in the foreground unless --detach',
|
|
145
|
+
),
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
const stop = Command.make('stop', { stateDir: stateDirFlag }, ({ stateDir }) =>
|
|
149
|
+
Effect.gen(function* stopDetached() {
|
|
150
|
+
const previous = yield* stopServer(stateDirFrom(stateDir));
|
|
151
|
+
yield* Console.log(
|
|
152
|
+
previous._tag === 'running' ? `Stopped (pid ${previous.pid}).` : 'Not running.',
|
|
153
|
+
);
|
|
154
|
+
}),
|
|
155
|
+
).pipe(Command.withDescription('Stop the detached server and wait until Caddy and frps exit'));
|
|
156
|
+
|
|
157
|
+
const status = Command.make('status', { stateDir: stateDirFlag }, ({ stateDir }) =>
|
|
158
|
+
Effect.gen(function* printStatus() {
|
|
159
|
+
const state = stateDirFrom(stateDir);
|
|
160
|
+
const current = yield* serverStatus(state);
|
|
161
|
+
if (current._tag === 'running') {
|
|
162
|
+
yield* Console.log(
|
|
163
|
+
`running: pid ${current.pid}, since ${current.since.toISOString()}, log ${state.log}`,
|
|
164
|
+
);
|
|
165
|
+
return;
|
|
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'),
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
const check = Command.make('check', { config: configFlag }, ({ config }) =>
|
|
179
|
+
Effect.gen(function* checkConfig() {
|
|
180
|
+
const file = yield* configFileOf(Option.getOrUndefined(config), process.env);
|
|
181
|
+
yield* loadServerConfig(file, process.env);
|
|
182
|
+
yield* Console.log(`${file ?? 'WT_TUNNEL_SERVER_CONFIG'} is a valid server config`);
|
|
183
|
+
}),
|
|
184
|
+
).pipe(Command.withDescription('Check the server config without starting anything'));
|
|
185
|
+
|
|
186
|
+
const cli = Command.make('wt-tunnel-server').pipe(
|
|
187
|
+
Command.withDescription(
|
|
188
|
+
'The wt-tunnel server: Caddy, frps and a Google sign-in service under one supervisor',
|
|
189
|
+
),
|
|
190
|
+
Command.withSubcommands([start, stop, status, check]),
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
const run = (version: string) => Command.run(cli, { version });
|
|
194
|
+
|
|
195
|
+
export { run };
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { readServerConfig, serverConfigFileName } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
5
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
6
|
+
import { Effect } from 'effect';
|
|
7
|
+
|
|
8
|
+
import { ServerError } from './errors.ts';
|
|
9
|
+
import { readRootCa } from './root-ca.ts';
|
|
10
|
+
|
|
11
|
+
const readText = (file: string) => Effect.tryPromise(() => readFile(file, 'utf8'));
|
|
12
|
+
|
|
13
|
+
/** Decodes a config's text; `dir` is where its `ca` paths are relative to. */
|
|
14
|
+
const decodeServerConfig = (text: string, source: string, dir: string) =>
|
|
15
|
+
readServerConfig({ dir, read: readText, source, text }).pipe(
|
|
16
|
+
Effect.mapError(({ message }: { readonly message: string }) => new ServerError({ message })),
|
|
17
|
+
Effect.tap((config) =>
|
|
18
|
+
Effect.try({
|
|
19
|
+
catch: () =>
|
|
20
|
+
new ServerError({ message: `${source}: ca.cert is not a readable certificate` }),
|
|
21
|
+
try: () => readRootCa(config),
|
|
22
|
+
}),
|
|
23
|
+
),
|
|
24
|
+
);
|
|
25
|
+
const configEnv = 'WT_TUNNEL_SERVER_CONFIG';
|
|
26
|
+
|
|
27
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
28
|
+
|
|
29
|
+
const isDirectory = (path: string) =>
|
|
30
|
+
Effect.tryPromise(async () => {
|
|
31
|
+
const stats = await stat(path);
|
|
32
|
+
return stats.isDirectory();
|
|
33
|
+
}).pipe(Effect.orElseSucceed(() => false));
|
|
34
|
+
|
|
35
|
+
const exists = (path: string) =>
|
|
36
|
+
Effect.tryPromise(() => stat(path)).pipe(
|
|
37
|
+
Effect.as(true),
|
|
38
|
+
Effect.orElseSucceed(() => false),
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* `--config` wins: a file, or a directory that holds wt-tunnel-server.json. Then
|
|
43
|
+
* WT_TUNNEL_SERVER_CONFIG, then ./wt-tunnel-server.json if it exists. Undefined means the JSON
|
|
44
|
+
* comes from the environment.
|
|
45
|
+
*/
|
|
46
|
+
const configFileOf = (flag: string | undefined, env: Env) =>
|
|
47
|
+
Effect.gen(function* findConfig() {
|
|
48
|
+
if (flag !== undefined) {
|
|
49
|
+
return (yield* isDirectory(flag)) ? join(flag, serverConfigFileName) : flag;
|
|
50
|
+
}
|
|
51
|
+
const fromEnv = (env[configEnv] ?? '') !== '';
|
|
52
|
+
return !fromEnv && (yield* exists(serverConfigFileName)) ? serverConfigFileName : flag;
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const readConfigFile = (file: string) =>
|
|
56
|
+
Effect.tryPromise({
|
|
57
|
+
catch: (cause) => new ServerError({ message: `cannot read ${file}: ${String(cause)}` }),
|
|
58
|
+
try: () => readFile(file, 'utf8'),
|
|
59
|
+
}).pipe(Effect.flatMap((text) => decodeServerConfig(text, file, dirname(file))));
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Reads `file`, or without one the JSON in WT_TUNNEL_SERVER_CONFIG, whose `ca` paths are relative
|
|
63
|
+
* to the current directory.
|
|
64
|
+
*/
|
|
65
|
+
const loadServerConfig = (file: string | undefined, env: Env) => {
|
|
66
|
+
if (file !== undefined) {
|
|
67
|
+
return readConfigFile(file);
|
|
68
|
+
}
|
|
69
|
+
const text = env[configEnv];
|
|
70
|
+
return text === undefined || text === ''
|
|
71
|
+
? Effect.fail(
|
|
72
|
+
new ServerError({
|
|
73
|
+
message: `pass --config <file or directory>, set ${configEnv}, or run in a directory that holds ${serverConfigFileName}`,
|
|
74
|
+
}),
|
|
75
|
+
)
|
|
76
|
+
: decodeServerConfig(text, configEnv, process.cwd());
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** An email passes when Google verified it and it, or its domain, is listed. */
|
|
80
|
+
const isAllowed = (allow: ServerConfig['allow'], email: string, emailVerified: boolean) => {
|
|
81
|
+
if (!emailVerified) {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
const address = email.toLowerCase();
|
|
85
|
+
const domain = address.slice(address.lastIndexOf('@') + 1);
|
|
86
|
+
return (
|
|
87
|
+
(allow.emails ?? []).some((listed) => listed.toLowerCase() === address) ||
|
|
88
|
+
(allow.emailDomains ?? []).some((listed) => listed === domain)
|
|
89
|
+
);
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export { configFileOf, decodeServerConfig, isAllowed, loadServerConfig };
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
2
|
+
|
|
3
|
+
import type { SignIn } from './auth.ts';
|
|
4
|
+
import type { RootCa } from './root-ca.ts';
|
|
5
|
+
import type { CodeStore } from './session.ts';
|
|
6
|
+
|
|
7
|
+
/** Everything a route reads besides the request itself. */
|
|
8
|
+
interface ServiceContext {
|
|
9
|
+
readonly codes: CodeStore;
|
|
10
|
+
readonly config: ServerConfig;
|
|
11
|
+
readonly now: () => number;
|
|
12
|
+
readonly rootCa: RootCa;
|
|
13
|
+
readonly signIn: SignIn;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The request's query string, parsed once. */
|
|
17
|
+
type Query = Readonly<Record<string, string>>;
|
|
18
|
+
|
|
19
|
+
const loginUrl = (context: ServiceContext, returnUrl: string) =>
|
|
20
|
+
`https://${context.config.authHost}/login?rd=${encodeURIComponent(returnUrl)}`;
|
|
21
|
+
|
|
22
|
+
export { loginUrl };
|
|
23
|
+
export type { Query, ServiceContext };
|
package/src/daemon.ts
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import type { ChildProcess } from 'node:child_process';
|
|
3
|
+
import { mkdir, open, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
4
|
+
import type { FileHandle } from 'node:fs/promises';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
|
|
8
|
+
import { Effect, Option } from 'effect';
|
|
9
|
+
|
|
10
|
+
import { ServerError } from './errors.ts';
|
|
11
|
+
|
|
12
|
+
/** Signal 0 checks that a process exists without touching it. */
|
|
13
|
+
const probeSignal = 0;
|
|
14
|
+
const firstPid = 1;
|
|
15
|
+
const logTailLines = 30;
|
|
16
|
+
const startupTimeout = '60 seconds';
|
|
17
|
+
const stopPollInterval = '100 millis';
|
|
18
|
+
/** Longer than the supervisor's own 10 s grace for its children. */
|
|
19
|
+
const stopPolls = 150;
|
|
20
|
+
const killPolls = 20;
|
|
21
|
+
|
|
22
|
+
/** The message a detached server sends its parent over IPC once every port accepts connections. */
|
|
23
|
+
const readyMessage = 'ready';
|
|
24
|
+
|
|
25
|
+
/** Where a detached server keeps its pid file and log. */
|
|
26
|
+
interface StateDir {
|
|
27
|
+
readonly dir: string;
|
|
28
|
+
readonly log: string;
|
|
29
|
+
readonly pid: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type ServerStatus =
|
|
33
|
+
| { readonly _tag: 'running'; readonly pid: number; readonly since: Date }
|
|
34
|
+
| { readonly _tag: 'stale'; readonly pid: number }
|
|
35
|
+
| { readonly _tag: 'stopped' };
|
|
36
|
+
|
|
37
|
+
/** `--state-dir`, else WT_TUNNEL_SERVER_STATE_DIR, else `$XDG_STATE_HOME/wt-tunnel-server`. */
|
|
38
|
+
const stateDirOf = (
|
|
39
|
+
flag: string | undefined,
|
|
40
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
41
|
+
): StateDir => {
|
|
42
|
+
const stateHome = env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state');
|
|
43
|
+
const dir = resolve(
|
|
44
|
+
flag ?? env.WT_TUNNEL_SERVER_STATE_DIR ?? join(stateHome, 'wt-tunnel-server'),
|
|
45
|
+
);
|
|
46
|
+
return { dir, log: join(dir, 'server.log'), pid: join(dir, 'server.pid') };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const errorCode = (error: unknown): unknown =>
|
|
50
|
+
error instanceof Error && 'code' in error ? error.code : undefined;
|
|
51
|
+
|
|
52
|
+
/** EPERM means the process exists but belongs to someone else. */
|
|
53
|
+
const exists = (pid: number) => {
|
|
54
|
+
try {
|
|
55
|
+
process.kill(pid, probeSignal);
|
|
56
|
+
return true;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
return errorCode(error) === 'EPERM';
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const psArgs = (pid: number) =>
|
|
63
|
+
Effect.callback<string>((resume) => {
|
|
64
|
+
execFile('ps', ['-o', 'args=', '-p', String(pid)], (failure: unknown, stdout) => {
|
|
65
|
+
resume(Effect.succeed(failure === null ? stdout : ''));
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* A pid file can outlive its process and the pid can be reused, so a pid only counts as ours while
|
|
71
|
+
* its argv still names this state dir. The detached server is started with `--state-dir <dir>`.
|
|
72
|
+
*/
|
|
73
|
+
const ownedBy = (pid: number, state: StateDir) =>
|
|
74
|
+
psArgs(pid).pipe(
|
|
75
|
+
Effect.map((args) => `${args.trimEnd()} `.includes(`--state-dir ${state.dir} `)),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
/** The file's text, or '' if it cannot be read. */
|
|
79
|
+
const readOrEmpty = (file: string) =>
|
|
80
|
+
Effect.tryPromise(() => readFile(file, 'utf8')).pipe(Effect.orElseSucceed(() => ''));
|
|
81
|
+
|
|
82
|
+
/** The pid a pid file names, if it names one. */
|
|
83
|
+
const parsePid = (text: string) => {
|
|
84
|
+
const pid = Number(text.trim());
|
|
85
|
+
return Number.isInteger(pid) && pid >= firstPid ? pid : undefined;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const serverStatus = (state: StateDir): Effect.Effect<ServerStatus> =>
|
|
89
|
+
Effect.gen(function* readPidFile() {
|
|
90
|
+
const pid = parsePid(yield* readOrEmpty(state.pid));
|
|
91
|
+
if (pid === undefined) {
|
|
92
|
+
return { _tag: 'stopped' };
|
|
93
|
+
}
|
|
94
|
+
if (!exists(pid) || !(yield* ownedBy(pid, state))) {
|
|
95
|
+
return { _tag: 'stale', pid };
|
|
96
|
+
}
|
|
97
|
+
const { mtime } = yield* Effect.promise(() => stat(state.pid));
|
|
98
|
+
return { _tag: 'running', pid, since: mtime };
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
/** Fails when another server already runs from this state dir; the caller itself does not count. */
|
|
102
|
+
const refuseIfRunning = (state: StateDir) =>
|
|
103
|
+
Effect.gen(function* checkPidFile() {
|
|
104
|
+
const current = yield* serverStatus(state);
|
|
105
|
+
if (current._tag === 'running' && current.pid !== process.pid) {
|
|
106
|
+
yield* new ServerError({
|
|
107
|
+
message: `already running (pid ${current.pid}, log ${state.log}). Run wt-tunnel-server stop first.`,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const logSize = (log: string) =>
|
|
113
|
+
Effect.tryPromise(() => stat(log)).pipe(
|
|
114
|
+
Effect.map(({ size }: { readonly size: number }) => size),
|
|
115
|
+
Effect.orElseSucceed(() => 0),
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
/** The log's last lines written since byte `from`, so an earlier run's lines are left out. */
|
|
119
|
+
const logTail = (log: string, from: number) =>
|
|
120
|
+
readOrEmpty(log).pipe(
|
|
121
|
+
Effect.map((text) =>
|
|
122
|
+
Buffer.from(text)
|
|
123
|
+
.subarray(from)
|
|
124
|
+
.toString()
|
|
125
|
+
.trimEnd()
|
|
126
|
+
.split('\n')
|
|
127
|
+
.slice(-logTailLines)
|
|
128
|
+
.join('\n'),
|
|
129
|
+
),
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Runs this CLI again with `args` in a new session, its output appended to the log. The child holds
|
|
134
|
+
* its own copy of the log descriptor, so ours is closed right away.
|
|
135
|
+
*/
|
|
136
|
+
const spawnServer = (state: StateDir, args: readonly string[]) =>
|
|
137
|
+
Effect.acquireUseRelease(
|
|
138
|
+
Effect.promise(() => open(state.log, 'a')),
|
|
139
|
+
(handle: Readonly<FileHandle>) =>
|
|
140
|
+
Effect.promise(async () => {
|
|
141
|
+
await handle.write(`--- wt-tunnel-server start, ${new Date().toISOString()} ---\n`);
|
|
142
|
+
const [script = ''] = process.argv.slice(1);
|
|
143
|
+
return spawn(process.execPath, [...process.execArgv, script, ...args], {
|
|
144
|
+
detached: true,
|
|
145
|
+
stdio: ['ignore', handle.fd, handle.fd, 'ipc'],
|
|
146
|
+
});
|
|
147
|
+
}),
|
|
148
|
+
(handle: Readonly<FileHandle>) => Effect.promise(() => handle.close()),
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
type Startup = { readonly _tag: 'exited'; readonly reason: string } | { readonly _tag: 'ready' };
|
|
152
|
+
|
|
153
|
+
/** Waits for the child's ready message, or for it to exit first. */
|
|
154
|
+
const startup = (child: ChildProcess) =>
|
|
155
|
+
Effect.callback<Startup>((resume) => {
|
|
156
|
+
child.on('message', (message) => {
|
|
157
|
+
if (message === readyMessage) {
|
|
158
|
+
resume(Effect.succeed({ _tag: 'ready' }));
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
child.once('error', (error: Readonly<Error>) => {
|
|
162
|
+
resume(Effect.succeed({ _tag: 'exited', reason: error.message }));
|
|
163
|
+
});
|
|
164
|
+
child.once('exit', (code, signal) => {
|
|
165
|
+
resume(Effect.succeed({ _tag: 'exited', reason: `code ${code} signal ${signal}` }));
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
/** The detached server leads its own process group, which holds Caddy and frps too. */
|
|
170
|
+
const groupExists = (pid: number) => exists(-pid);
|
|
171
|
+
|
|
172
|
+
const waitForGroupExit = (pid: number, polls: number) =>
|
|
173
|
+
Effect.gen(function* poll() {
|
|
174
|
+
for (let count = 0; count < polls && groupExists(pid); count++) {
|
|
175
|
+
yield* Effect.sleep(stopPollInterval);
|
|
176
|
+
}
|
|
177
|
+
return !groupExists(pid);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
/** SIGTERM to the server, then SIGKILL to its whole group if any of it outlives the grace period. */
|
|
181
|
+
const terminate = (pid: number) =>
|
|
182
|
+
Effect.gen(function* termThenKill() {
|
|
183
|
+
process.kill(pid, 'SIGTERM');
|
|
184
|
+
if (yield* waitForGroupExit(pid, stopPolls)) {
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
process.kill(-pid, 'SIGKILL');
|
|
188
|
+
if (!(yield* waitForGroupExit(pid, killPolls))) {
|
|
189
|
+
yield* new ServerError({ message: `process group ${pid} survived SIGKILL` });
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
const startFailed = (state: StateDir, from: number, reason: string) =>
|
|
194
|
+
Effect.gen(function* removePidFileAndReport() {
|
|
195
|
+
yield* Effect.promise(() => rm(state.pid, { force: true }));
|
|
196
|
+
const tail = yield* logTail(state.log, from);
|
|
197
|
+
return yield* new ServerError({
|
|
198
|
+
message: `the server did not start (${reason}). Last log lines (${state.log}):\n${tail}`,
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Waits for the ready message, and yields why the server did not start if it does not arrive. A
|
|
204
|
+
* server that is not ready in time is stopped.
|
|
205
|
+
*/
|
|
206
|
+
const awaitReady = (child: ChildProcess, pid: number) =>
|
|
207
|
+
Effect.gen(function* readyExitedOrTimedOut() {
|
|
208
|
+
const outcome = yield* Effect.timeoutOption(startup(child), startupTimeout);
|
|
209
|
+
if (Option.isNone(outcome)) {
|
|
210
|
+
yield* terminate(pid);
|
|
211
|
+
return Option.some(`not ready after ${startupTimeout}`);
|
|
212
|
+
}
|
|
213
|
+
if (outcome.value._tag === 'exited') {
|
|
214
|
+
return Option.some(`it exited with ${outcome.value.reason}`);
|
|
215
|
+
}
|
|
216
|
+
child.disconnect();
|
|
217
|
+
child.unref();
|
|
218
|
+
return Option.none();
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Starts the server in the background with `args`, and returns its pid once Caddy, frps and the
|
|
223
|
+
* auth service all listen. The caller has checked that none runs already.
|
|
224
|
+
*/
|
|
225
|
+
const startDetached = (state: StateDir, args: readonly string[]) =>
|
|
226
|
+
Effect.gen(function* spawnAndAwaitReady() {
|
|
227
|
+
const from = yield* Effect.promise(() => mkdir(state.dir, { recursive: true })).pipe(
|
|
228
|
+
Effect.andThen(logSize(state.log)),
|
|
229
|
+
);
|
|
230
|
+
const child = yield* spawnServer(state, args);
|
|
231
|
+
const { pid } = child;
|
|
232
|
+
if (pid === undefined) {
|
|
233
|
+
return yield* startFailed(state, from, 'it could not be spawned');
|
|
234
|
+
}
|
|
235
|
+
yield* Effect.promise(() => writeFile(state.pid, `${pid}\n`));
|
|
236
|
+
const failure = yield* awaitReady(child, pid);
|
|
237
|
+
if (Option.isSome(failure)) {
|
|
238
|
+
return yield* startFailed(state, from, failure.value);
|
|
239
|
+
}
|
|
240
|
+
return pid;
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const stopServer = (state: StateDir) =>
|
|
244
|
+
Effect.gen(function* terminateAndForget() {
|
|
245
|
+
const current = yield* serverStatus(state);
|
|
246
|
+
if (current._tag === 'running') {
|
|
247
|
+
yield* terminate(current.pid);
|
|
248
|
+
}
|
|
249
|
+
yield* Effect.promise(() => rm(state.pid, { force: true }));
|
|
250
|
+
return current;
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
export { readyMessage, refuseIfRunning, serverStatus, startDetached, stateDirOf, stopServer };
|
|
254
|
+
export type { StateDir };
|
package/src/dev-host.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http';
|
|
2
|
+
|
|
3
|
+
import type { Hostname } from '@tafrahq/wt-tunnel-contract';
|
|
4
|
+
import { Redacted } from 'effect';
|
|
5
|
+
|
|
6
|
+
import { isAllowed } from './config.ts';
|
|
7
|
+
import { loginUrl } from './context.ts';
|
|
8
|
+
import type { Query, ServiceContext } from './context.ts';
|
|
9
|
+
import { hostWithoutPort } from './hosts.ts';
|
|
10
|
+
import { header, notFound, page, redirect, status } from './reply.ts';
|
|
11
|
+
import type { Reply } from './reply.ts';
|
|
12
|
+
import {
|
|
13
|
+
cookiesWithoutSession,
|
|
14
|
+
mintSession,
|
|
15
|
+
sessionClearCookie,
|
|
16
|
+
sessionCookieValues,
|
|
17
|
+
sessionSetCookie,
|
|
18
|
+
verifySession,
|
|
19
|
+
} from './session.ts';
|
|
20
|
+
|
|
21
|
+
/** A request to `/_wt/*` on a dev host, with the configured domain that covers the host. */
|
|
22
|
+
interface DevRequest {
|
|
23
|
+
readonly context: ServiceContext;
|
|
24
|
+
readonly domain: Hostname;
|
|
25
|
+
readonly query: Query;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Forward-auth sends the original method; a browser loading a page gets a redirect, not a 401. */
|
|
29
|
+
const isNavigation = (request: IncomingMessage) =>
|
|
30
|
+
(header(request, 'x-forwarded-method') ?? request.method) === 'GET' &&
|
|
31
|
+
(header(request, 'sec-fetch-mode') === 'navigate' ||
|
|
32
|
+
(header(request, 'accept') ?? '').includes('text/html'));
|
|
33
|
+
|
|
34
|
+
/** The URL the browser asked for, rebuilt from what Caddy's forward_auth sends. */
|
|
35
|
+
const originalUrl = (request: IncomingMessage) => {
|
|
36
|
+
const host = header(request, 'x-forwarded-host') ?? header(request, 'host') ?? '';
|
|
37
|
+
return `https://${hostWithoutPort(host)}${header(request, 'x-forwarded-uri') ?? '/'}`;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** Allow-list changes take effect on the next request, not when old cookies expire. */
|
|
41
|
+
const signedIn = (request: IncomingMessage, { context, domain }: DevRequest) => {
|
|
42
|
+
const { config } = context;
|
|
43
|
+
const key = { domain, secret: Redacted.value(config.authSecret) };
|
|
44
|
+
return sessionCookieValues(header(request, 'cookie')).some((value) => {
|
|
45
|
+
const email = verifySession(key, value, context.now());
|
|
46
|
+
return email !== undefined && isAllowed(config.allow, email, true);
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Caddy copies this header of a successful check over the request's Cookie, and drops Cookie when
|
|
52
|
+
* the header is absent. So the app never sees `wt_session`, which is valid on every host of the dev
|
|
53
|
+
* domain and would let whoever runs one app act as its visitors on every other.
|
|
54
|
+
*/
|
|
55
|
+
const appCookieHeader = 'x-wt-app-cookie';
|
|
56
|
+
|
|
57
|
+
const verify = (request: IncomingMessage, dev: DevRequest): Reply => {
|
|
58
|
+
if (signedIn(request, dev)) {
|
|
59
|
+
const cookies = cookiesWithoutSession(header(request, 'cookie'));
|
|
60
|
+
return { headers: cookies === '' ? {} : { [appCookieHeader]: cookies }, status: status.ok };
|
|
61
|
+
}
|
|
62
|
+
return isNavigation(request)
|
|
63
|
+
? redirect(loginUrl(dev.context, originalUrl(request)))
|
|
64
|
+
: { body: 'sign-in required\n', status: status.unauthorized };
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const exchangeCode = (request: IncomingMessage, { context, query }: DevRequest): Reply => {
|
|
68
|
+
const grant = context.codes.redeem(query.code ?? '', context.now());
|
|
69
|
+
if (grant === undefined || grant.host !== hostWithoutPort(header(request, 'host') ?? '')) {
|
|
70
|
+
return page(status.badRequest, {
|
|
71
|
+
html: 'Open the page again to sign in.',
|
|
72
|
+
title: 'Sign-in link expired',
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const key = { domain: grant.domain, secret: Redacted.value(context.config.authSecret) };
|
|
76
|
+
const value = mintSession(key, grant.email, context.now());
|
|
77
|
+
return redirect(grant.url, [sessionSetCookie(value, grant.domain)]);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** Also ends the sign-in host's session, or the next visit would sign straight back in. */
|
|
81
|
+
const logout = ({ context, domain }: DevRequest): Reply =>
|
|
82
|
+
redirect(`https://${context.config.authHost}/logout`, [sessionClearCookie(domain)]);
|
|
83
|
+
|
|
84
|
+
const devHostRoute = (request: IncomingMessage, path: string, dev: DevRequest): Reply => {
|
|
85
|
+
switch (path) {
|
|
86
|
+
case '/_wt/verify': {
|
|
87
|
+
return verify(request, dev);
|
|
88
|
+
}
|
|
89
|
+
case '/_wt/callback': {
|
|
90
|
+
return exchangeCode(request, dev);
|
|
91
|
+
}
|
|
92
|
+
case '/_wt/logout': {
|
|
93
|
+
return logout(dev);
|
|
94
|
+
}
|
|
95
|
+
default: {
|
|
96
|
+
return notFound;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
export { appCookieHeader, devHostRoute };
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Schema } from 'effect';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in
|
|
5
|
+
* `Error`, as an error thrown without `new`.
|
|
6
|
+
*/
|
|
7
|
+
const { TaggedError: taggedErrorClass } = Schema;
|
|
8
|
+
|
|
9
|
+
/** An expected failure, with a message written for the person at the terminal. */
|
|
10
|
+
class ServerError extends taggedErrorClass<ServerError>()('ServerError', {
|
|
11
|
+
message: Schema.String,
|
|
12
|
+
}) {}
|
|
13
|
+
|
|
14
|
+
export { ServerError };
|