@tafrahq/wt-tunnel-client 0.0.0-stage → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +168 -2
- package/dist/bin.js +15 -0
- package/dist/bin.js.map +1 -0
- package/dist/cli-commands.js +27 -0
- package/dist/cli-commands.js.map +1 -0
- package/dist/cli-provision.js +25 -0
- package/dist/cli-provision.js.map +1 -0
- package/dist/cli-status.js +19 -0
- package/dist/cli-status.js.map +1 -0
- package/dist/cli-workspace.js +38 -0
- package/dist/cli-workspace.js.map +1 -0
- package/dist/cli-worktree.js +40 -0
- package/dist/cli-worktree.js.map +1 -0
- package/dist/cli.js +9 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.js +70 -0
- package/dist/config.js.map +1 -0
- package/dist/domain.js +26 -0
- package/dist/domain.js.map +1 -0
- package/dist/errno.js +6 -0
- package/dist/errno.js.map +1 -0
- package/dist/errors.js +7 -0
- package/dist/errors.js.map +1 -0
- package/dist/exec.js +18 -0
- package/dist/exec.js.map +1 -0
- package/dist/files.js +18 -0
- package/dist/files.js.map +1 -0
- package/dist/frpc-binary.js +16 -0
- package/dist/frpc-binary.js.map +1 -0
- package/dist/frpc-config.js +47 -0
- package/dist/frpc-config.js.map +1 -0
- package/dist/packages/binaries/src/frp.js +45 -0
- package/dist/packages/binaries/src/frp.js.map +1 -0
- package/dist/packages/binaries/src/install.js +110 -0
- package/dist/packages/binaries/src/install.js.map +1 -0
- package/dist/packages/contract/src/bin.js +20 -0
- package/dist/packages/contract/src/bin.js.map +1 -0
- package/dist/packages/contract/src/index.js +12 -0
- package/dist/packages/contract/src/index.js.map +1 -0
- package/dist/ports.js +121 -0
- package/dist/ports.js.map +1 -0
- package/dist/processes.js +118 -0
- package/dist/processes.js.map +1 -0
- package/dist/provision-frpc.js +100 -0
- package/dist/provision-frpc.js.map +1 -0
- package/dist/provision-ports.js +75 -0
- package/dist/provision-ports.js.map +1 -0
- package/dist/provision.js +28 -0
- package/dist/provision.js.map +1 -0
- package/dist/state.js +53 -0
- package/dist/state.js.map +1 -0
- package/dist/worktree.js +25 -0
- package/dist/worktree.js.map +1 -0
- package/llms.txt +33 -0
- package/package.json +64 -3
- package/src/bin.ts +14 -0
- package/src/cli-commands.ts +40 -0
- package/src/cli-provision.ts +34 -0
- package/src/cli-status.ts +29 -0
- package/src/cli-workspace.ts +78 -0
- package/src/cli-worktree.ts +62 -0
- package/src/cli.ts +15 -0
- package/src/config.ts +101 -0
- package/src/domain.ts +51 -0
- package/src/errno.ts +5 -0
- package/src/errors.ts +13 -0
- package/src/exec.ts +18 -0
- package/src/files.ts +20 -0
- package/src/frpc-binary.ts +27 -0
- package/src/frpc-config.ts +69 -0
- package/src/ports.ts +177 -0
- package/src/processes.ts +163 -0
- package/src/provision-frpc.ts +152 -0
- package/src/provision-ports.ts +116 -0
- package/src/provision.ts +41 -0
- package/src/resource.ts +28 -0
- package/src/state.ts +87 -0
- package/src/worktree.ts +52 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { Effect } from 'effect';
|
|
5
|
+
import { Command } from 'effect/cli';
|
|
6
|
+
|
|
7
|
+
import { loadWorkspace } from './config.ts';
|
|
8
|
+
import type { WtTunnelConfig } from './config.ts';
|
|
9
|
+
import { WtTunnelError } from './errors.ts';
|
|
10
|
+
import { routedApps } from './provision-ports.ts';
|
|
11
|
+
import type { ProvisionContext } from './resource.ts';
|
|
12
|
+
import { readState } from './state.ts';
|
|
13
|
+
import type { WorktreeState } from './state.ts';
|
|
14
|
+
import { stateFileOf, worktreeAt } from './worktree.ts';
|
|
15
|
+
import type { Worktree } from './worktree.ts';
|
|
16
|
+
|
|
17
|
+
/** The worktree root containing the current directory, and its config. */
|
|
18
|
+
const workspace = Effect.suspend(() => loadWorkspace(process.cwd()));
|
|
19
|
+
|
|
20
|
+
interface CurrentWorktree {
|
|
21
|
+
readonly config: WtTunnelConfig;
|
|
22
|
+
readonly state: WorktreeState;
|
|
23
|
+
readonly worktree: Worktree;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The provisioned worktree root containing the current directory; its names come from state. */
|
|
27
|
+
const currentWorktree = Effect.gen(function* worktreeOfCwd() {
|
|
28
|
+
const { root, config } = yield* workspace;
|
|
29
|
+
const state = yield* readState(stateFileOf(root));
|
|
30
|
+
if (state === undefined) {
|
|
31
|
+
return yield* new WtTunnelError({
|
|
32
|
+
message: `${root} is not provisioned. Run \`wt-tunnel-client worktree add <project> <worktree>\` first.`,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const current: CurrentWorktree = {
|
|
36
|
+
config,
|
|
37
|
+
state,
|
|
38
|
+
worktree: worktreeAt(root, state.project, state.worktree),
|
|
39
|
+
};
|
|
40
|
+
return current;
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** A command without arguments that acts on the worktree containing the current directory. */
|
|
44
|
+
const currentWorktreeCommand = <Failure, Requirements>(
|
|
45
|
+
name: string,
|
|
46
|
+
description: string,
|
|
47
|
+
action: (current: CurrentWorktree) => Effect.Effect<void, Failure, Requirements>,
|
|
48
|
+
) =>
|
|
49
|
+
Command.make(name, {}, () =>
|
|
50
|
+
currentWorktree.pipe(Effect.flatMap((current) => action(current))),
|
|
51
|
+
).pipe(Command.withDescription(description));
|
|
52
|
+
|
|
53
|
+
const prepareStateDir = (worktree: Worktree) =>
|
|
54
|
+
Effect.promise(async () => {
|
|
55
|
+
await mkdir(worktree.stateDir, { recursive: true });
|
|
56
|
+
// Self-ignoring, so the user's repo needs no .gitignore entry.
|
|
57
|
+
await writeFile(join(worktree.stateDir, '.gitignore'), '*\n');
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/** The `NAME=value` lines of the worktree's env file. */
|
|
61
|
+
const envLines = (worktree: Worktree) =>
|
|
62
|
+
Effect.promise(() => readFile(worktree.envFile, 'utf8')).pipe(
|
|
63
|
+
Effect.map((text) => text.split('\n').filter(Boolean)),
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
interface AppUrl {
|
|
67
|
+
readonly port: number;
|
|
68
|
+
readonly url: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const urls = (context: ProvisionContext, state: WorktreeState) =>
|
|
72
|
+
routedApps(context, state.ports).map(({ hostname, port }): AppUrl => ({
|
|
73
|
+
port,
|
|
74
|
+
url: `https://${hostname}`,
|
|
75
|
+
}));
|
|
76
|
+
|
|
77
|
+
export { currentWorktree, currentWorktreeCommand, envLines, prepareStateDir, urls, workspace };
|
|
78
|
+
export type { CurrentWorktree };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { rm } from 'node:fs/promises';
|
|
2
|
+
|
|
3
|
+
import { Console, Effect } from 'effect';
|
|
4
|
+
import { Argument, Command } from 'effect/cli';
|
|
5
|
+
|
|
6
|
+
import { provisionUp } from './cli-provision.ts';
|
|
7
|
+
import { currentWorktree, workspace } from './cli-workspace.ts';
|
|
8
|
+
import { removeAll, worktreeResources } from './provision.ts';
|
|
9
|
+
import { startingState } from './state.ts';
|
|
10
|
+
import { parseProjectName, parseWorktreeName, worktreeAt } from './worktree.ts';
|
|
11
|
+
|
|
12
|
+
const add = Command.make(
|
|
13
|
+
'add',
|
|
14
|
+
{
|
|
15
|
+
project: Argument.String('project').pipe(
|
|
16
|
+
Argument.withDescription(
|
|
17
|
+
'Project name, a DNS label. The tunnel server knows the worktree as <project>.<worktree>.',
|
|
18
|
+
),
|
|
19
|
+
),
|
|
20
|
+
worktree: Argument.String('worktree').pipe(
|
|
21
|
+
Argument.withDescription(
|
|
22
|
+
'Worktree name, a DNS label. URLs are https://<app>.<worktree>.<domain>.',
|
|
23
|
+
),
|
|
24
|
+
),
|
|
25
|
+
},
|
|
26
|
+
(input) =>
|
|
27
|
+
Effect.gen(function* addWorktree() {
|
|
28
|
+
const { root, config } = yield* workspace;
|
|
29
|
+
const project = yield* parseProjectName(input.project);
|
|
30
|
+
const name = yield* parseWorktreeName(input.worktree);
|
|
31
|
+
const worktree = worktreeAt(root, project, name);
|
|
32
|
+
const state = yield* startingState(worktree, config.domain);
|
|
33
|
+
return yield* provisionUp({ config, worktree }, state);
|
|
34
|
+
}),
|
|
35
|
+
).pipe(
|
|
36
|
+
Command.withDescription(
|
|
37
|
+
'Give the directory holding wt-tunnel.json (the worktree root) its private URLs',
|
|
38
|
+
),
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
const remove = Command.make('remove', {}, () =>
|
|
42
|
+
Effect.gen(function* removeWorktree() {
|
|
43
|
+
const { config, state, worktree } = yield* currentWorktree;
|
|
44
|
+
yield* removeAll({ config, worktree }, state);
|
|
45
|
+
const removed = worktreeResources.map((resource) => resource.name);
|
|
46
|
+
yield* Effect.promise(() => rm(worktree.stateDir, { force: true, recursive: true }));
|
|
47
|
+
yield* Console.log(
|
|
48
|
+
`Removed ${state.project} ${state.worktree}: its ${removed.join(', ')} and ${worktree.stateDir} are gone.`,
|
|
49
|
+
);
|
|
50
|
+
}),
|
|
51
|
+
).pipe(
|
|
52
|
+
Command.withDescription(
|
|
53
|
+
"Stop this worktree's frpc, release its ports and delete its .wt-tunnel directory",
|
|
54
|
+
),
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
const worktreeCommand = Command.make('worktree').pipe(
|
|
58
|
+
Command.withDescription('Provision and remove worktree roots'),
|
|
59
|
+
Command.withSubcommands([add, remove]),
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
export { worktreeCommand };
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Command } from 'effect/cli';
|
|
2
|
+
|
|
3
|
+
import { worktreeCommands } from './cli-commands.ts';
|
|
4
|
+
import { worktreeCommand } from './cli-worktree.ts';
|
|
5
|
+
|
|
6
|
+
const cli = Command.make('wt-tunnel-client').pipe(
|
|
7
|
+
Command.withDescription(
|
|
8
|
+
'Private HTTPS URLs for every git worktree, through your own tunnel server',
|
|
9
|
+
),
|
|
10
|
+
Command.withSubcommands([worktreeCommand, ...worktreeCommands]),
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
const run = (version: string) => Command.run(cli, { version });
|
|
14
|
+
|
|
15
|
+
export { run };
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { Hostname } from '@tafrahq/wt-tunnel-contract';
|
|
2
|
+
import { Array, Effect, FileSystem, Path, Schema } from 'effect';
|
|
3
|
+
|
|
4
|
+
import { AppLabel, EnvName, Port, ServerHost } from './domain.ts';
|
|
5
|
+
import { WtTunnelError } from './errors.ts';
|
|
6
|
+
|
|
7
|
+
const configFileName = 'wt-tunnel.json';
|
|
8
|
+
|
|
9
|
+
const AppConfig = Schema.Struct({
|
|
10
|
+
/** Pin the port instead of letting wt-tunnel reserve one. */
|
|
11
|
+
port: Schema.optionalKey(Port),
|
|
12
|
+
portEnv: EnvName,
|
|
13
|
+
/** `false` for services that only need a port, such as a database. */
|
|
14
|
+
route: Schema.optionalKey(Schema.Boolean),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
/** The tunnel server that every worktree's frpc connects to (docs/server-mode.md). */
|
|
18
|
+
const ServerConfig = Schema.Struct({
|
|
19
|
+
host: ServerHost,
|
|
20
|
+
port: Schema.optionalKey(Port),
|
|
21
|
+
});
|
|
22
|
+
type ServerConfig = typeof ServerConfig.Type;
|
|
23
|
+
|
|
24
|
+
const WtTunnelConfig = Schema.Struct({
|
|
25
|
+
apps: Schema.Record(AppLabel, AppConfig),
|
|
26
|
+
domain: Hostname,
|
|
27
|
+
server: ServerConfig,
|
|
28
|
+
});
|
|
29
|
+
type WtTunnelConfig = typeof WtTunnelConfig.Type;
|
|
30
|
+
|
|
31
|
+
const ConfigJson = Schema.fromJsonString(WtTunnelConfig);
|
|
32
|
+
|
|
33
|
+
const firstDuplicate = <Value>(values: readonly Value[]) =>
|
|
34
|
+
values.find((value, index) => values.indexOf(value) !== index);
|
|
35
|
+
|
|
36
|
+
/** What the schema cannot express: at least one app, and no port variable or pin used twice. */
|
|
37
|
+
const appsProblem = (apps: WtTunnelConfig['apps'], source: string): string | undefined => {
|
|
38
|
+
const envs = Object.values(apps).map((app) => app.portEnv);
|
|
39
|
+
if (!Array.isReadonlyArrayNonEmpty(envs)) {
|
|
40
|
+
return `${source} must define at least one app`;
|
|
41
|
+
}
|
|
42
|
+
const duplicate = firstDuplicate(envs);
|
|
43
|
+
if (duplicate !== undefined) {
|
|
44
|
+
return `${source} uses portEnv ${duplicate} twice`;
|
|
45
|
+
}
|
|
46
|
+
const clash = firstDuplicate(
|
|
47
|
+
Object.values(apps).flatMap((app) => (app.port === undefined ? [] : [app.port])),
|
|
48
|
+
);
|
|
49
|
+
return clash === undefined ? undefined : `${source} pins port ${clash} twice`;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const decodeConfig = (text: string, source: string) =>
|
|
53
|
+
Effect.gen(function* decodeAndCheck() {
|
|
54
|
+
const config = yield* Schema.decodeUnknownEffect(ConfigJson)(text).pipe(
|
|
55
|
+
Effect.mapError(
|
|
56
|
+
(schemaError) =>
|
|
57
|
+
new WtTunnelError({ message: `${source} is not a valid config: ${schemaError.message}` }),
|
|
58
|
+
),
|
|
59
|
+
);
|
|
60
|
+
const problem = appsProblem(config.apps, source);
|
|
61
|
+
if (problem !== undefined) {
|
|
62
|
+
return yield* new WtTunnelError({ message: problem });
|
|
63
|
+
}
|
|
64
|
+
return config;
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The worktree root: the nearest directory at or above `start` that holds wt-tunnel.json. Its
|
|
69
|
+
* `.wt-tunnel/` holds the state of what it serves.
|
|
70
|
+
*/
|
|
71
|
+
const findRoot = (start: string) =>
|
|
72
|
+
Effect.gen(function* walkUp() {
|
|
73
|
+
const fs = yield* FileSystem.FileSystem;
|
|
74
|
+
const path = yield* Path.Path;
|
|
75
|
+
let dir = path.resolve(start);
|
|
76
|
+
while (!(yield* fs.exists(path.join(dir, configFileName)).pipe(Effect.orDie))) {
|
|
77
|
+
const parent = path.dirname(dir);
|
|
78
|
+
if (parent === dir) {
|
|
79
|
+
return yield* new WtTunnelError({
|
|
80
|
+
message: `No ${configFileName} in ${start} or any directory above it. Run wt-tunnel-client from inside a checkout that has one.`,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
dir = parent;
|
|
84
|
+
}
|
|
85
|
+
return dir;
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
/** The root containing `start` and the config in it. */
|
|
89
|
+
const loadWorkspace = (start: string) =>
|
|
90
|
+
Effect.gen(function* readConfigFile() {
|
|
91
|
+
const fs = yield* FileSystem.FileSystem;
|
|
92
|
+
const path = yield* Path.Path;
|
|
93
|
+
const root = yield* findRoot(start);
|
|
94
|
+
const file = path.join(root, configFileName);
|
|
95
|
+
const text = yield* fs.readFileString(file).pipe(Effect.orDie);
|
|
96
|
+
const config = yield* decodeConfig(text, file);
|
|
97
|
+
return { config, root };
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
export { decodeConfig, loadWorkspace };
|
|
101
|
+
export type { ServerConfig, WtTunnelConfig };
|
package/src/domain.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
|
|
3
|
+
import { Hostname } from '@tafrahq/wt-tunnel-contract';
|
|
4
|
+
import { Brand, Schema } from 'effect';
|
|
5
|
+
|
|
6
|
+
const dnsLabel = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
|
|
7
|
+
const portMin = 1;
|
|
8
|
+
const portMax = 65_535;
|
|
9
|
+
|
|
10
|
+
const DnsLabel = Schema.String.check(Schema.isPattern(dnsLabel));
|
|
11
|
+
|
|
12
|
+
const WorktreeName = DnsLabel.pipe(Schema.brand('WorktreeName'));
|
|
13
|
+
type WorktreeName = typeof WorktreeName.Type;
|
|
14
|
+
|
|
15
|
+
const ProjectName = DnsLabel.pipe(Schema.brand('ProjectName'));
|
|
16
|
+
type ProjectName = typeof ProjectName.Type;
|
|
17
|
+
|
|
18
|
+
const AppLabel = DnsLabel.pipe(Schema.brand('AppLabel'));
|
|
19
|
+
type AppLabel = typeof AppLabel.Type;
|
|
20
|
+
|
|
21
|
+
const Port = Schema.Int.check(Schema.isBetween({ maximum: portMax, minimum: portMin })).pipe(
|
|
22
|
+
Schema.brand('Port'),
|
|
23
|
+
);
|
|
24
|
+
type Port = typeof Port.Type;
|
|
25
|
+
|
|
26
|
+
const isHostname = Schema.is(Hostname);
|
|
27
|
+
const isIpOrHostname = (value: string) =>
|
|
28
|
+
isIP(value) !== 0 || isHostname(value) || 'expected an IP address or a host name';
|
|
29
|
+
const ServerHost = Schema.String.check(Schema.makeFilter(isIpOrHostname));
|
|
30
|
+
|
|
31
|
+
const EnvName = Schema.String.check(Schema.isPattern(/^[A-Z_][A-Z0-9_]*$/u));
|
|
32
|
+
|
|
33
|
+
/** Brands host names this module builds from already valid parts, without re-validating them. */
|
|
34
|
+
const trustedHostname = Brand.nominal<Hostname>();
|
|
35
|
+
|
|
36
|
+
const worktreeZone = (worktree: WorktreeName, domain: Hostname): Hostname =>
|
|
37
|
+
trustedHostname(`${worktree}.${domain}`);
|
|
38
|
+
|
|
39
|
+
const hostnameFor = (app: AppLabel, worktree: WorktreeName, domain: Hostname): Hostname =>
|
|
40
|
+
trustedHostname(`${app}.${worktreeZone(worktree, domain)}`);
|
|
41
|
+
|
|
42
|
+
export {
|
|
43
|
+
AppLabel,
|
|
44
|
+
EnvName,
|
|
45
|
+
hostnameFor,
|
|
46
|
+
Port,
|
|
47
|
+
ProjectName,
|
|
48
|
+
ServerHost,
|
|
49
|
+
WorktreeName,
|
|
50
|
+
worktreeZone,
|
|
51
|
+
};
|
package/src/errno.ts
ADDED
package/src/errors.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Schema } from 'effect';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in
|
|
5
|
+
* `Error`, as an error thrown without `new`.
|
|
6
|
+
*/
|
|
7
|
+
const { TaggedError: taggedErrorClass } = Schema;
|
|
8
|
+
|
|
9
|
+
class WtTunnelError extends taggedErrorClass<WtTunnelError>()('WtTunnelError', {
|
|
10
|
+
message: Schema.String,
|
|
11
|
+
}) {}
|
|
12
|
+
|
|
13
|
+
export { WtTunnelError };
|
package/src/exec.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
import { Effect } from 'effect';
|
|
4
|
+
|
|
5
|
+
interface ExecFailure {
|
|
6
|
+
readonly cause: unknown;
|
|
7
|
+
readonly stderr: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Runs a program to completion and yields its stdout; a non-zero exit fails with its stderr. */
|
|
11
|
+
const execFileText = (file: string, args: readonly string[], cwd?: string) =>
|
|
12
|
+
Effect.callback<string, ExecFailure>((resume) => {
|
|
13
|
+
execFile(file, [...args], { cwd, encoding: 'utf8' }, (failure: unknown, stdout, stderr) => {
|
|
14
|
+
resume(failure === null ? Effect.succeed(stdout) : Effect.fail({ cause: failure, stderr }));
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export { execFileText };
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { access, readFile } from 'node:fs/promises';
|
|
2
|
+
|
|
3
|
+
/** Like `existsSync`: false for any path that cannot be accessed. */
|
|
4
|
+
const pathExists = async (path: string) => {
|
|
5
|
+
try {
|
|
6
|
+
await access(path);
|
|
7
|
+
return true;
|
|
8
|
+
} catch {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const readTextIfExists = async (file: string): Promise<string | undefined> => {
|
|
14
|
+
if (!(await pathExists(file))) {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
return readFile(file, 'utf8');
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export { pathExists, readTextIfExists };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
|
|
3
|
+
import { cacheHome, pinnedBinary } from '@tafrahq/wt-tunnel-binaries';
|
|
4
|
+
import { frpPin } from '@tafrahq/wt-tunnel-binaries/frp';
|
|
5
|
+
import { Effect } from 'effect';
|
|
6
|
+
|
|
7
|
+
import { WtTunnelError } from './errors.ts';
|
|
8
|
+
|
|
9
|
+
const pin = frpPin('frpc');
|
|
10
|
+
|
|
11
|
+
/** `WT_TUNNEL_FRPC`, else the cached frpc, downloaded on first use. */
|
|
12
|
+
const frpcBinary = Effect.suspend(() => {
|
|
13
|
+
const override = process.env.WT_TUNNEL_FRPC;
|
|
14
|
+
if (override !== undefined && override !== '') {
|
|
15
|
+
return Effect.succeed(override);
|
|
16
|
+
}
|
|
17
|
+
return pinnedBinary(pin, join(cacheHome(), 'wt-tunnel', 'frp', pin.version, 'frpc')).pipe(
|
|
18
|
+
Effect.mapError(
|
|
19
|
+
({ message }: { readonly message: string }) =>
|
|
20
|
+
new WtTunnelError({
|
|
21
|
+
message: `${message} Set WT_TUNNEL_FRPC to an frpc ${pin.version} binary instead.`,
|
|
22
|
+
}),
|
|
23
|
+
),
|
|
24
|
+
);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export { frpcBinary };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { tunnelPort } from '@tafrahq/wt-tunnel-contract';
|
|
2
|
+
import { Effect, Redacted } from 'effect';
|
|
3
|
+
|
|
4
|
+
import type { ServerConfig } from './config.ts';
|
|
5
|
+
import { WtTunnelError } from './errors.ts';
|
|
6
|
+
import type { RoutedApp } from './provision-ports.ts';
|
|
7
|
+
import type { Worktree } from './worktree.ts';
|
|
8
|
+
|
|
9
|
+
const tokenEnv = 'WT_TUNNEL_SERVER_TOKEN';
|
|
10
|
+
|
|
11
|
+
/** `host:port` of frps, with an IPv6 address in brackets as in a URL. */
|
|
12
|
+
const serverEndpoint = (server: ServerConfig) => {
|
|
13
|
+
const host = server.host.includes(':') ? `[${server.host}]` : server.host;
|
|
14
|
+
return `${host}:${server.port ?? tunnelPort}`;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** JSON's string escapes are valid in TOML basic strings. */
|
|
18
|
+
const tomlString = (value: string) => JSON.stringify(value);
|
|
19
|
+
|
|
20
|
+
const proxyLines = ({ app, hostname, port }: RoutedApp) => [
|
|
21
|
+
'',
|
|
22
|
+
'[[proxies]]',
|
|
23
|
+
`name = ${tomlString(app)}`,
|
|
24
|
+
'type = "http"',
|
|
25
|
+
'localIP = "127.0.0.1"',
|
|
26
|
+
`localPort = ${port}`,
|
|
27
|
+
`customDomains = [${tomlString(hostname)}]`,
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The config of a worktree's frpc. The token is a frp template that frpc fills in from its
|
|
32
|
+
* environment when it reads the file, so the token is never written down.
|
|
33
|
+
*/
|
|
34
|
+
const renderFrpcConfig = (
|
|
35
|
+
server: ServerConfig,
|
|
36
|
+
worktree: Pick<Worktree, 'name' | 'project'>,
|
|
37
|
+
apps: readonly RoutedApp[],
|
|
38
|
+
) =>
|
|
39
|
+
[
|
|
40
|
+
'# Written by wt-tunnel-client up.',
|
|
41
|
+
`serverAddr = ${tomlString(server.host)}`,
|
|
42
|
+
`serverPort = ${server.port ?? tunnelPort}`,
|
|
43
|
+
// The server names each proxy `<user>.<name>`. DNS labels hold no dot, so no two apps share one.
|
|
44
|
+
`user = ${tomlString(`${worktree.project}.${worktree.name}`)}`,
|
|
45
|
+
'loginFailExit = true',
|
|
46
|
+
'auth.method = "token"',
|
|
47
|
+
`auth.token = "{{ .Envs.${tokenEnv} }}"`,
|
|
48
|
+
'transport.tls.enable = true',
|
|
49
|
+
'log.to = "console"',
|
|
50
|
+
'log.disablePrintColor = true',
|
|
51
|
+
...apps.flatMap((app) => proxyLines(app)),
|
|
52
|
+
'',
|
|
53
|
+
].join('\n');
|
|
54
|
+
|
|
55
|
+
const serverToken = Effect.suspend(() => {
|
|
56
|
+
const token = process.env[tokenEnv];
|
|
57
|
+
return token === undefined || token === ''
|
|
58
|
+
? Effect.fail(
|
|
59
|
+
new WtTunnelError({
|
|
60
|
+
message: `Set ${tokenEnv} to the tunnel server's token (tunnelToken in its config).`,
|
|
61
|
+
}),
|
|
62
|
+
)
|
|
63
|
+
: Effect.succeed(Redacted.make(token));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
/** The environment that hands the token to frpc. */
|
|
67
|
+
const tokenEnvironment = (token: Redacted.Redacted) => ({ [tokenEnv]: Redacted.value(token) });
|
|
68
|
+
|
|
69
|
+
export { renderFrpcConfig, serverEndpoint, serverToken, tokenEnvironment };
|
package/src/ports.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { createServer } from 'node:net';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { Effect, Schema } from 'effect';
|
|
7
|
+
|
|
8
|
+
import { Port } from './domain.ts';
|
|
9
|
+
import { errorCode } from './errno.ts';
|
|
10
|
+
import { pathExists } from './files.ts';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Below Linux's ephemeral range (32768-60999), so the kernel never hands these ports to outgoing
|
|
14
|
+
* connections.
|
|
15
|
+
*/
|
|
16
|
+
const portRange = { first: 20_000, last: 29_999 } as const;
|
|
17
|
+
/** How many ports `portRange` holds, both ends included. */
|
|
18
|
+
const portCount = 10_000;
|
|
19
|
+
/** A stale claim is deleted once and the create retried; a second loss means someone else won. */
|
|
20
|
+
const claimAttempts = 2;
|
|
21
|
+
const loopback = '127.0.0.1';
|
|
22
|
+
|
|
23
|
+
type Claim =
|
|
24
|
+
| { readonly _tag: 'claimed' }
|
|
25
|
+
| { readonly _tag: 'ours' }
|
|
26
|
+
| { readonly _tag: 'taken'; readonly owner: string };
|
|
27
|
+
|
|
28
|
+
/** One claim attempt either settles the claim or deletes a stale one so the next can retry. */
|
|
29
|
+
type Attempt = Claim | { readonly _tag: 'staleRemoved' };
|
|
30
|
+
|
|
31
|
+
/** The part of an owner's state.json that says which ports it still uses. */
|
|
32
|
+
const PortsByApp = Schema.Record(Schema.String, Schema.Number);
|
|
33
|
+
const OwnerState = Schema.fromJsonString(Schema.Struct({ ports: Schema.optionalKey(PortsByApp) }));
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* One file per reserved port, shared by every worktree of every repo for this user. The file holds
|
|
37
|
+
* the owning worktree's directory. Only files, no daemon.
|
|
38
|
+
*/
|
|
39
|
+
const reservationsDir = () => {
|
|
40
|
+
const base =
|
|
41
|
+
process.env.WT_TUNNEL_STATE_DIR ??
|
|
42
|
+
join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'wt-tunnel');
|
|
43
|
+
return join(base, 'ports');
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Exclusive create is the lock: of two worktrees claiming one port, exactly one wins. */
|
|
47
|
+
const createExclusive = async (file: string, owner: string) => {
|
|
48
|
+
try {
|
|
49
|
+
await writeFile(file, owner, { flag: 'wx' });
|
|
50
|
+
return true;
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (errorCode(error) !== 'EEXIST') {
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A claim whose owner directory is gone, or whose owner's state no longer lists the port, is left
|
|
61
|
+
* over from a worktree deleted without `remove`.
|
|
62
|
+
*/
|
|
63
|
+
const isStale = (owner: string, port: number) =>
|
|
64
|
+
Effect.gen(function* ownerStillUsesPort() {
|
|
65
|
+
if (!(yield* Effect.promise(() => pathExists(owner)))) {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
return yield* Effect.tryPromise(() =>
|
|
69
|
+
readFile(join(owner, '.wt-tunnel', 'state.json'), 'utf8'),
|
|
70
|
+
).pipe(
|
|
71
|
+
Effect.flatMap(Schema.decodeUnknownEffect(OwnerState)),
|
|
72
|
+
Effect.map((state) => !Object.values(state.ports ?? {}).includes(port)),
|
|
73
|
+
// No readable state yet: the owner may be mid-add, so keep its claim.
|
|
74
|
+
Effect.orElseSucceed(() => false),
|
|
75
|
+
);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const readOwner = (file: string) => Effect.promise(() => readFile(file, 'utf8'));
|
|
79
|
+
|
|
80
|
+
const attemptClaim = (file: string, port: number, owner: string): Effect.Effect<Attempt> =>
|
|
81
|
+
Effect.gen(function* createOrInspect() {
|
|
82
|
+
if (yield* Effect.promise(() => createExclusive(file, owner))) {
|
|
83
|
+
return { _tag: 'claimed' };
|
|
84
|
+
}
|
|
85
|
+
const current = yield* readOwner(file);
|
|
86
|
+
if (current === owner) {
|
|
87
|
+
return { _tag: 'ours' };
|
|
88
|
+
}
|
|
89
|
+
if (!(yield* isStale(current, port))) {
|
|
90
|
+
return { _tag: 'taken', owner: current };
|
|
91
|
+
}
|
|
92
|
+
yield* Effect.promise(() => unlink(file));
|
|
93
|
+
return { _tag: 'staleRemoved' };
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const claim = (dir: string, port: number, owner: string): Effect.Effect<Claim> =>
|
|
97
|
+
Effect.gen(function* claimPortFile() {
|
|
98
|
+
yield* Effect.promise(() => mkdir(dir, { recursive: true }));
|
|
99
|
+
const file = join(dir, String(port));
|
|
100
|
+
for (let attempt = 0; attempt < claimAttempts; attempt++) {
|
|
101
|
+
const result = yield* attemptClaim(file, port, owner);
|
|
102
|
+
if (result._tag !== 'staleRemoved') {
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { _tag: 'taken', owner: yield* readOwner(file) };
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const unlinkIfOwned = async (file: string, owner: string) => {
|
|
110
|
+
try {
|
|
111
|
+
if ((await readFile(file, 'utf8')) === owner) {
|
|
112
|
+
await unlink(file);
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
// Released concurrently.
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/** Releases this owner's claims, except the ports it still uses. */
|
|
120
|
+
const release = (dir: string, owner: string, keep: readonly number[] = []) =>
|
|
121
|
+
Effect.gen(function* releaseOwnedFiles() {
|
|
122
|
+
if (!(yield* Effect.promise(() => pathExists(dir)))) {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
for (const name of yield* Effect.promise(() => readdir(dir))) {
|
|
126
|
+
if (!keep.includes(Number(name))) {
|
|
127
|
+
yield* Effect.promise(() => unlinkIfOwned(join(dir, name), owner));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
const isListening = (port: number) =>
|
|
133
|
+
Effect.callback<boolean>((resume) => {
|
|
134
|
+
const server = createServer();
|
|
135
|
+
server.once('error', () => {
|
|
136
|
+
resume(Effect.succeed(true));
|
|
137
|
+
});
|
|
138
|
+
server.listen(port, loopback, () => {
|
|
139
|
+
server.close(() => {
|
|
140
|
+
resume(Effect.succeed(false));
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
/** Claims `port` unless another worktree holds it or some program already listens on it. */
|
|
146
|
+
const reserveIfFree = (dir: string, owner: string, port: number) =>
|
|
147
|
+
Effect.gen(function* claimUnlessBusy() {
|
|
148
|
+
const result = yield* claim(dir, port, owner);
|
|
149
|
+
if (result._tag === 'taken') {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
if (result._tag === 'claimed' && (yield* isListening(port))) {
|
|
153
|
+
yield* Effect.promise(() => unlink(join(dir, String(port))));
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
return true;
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Reserves a port nobody has claimed and nothing is listening on, starting from a random point in
|
|
161
|
+
* the range so concurrent worktrees rarely contend.
|
|
162
|
+
*/
|
|
163
|
+
const allocate = (dir: string, owner: string, avoid: readonly number[]) =>
|
|
164
|
+
Effect.gen(function* firstFreePort() {
|
|
165
|
+
const start = Math.floor(Math.random() * portCount);
|
|
166
|
+
for (let index = 0; index < portCount; index++) {
|
|
167
|
+
const port = portRange.first + ((start + index) % portCount);
|
|
168
|
+
if (!avoid.includes(port) && (yield* reserveIfFree(dir, owner, port))) {
|
|
169
|
+
return Port.make(port);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return yield* Effect.die(
|
|
173
|
+
new Error(`every port in ${portRange.first}-${portRange.last} is reserved`),
|
|
174
|
+
);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
export { allocate, claim, portRange, release, reservationsDir };
|