@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/dist/render.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { tunnelPort } from "./packages/contract/src/index.js";
|
|
2
|
+
import { appCookieHeader } from "./dev-host.js";
|
|
3
|
+
import { askPath, newProxyPath } from "./internal.js";
|
|
4
|
+
import { Redacted } from "effect";
|
|
5
|
+
// src/render.ts
|
|
6
|
+
const authPort = 4e3;
|
|
7
|
+
const loopback = "127.0.0.1";
|
|
8
|
+
const vhostPort = 8080;
|
|
9
|
+
const defaultHttpsPort = 443;
|
|
10
|
+
const defaultPorts = {
|
|
11
|
+
http: 80,
|
|
12
|
+
https: defaultHttpsPort,
|
|
13
|
+
tunnel: tunnelPort
|
|
14
|
+
};
|
|
15
|
+
/** Caddy's global options: no admin API, the ports, the on-demand check and the root as a CA. */
|
|
16
|
+
const caddyGlobals = (paths, ports) => `{
|
|
17
|
+
admin off
|
|
18
|
+
http_port ${ports.http}
|
|
19
|
+
https_port ${ports.https}
|
|
20
|
+
persist_config off
|
|
21
|
+
skip_install_trust
|
|
22
|
+
storage file_system ${paths.storage}
|
|
23
|
+
on_demand_tls {
|
|
24
|
+
ask http://${loopback}:${authPort}${askPath}
|
|
25
|
+
}
|
|
26
|
+
pki {
|
|
27
|
+
ca wt {
|
|
28
|
+
name "wt-tunnel"
|
|
29
|
+
root {
|
|
30
|
+
cert ${paths.caCert}
|
|
31
|
+
key ${paths.caKey}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}`;
|
|
36
|
+
/**
|
|
37
|
+
* Dev hosts get certificates on demand from an intermediate Caddy signs with the deployment's root.
|
|
38
|
+
* The sign-in host sits outside the root's name constraints, and a device opens it before it trusts
|
|
39
|
+
* the root, so it gets a public certificate from Let's Encrypt over ACME. Caddy keeps no state
|
|
40
|
+
* across restarts, so it requests a new one at each start; if ACME fails, as on a machine the
|
|
41
|
+
* internet cannot reach, it falls back to its own internal CA.
|
|
42
|
+
*/
|
|
43
|
+
const renderCaddyfile = (config, paths, ports) => `${caddyGlobals(paths, ports)}
|
|
44
|
+
|
|
45
|
+
https://${config.authHost} {
|
|
46
|
+
tls {
|
|
47
|
+
issuer acme
|
|
48
|
+
issuer internal
|
|
49
|
+
}
|
|
50
|
+
reverse_proxy ${loopback}:${authPort}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
https:// {
|
|
54
|
+
tls {
|
|
55
|
+
on_demand
|
|
56
|
+
issuer internal {
|
|
57
|
+
ca wt
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
handle /_wt/* {
|
|
61
|
+
reverse_proxy ${loopback}:${authPort}
|
|
62
|
+
}
|
|
63
|
+
handle {
|
|
64
|
+
forward_auth ${loopback}:${authPort} {
|
|
65
|
+
uri /_wt/verify
|
|
66
|
+
copy_headers ${appCookieHeader}>Cookie
|
|
67
|
+
}
|
|
68
|
+
reverse_proxy ${loopback}:${vhostPort}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
http:// {
|
|
73
|
+
redir https://{host}${ports.https === defaultHttpsPort ? "" : `:${ports.https}`}{uri} permanent
|
|
74
|
+
}
|
|
75
|
+
`;
|
|
76
|
+
/** JSON string escapes are valid TOML basic-string escapes. */
|
|
77
|
+
const tomlString = (value) => JSON.stringify(value);
|
|
78
|
+
/**
|
|
79
|
+
* `proxyBindAddr` is the address frps binds its vhost listener on, so the vhost port is reachable
|
|
80
|
+
* only through Caddy. The plugin lets the auth service refuse every proxy that is not an http proxy
|
|
81
|
+
* for a dev host.
|
|
82
|
+
*/
|
|
83
|
+
const renderFrpsToml = (config, ports) => `bindAddr = "::"
|
|
84
|
+
bindPort = ${ports.tunnel}
|
|
85
|
+
proxyBindAddr = ${tomlString(loopback)}
|
|
86
|
+
vhostHTTPPort = ${vhostPort}
|
|
87
|
+
auth.method = "token"
|
|
88
|
+
auth.token = ${tomlString(Redacted.value(config.tunnelToken))}
|
|
89
|
+
transport.tls.force = true
|
|
90
|
+
log.to = "console"
|
|
91
|
+
log.disablePrintColor = true
|
|
92
|
+
|
|
93
|
+
[[httpPlugins]]
|
|
94
|
+
name = "wt-tunnel"
|
|
95
|
+
addr = ${tomlString(`${loopback}:${authPort}`)}
|
|
96
|
+
path = ${tomlString(newProxyPath)}
|
|
97
|
+
ops = ["NewProxy"]
|
|
98
|
+
`;
|
|
99
|
+
export { authPort, defaultPorts, loopback, renderCaddyfile, renderFrpsToml };
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=render.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render.js","names":[],"sources":["../src/render.ts"],"sourcesContent":["import { tunnelPort } from '@tafrahq/wt-tunnel-contract';\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Redacted } from 'effect';\n\nimport { appCookieHeader } from './dev-host.ts';\nimport { askPath, newProxyPath } from './internal.ts';\n\nconst authPort = 4000;\nconst loopback = '127.0.0.1';\nconst vhostPort = 8080;\nconst defaultHttpsPort = 443;\n\n/** The ports the server listens on for the outside world. */\ninterface Ports {\n readonly http: number;\n readonly https: number;\n readonly tunnel: number;\n}\n\nconst defaultPorts: Ports = { http: 80, https: defaultHttpsPort, tunnel: tunnelPort };\n\ninterface CaddyPaths {\n readonly caCert: string;\n readonly caKey: string;\n readonly storage: string;\n}\n\n/** Caddy's global options: no admin API, the ports, the on-demand check and the root as a CA. */\nconst caddyGlobals = (paths: CaddyPaths, ports: Ports) => `{\n\tadmin off\n\thttp_port ${ports.http}\n\thttps_port ${ports.https}\n\tpersist_config off\n\tskip_install_trust\n\tstorage file_system ${paths.storage}\n\ton_demand_tls {\n\t\task http://${loopback}:${authPort}${askPath}\n\t}\n\tpki {\n\t\tca wt {\n\t\t\tname \"wt-tunnel\"\n\t\t\troot {\n\t\t\t\tcert ${paths.caCert}\n\t\t\t\tkey ${paths.caKey}\n\t\t\t}\n\t\t}\n\t}\n}`;\n\n/**\n * Dev hosts get certificates on demand from an intermediate Caddy signs with the deployment's root.\n * The sign-in host sits outside the root's name constraints, and a device opens it before it trusts\n * the root, so it gets a public certificate from Let's Encrypt over ACME. Caddy keeps no state\n * across restarts, so it requests a new one at each start; if ACME fails, as on a machine the\n * internet cannot reach, it falls back to its own internal CA.\n */\nconst renderCaddyfile = (\n config: ServerConfig,\n paths: CaddyPaths,\n ports: Ports,\n) => `${caddyGlobals(paths, ports)}\n\nhttps://${config.authHost} {\n\ttls {\n\t\tissuer acme\n\t\tissuer internal\n\t}\n\treverse_proxy ${loopback}:${authPort}\n}\n\nhttps:// {\n\ttls {\n\t\ton_demand\n\t\tissuer internal {\n\t\t\tca wt\n\t\t}\n\t}\n\thandle /_wt/* {\n\t\treverse_proxy ${loopback}:${authPort}\n\t}\n\thandle {\n\t\tforward_auth ${loopback}:${authPort} {\n\t\t\turi /_wt/verify\n\t\t\tcopy_headers ${appCookieHeader}>Cookie\n\t\t}\n\t\treverse_proxy ${loopback}:${vhostPort}\n\t}\n}\n\nhttp:// {\n\tredir https://{host}${ports.https === defaultHttpsPort ? '' : `:${ports.https}`}{uri} permanent\n}\n`;\n\n/** JSON string escapes are valid TOML basic-string escapes. */\nconst tomlString = (value: string) => JSON.stringify(value);\n\n/**\n * `proxyBindAddr` is the address frps binds its vhost listener on, so the vhost port is reachable\n * only through Caddy. The plugin lets the auth service refuse every proxy that is not an http proxy\n * for a dev host.\n */\nconst renderFrpsToml = (config: ServerConfig, ports: Ports) => `bindAddr = \"::\"\nbindPort = ${ports.tunnel}\nproxyBindAddr = ${tomlString(loopback)}\nvhostHTTPPort = ${vhostPort}\nauth.method = \"token\"\nauth.token = ${tomlString(Redacted.value(config.tunnelToken))}\ntransport.tls.force = true\nlog.to = \"console\"\nlog.disablePrintColor = true\n\n[[httpPlugins]]\nname = \"wt-tunnel\"\naddr = ${tomlString(`${loopback}:${authPort}`)}\npath = ${tomlString(newProxyPath)}\nops = [\"NewProxy\"]\n`;\n\nexport { authPort, defaultPorts, loopback, renderCaddyfile, renderFrpsToml };\nexport type { Ports };\n"],"mappings":";;;;;AAOA,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,YAAY;AAClB,MAAM,mBAAmB;AASzB,MAAM,eAAsB;CAAE,MAAM;CAAI,OAAO;CAAkB,QAAQ;AAAW;;AASpF,MAAM,gBAAgB,OAAmB,UAAiB;;aAE7C,MAAM,KAAK;cACV,MAAM,MAAM;;;uBAGH,MAAM,QAAQ;;eAEtB,SAAS,GAAG,WAAW,QAAQ;;;;;;WAMnC,MAAM,OAAO;UACd,MAAM,MAAM;;;;;;;;;;;;AAatB,MAAM,mBACJ,QACA,OACA,UACG,GAAG,aAAa,OAAO,KAAK,EAAE;;UAEzB,OAAO,SAAS;;;;;iBAKT,SAAS,GAAG,SAAS;;;;;;;;;;;kBAWpB,SAAS,GAAG,SAAS;;;iBAGtB,SAAS,GAAG,SAAS;;kBAEpB,gBAAgB;;kBAEhB,SAAS,GAAG,UAAU;;;;;uBAKjB,MAAM,UAAU,mBAAmB,KAAK,IAAI,MAAM,QAAQ;;;;AAKjF,MAAM,cAAc,UAAkB,KAAK,UAAU,KAAK;;;;;;AAO1D,MAAM,kBAAkB,QAAsB,UAAiB;aAClD,MAAM,OAAO;kBACR,WAAW,QAAQ,EAAE;kBACrB,UAAU;;eAEb,WAAW,SAAS,MAAM,OAAO,WAAW,CAAC,EAAE;;;;;;;SAOrD,WAAW,GAAG,SAAS,GAAG,UAAU,EAAE;SACtC,WAAW,YAAY,EAAE"}
|
package/dist/reply.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { faviconLink } from "./brand.js";
|
|
2
|
+
// src/reply.ts
|
|
3
|
+
const status = {
|
|
4
|
+
badGateway: 502,
|
|
5
|
+
badRequest: 400,
|
|
6
|
+
forbidden: 403,
|
|
7
|
+
found: 302,
|
|
8
|
+
notFound: 404,
|
|
9
|
+
ok: 200,
|
|
10
|
+
serverError: 500,
|
|
11
|
+
unauthorized: 401
|
|
12
|
+
};
|
|
13
|
+
const escapeHtml = (text) => text.replaceAll(/[&<>"']/gu, (character) => `&#${character.codePointAt(0) ?? 0};`);
|
|
14
|
+
/** A small HTML page; `html` and `footer` go in as is, so escape anything user-controlled in them. */
|
|
15
|
+
const page = (code, text, setCookie = []) => ({
|
|
16
|
+
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 === void 0 ? "" : `<p>${text.footer}</p>`}\n`,
|
|
17
|
+
headers: {
|
|
18
|
+
"content-type": "text/html; charset=utf-8",
|
|
19
|
+
"set-cookie": setCookie
|
|
20
|
+
},
|
|
21
|
+
status: code
|
|
22
|
+
});
|
|
23
|
+
const notFound = page(status.notFound, {
|
|
24
|
+
html: "Nothing lives here.",
|
|
25
|
+
title: "Not found"
|
|
26
|
+
});
|
|
27
|
+
const redirect = (location, setCookie = []) => ({
|
|
28
|
+
headers: {
|
|
29
|
+
"cache-control": "no-store",
|
|
30
|
+
location,
|
|
31
|
+
"set-cookie": setCookie
|
|
32
|
+
},
|
|
33
|
+
status: status.found
|
|
34
|
+
});
|
|
35
|
+
const header = (request, name) => {
|
|
36
|
+
const value = request.headers[name];
|
|
37
|
+
return Array.isArray(value) ? value[0] : value;
|
|
38
|
+
};
|
|
39
|
+
const sendReply = (response, reply) => {
|
|
40
|
+
for (const [name, value] of Object.entries(reply.headers ?? {})) if (typeof value === "string" || value.length > 0) response.setHeader(name, typeof value === "string" ? value : [...value]);
|
|
41
|
+
response.writeHead(reply.status);
|
|
42
|
+
response.end(reply.body);
|
|
43
|
+
};
|
|
44
|
+
export { escapeHtml, header, notFound, page, redirect, sendReply, status };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=reply.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reply.js","names":[],"sources":["../src/reply.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport { faviconLink } from './brand.ts';\n\nconst status = {\n badGateway: 502,\n badRequest: 400,\n forbidden: 403,\n found: 302,\n notFound: 404,\n ok: 200,\n serverError: 500,\n unauthorized: 401,\n} as const;\n\n/** What a route answers; one writer turns it into the HTTP response. */\ninterface Reply {\n readonly body?: string;\n readonly headers?: Readonly<Record<string, string | readonly string[]>>;\n readonly status: number;\n}\n\nconst escapeHtml = (text: string) =>\n text.replaceAll(/[&<>\"']/gu, (character) => `&#${character.codePointAt(0) ?? 0};`);\n\n/** A small HTML page; `html` and `footer` go in as is, so escape anything user-controlled in them. */\nconst page = (\n code: number,\n text: { readonly footer?: string; readonly html: string; readonly title: string },\n setCookie: readonly string[] = [],\n): Reply => ({\n 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`,\n headers: { 'content-type': 'text/html; charset=utf-8', 'set-cookie': setCookie },\n status: code,\n});\n\nconst notFound = page(status.notFound, { html: 'Nothing lives here.', title: 'Not found' });\n\nconst redirect = (location: string, setCookie: readonly string[] = []): Reply => ({\n headers: { 'cache-control': 'no-store', location, 'set-cookie': setCookie },\n status: status.found,\n});\n\nconst header = (request: IncomingMessage, name: string) => {\n const value = request.headers[name];\n return Array.isArray(value) ? value[0] : value;\n};\n\nconst sendReply = (response: ServerResponse, reply: Reply) => {\n for (const [name, value] of Object.entries(reply.headers ?? {})) {\n if (typeof value === 'string' || value.length > 0) {\n response.setHeader(name, typeof value === 'string' ? value : [...value]);\n }\n }\n response.writeHead(reply.status);\n response.end(reply.body);\n};\n\nexport { escapeHtml, header, notFound, page, redirect, sendReply, status };\nexport type { Reply };\n"],"mappings":";;AAIA,MAAM,SAAS;CACb,YAAY;CACZ,YAAY;CACZ,WAAW;CACX,OAAO;CACP,UAAU;CACV,IAAI;CACJ,aAAa;CACb,cAAc;AAChB;AASA,MAAM,cAAc,SAClB,KAAK,WAAW,cAAc,cAAc,KAAK,UAAU,YAAY,CAAC,KAAK,EAAE,EAAE;;AAGnF,MAAM,QACJ,MACA,MACA,YAA+B,CAAC,OACrB;CACX,MAAM,2FAA2F,YAAY,SAAS,WAAW,KAAK,KAAK,EAAE,cAAc,WAAW,KAAK,KAAK,EAAE,UAAU,KAAK,KAAK,MAAM,KAAK,WAAW,KAAA,IAAY,KAAK,MAAM,KAAK,OAAO,MAAM;CACrQ,SAAS;EAAE,gBAAgB;EAA4B,cAAc;CAAU;CAC/E,QAAQ;AACV;AAEA,MAAM,WAAW,KAAK,OAAO,UAAU;CAAE,MAAM;CAAuB,OAAO;AAAY,CAAC;AAE1F,MAAM,YAAY,UAAkB,YAA+B,CAAC,OAAc;CAChF,SAAS;EAAE,iBAAiB;EAAY;EAAU,cAAc;CAAU;CAC1E,QAAQ,OAAO;AACjB;AAEA,MAAM,UAAU,SAA0B,SAAiB;CACzD,MAAM,QAAQ,QAAQ,QAAQ;CAC9B,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK;AAC3C;AAEA,MAAM,aAAa,UAA0B,UAAiB;CAC5D,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,MAAM,WAAW,CAAC,CAAC,GAC5D,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC9C,SAAS,UAAU,MAAM,OAAO,UAAU,WAAW,QAAQ,CAAC,GAAG,KAAK,CAAC;CAG3E,SAAS,UAAU,MAAM,MAAM;CAC/B,SAAS,IAAI,MAAM,IAAI;AACzB"}
|
package/dist/root-ca.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { permittedDnsNames, rootLabel } from "./packages/contract/src/root-ca.js";
|
|
2
|
+
import { X509Certificate, createHash } from "node:crypto";
|
|
3
|
+
// src/root-ca.ts
|
|
4
|
+
const utcDay = (date) => new Date(date).toISOString().split("T")[0] ?? "";
|
|
5
|
+
/** Throws when `ca.cert` holds no readable certificate; the config check calls it at startup. */
|
|
6
|
+
const readRootCa = (config) => {
|
|
7
|
+
const certificate = new X509Certificate(config.ca.cert);
|
|
8
|
+
return {
|
|
9
|
+
derBase64: certificate.raw.toString("base64"),
|
|
10
|
+
domains: config.domains,
|
|
11
|
+
fileName: `wt-tunnel-ca-${rootLabel(certificate) ?? config.domains[0]}`,
|
|
12
|
+
fingerprint: certificate.fingerprint256,
|
|
13
|
+
pem: certificate.toString(),
|
|
14
|
+
permitted: permittedDnsNames(certificate.raw),
|
|
15
|
+
subject: certificate.subject.split("\n").join(", "),
|
|
16
|
+
validFrom: utcDay(certificate.validFrom),
|
|
17
|
+
validTo: utcDay(certificate.validTo)
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
/** RFC 4122 URL namespace, the base for the profile's name-based UUIDs. */
|
|
21
|
+
const urlNamespace = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex");
|
|
22
|
+
const uuidBytes = 16;
|
|
23
|
+
/** Byte 6 carries the version in its high nibble, byte 8 the variant in its two high bits. */
|
|
24
|
+
const version = {
|
|
25
|
+
byte: 6,
|
|
26
|
+
keep: 16,
|
|
27
|
+
set: 80
|
|
28
|
+
};
|
|
29
|
+
const variant = {
|
|
30
|
+
byte: 8,
|
|
31
|
+
keep: 64,
|
|
32
|
+
set: 128
|
|
33
|
+
};
|
|
34
|
+
/** A version 5 UUID: the same name always gives the same UUID. */
|
|
35
|
+
const uuidV5 = (name) => {
|
|
36
|
+
const hash = createHash("sha1").update(urlNamespace).update(name).digest();
|
|
37
|
+
for (const field of [version, variant]) hash.writeUInt8(hash.readUInt8(field.byte) % field.keep + field.set, field.byte);
|
|
38
|
+
return hash.subarray(0, uuidBytes).toString("hex").toUpperCase().replace(/^(?<a>.{8})(?<b>.{4})(?<c>.{4})(?<d>.{4})(?<e>.{12})$/u, "$<a>-$<b>-$<c>-$<d>-$<e>");
|
|
39
|
+
};
|
|
40
|
+
const escapeXml = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
41
|
+
const plistString = (key, value) => `<key>${key}</key><string>${escapeXml(value)}</string>`;
|
|
42
|
+
/**
|
|
43
|
+
* An unsigned Apple configuration profile with one root certificate payload. Its UUIDs come from
|
|
44
|
+
* the fingerprint, so downloading it again gives the same profile, and iOS replaces rather than
|
|
45
|
+
* duplicates it.
|
|
46
|
+
*/
|
|
47
|
+
const mobileconfig = (root) => {
|
|
48
|
+
const fingerprintHex = root.fingerprint.replaceAll(":", "").toLowerCase();
|
|
49
|
+
const domains = root.domains.join(", ");
|
|
50
|
+
const identifier = `wt-tunnel.ca.${fingerprintHex.slice(0, uuidBytes)}`;
|
|
51
|
+
const description = `Lets this device open wt-tunnel dev URLs under ${domains}. The root can vouch only for names under those domains.`;
|
|
52
|
+
const name = `wt-tunnel root for ${domains}`;
|
|
53
|
+
return [
|
|
54
|
+
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
|
|
55
|
+
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
|
|
56
|
+
"<plist version=\"1.0\">",
|
|
57
|
+
"<dict>",
|
|
58
|
+
"<key>PayloadContent</key>",
|
|
59
|
+
"<array>",
|
|
60
|
+
"<dict>",
|
|
61
|
+
plistString("PayloadCertificateFileName", `${root.fileName}.crt`),
|
|
62
|
+
`<key>PayloadContent</key><data>${root.derBase64}</data>`,
|
|
63
|
+
plistString("PayloadDescription", description),
|
|
64
|
+
plistString("PayloadDisplayName", name),
|
|
65
|
+
plistString("PayloadIdentifier", `${identifier}.root`),
|
|
66
|
+
plistString("PayloadType", "com.apple.security.root"),
|
|
67
|
+
plistString("PayloadUUID", uuidV5(`wt-tunnel:ca:${fingerprintHex}:root`)),
|
|
68
|
+
"<key>PayloadVersion</key><integer>1</integer>",
|
|
69
|
+
"</dict>",
|
|
70
|
+
"</array>",
|
|
71
|
+
plistString("PayloadDescription", description),
|
|
72
|
+
plistString("PayloadDisplayName", name),
|
|
73
|
+
plistString("PayloadIdentifier", identifier),
|
|
74
|
+
"<key>PayloadRemovalDisallowed</key><false/>",
|
|
75
|
+
plistString("PayloadType", "Configuration"),
|
|
76
|
+
plistString("PayloadUUID", uuidV5(`wt-tunnel:ca:${fingerprintHex}:profile`)),
|
|
77
|
+
"<key>PayloadVersion</key><integer>1</integer>",
|
|
78
|
+
"</dict>",
|
|
79
|
+
"</plist>",
|
|
80
|
+
""
|
|
81
|
+
].join("\n");
|
|
82
|
+
};
|
|
83
|
+
export { mobileconfig, readRootCa };
|
|
84
|
+
|
|
85
|
+
//# sourceMappingURL=root-ca.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root-ca.js","names":[],"sources":["../src/root-ca.ts"],"sourcesContent":["import { X509Certificate, createHash } from 'node:crypto';\n\nimport { permittedDnsNames, rootLabel } from '@tafrahq/wt-tunnel-contract/root-ca';\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\n\n/** The public half of the deployment's root, as the trust page shows and serves it. */\ninterface RootCa {\n /** DER, base64, for the Apple profile. */\n readonly derBase64: string;\n /** Domains the deployment serves, for profile and page wording. */\n readonly domains: readonly string[];\n /**\n * Download name without extension, after the label in the root's common name (the tunnel host for\n * roots `wt-tunnel` makes), else after the first domain.\n */\n readonly fileName: string;\n /** SHA-256 over the DER, colon-separated uppercase hex. */\n readonly fingerprint: string;\n /** Re-encoded from the parsed certificate, so nothing else in `ca.cert` is ever served. */\n readonly pem: string;\n /** DNS names in the name constraints' permitted subtrees. */\n readonly permitted: readonly string[];\n readonly subject: string;\n /** Days as YYYY-MM-DD, in UTC. */\n readonly validFrom: string;\n readonly validTo: string;\n}\n\nconst utcDay = (date: string) => new Date(date).toISOString().split('T')[0] ?? '';\n\n/** Throws when `ca.cert` holds no readable certificate; the config check calls it at startup. */\nconst readRootCa = (config: Pick<ServerConfig, 'ca' | 'domains'>): RootCa => {\n const certificate = new X509Certificate(config.ca.cert);\n return {\n derBase64: certificate.raw.toString('base64'),\n domains: config.domains,\n fileName: `wt-tunnel-ca-${rootLabel(certificate) ?? config.domains[0]}`,\n fingerprint: certificate.fingerprint256,\n pem: certificate.toString(),\n permitted: permittedDnsNames(certificate.raw),\n subject: certificate.subject.split('\\n').join(', '),\n validFrom: utcDay(certificate.validFrom),\n validTo: utcDay(certificate.validTo),\n };\n};\n\n/** RFC 4122 URL namespace, the base for the profile's name-based UUIDs. */\nconst urlNamespace = Buffer.from('6ba7b8119dad11d180b400c04fd430c8', 'hex');\nconst uuidBytes = 16;\n/** Byte 6 carries the version in its high nibble, byte 8 the variant in its two high bits. */\nconst version = { byte: 6, keep: 0x10, set: 0x50 } as const;\nconst variant = { byte: 8, keep: 0x40, set: 0x80 } as const;\n\n/** A version 5 UUID: the same name always gives the same UUID. */\nconst uuidV5 = (name: string) => {\n const hash = createHash('sha1').update(urlNamespace).update(name).digest();\n for (const field of [version, variant]) {\n hash.writeUInt8((hash.readUInt8(field.byte) % field.keep) + field.set, field.byte);\n }\n return hash\n .subarray(0, uuidBytes)\n .toString('hex')\n .toUpperCase()\n .replace(/^(?<a>.{8})(?<b>.{4})(?<c>.{4})(?<d>.{4})(?<e>.{12})$/u, '$<a>-$<b>-$<c>-$<d>-$<e>');\n};\n\nconst escapeXml = (text: string) =>\n text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n\nconst plistString = (key: string, value: string) =>\n `<key>${key}</key><string>${escapeXml(value)}</string>`;\n\n/**\n * An unsigned Apple configuration profile with one root certificate payload. Its UUIDs come from\n * the fingerprint, so downloading it again gives the same profile, and iOS replaces rather than\n * duplicates it.\n */\nconst mobileconfig = (root: RootCa) => {\n const fingerprintHex = root.fingerprint.replaceAll(':', '').toLowerCase();\n const domains = root.domains.join(', ');\n const identifier = `wt-tunnel.ca.${fingerprintHex.slice(0, uuidBytes)}`;\n const description = `Lets this device open wt-tunnel dev URLs under ${domains}. The root can vouch only for names under those domains.`;\n const name = `wt-tunnel root for ${domains}`;\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n '<dict>',\n '<key>PayloadContent</key>',\n '<array>',\n '<dict>',\n plistString('PayloadCertificateFileName', `${root.fileName}.crt`),\n `<key>PayloadContent</key><data>${root.derBase64}</data>`,\n plistString('PayloadDescription', description),\n plistString('PayloadDisplayName', name),\n plistString('PayloadIdentifier', `${identifier}.root`),\n plistString('PayloadType', 'com.apple.security.root'),\n plistString('PayloadUUID', uuidV5(`wt-tunnel:ca:${fingerprintHex}:root`)),\n '<key>PayloadVersion</key><integer>1</integer>',\n '</dict>',\n '</array>',\n plistString('PayloadDescription', description),\n plistString('PayloadDisplayName', name),\n plistString('PayloadIdentifier', identifier),\n '<key>PayloadRemovalDisallowed</key><false/>',\n plistString('PayloadType', 'Configuration'),\n plistString('PayloadUUID', uuidV5(`wt-tunnel:ca:${fingerprintHex}:profile`)),\n '<key>PayloadVersion</key><integer>1</integer>',\n '</dict>',\n '</plist>',\n '',\n ].join('\\n');\n};\n\nexport { mobileconfig, readRootCa };\nexport type { RootCa };\n"],"mappings":";;;AA4BA,MAAM,UAAU,SAAiB,IAAI,KAAK,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM;;AAG/E,MAAM,cAAc,WAAyD;CAC3E,MAAM,cAAc,IAAI,gBAAgB,OAAO,GAAG,IAAI;CACtD,OAAO;EACL,WAAW,YAAY,IAAI,SAAS,QAAQ;EAC5C,SAAS,OAAO;EAChB,UAAU,gBAAgB,UAAU,WAAW,KAAK,OAAO,QAAQ;EACnE,aAAa,YAAY;EACzB,KAAK,YAAY,SAAS;EAC1B,WAAW,kBAAkB,YAAY,GAAG;EAC5C,SAAS,YAAY,QAAQ,MAAM,IAAI,CAAC,CAAC,KAAK,IAAI;EAClD,WAAW,OAAO,YAAY,SAAS;EACvC,SAAS,OAAO,YAAY,OAAO;CACrC;AACF;;AAGA,MAAM,eAAe,OAAO,KAAK,oCAAoC,KAAK;AAC1E,MAAM,YAAY;;AAElB,MAAM,UAAU;CAAE,MAAM;CAAG,MAAM;CAAM,KAAK;AAAK;AACjD,MAAM,UAAU;CAAE,MAAM;CAAG,MAAM;CAAM,KAAK;AAAK;;AAGjD,MAAM,UAAU,SAAiB;CAC/B,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,OAAO,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO;CACzE,KAAK,MAAM,SAAS,CAAC,SAAS,OAAO,GACnC,KAAK,WAAY,KAAK,U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
2
|
+
import { Effect, Redacted } from "effect";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
// src/runtime.ts
|
|
7
|
+
/**
|
|
8
|
+
* Writes the Caddyfile, frps.toml and the CA into a fresh private directory, deleted with the scope
|
|
9
|
+
* so no copy of the CA key outlives the server.
|
|
10
|
+
*/
|
|
11
|
+
const writeRuntimeFiles = (config, ports) => Effect.acquireRelease(Effect.promise(async () => {
|
|
12
|
+
const dir = await mkdtemp(join(tmpdir(), "wt-tunnel-server-"));
|
|
13
|
+
const paths = {
|
|
14
|
+
caCert: join(dir, "ca.crt"),
|
|
15
|
+
caKey: join(dir, "ca.key"),
|
|
16
|
+
storage: join(dir, "caddy")
|
|
17
|
+
};
|
|
18
|
+
await mkdir(paths.storage, { mode: 448 });
|
|
19
|
+
await writeFile(paths.caCert, config.ca.cert);
|
|
20
|
+
await writeFile(paths.caKey, Redacted.value(config.ca.key), { mode: 384 });
|
|
21
|
+
await writeFile(join(dir, "Caddyfile"), renderCaddyfile(config, paths, ports));
|
|
22
|
+
await writeFile(join(dir, "frps.toml"), renderFrpsToml(config, ports), { mode: 384 });
|
|
23
|
+
return dir;
|
|
24
|
+
}), (dir) => Effect.promise(() => rm(dir, {
|
|
25
|
+
force: true,
|
|
26
|
+
recursive: true
|
|
27
|
+
})));
|
|
28
|
+
const childSpecs = (dir, binaries) => {
|
|
29
|
+
const env = {
|
|
30
|
+
XDG_CONFIG_HOME: dir,
|
|
31
|
+
XDG_DATA_HOME: dir
|
|
32
|
+
};
|
|
33
|
+
return [{
|
|
34
|
+
args: [
|
|
35
|
+
"run",
|
|
36
|
+
"--adapter",
|
|
37
|
+
"caddyfile",
|
|
38
|
+
"--config",
|
|
39
|
+
join(dir, "Caddyfile")
|
|
40
|
+
],
|
|
41
|
+
command: binaries.caddy,
|
|
42
|
+
env,
|
|
43
|
+
name: "caddy"
|
|
44
|
+
}, {
|
|
45
|
+
args: ["-c", join(dir, "frps.toml")],
|
|
46
|
+
command: binaries.frps,
|
|
47
|
+
env,
|
|
48
|
+
name: "frps"
|
|
49
|
+
}];
|
|
50
|
+
};
|
|
51
|
+
export { childSpecs, writeRuntimeFiles };
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Effect, Redacted } from 'effect';\n\nimport type { Binaries } from './binaries.ts';\nimport { renderCaddyfile, renderFrpsToml } from './render.ts';\nimport type { Ports } from './render.ts';\n\n/**\n * Writes the Caddyfile, frps.toml and the CA into a fresh private directory, deleted with the scope\n * so no copy of the CA key outlives the server.\n */\nconst writeRuntimeFiles = (config: ServerConfig, ports: Ports) =>\n Effect.acquireRelease(\n Effect.promise(async () => {\n const dir = await mkdtemp(join(tmpdir(), 'wt-tunnel-server-'));\n const paths = {\n caCert: join(dir, 'ca.crt'),\n caKey: join(dir, 'ca.key'),\n storage: join(dir, 'caddy'),\n };\n await mkdir(paths.storage, { mode: 0o700 });\n await writeFile(paths.caCert, config.ca.cert);\n await writeFile(paths.caKey, Redacted.value(config.ca.key), { mode: 0o600 });\n await writeFile(join(dir, 'Caddyfile'), renderCaddyfile(config, paths, ports));\n await writeFile(join(dir, 'frps.toml'), renderFrpsToml(config, ports), { mode: 0o600 });\n return dir;\n }),\n (dir) => Effect.promise(() => rm(dir, { force: true, recursive: true })),\n );\n\nconst childSpecs = (dir: string, binaries: Binaries) => {\n // Caddy keeps its local CA and autosave under XDG dirs; keep them in the runtime dir.\n const env = { XDG_CONFIG_HOME: dir, XDG_DATA_HOME: dir };\n return [\n {\n args: ['run', '--adapter', 'caddyfile', '--config', join(dir, 'Caddyfile')],\n command: binaries.caddy,\n env,\n name: 'caddy',\n },\n { args: ['-c', join(dir, 'frps.toml')], command: binaries.frps, env, name: 'frps' },\n ];\n};\n\nexport { childSpecs, writeRuntimeFiles };\n"],"mappings":";;;;;;;;;;AAeA,MAAM,qBAAqB,QAAsB,UAC/C,OAAO,eACL,OAAO,QAAQ,YAAY;CACzB,MAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,GAAG,mBAAmB,CAAC;CAC7D,MAAM,QAAQ;EACZ,QAAQ,KAAK,KAAK,QAAQ;EAC1B,OAAO,KAAK,KAAK,QAAQ;EACzB,SAAS,KAAK,KAAK,OAAO;CAC5B;CACA,MAAM,MAAM,MAAM,SAAS,EAAE,MAAM,IAAM,CAAC;CAC1C,MAAM,UAAU,MAAM,QAAQ,OAAO,GAAG,IAAI;CAC5C,MAAM,UAAU,MAAM,OAAO,SAAS,MAAM,OAAO,GAAG,GAAG,GAAG,EAAE,MAAM,IAAM,CAAC;CAC3E,MAAM,UAAU,KAAK,KAAK,WAAW,GAAG,gBAAgB,QAAQ,OAAO,KAAK,CAAC;CAC7E,MAAM,UAAU,KAAK,KAAK,WAAW,GAAG,eAAe,QAAQ,KAAK,GAAG,EAAE,MAAM,IAAM,CAAC;CACtF,OAAO;AACT,CAAC,IACA,QAAQ,OAAO,cAAc,GAAG,KAAK;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC,CAAC,CACzE;AAEF,MAAM,cAAc,KAAa,aAAuB;CAEtD,MAAM,MAAM;EAAE,iBAAiB;EAAK,eAAe;CAAI;CACvD,OAAO,CACL;EACE,MAAM;GAAC;GAAO;GAAa;GAAa;GAAY,KAAK,KAAK,WAAW;EAAC;EAC1E,SAAS,SAAS;EAClB;EACA,MAAM;CACR,GACA;EAAE,MAAM,CAAC,MAAM,KAAK,KAAK,WAAW,CAAC;EAAG,SAAS,SAAS;EAAM;EAAK,MAAM;CAAO,CACpF;AACF"}
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { domainOf, hostWithoutPort } from "./hosts.js";
|
|
2
|
+
import { header, notFound, sendReply, status } from "./reply.js";
|
|
3
|
+
import { devHostRoute } from "./dev-host.js";
|
|
4
|
+
import { internalRoute } from "./internal.js";
|
|
5
|
+
import "./render.js";
|
|
6
|
+
import { caRoute } from "./ca-page.js";
|
|
7
|
+
import { signInRoute } from "./sign-in.js";
|
|
8
|
+
import { createServer } from "node:http";
|
|
9
|
+
// src/service.ts
|
|
10
|
+
const betterAuthPrefix = "/api/auth/";
|
|
11
|
+
const siteOf = (request, context) => {
|
|
12
|
+
const host = header(request, "host") ?? "";
|
|
13
|
+
if (host === `127.0.0.1:4000`) return { _tag: "internal" };
|
|
14
|
+
if (hostWithoutPort(host) === context.config.authHost) return { _tag: "auth" };
|
|
15
|
+
const domain = domainOf(host, context.config.domains);
|
|
16
|
+
return domain === void 0 ? void 0 : {
|
|
17
|
+
_tag: "dev",
|
|
18
|
+
domain
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
/** The sign-in host: the public certificate routes, then sign-in. */
|
|
22
|
+
const authRoute = (request, path, auth) => {
|
|
23
|
+
const ca = caRoute(request, path, auth.context.rootCa);
|
|
24
|
+
return ca === void 0 ? signInRoute(request, path, auth) : Promise.resolve(ca);
|
|
25
|
+
};
|
|
26
|
+
const route = (request, context) => {
|
|
27
|
+
const site = siteOf(request, context);
|
|
28
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
29
|
+
const query = Object.fromEntries(url.searchParams);
|
|
30
|
+
if (site === void 0) return Promise.resolve(notFound);
|
|
31
|
+
if (site._tag === "internal") return internalRoute(request, url.pathname, {
|
|
32
|
+
config: context.config,
|
|
33
|
+
query
|
|
34
|
+
});
|
|
35
|
+
if (site._tag === "auth") return authRoute(request, url.pathname, {
|
|
36
|
+
context,
|
|
37
|
+
query
|
|
38
|
+
});
|
|
39
|
+
return Promise.resolve(devHostRoute(request, url.pathname, {
|
|
40
|
+
context,
|
|
41
|
+
domain: site.domain,
|
|
42
|
+
query
|
|
43
|
+
}));
|
|
44
|
+
};
|
|
45
|
+
const respond = async (request, response, context) => {
|
|
46
|
+
try {
|
|
47
|
+
sendReply(response, await route(request, context));
|
|
48
|
+
} catch (error) {
|
|
49
|
+
console.error(`auth: ${request.method} ${request.url}: ${String(error)}`);
|
|
50
|
+
sendReply(response, { status: status.serverError });
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/** The auth service: the sign-in host, dev-host `/_wt/*`, and the checks Caddy and frps call. */
|
|
54
|
+
const createAuthService = (context) => createServer((request, response) => {
|
|
55
|
+
siteOf(request, context)?._tag === "auth" && (request.url ?? "").startsWith(betterAuthPrefix) ? context.signIn.handler(request, response) : respond(request, response, context);
|
|
56
|
+
});
|
|
57
|
+
export { createAuthService };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.js","names":[],"sources":["../src/service.ts"],"sourcesContent":["import { createServer } from 'node:http';\nimport type { IncomingMessage, Server, ServerResponse } from 'node:http';\n\nimport type { Hostname } from '@tafrahq/wt-tunnel-contract';\n\nimport { caRoute } from './ca-page.ts';\nimport type { Query, ServiceContext } from './context.ts';\nimport { devHostRoute } from './dev-host.ts';\nimport { domainOf, hostWithoutPort } from './hosts.ts';\nimport { internalRoute } from './internal.ts';\nimport { authPort, loopback } from './render.ts';\nimport { header, notFound, sendReply, status } from './reply.ts';\nimport type { Reply } from './reply.ts';\nimport { signInRoute } from './sign-in.ts';\n\nconst betterAuthPrefix = '/api/auth/';\n\n/**\n * Who a request is for, from its Host: the sign-in host, a dev host (with the domain that covers\n * it), or Caddy and frps calling on the loopback address.\n */\ntype Site =\n | { readonly _tag: 'auth' }\n | { readonly _tag: 'dev'; readonly domain: Hostname }\n | { readonly _tag: 'internal' };\n\nconst siteOf = (request: IncomingMessage, context: ServiceContext): Site | undefined => {\n const host = header(request, 'host') ?? '';\n if (host === `${loopback}:${authPort}`) {\n return { _tag: 'internal' };\n }\n if (hostWithoutPort(host) === context.config.authHost) {\n return { _tag: 'auth' };\n }\n const domain = domainOf(host, context.config.domains);\n return domain === undefined ? undefined : { _tag: 'dev', domain };\n};\n\n/** The sign-in host: the public certificate routes, then sign-in. */\nconst authRoute = (\n request: IncomingMessage,\n path: string,\n auth: { readonly context: ServiceContext; readonly query: Query },\n): Promise<Reply> => {\n const ca = caRoute(request, path, auth.context.rootCa);\n return ca === undefined ? signInRoute(request, path, auth) : Promise.resolve(ca);\n};\n\nconst route = (request: IncomingMessage, context: ServiceContext): Promise<Reply> => {\n const site = siteOf(request, context);\n const url = new URL(request.url ?? '/', 'http://localhost');\n const query = Object.fromEntries(url.searchParams);\n if (site === undefined) {\n return Promise.resolve(notFound);\n }\n if (site._tag === 'internal') {\n return internalRoute(request, url.pathname, { config: context.config, query });\n }\n if (site._tag === 'auth') {\n return authRoute(request, url.pathname, { context, query });\n }\n return Promise.resolve(\n devHostRoute(request, url.pathname, { context, domain: site.domain, query }),\n );\n};\n\nconst respond = async (\n request: IncomingMessage,\n response: ServerResponse,\n context: ServiceContext,\n) => {\n try {\n sendReply(response, await route(request, context));\n } catch (error) {\n console.error(`auth: ${request.method} ${request.url}: ${String(error)}`);\n sendReply(response, { status: status.serverError });\n }\n};\n\n/** The auth service: the sign-in host, dev-host `/_wt/*`, and the checks Caddy and frps call. */\nconst createAuthService = (context: ServiceContext): Server =>\n createServer((request, response) => {\n const toBetterAuth =\n siteOf(request, context)?._tag === 'auth' && (request.url ?? '').startsWith(betterAuthPrefix);\n void (toBetterAuth\n ? context.signIn.handler(request, response)\n : respond(request, response, context));\n });\n\nexport { createAuthService };\n"],"mappings":";;;;;;;;;AAeA,MAAM,mBAAmB;AAWzB,MAAM,UAAU,SAA0B,YAA8C;CACtF,MAAM,OAAO,OAAO,SAAS,MAAM,KAAK;CACxC,IAAI,SAAS,kBACX,OAAO,EA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AAO,CAAC,EAAE,SAAS,WAAW,QAAQ,OAAO,GAAA,CAAI,WAAW,gBAAgB,IAE1F,QAAQ,OAAO,QAAQ,SAAS,QAAQ,IACxC,QAAQ,SAAS,UAAU,OAAO;AACxC,CAAC"}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
// src/session.ts
|
|
3
|
+
const sessionCookieName = "wt_session";
|
|
4
|
+
/** Seven days. */
|
|
5
|
+
const sessionSeconds = 604800;
|
|
6
|
+
const codeMillis = 6e4;
|
|
7
|
+
const codeBytes = 32;
|
|
8
|
+
const cookieParts = 3;
|
|
9
|
+
const millisPerSecond = 1e3;
|
|
10
|
+
/**
|
|
11
|
+
* The MAC covers the dev domain too, so a cookie minted for one dev domain does not verify on
|
|
12
|
+
* another even when a browser is tricked into sending it there.
|
|
13
|
+
*/
|
|
14
|
+
const mac = ({ domain, secret }, emailPart, expiry) => createHmac("sha256", secret).update(`${sessionCookieName}|${domain}|${emailPart}|${expiry}`).digest("base64url");
|
|
15
|
+
/**
|
|
16
|
+
* `wt_session` value: `base64url(email) "." expiry "." base64url(HMAC-SHA256(authSecret,
|
|
17
|
+
* "wt_session|" domain "|" base64url(email) "|" expiry))`, expiry in Unix seconds.
|
|
18
|
+
*/
|
|
19
|
+
const mintSession = (key, email, nowMillis) => {
|
|
20
|
+
const emailPart = Buffer.from(email, "utf8").toString("base64url");
|
|
21
|
+
const expiry = String(Math.floor(nowMillis / millisPerSecond) + sessionSeconds);
|
|
22
|
+
return `${emailPart}.${expiry}.${mac(key, emailPart, expiry)}`;
|
|
23
|
+
};
|
|
24
|
+
const sameText = (left, right) => {
|
|
25
|
+
const leftBytes = Buffer.from(left);
|
|
26
|
+
const rightBytes = Buffer.from(right);
|
|
27
|
+
return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);
|
|
28
|
+
};
|
|
29
|
+
/** The email the cookie was minted for, when its MAC matches this key and it has not expired. */
|
|
30
|
+
const verifySession = (key, value, nowMillis) => {
|
|
31
|
+
const parts = value.split(".");
|
|
32
|
+
const [emailPart = "", expiry = "", signature = ""] = parts;
|
|
33
|
+
const email = parts.length === cookieParts && /^\d+$/u.test(expiry) && sameText(signature, mac(key, emailPart, expiry)) && Number(expiry) * millisPerSecond > nowMillis ? Buffer.from(emailPart, "base64url").toString("utf8") : "";
|
|
34
|
+
return email === "" ? void 0 : email;
|
|
35
|
+
};
|
|
36
|
+
const cookieAttributes = (domain) => `Domain=${domain}; Path=/; HttpOnly; Secure; SameSite=Lax`;
|
|
37
|
+
const sessionSetCookie = (value, domain) => `${sessionCookieName}=${value}; Max-Age=${sessionSeconds}; ${cookieAttributes(domain)}`;
|
|
38
|
+
const sessionClearCookie = (domain) => `${sessionCookieName}=; Max-Age=0; ${cookieAttributes(domain)}`;
|
|
39
|
+
/** A Cookie header's pairs other than `wt_session`, joined again; empty when none are left. */
|
|
40
|
+
const cookiesWithoutSession = (cookieHeader) => (cookieHeader ?? "").split(";").map((pair) => pair.trim()).filter((pair) => pair !== "" && !pair.startsWith(`${sessionCookieName}=`)).join("; ");
|
|
41
|
+
/** Every `wt_session` value in a Cookie header; a stale one may sit beside a fresh one. */
|
|
42
|
+
const sessionCookieValues = (cookieHeader) => (cookieHeader ?? "").split(";").map((pair) => pair.trim()).filter((pair) => pair.startsWith(`${sessionCookieName}=`)).map((pair) => pair.slice(11));
|
|
43
|
+
/** One-time codes in memory: random, single use, valid for 60 seconds. */
|
|
44
|
+
const createCodeStore = () => {
|
|
45
|
+
const codes = /* @__PURE__ */ new Map();
|
|
46
|
+
return {
|
|
47
|
+
issue: (grant, nowMillis) => {
|
|
48
|
+
for (const [code, entry] of codes) if (entry.expiresAt <= nowMillis) codes.delete(code);
|
|
49
|
+
const code = randomBytes(codeBytes).toString("base64url");
|
|
50
|
+
codes.set(code, {
|
|
51
|
+
...grant,
|
|
52
|
+
expiresAt: nowMillis + codeMillis
|
|
53
|
+
});
|
|
54
|
+
return code;
|
|
55
|
+
},
|
|
56
|
+
redeem: (code, nowMillis) => {
|
|
57
|
+
const entry = codes.get(code);
|
|
58
|
+
codes.delete(code);
|
|
59
|
+
return entry === void 0 || entry.expiresAt <= nowMillis ? void 0 : entry;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
export { cookiesWithoutSession, createCodeStore, mintSession, sessionClearCookie, sessionCookieValues, sessionSeconds, sessionSetCookie, verifySession };
|
|
64
|
+
|
|
65
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\n\nimport type { Hostname } from '@tafrahq/wt-tunnel-contract';\n\nconst sessionCookieName = 'wt_session';\n/** Seven days. */\nconst sessionSeconds = 604_800;\nconst codeMillis = 60_000;\nconst codeBytes = 32;\nconst cookieParts = 3;\n\n/** What a cookie is bound to: the auth secret and one dev domain. */\ninterface SessionKey {\n readonly domain: Hostname;\n readonly secret: string;\n}\n\nconst millisPerSecond = 1000;\n\n/**\n * The MAC covers the dev domain too, so a cookie minted for one dev domain does not verify on\n * another even when a browser is tricked into sending it there.\n */\nconst mac = ({ domain, secret }: SessionKey, emailPart: string, expiry: string) =>\n createHmac('sha256', secret)\n .update(`${sessionCookieName}|${domain}|${emailPart}|${expiry}`)\n .digest('base64url');\n\n/**\n * `wt_session` value: `base64url(email) \".\" expiry \".\" base64url(HMAC-SHA256(authSecret,\n * \"wt_session|\" domain \"|\" base64url(email) \"|\" expiry))`, expiry in Unix seconds.\n */\nconst mintSession = (key: SessionKey, email: string, nowMillis: number) => {\n const emailPart = Buffer.from(email, 'utf8').toString('base64url');\n const expiry = String(Math.floor(nowMillis / millisPerSecond) + sessionSeconds);\n return `${emailPart}.${expiry}.${mac(key, emailPart, expiry)}`;\n};\n\nconst sameText = (left: string, right: string) => {\n const leftBytes = Buffer.from(left);\n const rightBytes = Buffer.from(right);\n return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);\n};\n\n/** The email the cookie was minted for, when its MAC matches this key and it has not expired. */\nconst verifySession = (key: SessionKey, value: string, nowMillis: number) => {\n const parts = value.split('.');\n const [emailPart = '', expiry = '', signature = ''] = parts;\n const valid =\n parts.length === cookieParts &&\n /^\\d+$/u.test(expiry) &&\n sameText(signature, mac(key, emailPart, expiry)) &&\n Number(expiry) * millisPerSecond > nowMillis;\n const email = valid ? Buffer.from(emailPart, 'base64url').toString('utf8') : '';\n return email === '' ? undefined : email;\n};\n\nconst cookieAttributes = (domain: Hostname) =>\n `Domain=${domain}; Path=/; HttpOnly; Secure; SameSite=Lax`;\n\nconst sessionSetCookie = (value: string, domain: Hostname) =>\n `${sessionCookieName}=${value}; Max-Age=${sessionSeconds}; ${cookieAttributes(domain)}`;\n\nconst sessionClearCookie = (domain: Hostname) =>\n `${sessionCookieName}=; Max-Age=0; ${cookieAttributes(domain)}`;\n\n/** A Cookie header's pairs other than `wt_session`, joined again; empty when none are left. */\nconst cookiesWithoutSession = (cookieHeader: string | undefined) =>\n (cookieHeader ?? '')\n .split(';')\n .map((pair) => pair.trim())\n .filter((pair) => pair !== '' && !pair.startsWith(`${sessionCookieName}=`))\n .join('; ');\n\n/** Every `wt_session` value in a Cookie header; a stale one may sit beside a fresh one. */\nconst sessionCookieValues = (cookieHeader: string | undefined) =>\n (cookieHeader ?? '')\n .split(';')\n .map((pair) => pair.trim())\n .filter((pair) => pair.startsWith(`${sessionCookieName}=`))\n .map((pair) => pair.slice(sessionCookieName.length + 1));\n\ninterface Grant {\n readonly domain: Hostname;\n readonly email: string;\n readonly host: Hostname;\n /** Where `/_wt/callback` sends the browser once the cookie is set. */\n readonly url: string;\n}\n\ninterface CodeStore {\n readonly issue: (grant: Grant, nowMillis: number) => string;\n /** The grant behind an unexpired code; the code is gone afterwards either way. */\n readonly redeem: (code: string, nowMillis: number) => Grant | undefined;\n}\n\n/** One-time codes in memory: random, single use, valid for 60 seconds. */\nconst createCodeStore = (): CodeStore => {\n const codes = new Map<string, Grant & { readonly expiresAt: number }>();\n return {\n issue: (grant, nowMillis) => {\n for (const [code, entry] of codes) {\n if (entry.expiresAt <= nowMillis) {\n codes.delete(code);\n }\n }\n const code = randomBytes(codeBytes).toString('base64url');\n codes.set(code, { ...grant, expiresAt: nowMillis + codeMillis });\n return code;\n },\n redeem: (code, nowMillis) => {\n const entry = codes.get(code);\n codes.delete(code);\n return entry === undefined || entry.expiresAt <= nowMillis ? undefined : entry;\n },\n };\n};\n\nexport {\n cookiesWithoutSession,\n createCodeStore,\n mintSession,\n sessionClearCookie,\n sessionCookieValues,\n sessionSeconds,\n sessionSetCookie,\n verifySession,\n};\nexport type { CodeStore, Grant, SessionKey };\n"],"mappings":";;AAIA,MAAM,oBAAoB;;AAE1B,MAAM,iBAAiB;AACvB,MAAM,aAAa;AACnB,MAAM,YAAY;AAClB,MAAM,cAAc;AAQpB,MAAM,kBAAkB;;;;;AAMxB,MAAM,OAAO,EAAE,QAAQ,UAAsB,WAAmB,WAC9D,WAAW,UAAU,MAAM,CAAC,CACzB,OAAO,GAAG,kBAAkB,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,CAAC,CAC/D,OAAO,WAAW;;;;;AAMvB,MAAM,eAAe,KAAiB,OAAe,cAAsB;CACzE,MAAM,YAAY,OAAO,KAAK,OAAO,MAAM,CAAC,CAAC,SAAS,WAAW;CACjE,MAAM,SAAS,OAAO,KAAK,MAAM,YAAY,eAAe,IAAI,cAAc;CAC9E,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,IAAI,KAAK,WAAW,MAAM;AAC7D;AAEA,MAAM,YAAY,MAAc,UAAkB;CAChD,MAAM,YAAY,OAAO,KAAK,IAAI;CAClC,MAAM,aAAa,OAAO,KAAK,KAAK;CACpC,OAAO,UAAU,WAAW,WAAW,UAAU,gBAAgB,WAAW,UAAU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C,SAAS,WAAW;GACxD,MAAM,IAAI,MAAM;IAAE,GAAG;IAAO,WAAW,YAAY;GAAW,CAAC;GAC/D,OAAO;EACT;EACA,SAAS,MAAM,cAAc;GAC3B,MAAM,QAAQ,MAAM,IAAI,IAAI;GAC5B,MAAM,OAAO,IAAI;GACjB,OAAO,UAAU,KAAA,KAAa,MAAM,aAAa,YAAY,KAAA,IAAY;EAC3E;CACF;AACF"}
|
package/dist/sign-in.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { providerIds } from "./packages/contract/src/server-config.js";
|
|
2
|
+
import { isAllowed } from "./config.js";
|
|
3
|
+
import { loginUrl } from "./context.js";
|
|
4
|
+
import { parseReturnTarget } from "./hosts.js";
|
|
5
|
+
import { escapeHtml, page, redirect, status } from "./reply.js";
|
|
6
|
+
import "./ca-page.js";
|
|
7
|
+
// src/sign-in.ts
|
|
8
|
+
const finishPath = "/login/finish";
|
|
9
|
+
/** A sign-in host page, with a link to the certificate page under it. */
|
|
10
|
+
const authPage = (code, text, setCookie = []) => page(code, {
|
|
11
|
+
...text,
|
|
12
|
+
footer: `<a href="/ca">Trust this deployment's certificate</a>`
|
|
13
|
+
}, setCookie);
|
|
14
|
+
/** Sends a signed-in, allowed user back to the dev host with a one-time code. */
|
|
15
|
+
const finish = async (request, target, context) => {
|
|
16
|
+
const { setCookie, value: user } = await context.signIn.session(request);
|
|
17
|
+
if (user === void 0) return redirect(loginUrl(context, target.url), setCookie);
|
|
18
|
+
if (!isAllowed(context.config.allow, user.email, user.emailVerified)) {
|
|
19
|
+
const html = `${escapeHtml(user.email)} may not open these pages. <a href="/logout">Sign out</a> and try another account.`;
|
|
20
|
+
return authPage(status.forbidden, {
|
|
21
|
+
html,
|
|
22
|
+
title: "Not allowed"
|
|
23
|
+
}, setCookie);
|
|
24
|
+
}
|
|
25
|
+
const grant = {
|
|
26
|
+
domain: target.domain,
|
|
27
|
+
email: user.email,
|
|
28
|
+
host: target.host,
|
|
29
|
+
url: target.url
|
|
30
|
+
};
|
|
31
|
+
const code = context.codes.issue(grant, context.now());
|
|
32
|
+
return redirect(`https://${target.host}/_wt/callback?code=${code}`, setCookie);
|
|
33
|
+
};
|
|
34
|
+
const providerNames = {
|
|
35
|
+
cloudflare: "Cloudflare Access",
|
|
36
|
+
github: "GitHub",
|
|
37
|
+
google: "Google",
|
|
38
|
+
microsoft: "Microsoft"
|
|
39
|
+
};
|
|
40
|
+
/** The configured providers, in the order the sign-in page lists them. */
|
|
41
|
+
const configuredProviders = (context) => providerIds.filter((id) => context.config.providers[id] !== void 0);
|
|
42
|
+
/** One link per provider, each back to `/login` with the provider named. */
|
|
43
|
+
const chooseProvider = (providers, target) => {
|
|
44
|
+
const rd = encodeURIComponent(target.url);
|
|
45
|
+
const links = providers.map((id) => `<a href="/login?rd=${rd}&provider=${id}">Continue with ${providerNames[id]}</a>`).join("<br>");
|
|
46
|
+
return authPage(status.ok, {
|
|
47
|
+
html: links,
|
|
48
|
+
title: "Sign in"
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
const startSignIn = async (request, { context, provider, target }) => {
|
|
52
|
+
const callbackURL = `https://${context.config.authHost}${finishPath}?rd=${encodeURIComponent(target.url)}`;
|
|
53
|
+
const { setCookie, value: url } = await context.signIn.start(request, {
|
|
54
|
+
callbackURL,
|
|
55
|
+
provider
|
|
56
|
+
});
|
|
57
|
+
return url === void 0 ? authPage(status.badGateway, {
|
|
58
|
+
html: `${providerNames[provider]} sign-in did not start.`,
|
|
59
|
+
title: "Sign-in failed"
|
|
60
|
+
}) : redirect(url, setCookie);
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Skips sign-in when the sign-in host already has a session. Otherwise starts the provider the
|
|
64
|
+
* query names, or the only one configured, or lets the user choose.
|
|
65
|
+
*/
|
|
66
|
+
const login = async (request, target, { context, query }) => {
|
|
67
|
+
const { value: user } = await context.signIn.session(request);
|
|
68
|
+
if (user !== void 0) return finish(request, target, context);
|
|
69
|
+
const providers = configuredProviders(context);
|
|
70
|
+
const provider = providers.length === 1 ? providers[0] : providers.find((id) => id === query.provider);
|
|
71
|
+
return provider === void 0 ? chooseProvider(providers, target) : startSignIn(request, {
|
|
72
|
+
context,
|
|
73
|
+
provider,
|
|
74
|
+
target
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
const signOut = async (request, context) => {
|
|
78
|
+
const setCookie = await context.signIn.signOut(request);
|
|
79
|
+
return authPage(status.ok, {
|
|
80
|
+
html: "Each dev domain keeps its own session until you open its <code>/_wt/logout</code>.",
|
|
81
|
+
title: "Signed out"
|
|
82
|
+
}, setCookie);
|
|
83
|
+
};
|
|
84
|
+
/** Routes on the sign-in host other than Better Auth's own `/api/auth/*`. */
|
|
85
|
+
const signInRoute = (request, path, { context, query }) => {
|
|
86
|
+
if (path === "/logout") return signOut(request, context);
|
|
87
|
+
if (path !== "/login" && path !== finishPath) return Promise.resolve(authPage(status.notFound, {
|
|
88
|
+
html: "Nothing lives here.",
|
|
89
|
+
title: "Not found"
|
|
90
|
+
}));
|
|
91
|
+
const target = parseReturnTarget(query.rd, context.config.domains);
|
|
92
|
+
if (target === void 0) return Promise.resolve(authPage(status.badRequest, {
|
|
93
|
+
html: "The return address is not a dev host.",
|
|
94
|
+
title: "Bad sign-in link"
|
|
95
|
+
}));
|
|
96
|
+
return path === "/login" ? login(request, target, {
|
|
97
|
+
context,
|
|
98
|
+
query
|
|
99
|
+
}) : finish(request, target, context);
|
|
100
|
+
};
|
|
101
|
+
export { signInRoute };
|
|
102
|
+
|
|
103
|
+
//# sourceMappingURL=sign-in.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-in.js","names":[],"sources":["../src/sign-in.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\n\nimport { providerIds } from '@tafrahq/wt-tunnel-contract/server-config';\nimport type { ProviderId } from '@tafrahq/wt-tunnel-contract/server-config';\n\nimport { caPath } from './ca-page.ts';\nimport { isAllowed } from './config.ts';\nimport { loginUrl } from './context.ts';\nimport type { Query, ServiceContext } from './context.ts';\nimport { parseReturnTarget } from './hosts.ts';\nimport type { ReturnTarget } from './hosts.ts';\nimport { escapeHtml, page, redirect, status } from './reply.ts';\nimport type { Reply } from './reply.ts';\n\nconst finishPath = '/login/finish';\n\n/** A sign-in host page, with a link to the certificate page under it. */\nconst authPage = (\n code: number,\n text: { readonly html: string; readonly title: string },\n setCookie: readonly string[] = [],\n) =>\n page(\n code,\n { ...text, footer: `<a href=\"${caPath}\">Trust this deployment's certificate</a>` },\n setCookie,\n );\n\n/** Sends a signed-in, allowed user back to the dev host with a one-time code. */\nconst finish = async (\n request: IncomingMessage,\n target: ReturnTarget,\n context: ServiceContext,\n): Promise<Reply> => {\n const { setCookie, value: user } = await context.signIn.session(request);\n if (user === undefined) {\n return redirect(loginUrl(context, target.url), setCookie);\n }\n if (!isAllowed(context.config.allow, user.email, user.emailVerified)) {\n const html = `${escapeHtml(user.email)} may not open these pages. <a href=\"/logout\">Sign out</a> and try another account.`;\n return authPage(status.forbidden, { html, title: 'Not allowed' }, setCookie);\n }\n const grant = { domain: target.domain, email: user.email, host: target.host, url: target.url };\n const code = context.codes.issue(grant, context.now());\n return redirect(`https://${target.host}/_wt/callback?code=${code}`, setCookie);\n};\n\nconst providerNames: Readonly<Record<ProviderId, string>> = {\n cloudflare: 'Cloudflare Access',\n github: 'GitHub',\n google: 'Google',\n microsoft: 'Microsoft',\n};\n\n/** The configured providers, in the order the sign-in page lists them. */\nconst configuredProviders = (context: ServiceContext) =>\n providerIds.filter((id) => context.config.providers[id] !== undefined);\n\n/** One link per provider, each back to `/login` with the provider named. */\nconst chooseProvider = (providers: readonly ProviderId[], target: ReturnTarget) => {\n const rd = encodeURIComponent(target.url);\n const links = providers\n .map(\n (id) => `<a href=\"/login?rd=${rd}&provider=${id}\">Continue with ${providerNames[id]}</a>`,\n )\n .join('<br>');\n return authPage(status.ok, { html: links, title: 'Sign in' });\n};\n\nconst startSignIn = async (\n request: IncomingMessage,\n {\n context,\n provider,\n target,\n }: {\n readonly context: ServiceContext;\n readonly provider: ProviderId;\n readonly target: ReturnTarget;\n },\n): Promise<Reply> => {\n const callbackURL = `https://${context.config.authHost}${finishPath}?rd=${encodeURIComponent(target.url)}`;\n const { setCookie, value: url } = await context.signIn.start(request, { callbackURL, provider });\n return url === undefined\n ? authPage(status.badGateway, {\n html: `${providerNames[provider]} sign-in did not start.`,\n title: 'Sign-in failed',\n })\n : redirect(url, setCookie);\n};\n\n/**\n * Skips sign-in when the sign-in host already has a session. Otherwise starts the provider the\n * query names, or the only one configured, or lets the user choose.\n */\nconst login = async (\n request: IncomingMessage,\n target: ReturnTarget,\n { context, query }: { readonly context: ServiceContext; readonly query: Query },\n): Promise<Reply> => {\n const { value: user } = await context.signIn.session(request);\n if (user !== undefined) {\n return finish(request, target, context);\n }\n const providers = configuredProviders(context);\n const provider =\n providers.length === 1 ? providers[0] : providers.find((id) => id === query.provider);\n return provider === undefined\n ? chooseProvider(providers, target)\n : startSignIn(request, { context, provider, target });\n};\n\nconst signOut = async (request: IncomingMessage, context: ServiceContext): Promise<Reply> => {\n const setCookie = await context.signIn.signOut(request);\n const html = 'Each dev domain keeps its own session until you open its <code>/_wt/logout</code>.';\n return authPage(status.ok, { html, title: 'Signed out' }, setCookie);\n};\n\n/** Routes on the sign-in host other than Better Auth's own `/api/auth/*`. */\nconst signInRoute = (\n request: IncomingMessage,\n path: string,\n { context, query }: { readonly context: ServiceContext; readonly query: Query },\n): Promise<Reply> => {\n if (path === '/logout') {\n return signOut(request, context);\n }\n if (path !== '/login' && path !== finishPath) {\n return Promise.resolve(\n authPage(status.notFound, { html: 'Nothing lives here.', title: 'Not found' }),\n );\n }\n const target = parseReturnTarget(query.rd, context.config.domains);\n if (target === undefined) {\n return Promise.resolve(\n authPage(status.badRequest, {\n html: 'The return address is not a dev host.',\n title: 'Bad sign-in link',\n }),\n );\n }\n return path === '/login'\n ? login(request, target, { context, query })\n : finish(request, target, context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