echo-t3-bridge 0.0.0-stage → 0.1.1
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 +59 -2
- package/dist/cli.mjs +2309 -0
- package/dist/tsc/antigravity-quota.js +276 -0
- package/dist/tsc/bridge.js +413 -0
- package/dist/tsc/config.js +77 -0
- package/dist/tsc/dpop.js +196 -0
- package/dist/tsc/fs-list.js +38 -0
- package/dist/tsc/index.js +243 -0
- package/dist/tsc/local-t3.js +905 -0
- package/dist/tsc/provider-quotas.js +422 -0
- package/package.json +44 -4
- package/scripts/service.mjs +192 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir, hostname } from 'node:os';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
export const DEFAULT_HUB_SERVER = 'https://wq.stormapex.top';
|
|
5
|
+
export const DEFAULT_LOCAL_T3_URL = 'http://127.0.0.1:3773';
|
|
6
|
+
export const APP_VERSION = '0.1.0';
|
|
7
|
+
export function defaultDataDir() {
|
|
8
|
+
if (process.env.ECHO_T3_BRIDGE_DATA_DIR?.trim()) {
|
|
9
|
+
return resolve(process.env.ECHO_T3_BRIDGE_DATA_DIR.trim());
|
|
10
|
+
}
|
|
11
|
+
if (process.platform === 'darwin') {
|
|
12
|
+
return join(homedir(), 'Library', 'Application Support', 'echo-t3-bridge');
|
|
13
|
+
}
|
|
14
|
+
if (process.platform === 'win32') {
|
|
15
|
+
return join(process.env.APPDATA ?? homedir(), 'echo-t3-bridge');
|
|
16
|
+
}
|
|
17
|
+
return join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'echo-t3-bridge');
|
|
18
|
+
}
|
|
19
|
+
export function defaultConfigPath() {
|
|
20
|
+
if (process.env.ECHO_T3_BRIDGE_CONFIG?.trim()) {
|
|
21
|
+
return resolve(process.env.ECHO_T3_BRIDGE_CONFIG.trim());
|
|
22
|
+
}
|
|
23
|
+
return join(defaultDataDir(), 'config.json');
|
|
24
|
+
}
|
|
25
|
+
export function defaultDeviceLabel() {
|
|
26
|
+
return hostname().replace(/\.local$/i, '') || 'T3 Device';
|
|
27
|
+
}
|
|
28
|
+
export function normalizeServerUrl(raw) {
|
|
29
|
+
const trimmed = raw.trim().replace(/\/+$/, '');
|
|
30
|
+
if (!trimmed)
|
|
31
|
+
return DEFAULT_HUB_SERVER;
|
|
32
|
+
if (!/^https?:\/\//i.test(trimmed)) {
|
|
33
|
+
return `https://${trimmed}`;
|
|
34
|
+
}
|
|
35
|
+
return trimmed;
|
|
36
|
+
}
|
|
37
|
+
export async function loadConfig(configPath = defaultConfigPath()) {
|
|
38
|
+
try {
|
|
39
|
+
const raw = await readFile(configPath, 'utf8');
|
|
40
|
+
const parsed = JSON.parse(raw);
|
|
41
|
+
return {
|
|
42
|
+
version: 1,
|
|
43
|
+
hub: parsed.hub,
|
|
44
|
+
localT3: {
|
|
45
|
+
baseUrl: parsed.localT3?.baseUrl || DEFAULT_LOCAL_T3_URL,
|
|
46
|
+
accessToken: parsed.localT3?.accessToken,
|
|
47
|
+
t3Binary: parsed.localT3?.t3Binary,
|
|
48
|
+
},
|
|
49
|
+
knownThreadIds: Array.isArray(parsed.knownThreadIds) ? parsed.knownThreadIds : [],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return {
|
|
54
|
+
version: 1,
|
|
55
|
+
localT3: {
|
|
56
|
+
baseUrl: DEFAULT_LOCAL_T3_URL,
|
|
57
|
+
},
|
|
58
|
+
knownThreadIds: [],
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export async function saveConfig(config, configPath = defaultConfigPath()) {
|
|
63
|
+
await mkdir(dirname(configPath), { recursive: true, mode: 0o700 });
|
|
64
|
+
const tmpPath = `${configPath}.tmp.${process.pid}`;
|
|
65
|
+
await writeFile(tmpPath, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
|
|
66
|
+
await chmod(tmpPath, 0o600).catch(() => undefined);
|
|
67
|
+
const { rename } = await import('node:fs/promises');
|
|
68
|
+
await rename(tmpPath, configPath);
|
|
69
|
+
}
|
|
70
|
+
export async function clearHubCredentials(configPath = defaultConfigPath()) {
|
|
71
|
+
const cfg = await loadConfig(configPath);
|
|
72
|
+
delete cfg.hub;
|
|
73
|
+
await saveConfig(cfg, configPath);
|
|
74
|
+
}
|
|
75
|
+
export async function removeConfig(configPath = defaultConfigPath()) {
|
|
76
|
+
await unlink(configPath).catch(() => undefined);
|
|
77
|
+
}
|
package/dist/tsc/dpop.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { APP_VERSION, defaultDeviceLabel } from './config.js';
|
|
3
|
+
export const TOKEN_EXCHANGE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
|
|
4
|
+
export const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
|
|
5
|
+
export const BOOTSTRAP_TOKEN_TYPE = 'urn:t3:params:oauth:token-type:environment-bootstrap';
|
|
6
|
+
function base64Url(input) {
|
|
7
|
+
const buf = typeof input === 'string' ? Buffer.from(input, 'utf8') : input;
|
|
8
|
+
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
|
|
9
|
+
}
|
|
10
|
+
export function sha256Base64Url(value) {
|
|
11
|
+
return base64Url(crypto.createHash('sha256').update(value, 'utf8').digest());
|
|
12
|
+
}
|
|
13
|
+
/** Generate a fresh P-256 ECDSA key pair for RFC 9449 DPoP proofs. */
|
|
14
|
+
export function generateDpopKeyPair() {
|
|
15
|
+
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
|
|
16
|
+
namedCurve: 'P-256',
|
|
17
|
+
});
|
|
18
|
+
const jwk = publicKey.export({ format: 'jwk' });
|
|
19
|
+
const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
|
|
20
|
+
return {
|
|
21
|
+
privateKeyPem,
|
|
22
|
+
publicJwk: {
|
|
23
|
+
kty: 'EC',
|
|
24
|
+
crv: 'P-256',
|
|
25
|
+
x: jwk.x,
|
|
26
|
+
y: jwk.y,
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Normalize claim htu: scheme + host + pathname, without query or fragment. */
|
|
31
|
+
export function normalizeHtu(rawUrl) {
|
|
32
|
+
const parsed = new URL(rawUrl);
|
|
33
|
+
if (parsed.protocol === 'wss:')
|
|
34
|
+
parsed.protocol = 'https:';
|
|
35
|
+
else if (parsed.protocol === 'ws:')
|
|
36
|
+
parsed.protocol = 'http:';
|
|
37
|
+
parsed.search = '';
|
|
38
|
+
parsed.hash = '';
|
|
39
|
+
return parsed.toString();
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a compact DPoP JWT signed with ES256 (IEEE-P1363 64-byte signature),
|
|
43
|
+
* strictly matching echo_admin's `service/t3/dpop.go`.
|
|
44
|
+
*/
|
|
45
|
+
export function createDpopProof(options) {
|
|
46
|
+
const header = {
|
|
47
|
+
typ: 'dpop+jwt',
|
|
48
|
+
alg: 'ES256',
|
|
49
|
+
jwk: options.keyPair.publicJwk,
|
|
50
|
+
};
|
|
51
|
+
const payload = {
|
|
52
|
+
htm: options.method.toUpperCase(),
|
|
53
|
+
htu: normalizeHtu(options.url),
|
|
54
|
+
jti: crypto.randomUUID(),
|
|
55
|
+
iat: Math.floor(Date.now() / 1000),
|
|
56
|
+
};
|
|
57
|
+
if (options.accessToken) {
|
|
58
|
+
payload.ath = sha256Base64Url(options.accessToken);
|
|
59
|
+
}
|
|
60
|
+
const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;
|
|
61
|
+
const privateKey = crypto.createPrivateKey(options.keyPair.privateKeyPem);
|
|
62
|
+
const signature = crypto.sign('sha256', Buffer.from(signingInput, 'utf8'), {
|
|
63
|
+
key: privateKey,
|
|
64
|
+
dsaEncoding: 'ieee-p1363',
|
|
65
|
+
});
|
|
66
|
+
return `${signingInput}.${base64Url(signature)}`;
|
|
67
|
+
}
|
|
68
|
+
function mapPlatform() {
|
|
69
|
+
if (process.platform === 'darwin')
|
|
70
|
+
return 'darwin';
|
|
71
|
+
if (process.platform === 'win32')
|
|
72
|
+
return 'win32';
|
|
73
|
+
return 'linux';
|
|
74
|
+
}
|
|
75
|
+
/** Pair with Echo Hub using the one-time pairing code generated in YY Web. */
|
|
76
|
+
export async function pairWithHub(options) {
|
|
77
|
+
const serverUrl = options.serverUrl.replace(/\/+$/, '');
|
|
78
|
+
const tokenUrl = `${serverUrl}/api/t3/device/token`;
|
|
79
|
+
const keyPair = generateDpopKeyPair();
|
|
80
|
+
const label = options.label?.trim() || defaultDeviceLabel();
|
|
81
|
+
const proof = createDpopProof({
|
|
82
|
+
keyPair,
|
|
83
|
+
method: 'POST',
|
|
84
|
+
url: tokenUrl,
|
|
85
|
+
});
|
|
86
|
+
const body = new URLSearchParams({
|
|
87
|
+
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
88
|
+
subject_token: options.code.trim(),
|
|
89
|
+
subject_token_type: BOOTSTRAP_TOKEN_TYPE,
|
|
90
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
91
|
+
client_label: label,
|
|
92
|
+
client_device_type: 'desktop',
|
|
93
|
+
client_os: mapPlatform(),
|
|
94
|
+
client_app_version: `bridge-${APP_VERSION}`,
|
|
95
|
+
});
|
|
96
|
+
const response = await fetch(tokenUrl, {
|
|
97
|
+
method: 'POST',
|
|
98
|
+
headers: {
|
|
99
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
100
|
+
DPoP: proof,
|
|
101
|
+
},
|
|
102
|
+
body: body.toString(),
|
|
103
|
+
});
|
|
104
|
+
const data = (await response.json().catch(() => ({})));
|
|
105
|
+
if (!response.ok || !data.access_token || !data.environment_id) {
|
|
106
|
+
const detail = data.error_description || data.error || `HTTP ${response.status}`;
|
|
107
|
+
throw new Error(`Hub 配对失败: ${detail}`);
|
|
108
|
+
}
|
|
109
|
+
const now = Date.now();
|
|
110
|
+
return {
|
|
111
|
+
serverUrl,
|
|
112
|
+
environmentId: data.environment_id,
|
|
113
|
+
accessToken: data.access_token,
|
|
114
|
+
accessTokenExpiresAt: now + (Number(data.expires_in) || 3600) * 1000,
|
|
115
|
+
sessionExpiresAt: (Number(data.session_expires_at) || Math.floor(now / 1000) + 86400 * 30) * 1000,
|
|
116
|
+
label,
|
|
117
|
+
dpop: keyPair,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Renew an access token using the bound DPoP keypair. */
|
|
121
|
+
export async function renewHubToken(creds) {
|
|
122
|
+
const tokenUrl = `${creds.serverUrl}/api/t3/device/token`;
|
|
123
|
+
const proof = createDpopProof({
|
|
124
|
+
keyPair: creds.dpop,
|
|
125
|
+
method: 'POST',
|
|
126
|
+
url: tokenUrl,
|
|
127
|
+
});
|
|
128
|
+
const body = new URLSearchParams({
|
|
129
|
+
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
130
|
+
subject_token: creds.accessToken,
|
|
131
|
+
subject_token_type: ACCESS_TOKEN_TYPE,
|
|
132
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
133
|
+
client_label: creds.label,
|
|
134
|
+
client_device_type: 'desktop',
|
|
135
|
+
client_os: mapPlatform(),
|
|
136
|
+
client_app_version: `bridge-${APP_VERSION}`,
|
|
137
|
+
});
|
|
138
|
+
const response = await fetch(tokenUrl, {
|
|
139
|
+
method: 'POST',
|
|
140
|
+
headers: {
|
|
141
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
142
|
+
DPoP: proof,
|
|
143
|
+
},
|
|
144
|
+
body: body.toString(),
|
|
145
|
+
});
|
|
146
|
+
const data = (await response.json().catch(() => ({})));
|
|
147
|
+
if (!response.ok || !data.access_token) {
|
|
148
|
+
const detail = data.error_description || data.error || `HTTP ${response.status}`;
|
|
149
|
+
throw new Error(`Hub Token 续期失败: ${detail}`);
|
|
150
|
+
}
|
|
151
|
+
const now = Date.now();
|
|
152
|
+
return {
|
|
153
|
+
...creds,
|
|
154
|
+
accessToken: data.access_token,
|
|
155
|
+
accessTokenExpiresAt: now + (Number(data.expires_in) || 3600) * 1000,
|
|
156
|
+
sessionExpiresAt: data.session_expires_at ? data.session_expires_at * 1000 : creds.sessionExpiresAt,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/** Tell Hub to unpair this environment. */
|
|
160
|
+
export async function unpairFromHub(creds) {
|
|
161
|
+
const url = `${creds.serverUrl}/api/t3/device/environment`;
|
|
162
|
+
const proof = createDpopProof({
|
|
163
|
+
keyPair: creds.dpop,
|
|
164
|
+
method: 'DELETE',
|
|
165
|
+
url,
|
|
166
|
+
accessToken: creds.accessToken,
|
|
167
|
+
});
|
|
168
|
+
await fetch(url, {
|
|
169
|
+
method: 'DELETE',
|
|
170
|
+
headers: {
|
|
171
|
+
Authorization: `DPoP ${creds.accessToken}`,
|
|
172
|
+
DPoP: proof,
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/** Check Hub self status. */
|
|
177
|
+
export async function fetchHubSelf(creds) {
|
|
178
|
+
const url = `${creds.serverUrl}/api/t3/device/environment`;
|
|
179
|
+
const proof = createDpopProof({
|
|
180
|
+
keyPair: creds.dpop,
|
|
181
|
+
method: 'GET',
|
|
182
|
+
url,
|
|
183
|
+
accessToken: creds.accessToken,
|
|
184
|
+
});
|
|
185
|
+
const res = await fetch(url, {
|
|
186
|
+
method: 'GET',
|
|
187
|
+
headers: {
|
|
188
|
+
Authorization: `DPoP ${creds.accessToken}`,
|
|
189
|
+
DPoP: proof,
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
if (!res.ok)
|
|
193
|
+
return { ok: false, status: res.status };
|
|
194
|
+
const data = (await res.json().catch(() => ({})));
|
|
195
|
+
return { ok: true, status: res.status, ...data };
|
|
196
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
export async function listDirectories(rawPath) {
|
|
5
|
+
let target = (rawPath ?? '').trim();
|
|
6
|
+
if (!target || target === '~' || target === '~/') {
|
|
7
|
+
target = homedir();
|
|
8
|
+
}
|
|
9
|
+
else if (target.startsWith('~/')) {
|
|
10
|
+
target = join(homedir(), target.slice(2));
|
|
11
|
+
}
|
|
12
|
+
const absPath = resolve(target);
|
|
13
|
+
const names = await readdir(absPath);
|
|
14
|
+
const entries = [];
|
|
15
|
+
await Promise.all(names.map(async (name) => {
|
|
16
|
+
const fullPath = join(absPath, name);
|
|
17
|
+
try {
|
|
18
|
+
const info = await stat(fullPath);
|
|
19
|
+
if (info.isDirectory()) {
|
|
20
|
+
entries.push({
|
|
21
|
+
name,
|
|
22
|
+
path: fullPath,
|
|
23
|
+
hidden: name.startsWith('.'),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// skip unreadable entries
|
|
29
|
+
}
|
|
30
|
+
}));
|
|
31
|
+
entries.sort((a, b) => Number(a.hidden) - Number(b.hidden) || a.name.localeCompare(b.name));
|
|
32
|
+
const parentDir = dirname(absPath);
|
|
33
|
+
return {
|
|
34
|
+
path: absPath,
|
|
35
|
+
parent: parentDir !== absPath ? parentDir : null,
|
|
36
|
+
directories: entries,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { probeAntigravityUsage, resolveAgyBinary } from './antigravity-quota.js';
|
|
5
|
+
import { EchoT3Bridge } from './bridge.js';
|
|
6
|
+
import { APP_VERSION, clearHubCredentials, DEFAULT_HUB_SERVER, DEFAULT_LOCAL_T3_URL, defaultConfigPath, defaultDeviceLabel, loadConfig, normalizeServerUrl, saveConfig, } from './config.js';
|
|
7
|
+
import { fetchHubSelf, pairWithHub, unpairFromHub } from './dpop.js';
|
|
8
|
+
import { pairLocalOfficialT3, probeLocalT3Health, resolveLocalT3Binary } from './local-t3.js';
|
|
9
|
+
function parseArgs(argv) {
|
|
10
|
+
const positionals = [];
|
|
11
|
+
const flags = {};
|
|
12
|
+
for (let i = 0; i < argv.length; i++) {
|
|
13
|
+
const arg = argv[i];
|
|
14
|
+
if (arg.startsWith('--')) {
|
|
15
|
+
const eq = arg.indexOf('=');
|
|
16
|
+
if (eq > 0) {
|
|
17
|
+
flags[arg.slice(2, eq)] = arg.slice(eq + 1);
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
const key = arg.slice(2);
|
|
21
|
+
const next = argv[i + 1];
|
|
22
|
+
if (next && !next.startsWith('-')) {
|
|
23
|
+
flags[key] = next;
|
|
24
|
+
i++;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
flags[key] = true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
else if (arg === '-v') {
|
|
32
|
+
flags.version = true;
|
|
33
|
+
}
|
|
34
|
+
else if (arg === '-h') {
|
|
35
|
+
flags.help = true;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
positionals.push(arg);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
command: positionals[0] ?? 'help',
|
|
43
|
+
subcommand: positionals[1],
|
|
44
|
+
flags,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function strFlag(flags, ...names) {
|
|
48
|
+
for (const name of names) {
|
|
49
|
+
const val = flags[name];
|
|
50
|
+
if (typeof val === 'string' && val.trim())
|
|
51
|
+
return val.trim();
|
|
52
|
+
}
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
function printHelp() {
|
|
56
|
+
console.log(`echo-t3-bridge v${APP_VERSION}
|
|
57
|
+
零二开官方原版 T3 Code 的公网反向桥接客户端(与 toc-ocra 同风格 npm CLI)
|
|
58
|
+
|
|
59
|
+
用法:
|
|
60
|
+
echo-t3-bridge setup --code <配对码> [--server ${DEFAULT_HUB_SERVER}] [--label <设备名>]
|
|
61
|
+
一键完成公网配对 + 关联本机原版 T3 + 安装开机自启后台服务
|
|
62
|
+
|
|
63
|
+
echo-t3-bridge pair --code <配对码> [--server ${DEFAULT_HUB_SERVER}] [--label <设备名>]
|
|
64
|
+
(别名: enroll)仅执行公网配对与本机原版 T3 授权,不安装后台服务
|
|
65
|
+
|
|
66
|
+
echo-t3-bridge run
|
|
67
|
+
前台运行反向桥接守护进程(双向断线自动重连 + 实时事件流 + agy 额度增强)
|
|
68
|
+
|
|
69
|
+
echo-t3-bridge status | doctor
|
|
70
|
+
检查公网连接状态、本机官方原版 T3 服务状态、以及 agy 额度探测状态
|
|
71
|
+
|
|
72
|
+
echo-t3-bridge service <install|uninstall|restart>
|
|
73
|
+
(别名: service:install / service:uninstall)管理后台开机自启服务
|
|
74
|
+
|
|
75
|
+
echo-t3-bridge unpair
|
|
76
|
+
解除当前设备与公网 Hub 的绑定
|
|
77
|
+
|
|
78
|
+
选项:
|
|
79
|
+
--server <url> 公网 Hub 地址(默认 ${DEFAULT_HUB_SERVER})
|
|
80
|
+
--code <code> 在网页端点击「生成配对码」获取的一次性配对码
|
|
81
|
+
--label <name> 设备显示名称(默认取本机主机名)
|
|
82
|
+
--t3-url <url> 本机官方 T3 地址(默认自动探测,回退 ${DEFAULT_LOCAL_T3_URL})
|
|
83
|
+
--t3-bin <path> 指定本机官方 t3 可执行文件路径
|
|
84
|
+
--config <path> 指定配置文件路径(默认 ${defaultConfigPath()})
|
|
85
|
+
`);
|
|
86
|
+
}
|
|
87
|
+
function runServiceScript(action, configPath) {
|
|
88
|
+
const currentDir = dirname(fileURLToPath(import.meta.url));
|
|
89
|
+
const scriptPath = resolve(currentDir, '..', 'scripts', 'service.mjs');
|
|
90
|
+
const res = spawnSync(process.execPath, [scriptPath, action, '--config', configPath], {
|
|
91
|
+
stdio: 'inherit',
|
|
92
|
+
});
|
|
93
|
+
if (res.status !== 0) {
|
|
94
|
+
process.exit(res.status ?? 1);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async function doPair(flags, configPath) {
|
|
98
|
+
const code = strFlag(flags, 'code');
|
|
99
|
+
if (!code) {
|
|
100
|
+
throw new Error('缺少 --code 参数。请先在网页端点击「生成配对码」获取配对码。');
|
|
101
|
+
}
|
|
102
|
+
const serverUrl = normalizeServerUrl(strFlag(flags, 'server') ?? DEFAULT_HUB_SERVER);
|
|
103
|
+
const label = strFlag(flags, 'label') ?? defaultDeviceLabel();
|
|
104
|
+
const t3UrlOverride = strFlag(flags, 't3-url');
|
|
105
|
+
const t3BinOverride = strFlag(flags, 't3-bin');
|
|
106
|
+
console.log(`1/2 正在向公网 Hub (${serverUrl}) 配对设备「${label}」…`);
|
|
107
|
+
const hubCreds = await pairWithHub({ serverUrl, code, label });
|
|
108
|
+
console.log(`✓ 公网配对成功 (environment_id=${hubCreds.environmentId})`);
|
|
109
|
+
const cfg = await loadConfig(configPath);
|
|
110
|
+
cfg.hub = hubCreds;
|
|
111
|
+
if (t3UrlOverride)
|
|
112
|
+
cfg.localT3.baseUrl = t3UrlOverride.replace(/\/+$/, '');
|
|
113
|
+
if (t3BinOverride)
|
|
114
|
+
cfg.localT3.t3Binary = t3BinOverride;
|
|
115
|
+
console.log('2/2 正在自动连接本机官方原版 T3 Server…');
|
|
116
|
+
try {
|
|
117
|
+
const localPaired = await pairLocalOfficialT3({
|
|
118
|
+
baseUrl: t3UrlOverride,
|
|
119
|
+
t3Binary: cfg.localT3.t3Binary,
|
|
120
|
+
});
|
|
121
|
+
cfg.localT3.baseUrl = localPaired.baseUrl;
|
|
122
|
+
cfg.localT3.accessToken = localPaired.accessToken;
|
|
123
|
+
console.log(`✓ 已自动授权本机原版 T3 (${localPaired.baseUrl})`);
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
console.warn(`⚠ 本机原版 T3 暂未连通(稍后启动服务后会自动重试):${err instanceof Error ? err.message : String(err)}`);
|
|
127
|
+
}
|
|
128
|
+
await saveConfig(cfg, configPath);
|
|
129
|
+
console.log(`✓ 凭据已保存到 ${configPath}`);
|
|
130
|
+
}
|
|
131
|
+
async function doDoctor(configPath) {
|
|
132
|
+
const cfg = await loadConfig(configPath);
|
|
133
|
+
console.log(`echo-t3-bridge v${APP_VERSION}`);
|
|
134
|
+
console.log(`配置文件: ${configPath}`);
|
|
135
|
+
if (!cfg.hub) {
|
|
136
|
+
console.log('公网 Hub: 未配对(请运行 echo-t3-bridge setup --code <配对码>)');
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
const self = await fetchHubSelf(cfg.hub).catch(() => ({ ok: false, status: 0 }));
|
|
140
|
+
const envName = self.environment?.name || cfg.hub.label;
|
|
141
|
+
const online = self.online;
|
|
142
|
+
console.log(`公网 Hub: ${cfg.hub.serverUrl} | 设备: ${envName} (${cfg.hub.environmentId}) | 凭据: ${self.ok ? '有效' : `异常 (HTTP ${self.status})`} | 在线: ${online ? '● 在线' : '○ 离线'}`);
|
|
143
|
+
}
|
|
144
|
+
const t3Bin = resolveLocalT3Binary(cfg.localT3.t3Binary);
|
|
145
|
+
const localOk = await probeLocalT3Health(cfg.localT3.baseUrl);
|
|
146
|
+
console.log(`本机原版 T3: ${cfg.localT3.baseUrl} | 二进制: ${t3Bin} | 服务: ${localOk ? '● 运行中' : '○ 未启动(请运行 t3 up)'} | 本地令牌: ${cfg.localT3.accessToken ? '已授权' : '未授权'}`);
|
|
147
|
+
const agyBin = resolveAgyBinary();
|
|
148
|
+
const agyUsage = await probeAntigravityUsage(true);
|
|
149
|
+
if (agyUsage && agyUsage.windows.length > 0) {
|
|
150
|
+
const summary = agyUsage.windows
|
|
151
|
+
.map((w) => `${w.label} 剩 ${Math.round(100 - w.usedPercent)}%`)
|
|
152
|
+
.join(' | ');
|
|
153
|
+
console.log(`Antigravity 额度 (${agyBin}): ✓ ${summary}`);
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
console.log(`Antigravity 额度 (${agyBin}): 未检测到(如未安装 agy 可忽略)`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async function main() {
|
|
160
|
+
const parsed = parseArgs(process.argv.slice(2));
|
|
161
|
+
const configPath = strFlag(parsed.flags, 'config') ?? defaultConfigPath();
|
|
162
|
+
if (parsed.flags.version || parsed.command === 'version') {
|
|
163
|
+
console.log(APP_VERSION);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (parsed.flags.help || parsed.command === 'help') {
|
|
167
|
+
printHelp();
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
switch (parsed.command) {
|
|
171
|
+
case 'setup': {
|
|
172
|
+
await doPair(parsed.flags, configPath);
|
|
173
|
+
console.log('正在安装并启动后台开机自启服务…');
|
|
174
|
+
runServiceScript('install', configPath);
|
|
175
|
+
console.log('✓ 全部完成!设备已接入公网 Hub,可在网页端直接使用。');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
case 'pair':
|
|
179
|
+
case 'enroll': {
|
|
180
|
+
await doPair(parsed.flags, configPath);
|
|
181
|
+
console.log('提示:运行 `echo-t3-bridge run` 前台启动,或运行 `echo-t3-bridge service install` 安装后台服务。');
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
case 'run': {
|
|
185
|
+
const bridge = new EchoT3Bridge(configPath);
|
|
186
|
+
const shutdown = () => {
|
|
187
|
+
console.log('[bridge] 正在停止…');
|
|
188
|
+
bridge.stop();
|
|
189
|
+
process.exit(0);
|
|
190
|
+
};
|
|
191
|
+
process.on('SIGINT', shutdown);
|
|
192
|
+
process.on('SIGTERM', shutdown);
|
|
193
|
+
await bridge.start();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
case 'status':
|
|
197
|
+
case 'doctor': {
|
|
198
|
+
await doDoctor(configPath);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
case 'service:install': {
|
|
202
|
+
runServiceScript('install', configPath);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
case 'service:uninstall': {
|
|
206
|
+
runServiceScript('uninstall', configPath);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
case 'service': {
|
|
210
|
+
if (parsed.subcommand === 'install' || parsed.subcommand === 'restart') {
|
|
211
|
+
runServiceScript('install', configPath);
|
|
212
|
+
}
|
|
213
|
+
else if (parsed.subcommand === 'uninstall') {
|
|
214
|
+
runServiceScript('uninstall', configPath);
|
|
215
|
+
}
|
|
216
|
+
else if (parsed.subcommand === 'status') {
|
|
217
|
+
await doDoctor(configPath);
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
throw new Error('用法: echo-t3-bridge service <install|uninstall|restart|status>');
|
|
221
|
+
}
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
case 'unpair': {
|
|
225
|
+
const cfg = await loadConfig(configPath);
|
|
226
|
+
if (cfg.hub) {
|
|
227
|
+
await unpairFromHub(cfg.hub).catch(() => undefined);
|
|
228
|
+
await clearHubCredentials(configPath);
|
|
229
|
+
console.log('✓ 已解绑当前设备并清理本地公网凭据。');
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
console.log('当前未绑定公网 Hub。');
|
|
233
|
+
}
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
default:
|
|
237
|
+
throw new Error(`未知命令: ${parsed.command}。运行 \`echo-t3-bridge --help\` 查看帮助。`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
main().catch((err) => {
|
|
241
|
+
console.error(`错误: ${err instanceof Error ? err.message : String(err)}`);
|
|
242
|
+
process.exit(1);
|
|
243
|
+
});
|