@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/internal.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { domainOf } from "./hosts.js";
|
|
2
|
+
import { notFound, status } from "./reply.js";
|
|
3
|
+
import { Option, Schema } from "effect";
|
|
4
|
+
// src/internal.ts
|
|
5
|
+
const askPath = "/ask";
|
|
6
|
+
const newProxyPath = "/frps/new-proxy";
|
|
7
|
+
const maxBodyLength = 65536;
|
|
8
|
+
/** Caddy's on-demand TLS check: certificates only for dev hosts and the sign-in host. */
|
|
9
|
+
const ask = (query, config) => {
|
|
10
|
+
const host = query.domain ?? "";
|
|
11
|
+
return { status: host === config.authHost || domainOf(host, config.domains) !== void 0 ? status.ok : status.forbidden };
|
|
12
|
+
};
|
|
13
|
+
const CustomDomains = Schema.NullOr(Schema.Array(Schema.String));
|
|
14
|
+
/** The fields of frps's NewProxy plugin request that decide whether a proxy is allowed. */
|
|
15
|
+
const NewProxyContent = Schema.Struct({
|
|
16
|
+
custom_domains: Schema.optionalKey(CustomDomains),
|
|
17
|
+
proxy_type: Schema.String,
|
|
18
|
+
subdomain: Schema.optionalKey(Schema.String)
|
|
19
|
+
});
|
|
20
|
+
const NewProxyRequest = Schema.fromJsonString(Schema.Struct({ content: NewProxyContent }));
|
|
21
|
+
/** Why frps must refuse this proxy, or undefined for an http proxy that serves dev hosts only. */
|
|
22
|
+
const contentProblem = (content, config) => {
|
|
23
|
+
const hosts = content.custom_domains ?? [];
|
|
24
|
+
if (content.proxy_type !== "http") return `only http proxies are allowed, not ${content.proxy_type}`;
|
|
25
|
+
if ((content.subdomain ?? "") !== "" || hosts.length === 0) return "http proxies must name their dev hosts in customDomains";
|
|
26
|
+
const foreign = hosts.find((host) => domainOf(host, config.domains) === void 0);
|
|
27
|
+
return foreign === void 0 ? void 0 : `${foreign} is not under a configured domain`;
|
|
28
|
+
};
|
|
29
|
+
const proxyProblem = (body, config) => Option.match(Schema.decodeUnknownOption(NewProxyRequest)(body), {
|
|
30
|
+
onNone: () => "unreadable NewProxy request",
|
|
31
|
+
onSome: ({ content }) => contentProblem(content, config)
|
|
32
|
+
});
|
|
33
|
+
const readBody = async (request) => {
|
|
34
|
+
let body = "";
|
|
35
|
+
for await (const chunk of request) {
|
|
36
|
+
body += String(chunk);
|
|
37
|
+
if (body.length > maxBodyLength) throw new Error("request body too large");
|
|
38
|
+
}
|
|
39
|
+
return body;
|
|
40
|
+
};
|
|
41
|
+
/** Frps server plugin, NewProxy op: frps accepts the proxy only when `reject` is false. */
|
|
42
|
+
const newProxy = async (request, config) => {
|
|
43
|
+
const problem = proxyProblem(await readBody(request), config);
|
|
44
|
+
return {
|
|
45
|
+
body: JSON.stringify({
|
|
46
|
+
reject: problem !== void 0,
|
|
47
|
+
reject_reason: problem ?? "",
|
|
48
|
+
unchange: true
|
|
49
|
+
}),
|
|
50
|
+
headers: { "content-type": "application/json" },
|
|
51
|
+
status: status.ok
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/** Routes for Caddy and frps, which call on the loopback address. */
|
|
55
|
+
const internalRoute = (request, path, { config, query }) => {
|
|
56
|
+
if (path === "/ask") return Promise.resolve(ask(query, config));
|
|
57
|
+
if (path === "/frps/new-proxy" && request.method === "POST") return newProxy(request, config);
|
|
58
|
+
return Promise.resolve(notFound);
|
|
59
|
+
};
|
|
60
|
+
export { askPath, internalRoute, newProxyPath };
|
|
61
|
+
|
|
62
|
+
//# sourceMappingURL=internal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\n\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Option, Schema } from 'effect';\n\nimport type { Query } from './context.ts';\nimport { domainOf } from './hosts.ts';\nimport { notFound, status } from './reply.ts';\nimport type { Reply } from './reply.ts';\n\nconst askPath = '/ask';\nconst newProxyPath = '/frps/new-proxy';\nconst maxBodyLength = 65_536;\n\n/** Caddy's on-demand TLS check: certificates only for dev hosts and the sign-in host. */\nconst ask = (query: Query, config: ServerConfig): Reply => {\n const host = query.domain ?? '';\n const served = host === config.authHost || domainOf(host, config.domains) !== undefined;\n return { status: served ? status.ok : status.forbidden };\n};\n\nconst CustomDomains = Schema.NullOr(Schema.Array(Schema.String));\n\n/** The fields of frps's NewProxy plugin request that decide whether a proxy is allowed. */\nconst NewProxyContent = Schema.Struct({\n custom_domains: Schema.optionalKey(CustomDomains),\n proxy_type: Schema.String,\n subdomain: Schema.optionalKey(Schema.String),\n});\n\nconst NewProxyRequest = Schema.fromJsonString(Schema.Struct({ content: NewProxyContent }));\n\n/** Why frps must refuse this proxy, or undefined for an http proxy that serves dev hosts only. */\nconst contentProblem = (content: typeof NewProxyContent.Type, config: ServerConfig) => {\n const hosts = content.custom_domains ?? [];\n if (content.proxy_type !== 'http') {\n return `only http proxies are allowed, not ${content.proxy_type}`;\n }\n if ((content.subdomain ?? '') !== '' || hosts.length === 0) {\n return 'http proxies must name their dev hosts in customDomains';\n }\n const foreign = hosts.find((host) => domainOf(host, config.domains) === undefined);\n return foreign === undefined ? undefined : `${foreign} is not under a configured domain`;\n};\n\nconst proxyProblem = (body: string, config: ServerConfig) =>\n Option.match(Schema.decodeUnknownOption(NewProxyRequest)(body), {\n onNone: () => 'unreadable NewProxy request',\n onSome: ({ content }) => contentProblem(content, config),\n });\n\nconst readBody = async (request: IncomingMessage) => {\n let body = '';\n for await (const chunk of request) {\n body += String(chunk);\n if (body.length > maxBodyLength) {\n throw new Error('request body too large');\n }\n }\n return body;\n};\n\n/** Frps server plugin, NewProxy op: frps accepts the proxy only when `reject` is false. */\nconst newProxy = async (request: IncomingMessage, config: ServerConfig): Promise<Reply> => {\n const problem = proxyProblem(await readBody(request), config);\n const answer = { reject: problem !== undefined, reject_reason: problem ?? '', unchange: true };\n return {\n body: JSON.stringify(answer),\n headers: { 'content-type': 'application/json' },\n status: status.ok,\n };\n};\n\n/** Routes for Caddy and frps, which call on the loopback address. */\nconst internalRoute = (\n request: IncomingMessage,\n path: string,\n { config, query }: { readonly config: ServerConfig; readonly query: Query },\n): Promise<Reply> => {\n if (path === askPath) {\n return Promise.resolve(ask(query, config));\n }\n if (path === newProxyPath && request.method === 'POST') {\n return newProxy(request, config);\n }\n return Promise.resolve(notFound);\n};\n\nexport { askPath, internalRoute, newProxyPath };\n"],"mappings":";;;;AAUA,MAAM,UAAU;AAChB,MAAM,eAAe;AACrB,MAAM,gBAAgB;;AAGtB,MAAM,OAAO,OAAc,WAAgC;CACzD,MAAM,OAAO,MAAM,UAAU;CAE7B,OAAO,EAAE,QADM,SAAS,OAAO,YAAY,SAAS,MAAM,OAAO,OAAO,MAAM,KAAA,IACpD,OAAO,KAAK,OAAO,UAAU;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ACJ,SACA,MACA,EAAE,QAAQ,YACS;CACnB,IAAI,SAAA,QACF,OAAO,QAAQ,QAAQ,IAAI,OAAO,MAAM,CAAC;CAE3C,IAAI,SAAA,qBAAyB,QAAQ,WAAW,QAC9C,OAAO,SAAS,SAAS,MAAM;CAEjC,OAAO,QAAQ,QAAQ,QAAQ;AACjC"}
|
package/dist/listen.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ServerError } from "./errors.js";
|
|
2
|
+
import { readRootCa } from "./root-ca.js";
|
|
3
|
+
import { createCodeStore } from "./session.js";
|
|
4
|
+
import { authPort, loopback } from "./render.js";
|
|
5
|
+
import { createSignIn } from "./auth.js";
|
|
6
|
+
import { createAuthService } from "./service.js";
|
|
7
|
+
import { Console, Effect } from "effect";
|
|
8
|
+
// src/listen.ts
|
|
9
|
+
/** Binds the auth service for the scope. */
|
|
10
|
+
const serve = (server) => Effect.acquireRelease(Effect.callback((resume) => {
|
|
11
|
+
server.once("error", (error) => {
|
|
12
|
+
const message = `the auth service cannot listen on ${loopback}:${authPort}: ${error.message}`;
|
|
13
|
+
resume(Effect.fail(new ServerError({ message })));
|
|
14
|
+
});
|
|
15
|
+
server.listen(authPort, loopback, () => {
|
|
16
|
+
resume(Effect.void);
|
|
17
|
+
});
|
|
18
|
+
}), () => Effect.sync(() => {
|
|
19
|
+
server.close();
|
|
20
|
+
}));
|
|
21
|
+
/** The auth service, listening on the loopback address for the scope. */
|
|
22
|
+
const serveAuth = (config) => serve(createAuthService({
|
|
23
|
+
codes: createCodeStore(),
|
|
24
|
+
config,
|
|
25
|
+
now: Date.now,
|
|
26
|
+
rootCa: readRootCa(config),
|
|
27
|
+
signIn: createSignIn(config)
|
|
28
|
+
})).pipe(Effect.andThen(Console.log(`auth listening on ${loopback}:${authPort}`)));
|
|
29
|
+
export { serveAuth };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=listen.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"listen.js","names":[],"sources":["../src/listen.ts"],"sourcesContent":["import type { Server } from 'node:http';\n\nimport type { ServerConfig } from '@tafrahq/wt-tunnel-contract/server-config';\nimport { Console, Effect } from 'effect';\n\nimport { createSignIn } from './auth.ts';\nimport { ServerError } from './errors.ts';\nimport { authPort, loopback } from './render.ts';\nimport { readRootCa } from './root-ca.ts';\nimport { createAuthService } from './service.ts';\nimport { createCodeStore } from './session.ts';\n\n/** Binds the auth service for the scope. */\nconst serve = (server: Server) =>\n Effect.acquireRelease(\n Effect.callback<void, ServerError>((resume) => {\n server.once('error', (error: Readonly<Error>) => {\n const message = `the auth service cannot listen on ${loopback}:${authPort}: ${error.message}`;\n resume(Effect.fail(new ServerError({ message })));\n });\n server.listen(authPort, loopback, () => {\n resume(Effect.void);\n });\n }),\n () =>\n Effect.sync(() => {\n server.close();\n }),\n );\n\n/** The auth service, listening on the loopback address for the scope. */\nconst serveAuth = (config: ServerConfig) =>\n serve(\n createAuthService({\n codes: createCodeStore(),\n config,\n now: Date.now,\n rootCa: readRootCa(config),\n signIn: createSignIn(config),\n }),\n ).pipe(Effect.andThen(Console.log(`auth listening on ${loopback}:${authPort}`)));\n\nexport { serveAuth };\n"],"mappings":";;;;;;;;;AAaA,MAAM,SAAS,WACb,OAAO,eACL,OAAO,UAA6B,WAAW;CAC7C,OAAO,KAAK,UAAU,UAA2B;EAC/C,MAAM,UAAU,qCAAqC,SAAS,GAAG,SAAS,IAAI,MAAM;EACpF,OAAO,OAAO,KAAK,IAAI,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC;CAClD,CAAC;CACD,OAAO,OAAO,UAAU,gBAAgB;EACtC,OAAO,OAAO,IAAI;CACpB,CAAC;AACH,CAAC,SAEC,OAAO,WAAW;CAChB,OAAO,MAAM;AACf,CAAC,CACL;;AAGF,MAAM,aAAa,WACjB,MACE,kBAAkB;CAChB,OAAO,gBAAgB;CACvB;CACA,KAAK,KAAK;CACV,QAAQ,WAAW,MAAM;CACzB,QAAQ,aAAa,MAAM;AAC7B,CAAC,CACH,CAAC,CAAC,KAAK,OAAO,QAAQ,QAAQ,IAAI,qBAAqB,SAAS,GAAG,UAAU,CAAC,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// ../../packages/binaries/src/caddy.ts
|
|
2
|
+
const caddyVersion = "2.11.7";
|
|
3
|
+
const caddyTarball = (target, sha256) => ({
|
|
4
|
+
sha256,
|
|
5
|
+
url: `https://github.com/caddyserver/caddy/releases/download/v${caddyVersion}/caddy_${caddyVersion}_${target}.tar.gz`
|
|
6
|
+
});
|
|
7
|
+
/**
|
|
8
|
+
* SHA-256 of each tarball, computed after it matched the SHA-512 in the release's
|
|
9
|
+
* caddy_2.11.7_checksums.txt. The server's Dockerfile copies Caddy from the image of the same
|
|
10
|
+
* version.
|
|
11
|
+
*/
|
|
12
|
+
const caddyPin = {
|
|
13
|
+
name: "caddy",
|
|
14
|
+
tarballs: {
|
|
15
|
+
"darwin-arm64": caddyTarball("mac_arm64", "cda3030e5d5b13eb9f0b6fb541037f633bddd958c070c5f561d7a5cccb581665"),
|
|
16
|
+
"darwin-x64": caddyTarball("mac_amd64", "110c53e5c093e4cfce6eda787f94f23bef913c309f620fab26b4f678031841ad"),
|
|
17
|
+
"linux-arm64": caddyTarball("linux_arm64", "d8fc6d179a5d283028a472a5618564f6ad8a86fed513e64f032b3b0b7cc45e42"),
|
|
18
|
+
"linux-x64": caddyTarball("linux_amd64", "727b91701a392de6ebc5027509f548bf39979e5216340d0faed8fa5e69c84f8b")
|
|
19
|
+
},
|
|
20
|
+
version: caddyVersion
|
|
21
|
+
};
|
|
22
|
+
export { caddyPin };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=caddy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"caddy.js","names":[],"sources":["../../../../../../packages/binaries/src/caddy.ts"],"sourcesContent":["import type { Pin } from './install.ts';\n\nconst caddyVersion = '2.11.7';\n\nconst caddyTarball = (target: string, sha256: string) => ({\n sha256,\n url: `https://github.com/caddyserver/caddy/releases/download/v${caddyVersion}/caddy_${caddyVersion}_${target}.tar.gz`,\n});\n\n/**\n * SHA-256 of each tarball, computed after it matched the SHA-512 in the release's\n * caddy_2.11.7_checksums.txt. The server's Dockerfile copies Caddy from the image of the same\n * version.\n */\nconst caddyPin: Pin = {\n name: 'caddy',\n tarballs: {\n 'darwin-arm64': caddyTarball(\n 'mac_arm64',\n 'cda3030e5d5b13eb9f0b6fb541037f633bddd958c070c5f561d7a5cccb581665',\n ),\n 'darwin-x64': caddyTarball(\n 'mac_amd64',\n '110c53e5c093e4cfce6eda787f94f23bef913c309f620fab26b4f678031841ad',\n ),\n 'linux-arm64': caddyTarball(\n 'linux_arm64',\n 'd8fc6d179a5d283028a472a5618564f6ad8a86fed513e64f032b3b0b7cc45e42',\n ),\n 'linux-x64': caddyTarball(\n 'linux_amd64',\n '727b91701a392de6ebc5027509f548bf39979e5216340d0faed8fa5e69c84f8b',\n ),\n },\n version: caddyVersion,\n};\n\nexport { caddyPin };\n"],"mappings":";AAEA,MAAM,eAAe;AAErB,MAAM,gBAAgB,QAAgB,YAAoB;CACxD;CACA,KAAK,2DAA2D,aAAa,SAAS,aAAa,GAAG,OAAO;AAC/G;;;;;;AAOA,MAAM,WAAgB;CACpB,MAAM;CACN,UAAU;EACR,gBAAgB,aACd,aACA,kEACF;EACA,cAAc,aACZ,aACA,kEACF;EACA,eAAe,aACb,eACA,kEACF;EACA,aAAa,aACX,eACA,kEACF;CACF;CACA,SAAS;AACX"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// ../../packages/binaries/src/frp.ts
|
|
2
|
+
const frpVersion = "0.71.1";
|
|
3
|
+
/** Node's `process.arch` names to Go's, which frp's release names use. */
|
|
4
|
+
const goArch = {
|
|
5
|
+
arm64: "arm64",
|
|
6
|
+
x64: "amd64"
|
|
7
|
+
};
|
|
8
|
+
/** From the release's frp_sha256_checksums.txt. A tarball that does not match is never unpacked. */
|
|
9
|
+
const frpTarballs = [
|
|
10
|
+
[
|
|
11
|
+
"darwin",
|
|
12
|
+
"x64",
|
|
13
|
+
"8acb59b6fb998cc8d209d1373d90bf70fa5ec3efeb4dfbc7bda6ce3abd78cb45"
|
|
14
|
+
],
|
|
15
|
+
[
|
|
16
|
+
"darwin",
|
|
17
|
+
"arm64",
|
|
18
|
+
"d15d0324b99e14619c9aa46e37f6db588c06a09be4bc6f7948890b6b61077842"
|
|
19
|
+
],
|
|
20
|
+
[
|
|
21
|
+
"linux",
|
|
22
|
+
"x64",
|
|
23
|
+
"1d9875210972a5d1a62b2dc4c48df45ab0af05d3ca1b5e494a014428259df803"
|
|
24
|
+
],
|
|
25
|
+
[
|
|
26
|
+
"linux",
|
|
27
|
+
"arm64",
|
|
28
|
+
"8edf590b0c396fa42f9c147121a76af83cfc2002b08f5aef0ea1008c43482019"
|
|
29
|
+
]
|
|
30
|
+
];
|
|
31
|
+
/**
|
|
32
|
+
* One frp tarball holds both frpc and frps, so the client's frpc and the server's frps come from
|
|
33
|
+
* one pinned release.
|
|
34
|
+
*/
|
|
35
|
+
const frpPin = (name) => ({
|
|
36
|
+
name,
|
|
37
|
+
tarballs: Object.fromEntries(frpTarballs.map(([platform, arch, sha256]) => [`${platform}-${arch}`, {
|
|
38
|
+
sha256,
|
|
39
|
+
url: `https://github.com/fatedier/frp/releases/download/v${frpVersion}/frp_${frpVersion}_${platform}_${goArch[arch]}.tar.gz`
|
|
40
|
+
}])),
|
|
41
|
+
version: frpVersion
|
|
42
|
+
});
|
|
43
|
+
export { frpPin };
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=frp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"frp.js","names":[],"sources":["../../../../../../packages/binaries/src/frp.ts"],"sourcesContent":["import type { Pin } from './install.ts';\n\nconst frpVersion = '0.71.1';\n\n/** Node's `process.arch` names to Go's, which frp's release names use. */\nconst goArch = { arm64: 'arm64', x64: 'amd64' } as const;\n\n/** From the release's frp_sha256_checksums.txt. A tarball that does not match is never unpacked. */\nconst frpTarballs = [\n ['darwin', 'x64', '8acb59b6fb998cc8d209d1373d90bf70fa5ec3efeb4dfbc7bda6ce3abd78cb45'],\n ['darwin', 'arm64', 'd15d0324b99e14619c9aa46e37f6db588c06a09be4bc6f7948890b6b61077842'],\n ['linux', 'x64', '1d9875210972a5d1a62b2dc4c48df45ab0af05d3ca1b5e494a014428259df803'],\n ['linux', 'arm64', '8edf590b0c396fa42f9c147121a76af83cfc2002b08f5aef0ea1008c43482019'],\n] as const;\n\n/**\n * One frp tarball holds both frpc and frps, so the client's frpc and the server's frps come from\n * one pinned release.\n */\nconst frpPin = (name: 'frpc' | 'frps'): Pin => ({\n name,\n tarballs: Object.fromEntries(\n frpTarballs.map(([platform, arch, sha256]) => [\n `${platform}-${arch}`,\n {\n sha256,\n url: `https://github.com/fatedier/frp/releases/download/v${frpVersion}/frp_${frpVersion}_${platform}_${goArch[arch]}.tar.gz`,\n },\n ]),\n ),\n version: frpVersion,\n});\n\nexport { frpPin };\n"],"mappings":";AAEA,MAAM,aAAa;;AAGnB,MAAM,SAAS;CAAE,OAAO;CAAS,KAAK;AAAQ;;AAG9C,MAAM,cAAc;CAClB;EAAC;EAAU;EAAO;CAAkE;CACpF;EAAC;EAAU;EAAS;CAAkE;CACtF;EAAC;EAAS;EAAO;CAAkE;CACnF;EAAC;EAAS;EAAS;CAAkE;AACvF;;;;;AAMA,MAAM,UAAU,UAAgC;CAC9C;CACA,UAAU,OAAO,YACf,YAAY,KAAK,CAAC,UAAU,MAAM,YAAY,CAC5C,GAAG,SAAS,GAAG,QACf;EACE;EACA,KAAK,sDAAsD,WAAW,OAAO,WAAW,GAAG,SAAS,GAAG,OAAO,MAAM;CACtH,CACF,CAAC,CACH;CACA,SAAS;AACX"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { Console, Effect, Schema } from "effect";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { access, chmod, mkdir, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { gunzip } from "node:zlib";
|
|
8
|
+
// ../../packages/binaries/src/install.ts
|
|
9
|
+
const { TaggedError: taggedErrorClass } = Schema;
|
|
10
|
+
var InstallError = class extends taggedErrorClass()("InstallError", { message: Schema.String }) {};
|
|
11
|
+
const executableMode = 493;
|
|
12
|
+
const tarBlock = 512;
|
|
13
|
+
const tarName = {
|
|
14
|
+
end: 100,
|
|
15
|
+
start: 0
|
|
16
|
+
};
|
|
17
|
+
const tarSize = {
|
|
18
|
+
end: 136,
|
|
19
|
+
start: 124
|
|
20
|
+
};
|
|
21
|
+
const tarType = {
|
|
22
|
+
end: 157,
|
|
23
|
+
start: 156
|
|
24
|
+
};
|
|
25
|
+
const octal = 8;
|
|
26
|
+
/** Old tar writes NUL, ustar writes '0', for a regular file. */
|
|
27
|
+
const regularFileTypes = /* @__PURE__ */ new Set(["0", "\0"]);
|
|
28
|
+
/** A header block's fields; undefined for the zero block that ends the archive. */
|
|
29
|
+
const tarHeader = (block) => {
|
|
30
|
+
const path = block.toString("utf8", tarName.start, tarName.end).replace(/\0.*$/su, "");
|
|
31
|
+
const size = Number.parseInt(block.toString("ascii", tarSize.start, tarSize.end).trim(), octal);
|
|
32
|
+
if (path === "" || Number.isNaN(size)) return;
|
|
33
|
+
return {
|
|
34
|
+
path,
|
|
35
|
+
regularFile: regularFileTypes.has(block.toString("ascii", tarType.start, tarType.end)),
|
|
36
|
+
size
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* The bytes of the regular file named `name` (in any directory) in a tar archive. Reading the one
|
|
41
|
+
* entry in process means nothing in the archive decides which paths get written.
|
|
42
|
+
*/
|
|
43
|
+
const tarEntry = (archive, name) => {
|
|
44
|
+
let offset = 0;
|
|
45
|
+
while (offset + tarBlock <= archive.length) {
|
|
46
|
+
const header = tarHeader(archive.subarray(offset, offset + tarBlock));
|
|
47
|
+
if (header === void 0) return;
|
|
48
|
+
const data = offset + tarBlock;
|
|
49
|
+
if (header.regularFile && basename(header.path) === name) return archive.subarray(data, data + header.size);
|
|
50
|
+
offset = data + Math.ceil(header.size / tarBlock) * tarBlock;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
const fetchBytes = async (url) => {
|
|
54
|
+
const response = await fetch(url);
|
|
55
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
56
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
57
|
+
};
|
|
58
|
+
const installFailed = (pin, message) => new InstallError({ message: `Could not install ${pin.name}: ${message}` });
|
|
59
|
+
/** The rename is atomic, so a concurrent install sees no file or a complete one. */
|
|
60
|
+
const placeExecutable = async (destination, bytes) => {
|
|
61
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
62
|
+
const temp = `${destination}.${process.pid}.tmp`;
|
|
63
|
+
await writeFile(temp, bytes);
|
|
64
|
+
await chmod(temp, executableMode);
|
|
65
|
+
await rename(temp, destination);
|
|
66
|
+
};
|
|
67
|
+
const verifiedDownload = (pin, tarball, download) => Effect.gen(function* downloadThenHash() {
|
|
68
|
+
yield* Console.log(`Downloading ${pin.name} ${pin.version} from ${tarball.url}`);
|
|
69
|
+
const bytes = yield* Effect.tryPromise({
|
|
70
|
+
catch: (cause) => installFailed(pin, `${tarball.url}: ${String(cause)}`),
|
|
71
|
+
try: () => download(tarball.url)
|
|
72
|
+
});
|
|
73
|
+
const actual = createHash("sha256").update(bytes).digest("hex");
|
|
74
|
+
if (actual !== tarball.sha256) return yield* installFailed(pin, `${tarball.url} has SHA-256 ${actual}, expected ${tarball.sha256}. Nothing was installed.`);
|
|
75
|
+
return bytes;
|
|
76
|
+
});
|
|
77
|
+
/** Downloads the tarball, checks its SHA-256, and moves only the pinned executable into place. */
|
|
78
|
+
const installTarballEntry = (pin, { destination, download, tarball }) => Effect.gen(function* downloadVerifyExtract() {
|
|
79
|
+
const bytes = yield* verifiedDownload(pin, tarball, download);
|
|
80
|
+
const archive = yield* Effect.promise(() => promisify(gunzip)(bytes));
|
|
81
|
+
const executable = tarEntry(archive, pin.name);
|
|
82
|
+
if (executable === void 0) return yield* installFailed(pin, `${tarball.url} holds no ${pin.name}.`);
|
|
83
|
+
yield* Effect.promise(() => placeExecutable(destination, executable));
|
|
84
|
+
return destination;
|
|
85
|
+
});
|
|
86
|
+
const tarballFor = (pin, platform, arch) => pin.tarballs[`${platform}-${arch}`];
|
|
87
|
+
/** The user's cache directory: `$XDG_CACHE_HOME`, else the platform's usual place. */
|
|
88
|
+
const cacheHome = () => process.env.XDG_CACHE_HOME ?? (process.platform === "darwin" ? join(homedir(), "Library", "Caches") : join(homedir(), ".cache"));
|
|
89
|
+
const exists = (path) => Effect.promise(async () => {
|
|
90
|
+
try {
|
|
91
|
+
await access(path);
|
|
92
|
+
return true;
|
|
93
|
+
} catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
/** The executable at `destination`, downloaded there on first use. */
|
|
98
|
+
const pinnedBinary = (pin, destination) => Effect.gen(function* cachedOrDownload() {
|
|
99
|
+
if (yield* exists(destination)) return destination;
|
|
100
|
+
const tarball = tarballFor(pin, process.platform, process.arch);
|
|
101
|
+
if (tarball === void 0) return yield* installFailed(pin, `no pinned ${pin.version} build for ${process.platform} ${process.arch}.`);
|
|
102
|
+
return yield* installTarballEntry(pin, {
|
|
103
|
+
destination,
|
|
104
|
+
download: fetchBytes,
|
|
105
|
+
tarball
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
export { InstallError, cacheHome, installTarballEntry, pinnedBinary, tarballFor };
|
|
109
|
+
|
|
110
|
+
//# sourceMappingURL=install.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"install.js","names":[],"sources":["../../../../../../packages/binaries/src/install.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { access, chmod, mkdir, rename, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { gunzip } from 'node:zlib';\n\nimport { Console, Effect, Schema } from 'effect';\n\n/*\n * The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in\n * `Error`, as an error thrown without `new`.\n */\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass InstallError extends taggedErrorClass<InstallError>()('InstallError', {\n message: Schema.String,\n}) {}\n\n/** A release tarball and the SHA-256 it must have. */\ninterface Tarball {\n readonly sha256: string;\n readonly url: string;\n}\n\n/** One executable at one version, with a tarball per `<process.platform>-<process.arch>`. */\ninterface Pin {\n readonly name: string;\n readonly tarballs: Readonly<Partial<Record<string, Tarball>>>;\n readonly version: string;\n}\n\nconst executableMode = 0o755;\n\nconst tarBlock = 512;\nconst tarName = { end: 100, start: 0 } as const;\nconst tarSize = { end: 136, start: 124 } as const;\nconst tarType = { end: 157, start: 156 } as const;\nconst octal = 8;\n/** Old tar writes NUL, ustar writes '0', for a regular file. */\nconst regularFileTypes: ReadonlySet<string> = new Set(['0', '\\0']);\n\n/** A header block's fields; undefined for the zero block that ends the archive. */\nconst tarHeader = (\n block: Buffer,\n): { readonly path: string; readonly regularFile: boolean; readonly size: number } | undefined => {\n const path = block.toString('utf8', tarName.start, tarName.end).replace(/\\0.*$/su, '');\n const size = Number.parseInt(block.toString('ascii', tarSize.start, tarSize.end).trim(), octal);\n if (path === '' || Number.isNaN(size)) {\n return undefined;\n }\n const regularFile = regularFileTypes.has(block.toString('ascii', tarType.start, tarType.end));\n return { path, regularFile, size };\n};\n\n/**\n * The bytes of the regular file named `name` (in any directory) in a tar archive. Reading the one\n * entry in process means nothing in the archive decides which paths get written.\n */\nconst tarEntry = (archive: Buffer, name: string): Buffer | undefined => {\n let offset = 0;\n while (offset + tarBlock <= archive.length) {\n const header = tarHeader(archive.subarray(offset, offset + tarBlock));\n if (header === undefined) {\n return undefined;\n }\n const data = offset + tarBlock;\n if (header.regularFile && basename(header.path) === name) {\n return archive.subarray(data, data + header.size);\n }\n offset = data + Math.ceil(header.size / tarBlock) * tarBlock;\n }\n return undefined;\n};\n\ntype FetchBytes = (url: string) => Promise<Uint8Array>;\n\nconst fetchBytes: FetchBytes = async (url) => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return new Uint8Array(await response.arrayBuffer());\n};\n\nconst installFailed = (pin: Pin, message: string) =>\n new InstallError({ message: `Could not install ${pin.name}: ${message}` });\n\n/** The rename is atomic, so a concurrent install sees no file or a complete one. */\nconst placeExecutable = async (destination: string, bytes: Buffer) => {\n await mkdir(dirname(destination), { recursive: true });\n const temp = `${destination}.${process.pid}.tmp`;\n await writeFile(temp, bytes);\n await chmod(temp, executableMode);\n await rename(temp, destination);\n};\n\nconst verifiedDownload = (pin: Pin, tarball: Tarball, download: FetchBytes) =>\n Effect.gen(function* downloadThenHash() {\n yield* Console.log(`Downloading ${pin.name} ${pin.version} from ${tarball.url}`);\n const bytes = yield* Effect.tryPromise({\n catch: (cause) => installFailed(pin, `${tarball.url}: ${String(cause)}`),\n try: () => download(tarball.url),\n });\n const actual = createHash('sha256').update(bytes).digest('hex');\n if (actual !== tarball.sha256) {\n return yield* installFailed(\n pin,\n `${tarball.url} has SHA-256 ${actual}, expected ${tarball.sha256}. Nothing was installed.`,\n );\n }\n return bytes;\n });\n\n/** Where to install from and to. */\ninterface Install {\n readonly destination: string;\n readonly download: FetchBytes;\n readonly tarball: Tarball;\n}\n\n/** Downloads the tarball, checks its SHA-256, and moves only the pinned executable into place. */\nconst installTarballEntry = (pin: Pin, { destination, download, tarball }: Install) =>\n Effect.gen(function* downloadVerifyExtract() {\n const bytes = yield* verifiedDownload(pin, tarball, download);\n const archive = yield* Effect.promise(() => promisify(gunzip)(bytes));\n const executable = tarEntry(archive, pin.name);\n if (executable === undefined) {\n return yield* installFailed(pin, `${tarball.url} holds no ${pin.name}.`);\n }\n yield* Effect.promise(() => placeExecutable(destination, executable));\n return destination;\n });\n\nconst tarballFor = (pin: Pin, platform: string, arch: string) =>\n pin.tarballs[`${platform}-${arch}`];\n\n/** The user's cache directory: `$XDG_CACHE_HOME`, else the platform's usual place. */\nconst cacheHome = () =>\n process.env.XDG_CACHE_HOME ??\n (process.platform === 'darwin'\n ? join(homedir(), 'Library', 'Caches')\n : join(homedir(), '.cache'));\n\nconst exists = (path: string) =>\n Effect.promise(async () => {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n });\n\n/** The executable at `destination`, downloaded there on first use. */\nconst pinnedBinary = (pin: Pin, destination: string) =>\n Effect.gen(function* cachedOrDownload() {\n if (yield* exists(destination)) {\n return destination;\n }\n const tarball = tarballFor(pin, process.platform, process.arch);\n if (tarball === undefined) {\n return yield* installFailed(\n pin,\n `no pinned ${pin.version} build for ${process.platform} ${process.arch}.`,\n );\n }\n return yield* installTarballEntry(pin, { destination, download: fetchBytes, tarball });\n });\n\nexport { cacheHome, InstallError, installTarballEntry, pinnedBinary, tarballFor };\nexport type { FetchBytes, Install, Pin, Tarball };\n"],"mappings":";;;;;;;;AAaA,MAAM,EAAE,aAAa,qBAAqB;AAE1C,IAAM,eAAN,cAA2B,iBAA+B,CAAC,CAAC,gBAAgB,EAC1E,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;AAeJ,MAAM,iBAAiB;AAEvB,MAAM,WAAW;AACjB,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAE;AACrC,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAI;AACvC,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAI;AACvC,MAAM,QAAQ;;AAEd,MAAM,mCAAwC,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC;;AAGjE,MAAM,aACJ,UACgG;CAChG,MAAM,OAAO,MAAM,SAAS,QAAQ,QAAQ,OAAO,QAAQ,GA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AO;CACT;AACF,CAAC;;AAGH,MAAM,gBAAgB,KAAU,gBAC9B,OAAO,IAAI,UAAU,mBAAmB;CACtC,IAAI,OAAO,OAAO,WAAW,GAC3B,OAAO;CAET,MAAM,UAAU,WAAW,KAAK,QAAQ,UAAU,QAAQ,IAAI;CAC9D,IAAI,YAAY,KAAA,GACd,OAAO,OAAO,cACZ,KACA,aAAa,IAAI,QAAQ,aAAa,QAAQ,SAAS,GAAG,QAAQ,KAAK,EACzE;CAEF,OAAO,OAAO,oBAAoB,KAAK;EAAE;EAAa,UAAU;EAAY;CAAQ,CAAC;AACvF,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
// ../../packages/contract/src/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* A lowercase DNS name with at least two labels: the dev domains, the sign-in host and every dev
|
|
5
|
+
* host. The CLI accepts a domain only if the server could serve it.
|
|
6
|
+
*/
|
|
7
|
+
const Hostname = Schema.String.check(Schema.isPattern(/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u)).pipe(Schema.brand("Hostname"));
|
|
8
|
+
/** The port frps listens on for frpc, and the CLI's default `server.port`. */
|
|
9
|
+
const tunnelPort = 7e3;
|
|
10
|
+
export { Hostname, tunnelPort };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../packages/contract/src/index.ts"],"sourcesContent":["import { Schema } from 'effect';\n\nconst dnsName =\n /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\n\n/**\n * A lowercase DNS name with at least two labels: the dev domains, the sign-in host and every dev\n * host. The CLI accepts a domain only if the server could serve it.\n */\nconst Hostname = Schema.String.check(Schema.isPattern(dnsName)).pipe(Schema.brand('Hostname'));\ntype Hostname = typeof Hostname.Type;\n\n/** The port frps listens on for frpc, and the CLI's default `server.port`. */\nconst tunnelPort = 7000;\n\nexport { Hostname, tunnelPort };\n"],"mappings":";;;;;;AASA,MAAM,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,iGAAO,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,UAAU,CAAC;;AAI7F,MAAM,aAAa"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { X509Certificate } from "node:crypto";
|
|
3
|
+
// ../../packages/contract/src/root-ca.ts
|
|
4
|
+
const der = {
|
|
5
|
+
contextZero: 160,
|
|
6
|
+
dnsName: 130,
|
|
7
|
+
extensions: 163,
|
|
8
|
+
longLengthFlag: 128,
|
|
9
|
+
octetString: 4,
|
|
10
|
+
oid: 6
|
|
11
|
+
};
|
|
12
|
+
const headerBytes = 2;
|
|
13
|
+
/** 2.5.29.30, id-ce-nameConstraints. */
|
|
14
|
+
const nameConstraintsOid = Buffer.from("551d1e", "hex");
|
|
15
|
+
/** The TLV starting at `at`, and where the next one starts. */
|
|
16
|
+
const readTlv = (bytes, at) => {
|
|
17
|
+
const tag = bytes.readUInt8(at);
|
|
18
|
+
const short = bytes.readUInt8(at + 1);
|
|
19
|
+
const lengthBytes = short >= der.longLengthFlag ? short - der.longLengthFlag : 0;
|
|
20
|
+
const length = lengthBytes === 0 ? short : bytes.readUIntBE(at + headerBytes, lengthBytes);
|
|
21
|
+
const start = at + headerBytes + lengthBytes;
|
|
22
|
+
return {
|
|
23
|
+
next: start + length,
|
|
24
|
+
tlv: {
|
|
25
|
+
tag,
|
|
26
|
+
value: bytes.subarray(start, start + length)
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/** The TLVs packed one after another in `bytes`. */
|
|
31
|
+
const readTlvs = (bytes) => {
|
|
32
|
+
const tlvs = [];
|
|
33
|
+
for (let at = 0; at + headerBytes <= bytes.length;) {
|
|
34
|
+
const { next, tlv } = readTlv(bytes, at);
|
|
35
|
+
tlvs.push(tlv);
|
|
36
|
+
at = next;
|
|
37
|
+
}
|
|
38
|
+
return tlvs;
|
|
39
|
+
};
|
|
40
|
+
const firstValue = (bytes) => readTlvs(bytes)[0]?.value ?? Buffer.alloc(0);
|
|
41
|
+
/** The name constraints extension's value, or undefined when the certificate has none. */
|
|
42
|
+
const nameConstraints = (certificate) => {
|
|
43
|
+
const tbs = firstValue(firstValue(certificate));
|
|
44
|
+
const wrapper = readTlvs(tbs).find(({ tag }) => tag === der.extensions);
|
|
45
|
+
return readTlvs(firstValue(wrapper?.value ?? Buffer.alloc(0))).map(({ value }) => readTlvs(value)).find(([id]) => id?.tag === der.oid && id.value.equals(nameConstraintsOid))?.findLast(({ tag }) => tag === der.octetString)?.value;
|
|
46
|
+
};
|
|
47
|
+
/** `NameConstraints ::= SEQUENCE { permittedSubtrees [0] GeneralSubtrees OPTIONAL, ... }`. */
|
|
48
|
+
const permittedDnsNames = (certificate) => {
|
|
49
|
+
const constraints = nameConstraints(certificate);
|
|
50
|
+
const permitted = constraints === void 0 ? void 0 : readTlvs(firstValue(constraints)).find(({ tag }) => tag === der.contextZero);
|
|
51
|
+
return readTlvs(permitted?.value ?? Buffer.alloc(0)).map(({ value }) => readTlvs(value)[0]).filter((name) => name?.tag === der.dnsName).map((name) => name?.value.toString("ascii") ?? "");
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* The label in a wt-tunnel root's common name, or undefined for another subject. Only DNS-name
|
|
55
|
+
* characters, since the trust page puts it in a download's file name.
|
|
56
|
+
*/
|
|
57
|
+
const rootLabel = (certificate) => /^CN=wt-tunnel root \((?<label>[a-z0-9.-]+)\)$/mu.exec(certificate.subject)?.groups?.label;
|
|
58
|
+
Option.liftThrowable((pem) => new X509Certificate(pem));
|
|
59
|
+
export { permittedDnsNames, rootLabel };
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=root-ca.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root-ca.js","names":[],"sources":["../../../../../../packages/contract/src/root-ca.ts"],"sourcesContent":["import { X509Certificate, createPrivateKey, createPublicKey } from 'node:crypto';\n\nimport { Option } from 'effect';\n\n/** A DER tag and its contents. Tags in an X.509 certificate fit in one byte. */\ninterface Tlv {\n readonly tag: number;\n readonly value: Buffer;\n}\n\nconst der = {\n contextZero: 0xa0,\n dnsName: 0x82,\n extensions: 0xa3,\n longLengthFlag: 0x80,\n octetString: 0x04,\n oid: 0x06,\n} as const;\nconst headerBytes = 2;\n/** 2.5.29.30, id-ce-nameConstraints. */\nconst nameConstraintsOid = Buffer.from('551d1e', 'hex');\n\n/** The TLV starting at `at`, and where the next one starts. */\nconst readTlv = (bytes: Buffer, at: number) => {\n const tag = bytes.readUInt8(at);\n const short = bytes.readUInt8(at + 1);\n const lengthBytes = short >= der.longLengthFlag ? short - der.longLengthFlag : 0;\n const length = lengthBytes === 0 ? short : bytes.readUIntBE(at + headerBytes, lengthBytes);\n const start = at + headerBytes + lengthBytes;\n return { next: start + length, tlv: { tag, value: bytes.subarray(start, start + length) } };\n};\n\n/** The TLVs packed one after another in `bytes`. */\nconst readTlvs = (bytes: Buffer): readonly Tlv[] => {\n const tlvs: Tlv[] = [];\n for (let at = 0; at + headerBytes <= bytes.length;) {\n const { next, tlv } = readTlv(bytes, at);\n tlvs.push(tlv);\n at = next;\n }\n return tlvs;\n};\n\nconst firstValue = (bytes: Buffer) => readTlvs(bytes)[0]?.value ?? Buffer.alloc(0);\n\n/** The name constraints extension's value, or undefined when the certificate has none. */\nconst nameConstraints = (certificate: Buffer) => {\n const tbs = firstValue(firstValue(certificate));\n const wrapper = readTlvs(tbs).find(({ tag }) => tag === der.extensions);\n const extensions = readTlvs(firstValue(wrapper?.value ?? Buffer.alloc(0)));\n const fields = extensions\n .map(({ value }) => readTlvs(value))\n .find(([id]) => id?.tag === der.oid && id.value.equals(nameConstraintsOid));\n return fields?.findLast(({ tag }) => tag === der.octetString)?.value;\n};\n\n/** `NameConstraints ::= SEQUENCE { permittedSubtrees [0] GeneralSubtrees OPTIONAL, ... }`. */\nconst permittedDnsNames = (certificate: Buffer): readonly string[] => {\n const constraints = nameConstraints(certificate);\n const permitted =\n constraints === undefined\n ? undefined\n : readTlvs(firstValue(constraints)).find(({ tag }) => tag === der.contextZero);\n return readTlvs(permitted?.value ?? Buffer.alloc(0))\n .map(({ value }) => readTlvs(value)[0])\n .filter((name) => name?.tag === der.dnsName)\n .map((name) => name?.value.toString('ascii') ?? '');\n};\n\n/**\n * The subject's common name a wt-tunnel root carries. The label is only a name; the constraints\n * decide what the root may sign.\n */\nconst rootCommonName = (label: string) => `wt-tunnel root (${label})`;\n\n/**\n * The label in a wt-tunnel root's common name, or undefined for another subject. Only DNS-name\n * characters, since the trust page puts it in a download's file name.\n */\nconst rootLabel = (certificate: X509Certificate) =>\n /^CN=wt-tunnel root \\((?<label>[a-z0-9.-]+)\\)$/mu.exec(certificate.subject)?.groups?.label;\n\n/**\n * Whether a DNS name constraint covers `name`. Without a leading dot it covers the name itself and\n * every name under it; with one, only the names under it.\n */\nconst constraintCovers = (constraint: string, name: string) =>\n constraint.startsWith('.')\n ? name.endsWith(constraint)\n : name === constraint || name.endsWith(`.${constraint}`);\n\nconst spki = (key: ReturnType<typeof createPublicKey>) =>\n key.export({ format: 'der', type: 'spki' });\n\nconst keyMatches = (certificate: X509Certificate, keyPem: string) => {\n try {\n return spki(createPublicKey(createPrivateKey(keyPem))).equals(spki(certificate.publicKey));\n } catch {\n return false;\n }\n};\n\nconst parseCertificate = Option.liftThrowable((pem: string) => new X509Certificate(pem));\n\n/**\n * What makes a root unusable for these domains: a certificate that does not parse, no name\n * constraints, a domain they do not cover, or a key that is not the certificate's. Empty when the\n * root is fine. It reads the constraints the way the trust page does.\n */\nconst rootProblems = (input: {\n readonly cert: string;\n readonly domains: readonly string[];\n readonly key: string;\n}): readonly string[] => {\n const parsed = parseCertificate(input.cert);\n if (Option.isNone(parsed)) {\n return ['ca.cert is not a readable certificate'];\n }\n const certificate = parsed.value;\n const permitted = permittedDnsNames(certificate.raw);\n const uncovered = input.domains.filter(\n (domain) => !permitted.some((constraint) => constraintCovers(constraint, domain)),\n );\n return [\n ...(permitted.length === 0\n ? ['ca.cert has no DNS name constraints, so it could vouch for any site']\n : []),\n ...(permitted.length > 0 && uncovered.length > 0\n ? [\n `ca.cert's name constraints (${permitted.join(', ')}) do not cover ${uncovered.join(', ')}`,\n ]\n : []),\n ...(keyMatches(certificate, input.key) ? [] : ['ca.key is not the key of ca.cert']),\n ];\n};\n\nexport { permittedDnsNames, rootCommonName, rootLabel, rootProblems };\n"],"mappings":";;;AAUA,MAAM,MAAM;CACV,aAAa;CACb,SAAS;CACT,YAAY;CACZ,gBAAgB;CAChB,aAAa;CACb,KAAK;AACP;AACA,MAAM,cAAc;;AAEpB,MAAM,qBAAqB,OAAO,KAAK,UAAU,KAAK;;AAGtD,MAAM,WAAW,OAAe,OAAe;CAC7C,MAAM,MAAM,MAAM,UAAU,EAAE;CAC9B,MAAM,QAAQ,MAAM,UAAU,KAAK,CAAC;CACpC,MAAM,cAAc,SAAS,IAAI,iBAAiB,QAAQ,IAAI,iBAAiB;CAC/E,MAAM,SAAS,gBAAgB,IAAI,QAAQ,MAAM,WAAW,KAAK,aAAa,WAAW;CACzF,MAAM,QAAQ,KAAK,cAAc;CACjC,OAAO;EAAE,MAAM,QAAQ;EAAQ,KAAK;GAAE;GAAK,OAAO,MAAM,SAAS,OAAO,QAAQ,MAAM;EAAE;CAAE;AAC5F;;AAGA,MAAM,YAAY,UAAkC;CAClD,MAAM,OAAc,CAAC;CACrB,KAAK,IAAI,KAAK,GAAG,KAAK,eAAe,MAAM,SAAS;EAClD,MAAM,EAAE,MAAM,QAAQ,QAAQ,OAAO,EAAE;EACvC,KAAK,KAAK,GAAG;EACb,KAAK;CACP;CACA,OAAO;AACT;AAEA,MAAM,cAAc,UAAkB,SAAS,KAAK,CAAC,CAAC,EAAE,EAAE,SAAS,OAAO,MAAM,CAAC;;AAGjF,MAAM,mBAAmB,gBAAwB;CAC/C,MAAM,MAAM,WAAW,WAAW,WAAW,CAAC;CAC9C,MAAM,UAAU,SAAS,GAAG,CAAC,CAAC,MAAM,EAAE,UAAU,QAAQ,IAAI,UAAU;CAKtE,OAJmB,SAAS,WAAW,SAAS,SAAS,OAAO,MAAM,CAAC,CAAC,CAChD,CAAC,CACtB,KAAK,EAAE,YAAY,SAAS,KAAK,CAAC,CAAC,CACnC,MAAM,CAAC,QAAQ,IAAI,QAAQ,IAAI,OAAO,GAAG,MAAM,OAAO,kBAAkB,CAC/D,CAAC,EAAE,UAAU,EAAE,UAAU,QAAQ,IAAI,WAAW,CAAC,EAAE;AACjE;;AAGA,MAAM,qBAAqB,gBAA2C;CACpE,MAAM,cAAc,gBAAgB,WAAW;CAC/C,MAAM,YACJ,gBAAgB,KAAA,IACZ,KAAA,IACA,SAAS,WAAW,WAAW,CAAC,CAAC,CAAC,MAAM,EAAE,UAAU,QAAQ,IAAI,WAAW;CACjF,OAAO,SAAS,WAAW,SAAS,OAAO,MAAM,CAAC,CAAC,CAAC,CACjD,KAAK,EAAE,YAAY,SAAS,KAAK,CAAC,CAAC,EAAE,CAAC,CACtC,QAAQ,SAAS,MAAM,QAAQ,IAAI,OAAO,CAAC,CAC3C,KAAK,SAAS,MAAM,MAAM,SAAS,OAAO,KAAK,EAAE;AACtD;;;;;AAYA,MAAM,aAAa,gBACjB,kDAAkD,KAAK,YAAY,OAAO,CAAC,EAAE,QAAQ;AAsB9D,OAAO,eAAe,QAAgB,IAAI,gBAAgB,GAAG,CAAC"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { Hostname } from "./index.js";
|
|
2
|
+
import { Effect, Redacted, Schema } from "effect";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
// ../../packages/contract/src/server-config.ts
|
|
5
|
+
const authSecretMinLength = 32;
|
|
6
|
+
const tunnelTokenMinLength = 16;
|
|
7
|
+
/** The name `wt-tunnel deploy` writes the config under, and the server looks for by default. */
|
|
8
|
+
const serverConfigFileName = "wt-tunnel-server.json";
|
|
9
|
+
const Email = Schema.String.check(Schema.isPattern(/^[^@\s]+@[^@\s]+$/u));
|
|
10
|
+
const Secret = (minLength) => Schema.RedactedFromValue(Schema.String.check(Schema.isMinLength(minLength)));
|
|
11
|
+
const pemMarkers = {
|
|
12
|
+
cert: /-----BEGIN CERTIFICATE-----/u,
|
|
13
|
+
key: /-----BEGIN (?:EC |RSA )?PRIVATE KEY-----/u
|
|
14
|
+
};
|
|
15
|
+
const AllowList = Schema.Struct({
|
|
16
|
+
emailDomains: Schema.optionalKey(Schema.Array(Hostname)),
|
|
17
|
+
emails: Schema.optionalKey(Schema.Array(Email))
|
|
18
|
+
}).check(Schema.makeFilter((allow) => (allow.emails?.length ?? 0) + (allow.emailDomains?.length ?? 0) > 0 || "allow lists no emails and no email domains"));
|
|
19
|
+
const OAuthClient = {
|
|
20
|
+
clientId: Schema.NonEmptyString,
|
|
21
|
+
clientSecret: Schema.RedactedFromValue(Schema.NonEmptyString)
|
|
22
|
+
};
|
|
23
|
+
/** The sign-in providers a user may pick from, in the order the sign-in page lists them. */
|
|
24
|
+
const providerIds = [
|
|
25
|
+
"google",
|
|
26
|
+
"github",
|
|
27
|
+
"microsoft",
|
|
28
|
+
"cloudflare"
|
|
29
|
+
];
|
|
30
|
+
/**
|
|
31
|
+
* Where people sign in. Each provider is optional, and at least one must be set. `microsoft` takes
|
|
32
|
+
* the Entra ID tenant (default `common`, any account). `cloudflare` is a Cloudflare Access OIDC app
|
|
33
|
+
* in the Zero Trust team at `teamDomain`, such as `acme.cloudflareaccess.com`.
|
|
34
|
+
*/
|
|
35
|
+
const MicrosoftClient = Schema.Struct({
|
|
36
|
+
...OAuthClient,
|
|
37
|
+
tenantId: Schema.optionalKey(Schema.NonEmptyString)
|
|
38
|
+
});
|
|
39
|
+
const Providers = Schema.Struct({
|
|
40
|
+
cloudflare: Schema.optionalKey(Schema.Struct({
|
|
41
|
+
...OAuthClient,
|
|
42
|
+
teamDomain: Hostname
|
|
43
|
+
})),
|
|
44
|
+
github: Schema.optionalKey(Schema.Struct(OAuthClient)),
|
|
45
|
+
google: Schema.optionalKey(Schema.Struct(OAuthClient)),
|
|
46
|
+
microsoft: Schema.optionalKey(MicrosoftClient)
|
|
47
|
+
}).check(Schema.makeFilter((providers) => providerIds.some((id) => providers[id] !== void 0) || `providers sets none of ${providerIds.join(", ")}`));
|
|
48
|
+
/**
|
|
49
|
+
* The tunnel server's config file. The server decodes it at startup; the wt-tunnel CLI writes it
|
|
50
|
+
* and checks it against this same schema before deploying.
|
|
51
|
+
*/
|
|
52
|
+
const ServerConfigFile = Schema.Struct({
|
|
53
|
+
allow: AllowList,
|
|
54
|
+
/** The sign-in host, shared by every dev domain. */
|
|
55
|
+
authHost: Hostname,
|
|
56
|
+
/** Keys Better Auth and the dev-domain session cookie. */
|
|
57
|
+
authSecret: Secret(authSecretMinLength),
|
|
58
|
+
/**
|
|
59
|
+
* The name-constrained root that issues every dev-host certificate: its PEM files, relative to
|
|
60
|
+
* the config file's directory.
|
|
61
|
+
*/
|
|
62
|
+
ca: Schema.Struct({
|
|
63
|
+
cert: Schema.NonEmptyString,
|
|
64
|
+
key: Schema.NonEmptyString
|
|
65
|
+
}),
|
|
66
|
+
domains: Schema.NonEmptyArray(Hostname),
|
|
67
|
+
providers: Providers,
|
|
68
|
+
/** Shared secret that frpc presents to frps. */
|
|
69
|
+
tunnelToken: Secret(tunnelTokenMinLength)
|
|
70
|
+
});
|
|
71
|
+
const ServerConfigFileJson = Schema.fromJsonString(ServerConfigFile);
|
|
72
|
+
const { TaggedError: taggedErrorClass } = Schema;
|
|
73
|
+
var ServerConfigError = class extends taggedErrorClass()("ServerConfigError", { message: Schema.String }) {};
|
|
74
|
+
/** Where a `ca` path in a config file in `dir` points. */
|
|
75
|
+
const caFile = (dir, file) => isAbsolute(file) ? file : join(dir, file);
|
|
76
|
+
/**
|
|
77
|
+
* Decodes a config file's text, reads the root's files relative to `dir` with `read`, and checks
|
|
78
|
+
* that they hold PEM. Every schema problem is reported at once.
|
|
79
|
+
*/
|
|
80
|
+
const readServerConfig = (input) => Effect.gen(function* readConfig() {
|
|
81
|
+
const invalid = (message) => new ServerConfigError({ message: `${input.source} is not a valid server config: ${message}` });
|
|
82
|
+
const file = yield* Schema.decodeUnknownEffect(ServerConfigFileJson)(input.text, { errors: "all" }).pipe(Effect.mapError((schemaError) => invalid(schemaError.message)));
|
|
83
|
+
/** Never echoes the file's content: the key is secret. */
|
|
84
|
+
const readCa = (field) => {
|
|
85
|
+
const path = caFile(input.dir, file.ca[field]);
|
|
86
|
+
return input.read(path).pipe(Effect.mapError(() => invalid(`cannot read ca.${field} at ${path}`)), Effect.filterOrFail((text) => pemMarkers[field].test(text), () => invalid(`ca.${field} at ${path} holds no PEM ${field === "cert" ? "certificate" : "private key"}`)));
|
|
87
|
+
};
|
|
88
|
+
const ca = {
|
|
89
|
+
cert: yield* readCa("cert"),
|
|
90
|
+
key: Redacted.make(yield* readCa("key"))
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
...file,
|
|
94
|
+
ca
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
export { AllowList, Providers, ServerConfigError, ServerConfigFile, ServerConfigFileJson, caFile, providerIds, readServerConfig, serverConfigFileName };
|
|
98
|
+
|
|
99
|
+
//# sourceMappingURL=server-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-config.js","names":[],"sources":["../../../../../../packages/contract/src/server-config.ts"],"sourcesContent":["import { isAbsolute, join } from 'node:path';\n\nimport { Effect, Redacted, Schema } from 'effect';\n\nimport { Hostname } from './index.ts';\n\nconst authSecretMinLength = 32;\nconst tunnelTokenMinLength = 16;\n\n/** The name `wt-tunnel deploy` writes the config under, and the server looks for by default. */\nconst serverConfigFileName = 'wt-tunnel-server.json';\n\nconst Email = Schema.String.check(Schema.isPattern(/^[^@\\s]+@[^@\\s]+$/u));\n\nconst Secret = (minLength: number) =>\n Schema.RedactedFromValue(Schema.String.check(Schema.isMinLength(minLength)));\n\nconst pemMarkers = {\n cert: /-----BEGIN CERTIFICATE-----/u,\n key: /-----BEGIN (?:EC |RSA )?PRIVATE KEY-----/u,\n} as const;\n\nconst AllowList = Schema.Struct({\n emailDomains: Schema.optionalKey(Schema.Array(Hostname)),\n emails: Schema.optionalKey(Schema.Array(Email)),\n}).check(\n Schema.makeFilter(\n (allow) =>\n (allow.emails?.length ?? 0) + (allow.emailDomains?.length ?? 0) > 0 ||\n 'allow lists no emails and no email domains',\n ),\n);\n\nconst OAuthClient = {\n clientId: Schema.NonEmptyString,\n clientSecret: Schema.RedactedFromValue(Schema.NonEmptyString),\n};\n\n/** The sign-in providers a user may pick from, in the order the sign-in page lists them. */\nconst providerIds = ['google', 'github', 'microsoft', 'cloudflare'] as const;\ntype ProviderId = (typeof providerIds)[number];\n\n/**\n * Where people sign in. Each provider is optional, and at least one must be set. `microsoft` takes\n * the Entra ID tenant (default `common`, any account). `cloudflare` is a Cloudflare Access OIDC app\n * in the Zero Trust team at `teamDomain`, such as `acme.cloudflareaccess.com`.\n */\nconst MicrosoftClient = Schema.Struct({\n ...OAuthClient,\n tenantId: Schema.optionalKey(Schema.NonEmptyString),\n});\n\nconst Providers = Schema.Struct({\n cloudflare: Schema.optionalKey(Schema.Struct({ ...OAuthClient, teamDomain: Hostname })),\n github: Schema.optionalKey(Schema.Struct(OAuthClient)),\n google: Schema.optionalKey(Schema.Struct(OAuthClient)),\n microsoft: Schema.optionalKey(MicrosoftClient),\n}).check(\n Schema.makeFilter(\n (providers) =>\n providerIds.some((id) => providers[id] !== undefined) ||\n `providers sets none of ${providerIds.join(', ')}`,\n ),\n);\ntype Providers = typeof Providers.Type;\n\n/**\n * The tunnel server's config file. The server decodes it at startup; the wt-tunnel CLI writes it\n * and checks it against this same schema before deploying.\n */\nconst ServerConfigFile = Schema.Struct({\n allow: AllowList,\n /** The sign-in host, shared by every dev domain. */\n authHost: Hostname,\n /** Keys Better Auth and the dev-domain session cookie. */\n authSecret: Secret(authSecretMinLength),\n /**\n * The name-constrained root that issues every dev-host certificate: its PEM files, relative to\n * the config file's directory.\n */\n ca: Schema.Struct({ cert: Schema.NonEmptyString, key: Schema.NonEmptyString }),\n domains: Schema.NonEmptyArray(Hostname),\n providers: Providers,\n /** Shared secret that frpc presents to frps. */\n tunnelToken: Secret(tunnelTokenMinLength),\n});\ntype ServerConfigFile = typeof ServerConfigFile.Type;\n\nconst ServerConfigFileJson = Schema.fromJsonString(ServerConfigFile);\n\n/** The config as the server holds it: the root's PEM text in place of its file names. */\ninterface ServerConfig extends Omit<ServerConfigFile, 'ca'> {\n readonly ca: { readonly cert: string; readonly key: Redacted.Redacted };\n}\n\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass ServerConfigError extends taggedErrorClass<ServerConfigError>()('ServerConfigError', {\n message: Schema.String,\n}) {}\n\n/** Where a `ca` path in a config file in `dir` points. */\nconst caFile = (dir: string, file: string) => (isAbsolute(file) ? file : join(dir, file));\n\n/**\n * Decodes a config file's text, reads the root's files relative to `dir` with `read`, and checks\n * that they hold PEM. Every schema problem is reported at once.\n */\nconst readServerConfig = <ReadError>(input: {\n readonly dir: string;\n readonly read: (file: string) => Effect.Effect<string, ReadError>;\n readonly source: string;\n readonly text: string;\n}) =>\n Effect.gen(function* readConfig() {\n const invalid = (message: string) =>\n new ServerConfigError({\n message: `${input.source} is not a valid server config: ${message}`,\n });\n const file = yield* Schema.decodeUnknownEffect(ServerConfigFileJson)(input.text, {\n errors: 'all',\n }).pipe(Effect.mapError((schemaError) => invalid(schemaError.message)));\n /** Never echoes the file's content: the key is secret. */\n const readCa = (field: keyof typeof pemMarkers) => {\n const path = caFile(input.dir, file.ca[field]);\n return input.read(path).pipe(\n Effect.mapError(() => invalid(`cannot read ca.${field} at ${path}`)),\n Effect.filterOrFail(\n (text) => pemMarkers[field].test(text),\n () =>\n invalid(\n `ca.${field} at ${path} holds no PEM ${field === 'cert' ? 'certificate' : 'private key'}`,\n ),\n ),\n );\n };\n const ca = { cert: yield* readCa('cert'), key: Redacted.make(yield* readCa('key')) };\n const config: ServerConfig = { ...file, ca };\n return config;\n });\n\nexport {\n AllowList,\n Providers,\n providerIds,\n ServerConfigError,\n ServerConfigFile,\n ServerConfigFileJson,\n caFile,\n readServerConfig,\n serverConfigFileName,\n};\nexport type { ProviderId, ServerConfig };\n"],"mappings":";;;;AAMA,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;;AAG7B,MAAM,uBAAuB;AAE7B,MAAM,QAAQ,OAAO,OAAO,MAAM,OAAO,UAAU,oBAAoB,CAAC;AAExE,MAAM,UAAU,cACd,OAAO,kBAAkB,OAAO,OAAO,MAAM,OAAO,YAAY,SAAS,CAAC,CAAC;AAE7E,MAAM,aAAa;CACjB,MAAM;CACN,KAAK;AACP;AAEA,MAAM,YAAY,OAAO,OAAO;CAC9B,cAAc,OAAO,YAAY,OAAO,MAAM,QAAQ,CAAC;CACvD,QAAQ,OAAO,YAAY,OAAO,MAAM,KAAK,CAAC;AAChD,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,WACE,MAAM,QAAQ,UAAU,MAAM,MAAM,cAAc,UAAU,KAAK,KAClE,4CACJ,CACF;AAEA,MAAM,cAAc;CAClB,UAAU,OAAO;CACjB,cAAc,OAAO,kBAAkB,OAAO,cAAc;AAC9D;;AAGA,MAAM,cAAc;CAAC;CAAU;CAAU;CAAa;AAAY;;;;;;AAQlE,MAAM,kBAAkB,OAAO,OAAO;CACpC,GAAG;CACH,UAAU,OAAO,YAAY,OAAO,cAAc;AACpD,CAAC;AAED,MAAM,YAAY,OAAO,OAAO;CAC9B,YAAY,OAAO,YAAY,OAAO,OAAO;EAAE,GAAG;EAAa,YAAY;CAAS,CAAC,CAAC;CACtF,QA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B,MAAM,MAAM,MAAM,CAAC,GACnE,OAAO,cACJ,SAAS,WAAW,MAAM,CAAC,KAAK,IAAI,SAEnC,QACE,MAAM,MAAM,MAAM,KAAK,gBAAgB,UAAU,SAAS,gBAAgB,eAC5E,CACJ,CACF;CACF;CACA,MAAM,KAAK;EAAE,MAAM,OAAO,OAAO,MAAM;EAAG,KAAK,SAAS,KAAK,OAAO,OAAO,KAAK,CAAC;CAAE;CAEnF,OAAO;EADwB,GAAG;EAAM;CAC5B;AACd,CAAC"}
|
package/dist/ready.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { readyMessage } from "./daemon.js";
|
|
2
|
+
import { loopback } from "./render.js";
|
|
3
|
+
import { Console, Effect } from "effect";
|
|
4
|
+
import { connect } from "node:net";
|
|
5
|
+
// src/ready.ts
|
|
6
|
+
const pollInterval = "100 millis";
|
|
7
|
+
const ignoreSendError = () => {};
|
|
8
|
+
const accepts = (port) => Effect.callback((resume) => {
|
|
9
|
+
const socket = connect({
|
|
10
|
+
host: loopback,
|
|
11
|
+
port
|
|
12
|
+
});
|
|
13
|
+
const settle = (open) => () => {
|
|
14
|
+
socket.destroy();
|
|
15
|
+
resume(Effect.succeed(open));
|
|
16
|
+
};
|
|
17
|
+
socket.once("connect", settle(true));
|
|
18
|
+
socket.once("error", settle(false));
|
|
19
|
+
});
|
|
20
|
+
const allAccept = (ports) => Effect.all([
|
|
21
|
+
ports.https,
|
|
22
|
+
ports.http,
|
|
23
|
+
ports.tunnel
|
|
24
|
+
].map((port) => accepts(port))).pipe(Effect.map((open) => open.every(Boolean)));
|
|
25
|
+
/**
|
|
26
|
+
* Waits until Caddy and frps accept connections on every public port, then logs `ready` and tells
|
|
27
|
+
* the parent of a detached server over IPC.
|
|
28
|
+
*/
|
|
29
|
+
const announceWhenReady = (ports) => Effect.gen(function* pollThenAnnounce() {
|
|
30
|
+
while (!(yield* allAccept(ports))) yield* Effect.sleep(pollInterval);
|
|
31
|
+
yield* Console.log(`ready: https on :${ports.https}, http on :${ports.http}, tunnel on :${ports.tunnel}`);
|
|
32
|
+
process.send?.(readyMessage, void 0, void 0, ignoreSendError);
|
|
33
|
+
});
|
|
34
|
+
export { announceWhenReady };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=ready.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ready.js","names":[],"sources":["../src/ready.ts"],"sourcesContent":["import { connect } from 'node:net';\n\nimport { Console, Effect } from 'effect';\n\nimport { readyMessage } from './daemon.ts';\nimport { loopback } from './render.ts';\nimport type { Ports } from './render.ts';\n\nconst pollInterval = '100 millis';\n\nconst ignoreSendError = () => {\n // A detached server outlives a parent that was killed while waiting for it.\n};\n\nconst accepts = (port: number) =>\n Effect.callback<boolean>((resume) => {\n const socket = connect({ host: loopback, port });\n const settle = (open: boolean) => () => {\n socket.destroy();\n resume(Effect.succeed(open));\n };\n socket.once('connect', settle(true));\n socket.once('error', settle(false));\n });\n\nconst allAccept = (ports: Ports) =>\n Effect.all([ports.https, ports.http, ports.tunnel].map((port) => accepts(port))).pipe(\n Effect.map((open: readonly boolean[]) => open.every(Boolean)),\n );\n\n/**\n * Waits until Caddy and frps accept connections on every public port, then logs `ready` and tells\n * the parent of a detached server over IPC.\n */\nconst announceWhenReady = (ports: Ports) =>\n Effect.gen(function* pollThenAnnounce() {\n while (!(yield* allAccept(ports))) {\n yield* Effect.sleep(pollInterval);\n }\n yield* Console.log(\n `ready: https on :${ports.https}, http on :${ports.http}, tunnel on :${ports.tunnel}`,\n );\n /*\n * With a callback, a parent that has already gone away is an error passed to it rather than an\n * 'error' event that would crash the server and orphan Caddy and frps.\n */\n process.send?.(readyMessage, undefined, undefined, ignoreSendError);\n });\n\nexport { announceWhenReady };\n"],"mappings":";;;;;AAQA,MAAM,eAAe;AAErB,MAAM,wBAAwB,CAE9B;AAEA,MAAM,WAAW,SACf,OAAO,UAAmB,WAAW;CACnC,MAAM,SAAS,QAAQ;EAAE,MAAM;EAAU;CAAK,CAAC;CAC/C,MAAM,UAAU,eAAwB;EACtC,OAAO,QAAQ;EACf,OAAO,OAAO,QAAQ,IAAI,CAAC;CAC7B;CACA,OAAO,KAAK,WAAW,OAAO,IAAI,CAAC;CACnC,OAAO,KAAK,SAAS,OAAO,KAAK,CAAC;AACpC,CAAC;AAEH,MAAM,aAAa,UACjB,OAAO,IAAI;CAAC,MAAM;CAAO,MAAM;CAAM,MAAM;AAAM,CAAC,CAAC,KAAK,SAAS,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAC,KAC/E,OAAO,KAAK,SAA6B,KAAK,MAAM,OAAO,CAAC,CAC9D;;;;;AAMF,MAAM,qBAAqB,UACzB,OAAO,IAAI,UAAU,mBAAmB;CACtC,OAAO,EAAE,OAAO,UAAU,KAAK,IAC7B,OAAO,OAAO,MAAM,YAAY;CAElC,OAAO,QAAQ,IACb,oBAAoB,MAAM,MAAM,aAAa,MAAM,KAAK,eAAe,MAAM,QAC/E;CAKA,QAAQ,OAAO,cAAc,KAAA,GAAW,KAAA,GAAW,eAAe;AACpE,CAAC"}
|