@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/hosts.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Hostname } from '@tafrahq/wt-tunnel-contract';
|
|
2
|
+
import { Brand } from 'effect';
|
|
3
|
+
|
|
4
|
+
const trustedHostname = Brand.nominal<Hostname>();
|
|
5
|
+
|
|
6
|
+
/** Strips the port and lowercases, as browsers send Host case-insensitively. */
|
|
7
|
+
const hostWithoutPort = (host: string) => host.replace(/:\d+$/u, '').toLowerCase();
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The configured domain that serves `host`: the host equals it or ends with `.<domain>`. The
|
|
11
|
+
* longest match wins, so `a.dev.x.com` belongs to `dev.x.com` even when `x.com` is configured too.
|
|
12
|
+
*/
|
|
13
|
+
const domainOf = (host: string, domains: readonly Hostname[]): Hostname | undefined => {
|
|
14
|
+
const name = hostWithoutPort(host);
|
|
15
|
+
let match: Hostname | undefined = undefined;
|
|
16
|
+
for (const domain of domains) {
|
|
17
|
+
const covers = name === domain || name.endsWith(`.${domain}`);
|
|
18
|
+
if (covers && (match === undefined || domain.length > match.length)) {
|
|
19
|
+
match = domain;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return match;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
interface ReturnTarget {
|
|
26
|
+
readonly domain: Hostname;
|
|
27
|
+
readonly host: Hostname;
|
|
28
|
+
readonly url: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Validates a sign-in return URL (`rd`): https on the default port, no credentials, and a host
|
|
33
|
+
* under a configured domain. Anything else could turn the sign-in host into an open redirect.
|
|
34
|
+
*/
|
|
35
|
+
const parseReturnTarget = (
|
|
36
|
+
rd: string | undefined,
|
|
37
|
+
domains: readonly Hostname[],
|
|
38
|
+
): ReturnTarget | undefined => {
|
|
39
|
+
const url = rd !== undefined && URL.canParse(rd) ? new URL(rd) : undefined;
|
|
40
|
+
const plain =
|
|
41
|
+
url?.protocol === 'https:' && url.port === '' && url.username === '' && url.password === '';
|
|
42
|
+
const domain = plain ? domainOf(url.hostname, domains) : undefined;
|
|
43
|
+
return plain && domain !== undefined
|
|
44
|
+
? { domain, host: trustedHostname(url.hostname), url: url.href }
|
|
45
|
+
: undefined;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export { domainOf, hostWithoutPort, parseReturnTarget };
|
|
49
|
+
export type { ReturnTarget };
|
package/src/internal.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http';
|
|
2
|
+
|
|
3
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
4
|
+
import { Option, Schema } from 'effect';
|
|
5
|
+
|
|
6
|
+
import type { Query } from './context.ts';
|
|
7
|
+
import { domainOf } from './hosts.ts';
|
|
8
|
+
import { notFound, status } from './reply.ts';
|
|
9
|
+
import type { Reply } from './reply.ts';
|
|
10
|
+
|
|
11
|
+
const askPath = '/ask';
|
|
12
|
+
const newProxyPath = '/frps/new-proxy';
|
|
13
|
+
const maxBodyLength = 65_536;
|
|
14
|
+
|
|
15
|
+
/** Caddy's on-demand TLS check: certificates only for dev hosts and the sign-in host. */
|
|
16
|
+
const ask = (query: Query, config: ServerConfig): Reply => {
|
|
17
|
+
const host = query.domain ?? '';
|
|
18
|
+
const served = host === config.authHost || domainOf(host, config.domains) !== undefined;
|
|
19
|
+
return { status: served ? status.ok : status.forbidden };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const CustomDomains = Schema.NullOr(Schema.Array(Schema.String));
|
|
23
|
+
|
|
24
|
+
/** The fields of frps's NewProxy plugin request that decide whether a proxy is allowed. */
|
|
25
|
+
const NewProxyContent = Schema.Struct({
|
|
26
|
+
custom_domains: Schema.optionalKey(CustomDomains),
|
|
27
|
+
proxy_type: Schema.String,
|
|
28
|
+
subdomain: Schema.optionalKey(Schema.String),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const NewProxyRequest = Schema.fromJsonString(Schema.Struct({ content: NewProxyContent }));
|
|
32
|
+
|
|
33
|
+
/** Why frps must refuse this proxy, or undefined for an http proxy that serves dev hosts only. */
|
|
34
|
+
const contentProblem = (content: typeof NewProxyContent.Type, config: ServerConfig) => {
|
|
35
|
+
const hosts = content.custom_domains ?? [];
|
|
36
|
+
if (content.proxy_type !== 'http') {
|
|
37
|
+
return `only http proxies are allowed, not ${content.proxy_type}`;
|
|
38
|
+
}
|
|
39
|
+
if ((content.subdomain ?? '') !== '' || hosts.length === 0) {
|
|
40
|
+
return 'http proxies must name their dev hosts in customDomains';
|
|
41
|
+
}
|
|
42
|
+
const foreign = hosts.find((host) => domainOf(host, config.domains) === undefined);
|
|
43
|
+
return foreign === undefined ? undefined : `${foreign} is not under a configured domain`;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const proxyProblem = (body: string, config: ServerConfig) =>
|
|
47
|
+
Option.match(Schema.decodeUnknownOption(NewProxyRequest)(body), {
|
|
48
|
+
onNone: () => 'unreadable NewProxy request',
|
|
49
|
+
onSome: ({ content }) => contentProblem(content, config),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const readBody = async (request: IncomingMessage) => {
|
|
53
|
+
let body = '';
|
|
54
|
+
for await (const chunk of request) {
|
|
55
|
+
body += String(chunk);
|
|
56
|
+
if (body.length > maxBodyLength) {
|
|
57
|
+
throw new Error('request body too large');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return body;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** Frps server plugin, NewProxy op: frps accepts the proxy only when `reject` is false. */
|
|
64
|
+
const newProxy = async (request: IncomingMessage, config: ServerConfig): Promise<Reply> => {
|
|
65
|
+
const problem = proxyProblem(await readBody(request), config);
|
|
66
|
+
const answer = { reject: problem !== undefined, reject_reason: problem ?? '', unchange: true };
|
|
67
|
+
return {
|
|
68
|
+
body: JSON.stringify(answer),
|
|
69
|
+
headers: { 'content-type': 'application/json' },
|
|
70
|
+
status: status.ok,
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** Routes for Caddy and frps, which call on the loopback address. */
|
|
75
|
+
const internalRoute = (
|
|
76
|
+
request: IncomingMessage,
|
|
77
|
+
path: string,
|
|
78
|
+
{ config, query }: { readonly config: ServerConfig; readonly query: Query },
|
|
79
|
+
): Promise<Reply> => {
|
|
80
|
+
if (path === askPath) {
|
|
81
|
+
return Promise.resolve(ask(query, config));
|
|
82
|
+
}
|
|
83
|
+
if (path === newProxyPath && request.method === 'POST') {
|
|
84
|
+
return newProxy(request, config);
|
|
85
|
+
}
|
|
86
|
+
return Promise.resolve(notFound);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export { askPath, internalRoute, newProxyPath };
|
package/src/listen.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Server } from 'node:http';
|
|
2
|
+
|
|
3
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
4
|
+
import { Console, Effect } from 'effect';
|
|
5
|
+
|
|
6
|
+
import { createSignIn } from './auth.ts';
|
|
7
|
+
import { ServerError } from './errors.ts';
|
|
8
|
+
import { authPort, loopback } from './render.ts';
|
|
9
|
+
import { readRootCa } from './root-ca.ts';
|
|
10
|
+
import { createAuthService } from './service.ts';
|
|
11
|
+
import { createCodeStore } from './session.ts';
|
|
12
|
+
|
|
13
|
+
/** Binds the auth service for the scope. */
|
|
14
|
+
const serve = (server: Server) =>
|
|
15
|
+
Effect.acquireRelease(
|
|
16
|
+
Effect.callback<void, ServerError>((resume) => {
|
|
17
|
+
server.once('error', (error: Readonly<Error>) => {
|
|
18
|
+
const message = `the auth service cannot listen on ${loopback}:${authPort}: ${error.message}`;
|
|
19
|
+
resume(Effect.fail(new ServerError({ message })));
|
|
20
|
+
});
|
|
21
|
+
server.listen(authPort, loopback, () => {
|
|
22
|
+
resume(Effect.void);
|
|
23
|
+
});
|
|
24
|
+
}),
|
|
25
|
+
() =>
|
|
26
|
+
Effect.sync(() => {
|
|
27
|
+
server.close();
|
|
28
|
+
}),
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
/** The auth service, listening on the loopback address for the scope. */
|
|
32
|
+
const serveAuth = (config: ServerConfig) =>
|
|
33
|
+
serve(
|
|
34
|
+
createAuthService({
|
|
35
|
+
codes: createCodeStore(),
|
|
36
|
+
config,
|
|
37
|
+
now: Date.now,
|
|
38
|
+
rootCa: readRootCa(config),
|
|
39
|
+
signIn: createSignIn(config),
|
|
40
|
+
}),
|
|
41
|
+
).pipe(Effect.andThen(Console.log(`auth listening on ${loopback}:${authPort}`)));
|
|
42
|
+
|
|
43
|
+
export { serveAuth };
|
package/src/ready.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { connect } from 'node:net';
|
|
2
|
+
|
|
3
|
+
import { Console, Effect } from 'effect';
|
|
4
|
+
|
|
5
|
+
import { readyMessage } from './daemon.ts';
|
|
6
|
+
import { loopback } from './render.ts';
|
|
7
|
+
import type { Ports } from './render.ts';
|
|
8
|
+
|
|
9
|
+
const pollInterval = '100 millis';
|
|
10
|
+
|
|
11
|
+
const ignoreSendError = () => {
|
|
12
|
+
// A detached server outlives a parent that was killed while waiting for it.
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const accepts = (port: number) =>
|
|
16
|
+
Effect.callback<boolean>((resume) => {
|
|
17
|
+
const socket = connect({ host: loopback, port });
|
|
18
|
+
const settle = (open: boolean) => () => {
|
|
19
|
+
socket.destroy();
|
|
20
|
+
resume(Effect.succeed(open));
|
|
21
|
+
};
|
|
22
|
+
socket.once('connect', settle(true));
|
|
23
|
+
socket.once('error', settle(false));
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const allAccept = (ports: Ports) =>
|
|
27
|
+
Effect.all([ports.https, ports.http, ports.tunnel].map((port) => accepts(port))).pipe(
|
|
28
|
+
Effect.map((open: readonly boolean[]) => open.every(Boolean)),
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Waits until Caddy and frps accept connections on every public port, then logs `ready` and tells
|
|
33
|
+
* the parent of a detached server over IPC.
|
|
34
|
+
*/
|
|
35
|
+
const announceWhenReady = (ports: Ports) =>
|
|
36
|
+
Effect.gen(function* pollThenAnnounce() {
|
|
37
|
+
while (!(yield* allAccept(ports))) {
|
|
38
|
+
yield* Effect.sleep(pollInterval);
|
|
39
|
+
}
|
|
40
|
+
yield* Console.log(
|
|
41
|
+
`ready: https on :${ports.https}, http on :${ports.http}, tunnel on :${ports.tunnel}`,
|
|
42
|
+
);
|
|
43
|
+
/*
|
|
44
|
+
* With a callback, a parent that has already gone away is an error passed to it rather than an
|
|
45
|
+
* 'error' event that would crash the server and orphan Caddy and frps.
|
|
46
|
+
*/
|
|
47
|
+
process.send?.(readyMessage, undefined, undefined, ignoreSendError);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export { announceWhenReady };
|
package/src/render.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { tunnelPort } from '@tafrahq/wt-tunnel-contract';
|
|
2
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
3
|
+
import { Redacted } from 'effect';
|
|
4
|
+
|
|
5
|
+
import { appCookieHeader } from './dev-host.ts';
|
|
6
|
+
import { askPath, newProxyPath } from './internal.ts';
|
|
7
|
+
|
|
8
|
+
const authPort = 4000;
|
|
9
|
+
const loopback = '127.0.0.1';
|
|
10
|
+
const vhostPort = 8080;
|
|
11
|
+
const defaultHttpsPort = 443;
|
|
12
|
+
|
|
13
|
+
/** The ports the server listens on for the outside world. */
|
|
14
|
+
interface Ports {
|
|
15
|
+
readonly http: number;
|
|
16
|
+
readonly https: number;
|
|
17
|
+
readonly tunnel: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const defaultPorts: Ports = { http: 80, https: defaultHttpsPort, tunnel: tunnelPort };
|
|
21
|
+
|
|
22
|
+
interface CaddyPaths {
|
|
23
|
+
readonly caCert: string;
|
|
24
|
+
readonly caKey: string;
|
|
25
|
+
readonly storage: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Caddy's global options: no admin API, the ports, the on-demand check and the root as a CA. */
|
|
29
|
+
const caddyGlobals = (paths: CaddyPaths, ports: Ports) => `{
|
|
30
|
+
admin off
|
|
31
|
+
http_port ${ports.http}
|
|
32
|
+
https_port ${ports.https}
|
|
33
|
+
persist_config off
|
|
34
|
+
skip_install_trust
|
|
35
|
+
storage file_system ${paths.storage}
|
|
36
|
+
on_demand_tls {
|
|
37
|
+
ask http://${loopback}:${authPort}${askPath}
|
|
38
|
+
}
|
|
39
|
+
pki {
|
|
40
|
+
ca wt {
|
|
41
|
+
name "wt-tunnel"
|
|
42
|
+
root {
|
|
43
|
+
cert ${paths.caCert}
|
|
44
|
+
key ${paths.caKey}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}`;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Dev hosts get certificates on demand from an intermediate Caddy signs with the deployment's root.
|
|
52
|
+
* The sign-in host sits outside the root's name constraints, and a device opens it before it trusts
|
|
53
|
+
* the root, so it gets a public certificate from Let's Encrypt over ACME. Caddy keeps no state
|
|
54
|
+
* across restarts, so it requests a new one at each start; if ACME fails, as on a machine the
|
|
55
|
+
* internet cannot reach, it falls back to its own internal CA.
|
|
56
|
+
*/
|
|
57
|
+
const renderCaddyfile = (
|
|
58
|
+
config: ServerConfig,
|
|
59
|
+
paths: CaddyPaths,
|
|
60
|
+
ports: Ports,
|
|
61
|
+
) => `${caddyGlobals(paths, ports)}
|
|
62
|
+
|
|
63
|
+
https://${config.authHost} {
|
|
64
|
+
tls {
|
|
65
|
+
issuer acme
|
|
66
|
+
issuer internal
|
|
67
|
+
}
|
|
68
|
+
reverse_proxy ${loopback}:${authPort}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
https:// {
|
|
72
|
+
tls {
|
|
73
|
+
on_demand
|
|
74
|
+
issuer internal {
|
|
75
|
+
ca wt
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
handle /_wt/* {
|
|
79
|
+
reverse_proxy ${loopback}:${authPort}
|
|
80
|
+
}
|
|
81
|
+
handle {
|
|
82
|
+
forward_auth ${loopback}:${authPort} {
|
|
83
|
+
uri /_wt/verify
|
|
84
|
+
copy_headers ${appCookieHeader}>Cookie
|
|
85
|
+
}
|
|
86
|
+
reverse_proxy ${loopback}:${vhostPort}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
http:// {
|
|
91
|
+
redir https://{host}${ports.https === defaultHttpsPort ? '' : `:${ports.https}`}{uri} permanent
|
|
92
|
+
}
|
|
93
|
+
`;
|
|
94
|
+
|
|
95
|
+
/** JSON string escapes are valid TOML basic-string escapes. */
|
|
96
|
+
const tomlString = (value: string) => JSON.stringify(value);
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* `proxyBindAddr` is the address frps binds its vhost listener on, so the vhost port is reachable
|
|
100
|
+
* only through Caddy. The plugin lets the auth service refuse every proxy that is not an http proxy
|
|
101
|
+
* for a dev host.
|
|
102
|
+
*/
|
|
103
|
+
const renderFrpsToml = (config: ServerConfig, ports: Ports) => `bindAddr = "::"
|
|
104
|
+
bindPort = ${ports.tunnel}
|
|
105
|
+
proxyBindAddr = ${tomlString(loopback)}
|
|
106
|
+
vhostHTTPPort = ${vhostPort}
|
|
107
|
+
auth.method = "token"
|
|
108
|
+
auth.token = ${tomlString(Redacted.value(config.tunnelToken))}
|
|
109
|
+
transport.tls.force = true
|
|
110
|
+
log.to = "console"
|
|
111
|
+
log.disablePrintColor = true
|
|
112
|
+
|
|
113
|
+
[[httpPlugins]]
|
|
114
|
+
name = "wt-tunnel"
|
|
115
|
+
addr = ${tomlString(`${loopback}:${authPort}`)}
|
|
116
|
+
path = ${tomlString(newProxyPath)}
|
|
117
|
+
ops = ["NewProxy"]
|
|
118
|
+
`;
|
|
119
|
+
|
|
120
|
+
export { authPort, defaultPorts, loopback, renderCaddyfile, renderFrpsToml };
|
|
121
|
+
export type { Ports };
|
package/src/reply.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
|
|
3
|
+
import { faviconLink } from './brand.ts';
|
|
4
|
+
|
|
5
|
+
const status = {
|
|
6
|
+
badGateway: 502,
|
|
7
|
+
badRequest: 400,
|
|
8
|
+
forbidden: 403,
|
|
9
|
+
found: 302,
|
|
10
|
+
notFound: 404,
|
|
11
|
+
ok: 200,
|
|
12
|
+
serverError: 500,
|
|
13
|
+
unauthorized: 401,
|
|
14
|
+
} as const;
|
|
15
|
+
|
|
16
|
+
/** What a route answers; one writer turns it into the HTTP response. */
|
|
17
|
+
interface Reply {
|
|
18
|
+
readonly body?: string;
|
|
19
|
+
readonly headers?: Readonly<Record<string, string | readonly string[]>>;
|
|
20
|
+
readonly status: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const escapeHtml = (text: string) =>
|
|
24
|
+
text.replaceAll(/[&<>"']/gu, (character) => `&#${character.codePointAt(0) ?? 0};`);
|
|
25
|
+
|
|
26
|
+
/** A small HTML page; `html` and `footer` go in as is, so escape anything user-controlled in them. */
|
|
27
|
+
const page = (
|
|
28
|
+
code: number,
|
|
29
|
+
text: { readonly footer?: string; readonly html: string; readonly title: string },
|
|
30
|
+
setCookie: readonly string[] = [],
|
|
31
|
+
): Reply => ({
|
|
32
|
+
body: `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">${faviconLink}<title>${escapeHtml(text.title)}</title><h1>${escapeHtml(text.title)}</h1><p>${text.html}</p>${text.footer === undefined ? '' : `<p>${text.footer}</p>`}\n`,
|
|
33
|
+
headers: { 'content-type': 'text/html; charset=utf-8', 'set-cookie': setCookie },
|
|
34
|
+
status: code,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const notFound = page(status.notFound, { html: 'Nothing lives here.', title: 'Not found' });
|
|
38
|
+
|
|
39
|
+
const redirect = (location: string, setCookie: readonly string[] = []): Reply => ({
|
|
40
|
+
headers: { 'cache-control': 'no-store', location, 'set-cookie': setCookie },
|
|
41
|
+
status: status.found,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const header = (request: IncomingMessage, name: string) => {
|
|
45
|
+
const value = request.headers[name];
|
|
46
|
+
return Array.isArray(value) ? value[0] : value;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const sendReply = (response: ServerResponse, reply: Reply) => {
|
|
50
|
+
for (const [name, value] of Object.entries(reply.headers ?? {})) {
|
|
51
|
+
if (typeof value === 'string' || value.length > 0) {
|
|
52
|
+
response.setHeader(name, typeof value === 'string' ? value : [...value]);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
response.writeHead(reply.status);
|
|
56
|
+
response.end(reply.body);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export { escapeHtml, header, notFound, page, redirect, sendReply, status };
|
|
60
|
+
export type { Reply };
|
package/src/root-ca.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { X509Certificate, createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import { permittedDnsNames, rootLabel } from '@tafrahq/wt-tunnel-contract/root-ca';
|
|
4
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
5
|
+
|
|
6
|
+
/** The public half of the deployment's root, as the trust page shows and serves it. */
|
|
7
|
+
interface RootCa {
|
|
8
|
+
/** DER, base64, for the Apple profile. */
|
|
9
|
+
readonly derBase64: string;
|
|
10
|
+
/** Domains the deployment serves, for profile and page wording. */
|
|
11
|
+
readonly domains: readonly string[];
|
|
12
|
+
/**
|
|
13
|
+
* Download name without extension, after the label in the root's common name (the tunnel host for
|
|
14
|
+
* roots `wt-tunnel` makes), else after the first domain.
|
|
15
|
+
*/
|
|
16
|
+
readonly fileName: string;
|
|
17
|
+
/** SHA-256 over the DER, colon-separated uppercase hex. */
|
|
18
|
+
readonly fingerprint: string;
|
|
19
|
+
/** Re-encoded from the parsed certificate, so nothing else in `ca.cert` is ever served. */
|
|
20
|
+
readonly pem: string;
|
|
21
|
+
/** DNS names in the name constraints' permitted subtrees. */
|
|
22
|
+
readonly permitted: readonly string[];
|
|
23
|
+
readonly subject: string;
|
|
24
|
+
/** Days as YYYY-MM-DD, in UTC. */
|
|
25
|
+
readonly validFrom: string;
|
|
26
|
+
readonly validTo: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const utcDay = (date: string) => new Date(date).toISOString().split('T')[0] ?? '';
|
|
30
|
+
|
|
31
|
+
/** Throws when `ca.cert` holds no readable certificate; the config check calls it at startup. */
|
|
32
|
+
const readRootCa = (config: Pick<ServerConfig, 'ca' | 'domains'>): RootCa => {
|
|
33
|
+
const certificate = new X509Certificate(config.ca.cert);
|
|
34
|
+
return {
|
|
35
|
+
derBase64: certificate.raw.toString('base64'),
|
|
36
|
+
domains: config.domains,
|
|
37
|
+
fileName: `wt-tunnel-ca-${rootLabel(certificate) ?? config.domains[0]}`,
|
|
38
|
+
fingerprint: certificate.fingerprint256,
|
|
39
|
+
pem: certificate.toString(),
|
|
40
|
+
permitted: permittedDnsNames(certificate.raw),
|
|
41
|
+
subject: certificate.subject.split('\n').join(', '),
|
|
42
|
+
validFrom: utcDay(certificate.validFrom),
|
|
43
|
+
validTo: utcDay(certificate.validTo),
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** RFC 4122 URL namespace, the base for the profile's name-based UUIDs. */
|
|
48
|
+
const urlNamespace = Buffer.from('6ba7b8119dad11d180b400c04fd430c8', 'hex');
|
|
49
|
+
const uuidBytes = 16;
|
|
50
|
+
/** Byte 6 carries the version in its high nibble, byte 8 the variant in its two high bits. */
|
|
51
|
+
const version = { byte: 6, keep: 0x10, set: 0x50 } as const;
|
|
52
|
+
const variant = { byte: 8, keep: 0x40, set: 0x80 } as const;
|
|
53
|
+
|
|
54
|
+
/** A version 5 UUID: the same name always gives the same UUID. */
|
|
55
|
+
const uuidV5 = (name: string) => {
|
|
56
|
+
const hash = createHash('sha1').update(urlNamespace).update(name).digest();
|
|
57
|
+
for (const field of [version, variant]) {
|
|
58
|
+
hash.writeUInt8((hash.readUInt8(field.byte) % field.keep) + field.set, field.byte);
|
|
59
|
+
}
|
|
60
|
+
return hash
|
|
61
|
+
.subarray(0, uuidBytes)
|
|
62
|
+
.toString('hex')
|
|
63
|
+
.toUpperCase()
|
|
64
|
+
.replace(/^(?<a>.{8})(?<b>.{4})(?<c>.{4})(?<d>.{4})(?<e>.{12})$/u, '$<a>-$<b>-$<c>-$<d>-$<e>');
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const escapeXml = (text: string) =>
|
|
68
|
+
text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
|
|
69
|
+
|
|
70
|
+
const plistString = (key: string, value: string) =>
|
|
71
|
+
`<key>${key}</key><string>${escapeXml(value)}</string>`;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* An unsigned Apple configuration profile with one root certificate payload. Its UUIDs come from
|
|
75
|
+
* the fingerprint, so downloading it again gives the same profile, and iOS replaces rather than
|
|
76
|
+
* duplicates it.
|
|
77
|
+
*/
|
|
78
|
+
const mobileconfig = (root: RootCa) => {
|
|
79
|
+
const fingerprintHex = root.fingerprint.replaceAll(':', '').toLowerCase();
|
|
80
|
+
const domains = root.domains.join(', ');
|
|
81
|
+
const identifier = `wt-tunnel.ca.${fingerprintHex.slice(0, uuidBytes)}`;
|
|
82
|
+
const description = `Lets this device open wt-tunnel dev URLs under ${domains}. The root can vouch only for names under those domains.`;
|
|
83
|
+
const name = `wt-tunnel root for ${domains}`;
|
|
84
|
+
return [
|
|
85
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
86
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
87
|
+
'<plist version="1.0">',
|
|
88
|
+
'<dict>',
|
|
89
|
+
'<key>PayloadContent</key>',
|
|
90
|
+
'<array>',
|
|
91
|
+
'<dict>',
|
|
92
|
+
plistString('PayloadCertificateFileName', `${root.fileName}.crt`),
|
|
93
|
+
`<key>PayloadContent</key><data>${root.derBase64}</data>`,
|
|
94
|
+
plistString('PayloadDescription', description),
|
|
95
|
+
plistString('PayloadDisplayName', name),
|
|
96
|
+
plistString('PayloadIdentifier', `${identifier}.root`),
|
|
97
|
+
plistString('PayloadType', 'com.apple.security.root'),
|
|
98
|
+
plistString('PayloadUUID', uuidV5(`wt-tunnel:ca:${fingerprintHex}:root`)),
|
|
99
|
+
'<key>PayloadVersion</key><integer>1</integer>',
|
|
100
|
+
'</dict>',
|
|
101
|
+
'</array>',
|
|
102
|
+
plistString('PayloadDescription', description),
|
|
103
|
+
plistString('PayloadDisplayName', name),
|
|
104
|
+
plistString('PayloadIdentifier', identifier),
|
|
105
|
+
'<key>PayloadRemovalDisallowed</key><false/>',
|
|
106
|
+
plistString('PayloadType', 'Configuration'),
|
|
107
|
+
plistString('PayloadUUID', uuidV5(`wt-tunnel:ca:${fingerprintHex}:profile`)),
|
|
108
|
+
'<key>PayloadVersion</key><integer>1</integer>',
|
|
109
|
+
'</dict>',
|
|
110
|
+
'</plist>',
|
|
111
|
+
'',
|
|
112
|
+
].join('\n');
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export { mobileconfig, readRootCa };
|
|
116
|
+
export type { RootCa };
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';
|
|
6
|
+
import { Effect, Redacted } from 'effect';
|
|
7
|
+
|
|
8
|
+
import type { Binaries } from './binaries.ts';
|
|
9
|
+
import { renderCaddyfile, renderFrpsToml } from './render.ts';
|
|
10
|
+
import type { Ports } from './render.ts';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Writes the Caddyfile, frps.toml and the CA into a fresh private directory, deleted with the scope
|
|
14
|
+
* so no copy of the CA key outlives the server.
|
|
15
|
+
*/
|
|
16
|
+
const writeRuntimeFiles = (config: ServerConfig, ports: Ports) =>
|
|
17
|
+
Effect.acquireRelease(
|
|
18
|
+
Effect.promise(async () => {
|
|
19
|
+
const dir = await mkdtemp(join(tmpdir(), 'wt-tunnel-server-'));
|
|
20
|
+
const paths = {
|
|
21
|
+
caCert: join(dir, 'ca.crt'),
|
|
22
|
+
caKey: join(dir, 'ca.key'),
|
|
23
|
+
storage: join(dir, 'caddy'),
|
|
24
|
+
};
|
|
25
|
+
await mkdir(paths.storage, { mode: 0o700 });
|
|
26
|
+
await writeFile(paths.caCert, config.ca.cert);
|
|
27
|
+
await writeFile(paths.caKey, Redacted.value(config.ca.key), { mode: 0o600 });
|
|
28
|
+
await writeFile(join(dir, 'Caddyfile'), renderCaddyfile(config, paths, ports));
|
|
29
|
+
await writeFile(join(dir, 'frps.toml'), renderFrpsToml(config, ports), { mode: 0o600 });
|
|
30
|
+
return dir;
|
|
31
|
+
}),
|
|
32
|
+
(dir) => Effect.promise(() => rm(dir, { force: true, recursive: true })),
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
const childSpecs = (dir: string, binaries: Binaries) => {
|
|
36
|
+
// Caddy keeps its local CA and autosave under XDG dirs; keep them in the runtime dir.
|
|
37
|
+
const env = { XDG_CONFIG_HOME: dir, XDG_DATA_HOME: dir };
|
|
38
|
+
return [
|
|
39
|
+
{
|
|
40
|
+
args: ['run', '--adapter', 'caddyfile', '--config', join(dir, 'Caddyfile')],
|
|
41
|
+
command: binaries.caddy,
|
|
42
|
+
env,
|
|
43
|
+
name: 'caddy',
|
|
44
|
+
},
|
|
45
|
+
{ args: ['-c', join(dir, 'frps.toml')], command: binaries.frps, env, name: 'frps' },
|
|
46
|
+
];
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export { childSpecs, writeRuntimeFiles };
|
package/src/service.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
|
|
3
|
+
|
|
4
|
+
import type { Hostname } from '@tafrahq/wt-tunnel-contract';
|
|
5
|
+
|
|
6
|
+
import { caRoute } from './ca-page.ts';
|
|
7
|
+
import type { Query, ServiceContext } from './context.ts';
|
|
8
|
+
import { devHostRoute } from './dev-host.ts';
|
|
9
|
+
import { domainOf, hostWithoutPort } from './hosts.ts';
|
|
10
|
+
import { internalRoute } from './internal.ts';
|
|
11
|
+
import { authPort, loopback } from './render.ts';
|
|
12
|
+
import { header, notFound, sendReply, status } from './reply.ts';
|
|
13
|
+
import type { Reply } from './reply.ts';
|
|
14
|
+
import { signInRoute } from './sign-in.ts';
|
|
15
|
+
|
|
16
|
+
const betterAuthPrefix = '/api/auth/';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Who a request is for, from its Host: the sign-in host, a dev host (with the domain that covers
|
|
20
|
+
* it), or Caddy and frps calling on the loopback address.
|
|
21
|
+
*/
|
|
22
|
+
type Site =
|
|
23
|
+
| { readonly _tag: 'auth' }
|
|
24
|
+
| { readonly _tag: 'dev'; readonly domain: Hostname }
|
|
25
|
+
| { readonly _tag: 'internal' };
|
|
26
|
+
|
|
27
|
+
const siteOf = (request: IncomingMessage, context: ServiceContext): Site | undefined => {
|
|
28
|
+
const host = header(request, 'host') ?? '';
|
|
29
|
+
if (host === `${loopback}:${authPort}`) {
|
|
30
|
+
return { _tag: 'internal' };
|
|
31
|
+
}
|
|
32
|
+
if (hostWithoutPort(host) === context.config.authHost) {
|
|
33
|
+
return { _tag: 'auth' };
|
|
34
|
+
}
|
|
35
|
+
const domain = domainOf(host, context.config.domains);
|
|
36
|
+
return domain === undefined ? undefined : { _tag: 'dev', domain };
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** The sign-in host: the public certificate routes, then sign-in. */
|
|
40
|
+
const authRoute = (
|
|
41
|
+
request: IncomingMessage,
|
|
42
|
+
path: string,
|
|
43
|
+
auth: { readonly context: ServiceContext; readonly query: Query },
|
|
44
|
+
): Promise<Reply> => {
|
|
45
|
+
const ca = caRoute(request, path, auth.context.rootCa);
|
|
46
|
+
return ca === undefined ? signInRoute(request, path, auth) : Promise.resolve(ca);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const route = (request: IncomingMessage, context: ServiceContext): Promise<Reply> => {
|
|
50
|
+
const site = siteOf(request, context);
|
|
51
|
+
const url = new URL(request.url ?? '/', 'http://localhost');
|
|
52
|
+
const query = Object.fromEntries(url.searchParams);
|
|
53
|
+
if (site === undefined) {
|
|
54
|
+
return Promise.resolve(notFound);
|
|
55
|
+
}
|
|
56
|
+
if (site._tag === 'internal') {
|
|
57
|
+
return internalRoute(request, url.pathname, { config: context.config, query });
|
|
58
|
+
}
|
|
59
|
+
if (site._tag === 'auth') {
|
|
60
|
+
return authRoute(request, url.pathname, { context, query });
|
|
61
|
+
}
|
|
62
|
+
return Promise.resolve(
|
|
63
|
+
devHostRoute(request, url.pathname, { context, domain: site.domain, query }),
|
|
64
|
+
);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const respond = async (
|
|
68
|
+
request: IncomingMessage,
|
|
69
|
+
response: ServerResponse,
|
|
70
|
+
context: ServiceContext,
|
|
71
|
+
) => {
|
|
72
|
+
try {
|
|
73
|
+
sendReply(response, await route(request, context));
|
|
74
|
+
} catch (error) {
|
|
75
|
+
console.error(`auth: ${request.method} ${request.url}: ${String(error)}`);
|
|
76
|
+
sendReply(response, { status: status.serverError });
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** The auth service: the sign-in host, dev-host `/_wt/*`, and the checks Caddy and frps call. */
|
|
81
|
+
const createAuthService = (context: ServiceContext): Server =>
|
|
82
|
+
createServer((request, response) => {
|
|
83
|
+
const toBetterAuth =
|
|
84
|
+
siteOf(request, context)?._tag === 'auth' && (request.url ?? '').startsWith(betterAuthPrefix);
|
|
85
|
+
void (toBetterAuth
|
|
86
|
+
? context.signIn.handler(request, response)
|
|
87
|
+
: respond(request, response, context));
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
export { createAuthService };
|