@ainecto/cli 0.15.3 → 0.16.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/README.md +1 -1
- package/dist/bin/ainecto.js +813 -310
- package/dist/bin/ainecto.js.map +1 -1
- package/dist/bin/mcp.js +2 -2
- package/package.json +2 -2
package/dist/bin/ainecto.js
CHANGED
|
@@ -5699,8 +5699,8 @@ function legacyRoleInput(flag, envVars = process.env) {
|
|
|
5699
5699
|
|
|
5700
5700
|
// src/core/version.ts
|
|
5701
5701
|
var UNBUNDLED_VERSION = "dev";
|
|
5702
|
-
var CLI_VERSION = true ? "0.
|
|
5703
|
-
var CLI_BUILD = true ? "
|
|
5702
|
+
var CLI_VERSION = true ? "0.16.0" : UNBUNDLED_VERSION;
|
|
5703
|
+
var CLI_BUILD = true ? "0159129" : void 0;
|
|
5704
5704
|
function cliVersionLabel(version, build, release2) {
|
|
5705
5705
|
return release2 || build === void 0 ? version : `${version}-dev+${build}`;
|
|
5706
5706
|
}
|
|
@@ -10997,17 +10997,17 @@ function assertNoArgs(command, argv) {
|
|
|
10997
10997
|
}
|
|
10998
10998
|
|
|
10999
10999
|
// src/adapters/cli/termCommand.ts
|
|
11000
|
-
import { closeSync as
|
|
11000
|
+
import { closeSync as closeSync3, writeSync } from "fs";
|
|
11001
11001
|
import { resolve as resolve3 } from "path";
|
|
11002
11002
|
|
|
11003
11003
|
// src/core/term/client.ts
|
|
11004
|
-
import { closeSync, openSync as openSync2, readFileSync } from "fs";
|
|
11004
|
+
import { closeSync as closeSync2, openSync as openSync2, readFileSync } from "fs";
|
|
11005
11005
|
import { randomUUID } from "crypto";
|
|
11006
11006
|
import { connect } from "net";
|
|
11007
11007
|
import { Readable } from "stream";
|
|
11008
11008
|
|
|
11009
11009
|
// src/core/term/daemonLock.ts
|
|
11010
|
-
import { constants, openSync } from "fs";
|
|
11010
|
+
import { closeSync, constants, openSync } from "fs";
|
|
11011
11011
|
import { createServer as createServer2 } from "net";
|
|
11012
11012
|
|
|
11013
11013
|
// src/core/term/errors.ts
|
|
@@ -11059,18 +11059,29 @@ var FILE_LOCK = {
|
|
|
11059
11059
|
darwin: { flags: constants.O_RDWR | constants.O_CREAT | constants.O_NONBLOCK | DARWIN_O_EXLOCK, busy: ["EAGAIN", "EWOULDBLOCK"] },
|
|
11060
11060
|
win32: { flags: constants.O_RDWR | constants.O_CREAT | WIN32_UV_FS_O_EXLOCK, busy: ["EBUSY"] }
|
|
11061
11061
|
};
|
|
11062
|
-
var
|
|
11063
|
-
var heldServer;
|
|
11062
|
+
var held = [];
|
|
11064
11063
|
async function acquireDaemonLock(paths) {
|
|
11064
|
+
const lock = await acquireProcessLock(paths);
|
|
11065
|
+
if (!lock) return { held: false };
|
|
11066
|
+
held.push(lock);
|
|
11067
|
+
return { held: true };
|
|
11068
|
+
}
|
|
11069
|
+
async function acquirePcBridgeLock(paths) {
|
|
11070
|
+
return await acquireProcessLock({
|
|
11071
|
+
lockFile: paths.lockFile.replace(/daemon\.lock$/, "pc-bridge.lock"),
|
|
11072
|
+
abstractLockName: paths.abstractLockName.replace(/\.lock$/, "-pc-bridge.lock")
|
|
11073
|
+
});
|
|
11074
|
+
}
|
|
11075
|
+
async function acquireProcessLock(paths) {
|
|
11065
11076
|
assertTermRuntime();
|
|
11066
11077
|
const fileLock = FILE_LOCK[process.platform];
|
|
11067
11078
|
if (fileLock) {
|
|
11068
11079
|
try {
|
|
11069
|
-
|
|
11070
|
-
return {
|
|
11080
|
+
const fd = openSync(paths.lockFile, fileLock.flags, PRIVATE_FILE_MODE);
|
|
11081
|
+
return { release: () => closeSync(fd) };
|
|
11071
11082
|
} catch (error) {
|
|
11072
11083
|
if (fileLock.busy.some((code) => isNodeError(error, code))) {
|
|
11073
|
-
return
|
|
11084
|
+
return void 0;
|
|
11074
11085
|
}
|
|
11075
11086
|
throw error;
|
|
11076
11087
|
}
|
|
@@ -11080,15 +11091,14 @@ async function acquireDaemonLock(paths) {
|
|
|
11080
11091
|
return await new Promise((resolve4, reject) => {
|
|
11081
11092
|
server.once("error", (error) => {
|
|
11082
11093
|
if (isNodeError(error, "EADDRINUSE")) {
|
|
11083
|
-
resolve4(
|
|
11094
|
+
resolve4(void 0);
|
|
11084
11095
|
return;
|
|
11085
11096
|
}
|
|
11086
11097
|
reject(error);
|
|
11087
11098
|
});
|
|
11088
11099
|
server.listen(paths.abstractLockName, () => {
|
|
11089
|
-
heldServer = server;
|
|
11090
11100
|
server.unref();
|
|
11091
|
-
resolve4({
|
|
11101
|
+
resolve4({ release: () => server.close() });
|
|
11092
11102
|
});
|
|
11093
11103
|
});
|
|
11094
11104
|
}
|
|
@@ -11668,7 +11678,7 @@ async function spawnDaemon(paths) {
|
|
|
11668
11678
|
env: process.env
|
|
11669
11679
|
});
|
|
11670
11680
|
} finally {
|
|
11671
|
-
|
|
11681
|
+
closeSync2(stderrFd);
|
|
11672
11682
|
}
|
|
11673
11683
|
const channel = child.stdio[3];
|
|
11674
11684
|
if (!(channel instanceof Readable)) {
|
|
@@ -11711,15 +11721,27 @@ function parseReadiness(line) {
|
|
|
11711
11721
|
}
|
|
11712
11722
|
return { status: "error", message: `unexpected readiness line: ${line}` };
|
|
11713
11723
|
}
|
|
11714
|
-
function
|
|
11724
|
+
function readDaemonInfo(paths) {
|
|
11715
11725
|
try {
|
|
11716
11726
|
const value = JSON.parse(readFileSync(paths.daemonInfo, "utf8"));
|
|
11717
11727
|
const pid = value && typeof value === "object" && "pid" in value ? value.pid : void 0;
|
|
11718
|
-
|
|
11728
|
+
const version = value && typeof value === "object" && "version" in value ? value.version : void 0;
|
|
11729
|
+
return typeof pid === "number" ? { pid, ...typeof version === "string" ? { version } : {} } : void 0;
|
|
11719
11730
|
} catch {
|
|
11720
11731
|
return void 0;
|
|
11721
11732
|
}
|
|
11722
11733
|
}
|
|
11734
|
+
function daemonPid(paths) {
|
|
11735
|
+
return readDaemonInfo(paths)?.pid;
|
|
11736
|
+
}
|
|
11737
|
+
async function waitForPidGone(pid, ms) {
|
|
11738
|
+
const until = Date.now() + ms;
|
|
11739
|
+
while (isAlive(pid)) {
|
|
11740
|
+
if (Date.now() >= until) return false;
|
|
11741
|
+
await new Promise((resolve4) => setTimeout(resolve4, 100));
|
|
11742
|
+
}
|
|
11743
|
+
return true;
|
|
11744
|
+
}
|
|
11723
11745
|
function notListening(paths) {
|
|
11724
11746
|
const pid = daemonPid(paths);
|
|
11725
11747
|
const holder = pid !== void 0 && isAlive(pid) ? `Daemon pid ${pid} holds the lock but is not listening on ${paths.socket} \u2014 it may be stopped or hung. ${stuckProcessHint(pid)}` : "No running daemon answered.";
|
|
@@ -12126,7 +12148,7 @@ var QueryFilter = class _QueryFilter {
|
|
|
12126
12148
|
}
|
|
12127
12149
|
const whole = this.held + terminator;
|
|
12128
12150
|
const meaning = DISPATCHES.has(action) ? this.meaning + terminator : this.meaning;
|
|
12129
|
-
const
|
|
12151
|
+
const held2 = this.held;
|
|
12130
12152
|
this.held = "";
|
|
12131
12153
|
this.meaning = "";
|
|
12132
12154
|
if (this.dropTerminator && action === VtAction.ESC_DISPATCH && meaning === "\\") {
|
|
@@ -12145,7 +12167,7 @@ var QueryFilter = class _QueryFilter {
|
|
|
12145
12167
|
if (pieces === void 0) {
|
|
12146
12168
|
return this.release(whole);
|
|
12147
12169
|
}
|
|
12148
|
-
const introducer =
|
|
12170
|
+
const introducer = held2.startsWith(C1_OSC) ? C1_OSC : `${ESC}]`;
|
|
12149
12171
|
return this.releaseString(pieces.map((payload) => `${introducer}${payload}${terminator}`).join(""), terminator);
|
|
12150
12172
|
}
|
|
12151
12173
|
case VtAction.DCS_UNHOOK:
|
|
@@ -13301,7 +13323,7 @@ async function daemonCommand(paths, argv) {
|
|
|
13301
13323
|
writeSync(readyFd, `${JSON.stringify(readiness)}
|
|
13302
13324
|
`);
|
|
13303
13325
|
} finally {
|
|
13304
|
-
|
|
13326
|
+
closeSync3(readyFd);
|
|
13305
13327
|
}
|
|
13306
13328
|
};
|
|
13307
13329
|
let code;
|
|
@@ -13558,6 +13580,7 @@ function createPcHttp(input) {
|
|
|
13558
13580
|
);
|
|
13559
13581
|
const onStop = () => controller.abort(new DOMException("stopped", "AbortError"));
|
|
13560
13582
|
options.signal?.addEventListener("abort", onStop, { once: true });
|
|
13583
|
+
if (options.signal?.aborted) onStop();
|
|
13561
13584
|
const headers = { "Content-Type": "application/json", Accept: "application/json" };
|
|
13562
13585
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
13563
13586
|
if (sessionToken && op !== "open") headers[input.sessionHeader] = sessionToken;
|
|
@@ -14839,16 +14862,20 @@ var subtle = webcrypto.subtle;
|
|
|
14839
14862
|
var VERSION = "ainecto-e2e-v1";
|
|
14840
14863
|
var PAIR_LABEL = "ainecto-pair-v1";
|
|
14841
14864
|
var PAIR_DONE_LABEL = "ainecto-pair-v1/done";
|
|
14865
|
+
var PAIR_APPROVE_LABEL = "ainecto-pair-v1/approve";
|
|
14866
|
+
var PAIR_CODE_INFO = { a: "ainecto-pair-code-A", b: "ainecto-pair-code-B" };
|
|
14842
14867
|
var REGISTER_INFO = { browser: "ainecto-register-v1 browser", pc: "ainecto-register-v1 pc", account: "ainecto-register-v1 account" };
|
|
14843
14868
|
var REGISTER_OFFER_LABEL = "ainecto-register-v1/offer";
|
|
14844
14869
|
var REGISTER_REVEAL_LABEL = "ainecto-register-v1/reveal";
|
|
14845
14870
|
var REGISTER_TAG_BYTES = 8;
|
|
14846
14871
|
var KEY_INFO = { browserToPc: "ainecto-e2e-v1 b2p", pcToBrowser: "ainecto-e2e-v1 p2b", connId: "ainecto-e2e-v1 conn-id" };
|
|
14872
|
+
var PAIR_CODE_LIMIT = 4294e6;
|
|
14847
14873
|
var MAX_MESSAGES_PER_KEY = 2 ** 32;
|
|
14848
14874
|
var PUBLIC_KEY_BYTES = 65;
|
|
14849
14875
|
var NONCE_SEED_BYTES = 32;
|
|
14850
14876
|
var SIGNATURE_BYTES = 64;
|
|
14851
14877
|
var CONN_ID_BYTES = 16;
|
|
14878
|
+
var PAIR_CODE_DIGITS = 6;
|
|
14852
14879
|
var E2eError = class extends Error {
|
|
14853
14880
|
constructor(code, message2) {
|
|
14854
14881
|
super(message2);
|
|
@@ -15003,10 +15030,38 @@ async function pairTranscript(input) {
|
|
|
15003
15030
|
expectLength("nB", input.nB, NONCE_SEED_BYTES);
|
|
15004
15031
|
return await sha256(enc(PAIR_LABEL, input.userId, input.pcId, input.pcPublicRaw, input.browserPublicRaw, input.nP, input.nB));
|
|
15005
15032
|
}
|
|
15033
|
+
function pairCodeFromBlock(block) {
|
|
15034
|
+
expectLength("code block", block, 32);
|
|
15035
|
+
const view = new DataView(block.buffer, block.byteOffset, block.byteLength);
|
|
15036
|
+
for (let offset = 0; offset < 32; offset += 4) {
|
|
15037
|
+
const value = view.getUint32(offset, false);
|
|
15038
|
+
if (value < PAIR_CODE_LIMIT) {
|
|
15039
|
+
return String(value % 10 ** PAIR_CODE_DIGITS).padStart(PAIR_CODE_DIGITS, "0");
|
|
15040
|
+
}
|
|
15041
|
+
}
|
|
15042
|
+
return void 0;
|
|
15043
|
+
}
|
|
15044
|
+
async function pairCodes(transcript) {
|
|
15045
|
+
expectLength("transcript", transcript, 32);
|
|
15046
|
+
const prk = await subtle.importKey("raw", transcript, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
15047
|
+
const code = async (info) => {
|
|
15048
|
+
const block = new Uint8Array(await subtle.sign("HMAC", prk, concatBytes(utf8(info), Uint8Array.of(1))));
|
|
15049
|
+
const value = pairCodeFromBlock(block);
|
|
15050
|
+
if (value === void 0) {
|
|
15051
|
+
throw new E2eError("E2E_PAIR_CODE_UNAVAILABLE", "No usable registration code in this attempt \u2014 run `npx -y ainecto@latest` again.");
|
|
15052
|
+
}
|
|
15053
|
+
return value;
|
|
15054
|
+
};
|
|
15055
|
+
return { a: await code(PAIR_CODE_INFO.a), b: await code(PAIR_CODE_INFO.b) };
|
|
15056
|
+
}
|
|
15006
15057
|
function pairDoneInput(transcript) {
|
|
15007
15058
|
expectLength("transcript", transcript, 32);
|
|
15008
15059
|
return enc(PAIR_DONE_LABEL, transcript);
|
|
15009
15060
|
}
|
|
15061
|
+
function pairApproveInput(transcript) {
|
|
15062
|
+
expectLength("transcript", transcript, 32);
|
|
15063
|
+
return enc(PAIR_APPROVE_LABEL, transcript);
|
|
15064
|
+
}
|
|
15010
15065
|
async function registerKeys(secret) {
|
|
15011
15066
|
expectLength("register secret", secret, NONCE_SEED_BYTES);
|
|
15012
15067
|
const ikm = await subtle.importKey("raw", secret, "HKDF", false, ["deriveBits"]);
|
|
@@ -15295,7 +15350,7 @@ var ANSWER_CODES = ["TERM_NO_SESSION", "TERM_SESSION_EXISTS", "TERM_BAD_REQUEST"
|
|
|
15295
15350
|
function answerCodeOf(code) {
|
|
15296
15351
|
return ANSWER_CODES.includes(code) ? code : "TERM_FAILED";
|
|
15297
15352
|
}
|
|
15298
|
-
var COMMAND_KINDS = ["confirm", "input", "key", "resize", "create", "kill", "label"];
|
|
15353
|
+
var COMMAND_KINDS = ["confirm", "input", "key", "resize", "create", "kill", "label", "device"];
|
|
15299
15354
|
var ChannelSealError = class extends Error {
|
|
15300
15355
|
constructor(reason, message2) {
|
|
15301
15356
|
super(message2);
|
|
@@ -15340,6 +15395,12 @@ var ChannelBook = class {
|
|
|
15340
15395
|
drop(channelId) {
|
|
15341
15396
|
return this.channels.delete(channelId);
|
|
15342
15397
|
}
|
|
15398
|
+
/** 그 브라우저 키의 채널을 모두 지운다(연결 중·활성 — 기기 지우기, approve-new-device §3-6) — 지운 id 들. */
|
|
15399
|
+
dropBrowser(keyId) {
|
|
15400
|
+
const ids = [...this.channels.values()].filter((channel) => channel.browser.keyId === keyId).map((channel) => channel.channelId);
|
|
15401
|
+
for (const id of ids) this.channels.delete(id);
|
|
15402
|
+
return ids;
|
|
15403
|
+
}
|
|
15343
15404
|
/** 모두 지운다(원격 끔·링크 다시 열기) — 지운 id 들. */
|
|
15344
15405
|
dropAll() {
|
|
15345
15406
|
const ids = [...this.channels.keys()];
|
|
@@ -15543,6 +15604,29 @@ function sealedCommand(wire, plaintext) {
|
|
|
15543
15604
|
const label = text(body.label);
|
|
15544
15605
|
return targets(true) && label ? { kind: "label", opId, session, instance, label } : void 0;
|
|
15545
15606
|
}
|
|
15607
|
+
case "device": {
|
|
15608
|
+
if (!opId || wire.opId !== opId || wire.session !== void 0 || wire.projectUuid !== void 0) return void 0;
|
|
15609
|
+
const action = deviceAction(body);
|
|
15610
|
+
return action ? { kind: "device", opId, action } : void 0;
|
|
15611
|
+
}
|
|
15612
|
+
}
|
|
15613
|
+
}
|
|
15614
|
+
function deviceAction(body) {
|
|
15615
|
+
switch (body.action) {
|
|
15616
|
+
case "pending":
|
|
15617
|
+
return { action: "pending" };
|
|
15618
|
+
case "list":
|
|
15619
|
+
return { action: "list" };
|
|
15620
|
+
case "approve": {
|
|
15621
|
+
const transcript = fromB64u(body.T, 32);
|
|
15622
|
+
return transcript && typeof body.accept === "boolean" ? { action: "approve", transcript, accept: body.accept } : void 0;
|
|
15623
|
+
}
|
|
15624
|
+
case "remove": {
|
|
15625
|
+
const keyId = text(body.keyId);
|
|
15626
|
+
return keyId ? { action: "remove", keyId } : void 0;
|
|
15627
|
+
}
|
|
15628
|
+
default:
|
|
15629
|
+
return void 0;
|
|
15546
15630
|
}
|
|
15547
15631
|
}
|
|
15548
15632
|
function record2(value) {
|
|
@@ -15739,6 +15823,7 @@ var RemoteViewer = class {
|
|
|
15739
15823
|
this.deps.onChannelEnded(error instanceof ChannelSealError ? error.reason : "CHANNEL_GONE");
|
|
15740
15824
|
return;
|
|
15741
15825
|
}
|
|
15826
|
+
if (this.stopped) return;
|
|
15742
15827
|
try {
|
|
15743
15828
|
await this.deps.http.call("frame", { ...outer, ...box }, { signal: this.stopper.signal });
|
|
15744
15829
|
sentKey = key;
|
|
@@ -15857,106 +15942,530 @@ function record3(value) {
|
|
|
15857
15942
|
return value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : void 0;
|
|
15858
15943
|
}
|
|
15859
15944
|
|
|
15860
|
-
// src/core/
|
|
15861
|
-
var
|
|
15862
|
-
var
|
|
15863
|
-
|
|
15864
|
-
|
|
15865
|
-
|
|
15866
|
-
|
|
15867
|
-
|
|
15868
|
-
|
|
15945
|
+
// src/core/pc/pcNotify.ts
|
|
15946
|
+
var NOTIFY_BATCH_MS = 6e4;
|
|
15947
|
+
var WHAT = {
|
|
15948
|
+
paired: "was registered with this PC",
|
|
15949
|
+
session: "opened a terminal connection to this PC",
|
|
15950
|
+
shell: "started a new shell on this PC",
|
|
15951
|
+
command: "started a command in a new terminal on this PC",
|
|
15952
|
+
"device-request": "asks to open this PC's terminal \u2014 open AiNecto Terminal in a browser you already use to allow or refuse it"
|
|
15953
|
+
};
|
|
15954
|
+
function notificationText(event, more) {
|
|
15955
|
+
const time = `${String(event.at.getHours()).padStart(2, "0")}:${String(event.at.getMinutes()).padStart(2, "0")}`;
|
|
15956
|
+
return {
|
|
15957
|
+
title: "AiNecto",
|
|
15958
|
+
body: `${event.browserName} ${WHAT[event.kind]} \u2014 ${time}${more > 0 ? ` (+${more} more)` : ""}. Not you? Run \`ainecto remote off\`.`
|
|
15959
|
+
};
|
|
15869
15960
|
}
|
|
15870
|
-
|
|
15871
|
-
|
|
15872
|
-
|
|
15873
|
-
|
|
15874
|
-
|
|
15875
|
-
|
|
15876
|
-
|
|
15877
|
-
|
|
15878
|
-
|
|
15879
|
-
|
|
15880
|
-
|
|
15881
|
-
|
|
15882
|
-
|
|
15883
|
-
|
|
15884
|
-
|
|
15885
|
-
|
|
15886
|
-
|
|
15887
|
-
|
|
15961
|
+
var systemClock = {
|
|
15962
|
+
now: () => Date.now(),
|
|
15963
|
+
setTimer: (run, ms) => {
|
|
15964
|
+
const timer = setTimeout(run, ms);
|
|
15965
|
+
timer.unref?.();
|
|
15966
|
+
return timer;
|
|
15967
|
+
},
|
|
15968
|
+
clearTimer: (timer) => clearTimeout(timer)
|
|
15969
|
+
};
|
|
15970
|
+
var NotifyBatcher = class {
|
|
15971
|
+
constructor(show, clock = systemClock) {
|
|
15972
|
+
this.show = show;
|
|
15973
|
+
this.clock = clock;
|
|
15974
|
+
}
|
|
15975
|
+
show;
|
|
15976
|
+
clock;
|
|
15977
|
+
slots = /* @__PURE__ */ new Map();
|
|
15978
|
+
add(event) {
|
|
15979
|
+
const key = `${event.keyId}\0${event.kind}`;
|
|
15980
|
+
const now = this.clock.now();
|
|
15981
|
+
const slot = this.slots.get(key);
|
|
15982
|
+
if (!slot || now >= slot.endsAt) {
|
|
15983
|
+
this.show(event, 0);
|
|
15984
|
+
this.slots.set(key, { endsAt: now + NOTIFY_BATCH_MS, pending: void 0, timer: void 0 });
|
|
15985
|
+
return;
|
|
15888
15986
|
}
|
|
15889
|
-
|
|
15987
|
+
slot.pending = { event, count: (slot.pending?.count ?? 0) + 1 };
|
|
15988
|
+
slot.timer ??= this.clock.setTimer(() => this.close(key), slot.endsAt - now);
|
|
15989
|
+
}
|
|
15990
|
+
flush() {
|
|
15991
|
+
for (const [key, slot] of this.slots) {
|
|
15992
|
+
if (slot.timer !== void 0) this.clock.clearTimer(slot.timer);
|
|
15993
|
+
if (slot.pending) this.show(slot.pending.event, slot.pending.count - 1);
|
|
15994
|
+
this.slots.delete(key);
|
|
15995
|
+
}
|
|
15996
|
+
}
|
|
15997
|
+
close(key) {
|
|
15998
|
+
const slot = this.slots.get(key);
|
|
15999
|
+
if (!slot) return;
|
|
16000
|
+
slot.timer = void 0;
|
|
16001
|
+
if (!slot.pending) return;
|
|
16002
|
+
const { event, count } = slot.pending;
|
|
16003
|
+
slot.pending = void 0;
|
|
16004
|
+
slot.endsAt = this.clock.now() + NOTIFY_BATCH_MS;
|
|
16005
|
+
this.show(event, count - 1);
|
|
16006
|
+
}
|
|
16007
|
+
};
|
|
16008
|
+
function notifyFailureReason(error) {
|
|
16009
|
+
if (error && typeof error === "object") {
|
|
16010
|
+
const value = error;
|
|
16011
|
+
if (value.code === "ENOENT") return "not-found";
|
|
16012
|
+
if (value.code === "EACCES") return "no-permission";
|
|
16013
|
+
if (typeof value.signal === "string" && value.signal !== "") return "signal";
|
|
16014
|
+
if (typeof value.code === "number") return `exit-${value.code}`;
|
|
16015
|
+
}
|
|
16016
|
+
return "failed";
|
|
15890
16017
|
}
|
|
15891
|
-
|
|
15892
|
-
|
|
15893
|
-
|
|
15894
|
-
const
|
|
15895
|
-
|
|
15896
|
-
const
|
|
15897
|
-
|
|
15898
|
-
if (
|
|
15899
|
-
|
|
15900
|
-
|
|
15901
|
-
|
|
15902
|
-
|
|
16018
|
+
function createPcNotifier(input) {
|
|
16019
|
+
const tool = notifyTool(input.platform);
|
|
16020
|
+
const run = input.run ?? runQuiet;
|
|
16021
|
+
const clock = input.clock ?? systemClock;
|
|
16022
|
+
let last = Promise.resolve();
|
|
16023
|
+
const show = (event, more) => {
|
|
16024
|
+
input.log.write({ event: "pc_notify", kind: event.kind, browserKeyId: event.keyId, more, tool: tool?.name ?? "none" });
|
|
16025
|
+
if (!tool) {
|
|
16026
|
+
input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: "none", reason: "no-tool-on-this-os" });
|
|
16027
|
+
last = Promise.resolve();
|
|
16028
|
+
return;
|
|
16029
|
+
}
|
|
16030
|
+
const { title, body } = notificationText(event, more);
|
|
16031
|
+
last = run(tool.file, tool.args(title, body)).then(
|
|
16032
|
+
() => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: true, tool: tool.name }),
|
|
16033
|
+
(error) => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: tool.name, reason: notifyFailureReason(error) })
|
|
16034
|
+
);
|
|
15903
16035
|
};
|
|
15904
|
-
const
|
|
15905
|
-
|
|
15906
|
-
|
|
15907
|
-
|
|
15908
|
-
|
|
15909
|
-
|
|
15910
|
-
|
|
15911
|
-
|
|
15912
|
-
|
|
16036
|
+
const batcher = new NotifyBatcher(show, clock);
|
|
16037
|
+
return {
|
|
16038
|
+
async notify(event) {
|
|
16039
|
+
const before = last;
|
|
16040
|
+
batcher.add({ ...event, at: new Date(clock.now()) });
|
|
16041
|
+
if (last !== before) await last;
|
|
16042
|
+
},
|
|
16043
|
+
async flush() {
|
|
16044
|
+
const before = last;
|
|
16045
|
+
batcher.flush();
|
|
16046
|
+
if (last !== before) await last;
|
|
16047
|
+
}
|
|
16048
|
+
};
|
|
16049
|
+
}
|
|
16050
|
+
|
|
16051
|
+
// src/core/pc/pcApproval.ts
|
|
16052
|
+
var ApprovalSlot = class {
|
|
16053
|
+
current;
|
|
16054
|
+
/** 대기 중인 것이 있나. */
|
|
16055
|
+
get busy() {
|
|
16056
|
+
return this.current !== void 0;
|
|
16057
|
+
}
|
|
16058
|
+
/** 등록 작업이 결정을 기다린다. signal 이 끝나면 대기를 비우고 거절(reject)한다. 이미 대기 중이면 거절한다(다리당 하나). */
|
|
16059
|
+
wait(request, at, signal) {
|
|
16060
|
+
if (this.current) return Promise.reject(new Error("Another device approval is already waiting."));
|
|
16061
|
+
return new Promise((resolve4, reject) => {
|
|
16062
|
+
const clear = () => {
|
|
16063
|
+
signal.removeEventListener("abort", onAbort);
|
|
16064
|
+
if (this.current?.request === request) this.current = void 0;
|
|
16065
|
+
};
|
|
16066
|
+
const onAbort = () => {
|
|
16067
|
+
clear();
|
|
16068
|
+
reject(new Error("The device approval ended before anyone answered."));
|
|
16069
|
+
};
|
|
16070
|
+
if (signal.aborted) {
|
|
16071
|
+
onAbort();
|
|
16072
|
+
return;
|
|
16073
|
+
}
|
|
16074
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
16075
|
+
this.current = {
|
|
16076
|
+
request,
|
|
16077
|
+
at,
|
|
16078
|
+
settle: (approval) => {
|
|
16079
|
+
clear();
|
|
16080
|
+
resolve4(approval);
|
|
16081
|
+
},
|
|
16082
|
+
fail: (error) => {
|
|
16083
|
+
clear();
|
|
16084
|
+
reject(error);
|
|
16085
|
+
}
|
|
16086
|
+
};
|
|
16087
|
+
});
|
|
16088
|
+
}
|
|
16089
|
+
/** 이미 믿는 브라우저가 물어 가져갈 것 — 없으면 undefined. */
|
|
16090
|
+
pending() {
|
|
16091
|
+
return this.current ? { request: this.current.request, at: this.current.at } : void 0;
|
|
16092
|
+
}
|
|
16093
|
+
/** 허용·거절 — T 가 지금 대기 중인 것과 같을 때만 한 번 소비한다. approverKeyId = 명령을 보낸 채널의 브라우저 키. */
|
|
16094
|
+
decide(transcript, accept, approverKeyId) {
|
|
16095
|
+
const current = this.current;
|
|
16096
|
+
if (!current || !macEquals(current.request.transcript, transcript)) return "stale";
|
|
16097
|
+
current.settle(accept ? { accepted: true, approverKeyId } : { accepted: false });
|
|
16098
|
+
return accept ? "recorded" : "rejected";
|
|
16099
|
+
}
|
|
16100
|
+
/** 그 키를 지웠다 — 그 키가 후보인 대기면 끝낸다(허용한 쪽 키는 핀을 쓰는 갱신에서 다시 본다). 끝냈으면 true. */
|
|
16101
|
+
cancelInvolving(keyId) {
|
|
16102
|
+
if (this.current?.request.keyId !== keyId) return false;
|
|
16103
|
+
this.current.fail(new Error("The device was removed while it was waiting for approval."));
|
|
16104
|
+
return true;
|
|
16105
|
+
}
|
|
16106
|
+
};
|
|
16107
|
+
|
|
16108
|
+
// src/core/pc/pcPairing.ts
|
|
16109
|
+
var PAIR_WAIT_MS = 5 * 6e4;
|
|
16110
|
+
async function runPairing(input) {
|
|
16111
|
+
const deadline = new AbortController();
|
|
16112
|
+
const timer = setTimeout(() => deadline.abort(), input.waitMs);
|
|
16113
|
+
let cancelled = false;
|
|
16114
|
+
const onCancel = () => {
|
|
16115
|
+
cancelled = true;
|
|
16116
|
+
deadline.abort();
|
|
16117
|
+
};
|
|
16118
|
+
input.cancel?.addEventListener("abort", onCancel, { once: true });
|
|
16119
|
+
if (input.cancel?.aborted) onCancel();
|
|
16120
|
+
const { signal } = deadline;
|
|
16121
|
+
const relayed = async (step) => {
|
|
15913
16122
|
try {
|
|
15914
|
-
|
|
16123
|
+
return await step();
|
|
15915
16124
|
} catch (error) {
|
|
15916
|
-
|
|
16125
|
+
if (signal.aborted) return "timeout";
|
|
16126
|
+
throw error;
|
|
15917
16127
|
}
|
|
15918
|
-
|
|
15919
|
-
|
|
15920
|
-
|
|
15921
|
-
|
|
15922
|
-
|
|
15923
|
-
|
|
15924
|
-
|
|
15925
|
-
|
|
15926
|
-
|
|
15927
|
-
|
|
15928
|
-
|
|
15929
|
-
|
|
15930
|
-
|
|
15931
|
-
const
|
|
15932
|
-
|
|
15933
|
-
|
|
15934
|
-
|
|
15935
|
-
|
|
15936
|
-
|
|
15937
|
-
|
|
15938
|
-
|
|
15939
|
-
|
|
15940
|
-
|
|
15941
|
-
|
|
15942
|
-
|
|
15943
|
-
|
|
15944
|
-
|
|
15945
|
-
|
|
15946
|
-
|
|
15947
|
-
|
|
15948
|
-
|
|
15949
|
-
|
|
15950
|
-
|
|
15951
|
-
|
|
15952
|
-
|
|
15953
|
-
|
|
15954
|
-
|
|
15955
|
-
|
|
15956
|
-
|
|
15957
|
-
|
|
15958
|
-
|
|
15959
|
-
|
|
16128
|
+
};
|
|
16129
|
+
let outcome;
|
|
16130
|
+
try {
|
|
16131
|
+
outcome = await pairOnce();
|
|
16132
|
+
if (cancelled && outcome.kind === "timeout") outcome = { kind: "cancelled" };
|
|
16133
|
+
return outcome;
|
|
16134
|
+
} finally {
|
|
16135
|
+
clearTimeout(timer);
|
|
16136
|
+
input.cancel?.removeEventListener("abort", onCancel);
|
|
16137
|
+
if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
|
|
16138
|
+
}
|
|
16139
|
+
async function pairOnce() {
|
|
16140
|
+
const pcPublicRaw = publicRawFromJwk(input.pcKey);
|
|
16141
|
+
const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
|
|
16142
|
+
const commit = await pairCommitment(pcPublicRaw, nP);
|
|
16143
|
+
const offer = await relayed(() => input.transport.offer(commit, signal));
|
|
16144
|
+
if (offer === "timeout") return { kind: "timeout" };
|
|
16145
|
+
const publicJwk = publicJwkFromRaw(offer.publicRaw);
|
|
16146
|
+
await assertSigningPublicKey(publicJwk);
|
|
16147
|
+
if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
|
|
16148
|
+
throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 browser registration aborted.");
|
|
16149
|
+
}
|
|
16150
|
+
const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
|
|
16151
|
+
const transcript = () => pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
|
|
16152
|
+
const confirm = input.confirm;
|
|
16153
|
+
if (confirm.kind === "approval") {
|
|
16154
|
+
const consent = input.transport.deviceConsent?.bind(input.transport);
|
|
16155
|
+
if (!consent) throw new E2eError("E2E_BAD_INPUT", "This relay cannot carry the new device's consent \u2014 device approval aborted.");
|
|
16156
|
+
const t2 = await transcript();
|
|
16157
|
+
const request = { transcript: t2, code: (await pairCodes(t2)).a, name: browser.name, keyId: browser.keyId };
|
|
16158
|
+
const step = new AbortController();
|
|
16159
|
+
const stop = () => step.abort();
|
|
16160
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
16161
|
+
let approverKeyId;
|
|
16162
|
+
let agreed;
|
|
16163
|
+
try {
|
|
16164
|
+
const byBrowser = confirm.approve(request, step.signal).then((approval) => {
|
|
16165
|
+
if (approval.accepted) approverKeyId = approval.approverKeyId;
|
|
16166
|
+
return approval.accepted;
|
|
16167
|
+
});
|
|
16168
|
+
const byDevice = input.transport.reveal(pcPublicRaw, nP, step.signal).then(() => consent(step.signal)).then((sig) => sig !== void 0 && verifyBytes(publicJwk, sig, pairApproveInput(t2)));
|
|
16169
|
+
agreed = await relayed(() => bothAgree(byBrowser, byDevice));
|
|
16170
|
+
} finally {
|
|
16171
|
+
signal.removeEventListener("abort", stop);
|
|
16172
|
+
step.abort();
|
|
16173
|
+
}
|
|
16174
|
+
if (agreed === "timeout") return { kind: "timeout" };
|
|
16175
|
+
if (!agreed || await input.pin(browser, approverKeyId) === false) return { kind: "code-mismatch" };
|
|
16176
|
+
return await finish(browser, t2, async () => {
|
|
16177
|
+
});
|
|
16178
|
+
}
|
|
16179
|
+
const keys = await registerKeys(confirm.secret);
|
|
16180
|
+
const expected = await registerOfferMac(keys.browser, {
|
|
16181
|
+
userId: input.userId,
|
|
16182
|
+
pcId: input.pcId,
|
|
16183
|
+
attemptId: offer.attemptId,
|
|
16184
|
+
commit,
|
|
16185
|
+
browserPublicRaw: offer.publicRaw,
|
|
16186
|
+
keyId: offer.keyId,
|
|
16187
|
+
nB: offer.nB,
|
|
16188
|
+
name: offer.name
|
|
16189
|
+
});
|
|
16190
|
+
if (!offer.macB || !macEquals(offer.macB, expected)) return { kind: "code-mismatch" };
|
|
16191
|
+
const t = await transcript();
|
|
16192
|
+
await input.pin(browser);
|
|
16193
|
+
const macP = await registerRevealMac(keys.pc, { transcript: t, attemptId: offer.attemptId });
|
|
16194
|
+
return await finish(browser, t, () => input.transport.reveal(pcPublicRaw, nP, signal, macP));
|
|
16195
|
+
}
|
|
16196
|
+
async function finish(browser, transcript, before) {
|
|
16197
|
+
const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
|
|
16198
|
+
let doneError;
|
|
16199
|
+
try {
|
|
16200
|
+
await before();
|
|
16201
|
+
await input.transport.done(signature, signal);
|
|
16202
|
+
} catch (error) {
|
|
16203
|
+
doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
|
|
16204
|
+
}
|
|
16205
|
+
return { kind: "paired", browser, doneError };
|
|
16206
|
+
}
|
|
16207
|
+
}
|
|
16208
|
+
function bothAgree(a, b) {
|
|
16209
|
+
return new Promise((resolve4, reject) => {
|
|
16210
|
+
let left = 2;
|
|
16211
|
+
let settled = false;
|
|
16212
|
+
const settle = (fn) => {
|
|
16213
|
+
if (settled) return;
|
|
16214
|
+
settled = true;
|
|
16215
|
+
fn();
|
|
16216
|
+
};
|
|
16217
|
+
for (const each of [a, b]) {
|
|
16218
|
+
each.then((ok) => {
|
|
16219
|
+
if (!ok) settle(() => resolve4(false));
|
|
16220
|
+
else if (--left === 0) settle(() => resolve4(true));
|
|
16221
|
+
}, (error) => settle(() => reject(error)));
|
|
16222
|
+
}
|
|
16223
|
+
});
|
|
16224
|
+
}
|
|
16225
|
+
|
|
16226
|
+
// src/core/pc/pcDevices.ts
|
|
16227
|
+
var DeviceManager = class {
|
|
16228
|
+
constructor(deps) {
|
|
16229
|
+
this.deps = deps;
|
|
16230
|
+
this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
16231
|
+
}
|
|
16232
|
+
deps;
|
|
16233
|
+
slot = new ApprovalSlot();
|
|
16234
|
+
running;
|
|
16235
|
+
quietUntil = 0;
|
|
16236
|
+
/** keyId → 지운 시각(ms). 그보다 먼저 시작한 등록은 그 키를 쓰지 못한다(다시 요청하면 새 등록이라 쓸 수 있다). */
|
|
16237
|
+
removedAt = /* @__PURE__ */ new Map();
|
|
16238
|
+
now;
|
|
16239
|
+
/** poll 의 pair-request — 받을 수 있으면 등록 작업을 백그라운드로 시작한다(기다리지 않는다). */
|
|
16240
|
+
async onPairRequest(requestId) {
|
|
16241
|
+
const refuse = (reason) => this.deps.log({ event: "pc_device", step: "request", requestId, result: "ignored", reason });
|
|
16242
|
+
if (!this.deps.remoteOn()) return refuse("remote-off");
|
|
16243
|
+
if (this.running) return refuse("busy");
|
|
16244
|
+
if (this.now().getTime() < this.quietUntil) return refuse("quiet");
|
|
16245
|
+
const account2 = await this.account();
|
|
16246
|
+
if (!account2 || account2.browsers.length === 0) return refuse("no-trusted-browser");
|
|
16247
|
+
const stop = new AbortController();
|
|
16248
|
+
this.running = { requestId, stop };
|
|
16249
|
+
this.deps.log({ event: "pc_device", step: "request", requestId, result: "started" });
|
|
16250
|
+
void this.pair(requestId, account2.pcKey, stop).finally(() => {
|
|
16251
|
+
if (this.running?.requestId === requestId) this.running = void 0;
|
|
16252
|
+
});
|
|
16253
|
+
}
|
|
16254
|
+
/** 다리 끝·원격 꺼짐·링크 다시 열기 — 진행 중 등록을 끝낸다(abort 를 보낸다). */
|
|
16255
|
+
stop() {
|
|
16256
|
+
this.running?.stop.abort();
|
|
16257
|
+
}
|
|
16258
|
+
/** 이미 믿는 브라우저의 봉인 명령 하나 — 봉인 답의 result. browser = 명령을 보낸 채널의 브라우저. */
|
|
16259
|
+
async command(action, browser) {
|
|
16260
|
+
switch (action.action) {
|
|
16261
|
+
case "pending": {
|
|
16262
|
+
const pending = this.slot.pending();
|
|
16263
|
+
return {
|
|
16264
|
+
request: pending ? { T: b64u2(pending.request.transcript), code: pending.request.code, name: pending.request.name, at: pending.at.toISOString() } : null
|
|
16265
|
+
};
|
|
16266
|
+
}
|
|
16267
|
+
case "approve": {
|
|
16268
|
+
const result = this.slot.decide(action.transcript, action.accept, browser.keyId);
|
|
16269
|
+
this.deps.log({ event: "pc_device", step: "approve", keyId: browser.keyId, result });
|
|
16270
|
+
return { result };
|
|
16271
|
+
}
|
|
16272
|
+
case "list": {
|
|
16273
|
+
const account2 = await this.account();
|
|
16274
|
+
return {
|
|
16275
|
+
devices: (account2?.browsers ?? []).map((item) => ({
|
|
16276
|
+
keyId: item.keyId,
|
|
16277
|
+
name: item.name,
|
|
16278
|
+
pairedAt: item.pairedAt,
|
|
16279
|
+
current: item.keyId === browser.keyId
|
|
16280
|
+
}))
|
|
16281
|
+
};
|
|
16282
|
+
}
|
|
16283
|
+
case "remove": {
|
|
16284
|
+
this.removedAt.set(action.keyId, this.now().getTime());
|
|
16285
|
+
this.slot.cancelInvolving(action.keyId);
|
|
16286
|
+
let removed = false;
|
|
16287
|
+
await updatePcKeys(this.deps.keysPath, (keys) => {
|
|
16288
|
+
const account2 = keys.accounts[this.deps.accountKey];
|
|
16289
|
+
if (!account2?.browsers.some((item) => item.keyId === action.keyId)) return void 0;
|
|
16290
|
+
removed = true;
|
|
16291
|
+
return { accounts: { ...keys.accounts, [this.deps.accountKey]: {
|
|
16292
|
+
...account2,
|
|
16293
|
+
browsers: account2.browsers.filter((item) => item.keyId !== action.keyId)
|
|
16294
|
+
} } };
|
|
16295
|
+
});
|
|
16296
|
+
await this.deps.closeKey(action.keyId);
|
|
16297
|
+
this.deps.log({ event: "pc_device", step: "remove", keyId: action.keyId, result: removed ? "removed" : "absent" });
|
|
16298
|
+
return { removed };
|
|
16299
|
+
}
|
|
16300
|
+
}
|
|
16301
|
+
}
|
|
16302
|
+
async pair(requestId, pcKey, stop) {
|
|
16303
|
+
let outcome;
|
|
16304
|
+
let reason;
|
|
16305
|
+
const startedAt = this.now().getTime();
|
|
16306
|
+
try {
|
|
16307
|
+
outcome = await runPairing({
|
|
16308
|
+
userId: transcriptUserId(this.deps.userId),
|
|
16309
|
+
pcId: this.deps.pcId,
|
|
16310
|
+
pcKey,
|
|
16311
|
+
transport: this.deps.relay(requestId),
|
|
16312
|
+
confirm: {
|
|
16313
|
+
kind: "approval",
|
|
16314
|
+
approve: (request, signal) => {
|
|
16315
|
+
this.deps.notifyRequest(request.name);
|
|
16316
|
+
this.deps.log({ event: "pc_device", step: "waiting", requestId, keyId: request.keyId });
|
|
16317
|
+
return this.slot.wait(request, this.now(), signal);
|
|
16318
|
+
}
|
|
16319
|
+
},
|
|
16320
|
+
pin: async (browser, approverKeyId) => await this.pinApproved(browser, approverKeyId, pcKey, this.now().toISOString(), startedAt, stop.signal),
|
|
16321
|
+
waitMs: this.deps.waitMs ?? PAIR_WAIT_MS,
|
|
16322
|
+
cancel: stop.signal
|
|
16323
|
+
});
|
|
16324
|
+
} catch (error) {
|
|
16325
|
+
reason = error instanceof Error ? error.message : String(error);
|
|
16326
|
+
}
|
|
16327
|
+
if (outcome?.kind === "paired" && outcome.doneError !== void 0) reason = outcome.doneError;
|
|
16328
|
+
const result = outcome === void 0 ? "error" : outcome.kind === "paired" && outcome.doneError !== void 0 ? "done-failed" : outcome.kind;
|
|
16329
|
+
if (result !== "paired" && result !== "timeout") this.quietUntil = this.now().getTime() + NOTIFY_BATCH_MS;
|
|
16330
|
+
this.deps.log({
|
|
16331
|
+
event: "pc_device",
|
|
16332
|
+
step: "finished",
|
|
16333
|
+
requestId,
|
|
16334
|
+
result,
|
|
16335
|
+
...outcome?.kind === "paired" ? { keyId: outcome.browser.keyId } : {},
|
|
16336
|
+
...reason ? { reason } : {}
|
|
16337
|
+
});
|
|
16338
|
+
}
|
|
16339
|
+
/** 양쪽 동의 뒤 — 같은 갱신 안에서 «허용한 키가 아직 있음 · PC 키 그대로»를 다시 보고 쓴다. 아니면 false(핀 0). */
|
|
16340
|
+
async pinApproved(browser, approverKeyId, pcKey, pairedAt, startedAt, stopped) {
|
|
16341
|
+
let pinned = false;
|
|
16342
|
+
const deadline = startedAt + (this.deps.waitMs ?? PAIR_WAIT_MS);
|
|
16343
|
+
await updatePcKeys(this.deps.keysPath, (keys) => {
|
|
16344
|
+
if (stopped.aborted || this.now().getTime() >= deadline) return void 0;
|
|
16345
|
+
if ((this.removedAt.get(browser.keyId) ?? -1) >= startedAt) return void 0;
|
|
16346
|
+
if (approverKeyId !== void 0 && (this.removedAt.get(approverKeyId) ?? -1) >= startedAt) return void 0;
|
|
16347
|
+
const account2 = keys.accounts[this.deps.accountKey];
|
|
16348
|
+
if (!account2 || account2.pcKey.d !== pcKey.d || !account2.browsers.some((item) => item.keyId === approverKeyId)) return void 0;
|
|
16349
|
+
if (account2.pendingTurnOff?.removals.some((item) => item.keyId === browser.keyId)) return void 0;
|
|
16350
|
+
pinned = true;
|
|
16351
|
+
return withBrowser(keys, this.deps.accountKey, pcKey, { ...browser, pairedAt });
|
|
16352
|
+
});
|
|
16353
|
+
return pinned;
|
|
16354
|
+
}
|
|
16355
|
+
async account() {
|
|
16356
|
+
try {
|
|
16357
|
+
return (await loadPcKeys(this.deps.keysPath)).accounts[this.deps.accountKey];
|
|
16358
|
+
} catch {
|
|
16359
|
+
return void 0;
|
|
16360
|
+
}
|
|
16361
|
+
}
|
|
16362
|
+
};
|
|
16363
|
+
function b64u2(bytes) {
|
|
16364
|
+
return Buffer.from(bytes).toString("base64url");
|
|
16365
|
+
}
|
|
16366
|
+
|
|
16367
|
+
// src/core/term/remote.ts
|
|
16368
|
+
var REMOTE_STATE_PREFIX = "Remote terminal: ";
|
|
16369
|
+
var REMOTE_OFF_BY_WEB_LINE = `${REMOTE_STATE_PREFIX}turned off from the web.`;
|
|
16370
|
+
var REMOTE_NOT_FOUND = "REMOTE_NOT_FOUND";
|
|
16371
|
+
var E2E_VERSION = 1;
|
|
16372
|
+
function openRemoteLog(paths) {
|
|
16373
|
+
const log = new DaemonLog(paths.remoteLog, paths.previousRemoteLog);
|
|
16374
|
+
log.enableRotation();
|
|
16375
|
+
return log;
|
|
16376
|
+
}
|
|
16377
|
+
function createRemoteHttp(input) {
|
|
16378
|
+
return createPcHttp({
|
|
16379
|
+
endpoint: input.endpoint,
|
|
16380
|
+
path: "term/pc",
|
|
16381
|
+
tokenProvider: input.tokenProvider,
|
|
16382
|
+
timeoutMs: CALL_TIMEOUT_MS,
|
|
16383
|
+
sessionHeader: "X-Remote-Token",
|
|
16384
|
+
fetchImpl: input.fetchImpl,
|
|
16385
|
+
logging: {
|
|
16386
|
+
log: input.log,
|
|
16387
|
+
request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
|
|
16388
|
+
response: ({ callId, op, ms }, outcome) => ({
|
|
16389
|
+
event: "remote_call_response",
|
|
16390
|
+
callId,
|
|
16391
|
+
op,
|
|
16392
|
+
...outcome.ok ? { ok: true, status: outcome.status, ...answerSummary(outcome.body) } : outcome,
|
|
16393
|
+
ms
|
|
16394
|
+
})
|
|
16395
|
+
}
|
|
16396
|
+
});
|
|
16397
|
+
}
|
|
16398
|
+
var viewerKey = (watch) => `${watch.channelId}\0${watch.session}`;
|
|
16399
|
+
async function runRemoteBridge(deps) {
|
|
16400
|
+
let ending;
|
|
16401
|
+
const stopper = new AbortController();
|
|
16402
|
+
const viewers = /* @__PURE__ */ new Map();
|
|
16403
|
+
const book = new ChannelBook(deps.pcId);
|
|
16404
|
+
let devices;
|
|
16405
|
+
const end = (outcome) => {
|
|
16406
|
+
if (ending) return;
|
|
16407
|
+
ending = outcome;
|
|
16408
|
+
devices?.stop();
|
|
16409
|
+
stopper.abort();
|
|
16410
|
+
for (const { viewer } of viewers.values()) viewer.stop();
|
|
16411
|
+
viewers.clear();
|
|
16412
|
+
};
|
|
16413
|
+
const onUserStop = () => end({ exitCode: 0, reason: "Stopped.", close: true });
|
|
16414
|
+
if (deps.signal.aborted) onUserStop();
|
|
16415
|
+
deps.signal.addEventListener("abort", onUserStop, { once: true });
|
|
16416
|
+
const control = new DaemonControl(deps.paths);
|
|
16417
|
+
let listWatch;
|
|
16418
|
+
try {
|
|
16419
|
+
const first = await currentSessions(deps);
|
|
16420
|
+
if (ending) return { exitCode: ending.exitCode, reason: ending.reason };
|
|
16421
|
+
let link2;
|
|
16422
|
+
try {
|
|
16423
|
+
link2 = await openLink2(deps, 1, deps.remoteEnabled, deps.remoteEnabled ? first : [], void 0);
|
|
16424
|
+
} catch (error) {
|
|
16425
|
+
return { exitCode: 1, reason: refused(error).reason };
|
|
16426
|
+
}
|
|
16427
|
+
let remote = startState(deps.remoteEnabled);
|
|
16428
|
+
let uploaded = deps.remoteEnabled ? sessionsKey(first) : void 0;
|
|
16429
|
+
let watchList = [];
|
|
16430
|
+
deps.log.write({
|
|
16431
|
+
event: "remote_opened",
|
|
16432
|
+
linkId: link2.linkId,
|
|
16433
|
+
sessions: deps.remoteEnabled ? first.length : 0,
|
|
16434
|
+
remote,
|
|
16435
|
+
pollHoldSeconds: link2.pollHoldSeconds,
|
|
16436
|
+
frameMaxBytes: link2.frameMaxBytes
|
|
16437
|
+
});
|
|
16438
|
+
deps.print(deps.remoteEnabled ? `${REMOTE_STATE_PREFIX}on \u2014 ${first.length} session(s) from ${deps.hostName} are listed in AiNecto on the web.` : `${REMOTE_STATE_PREFIX}off on this PC (\`ainecto remote on\` allows it).`);
|
|
16439
|
+
let syncing = Promise.resolve();
|
|
16440
|
+
const syncList = () => {
|
|
16441
|
+
syncing = syncing.then(async () => {
|
|
16442
|
+
if (ending || remote !== "on") return;
|
|
16443
|
+
let sessions;
|
|
16444
|
+
try {
|
|
16445
|
+
sessions = await currentSessions(deps);
|
|
16446
|
+
} catch (error) {
|
|
16447
|
+
daemonFailed(deps, "ls", void 0, error);
|
|
16448
|
+
return;
|
|
16449
|
+
}
|
|
16450
|
+
const key = sessionsKey(sessions);
|
|
16451
|
+
if (key === uploaded) return;
|
|
16452
|
+
try {
|
|
16453
|
+
await deps.http.call("sessions", { linkId: link2.linkId, sessions }, { signal: stopper.signal });
|
|
16454
|
+
uploaded = key;
|
|
16455
|
+
for (const { viewer } of viewers.values()) viewer.refresh();
|
|
16456
|
+
} catch {
|
|
16457
|
+
}
|
|
16458
|
+
});
|
|
16459
|
+
return syncing;
|
|
16460
|
+
};
|
|
16461
|
+
listWatch = await openTermClient(deps.paths, { start: false });
|
|
16462
|
+
if (listWatch) {
|
|
16463
|
+
listWatch.onEvent((event) => {
|
|
16464
|
+
if (event.event === "sessions") void syncList();
|
|
16465
|
+
});
|
|
16466
|
+
try {
|
|
16467
|
+
await listWatch.request({ op: "watch-sessions" });
|
|
16468
|
+
} catch (error) {
|
|
15960
16469
|
daemonFailed(deps, "watch-sessions", void 0, error);
|
|
15961
16470
|
}
|
|
15962
16471
|
}
|
|
@@ -16055,6 +16564,7 @@ async function runRemoteBridge(deps) {
|
|
|
16055
16564
|
void syncList();
|
|
16056
16565
|
deps.print(`${REMOTE_STATE_PREFIX}on.`);
|
|
16057
16566
|
} else {
|
|
16567
|
+
devices?.stop();
|
|
16058
16568
|
await closeAllChannels("REMOTE_OFF");
|
|
16059
16569
|
deps.print(remote === "off-by-web" ? `${REMOTE_OFF_BY_WEB_LINE} Run \`ainecto\` (or \`ainecto remote on\`) on this PC to turn it back on.` : `${REMOTE_STATE_PREFIX}off on this PC (\`ainecto remote on\` allows it).`);
|
|
16060
16570
|
}
|
|
@@ -16092,7 +16602,36 @@ async function runRemoteBridge(deps) {
|
|
|
16092
16602
|
return;
|
|
16093
16603
|
}
|
|
16094
16604
|
};
|
|
16605
|
+
const closeKey = async (keyId) => {
|
|
16606
|
+
for (const channelId of book.dropBrowser(keyId)) {
|
|
16607
|
+
stopViewers(channelId);
|
|
16608
|
+
commands.forgetChannel(channelId);
|
|
16609
|
+
deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "pc", reason: "PAIRING_REQUIRED", browserKeyId: keyId });
|
|
16610
|
+
try {
|
|
16611
|
+
await deps.http.call("channel/close", { linkId: link2.linkId, channelId, reason: "PAIRING_REQUIRED" }, { signal: stopper.signal });
|
|
16612
|
+
} catch {
|
|
16613
|
+
}
|
|
16614
|
+
}
|
|
16615
|
+
};
|
|
16616
|
+
if (deps.trust && deps.pairRelay) {
|
|
16617
|
+
const trust = deps.trust;
|
|
16618
|
+
const relay = deps.pairRelay;
|
|
16619
|
+
devices = new DeviceManager({
|
|
16620
|
+
keysPath: trust.keysPath,
|
|
16621
|
+
accountKey: trust.accountKey,
|
|
16622
|
+
userId: trust.userId,
|
|
16623
|
+
pcId: deps.pcId,
|
|
16624
|
+
relay,
|
|
16625
|
+
notifyRequest: (name) => void deps.notifier.notify({ kind: "device-request", keyId: "device-request", browserName: name }),
|
|
16626
|
+
log: (record4) => deps.log.write(record4),
|
|
16627
|
+
closeKey,
|
|
16628
|
+
// ★PC 설정이 먼저다 — 서버 poll 의 remote 로는 줄일 수만 있다(서버가 «켜짐»을 보내도 PC 에서 끈 원격은 열리지 않는다).
|
|
16629
|
+
remoteOn: () => deps.remoteEnabled && remote === "on" && !ending
|
|
16630
|
+
});
|
|
16631
|
+
}
|
|
16095
16632
|
const commands = new CommandRunner(deps, control, book, () => remote, () => link2.linkId, stopper.signal, {
|
|
16633
|
+
devices: () => devices,
|
|
16634
|
+
trusted: async (keyId) => (await loadTrust(deps))?.browsers.some((item) => item.keyId === keyId) === true,
|
|
16096
16635
|
closeChannel,
|
|
16097
16636
|
refreshChannel,
|
|
16098
16637
|
resized: (session, size) => {
|
|
@@ -16127,6 +16666,7 @@ async function runRemoteBridge(deps) {
|
|
|
16127
16666
|
end(refused(reopenError));
|
|
16128
16667
|
break;
|
|
16129
16668
|
}
|
|
16669
|
+
devices?.stop();
|
|
16130
16670
|
const dropped = book.dropAll();
|
|
16131
16671
|
for (const channelId of dropped) {
|
|
16132
16672
|
stopViewers(channelId);
|
|
@@ -16182,6 +16722,9 @@ async function runRemoteBridge(deps) {
|
|
|
16182
16722
|
case "watch":
|
|
16183
16723
|
watchList = item.channels;
|
|
16184
16724
|
break;
|
|
16725
|
+
case "pair-request":
|
|
16726
|
+
await devices?.onPairRequest(item.requestId);
|
|
16727
|
+
break;
|
|
16185
16728
|
case "channel-closed":
|
|
16186
16729
|
if (book.drop(item.channelId)) {
|
|
16187
16730
|
deps.log.write({ event: "remote_channel", channelId: item.channelId, state: "closed", by: "web" });
|
|
@@ -16218,14 +16761,16 @@ function startState(remoteEnabled) {
|
|
|
16218
16761
|
return remoteEnabled ? "on" : "off-by-pc";
|
|
16219
16762
|
}
|
|
16220
16763
|
async function openLink2(deps, generation, remoteEnabled, sessions, signal) {
|
|
16221
|
-
const
|
|
16222
|
-
|
|
16223
|
-
|
|
16224
|
-
|
|
16225
|
-
|
|
16226
|
-
|
|
16227
|
-
|
|
16228
|
-
|
|
16764
|
+
const base = { pcId: deps.pcId, hostName: deps.hostName, cliVersion: deps.cliVersion, remoteEnabled, sessions, e2e: E2E_VERSION };
|
|
16765
|
+
const devices = deps.trust !== void 0 && deps.pairRelay !== void 0;
|
|
16766
|
+
let opened;
|
|
16767
|
+
try {
|
|
16768
|
+
opened = await deps.http.call("open", devices ? { ...base, devices: true } : base, signal ? { signal } : void 0);
|
|
16769
|
+
} catch (error) {
|
|
16770
|
+
if (!devices || !(error instanceof PcCallError && error.status === 400 && error.code === "INVALID")) throw error;
|
|
16771
|
+
deps.log.write({ event: "remote_open_without_devices", reason: "server refused the devices field" });
|
|
16772
|
+
opened = await deps.http.call("open", base, signal ? { signal } : void 0);
|
|
16773
|
+
}
|
|
16229
16774
|
const limits = serverLimits2(opened.limits);
|
|
16230
16775
|
if (typeof opened.linkId !== "string" || typeof opened.linkToken !== "string" || !limits) {
|
|
16231
16776
|
throw new TermError("TERM_REMOTE_BAD_RESPONSE", "AiNecto answered open without linkId, linkToken or limits.");
|
|
@@ -16331,15 +16876,76 @@ var CommandRunner = class {
|
|
|
16331
16876
|
await this.hooks.closeChannel(wire.channelId, outcome.reason);
|
|
16332
16877
|
return;
|
|
16333
16878
|
case "confirmed":
|
|
16879
|
+
if (!await this.hooks.trusted(outcome.browser.keyId)) {
|
|
16880
|
+
await this.hooks.closeChannel(wire.channelId, "PAIRING_REQUIRED", outcome.browser);
|
|
16881
|
+
return;
|
|
16882
|
+
}
|
|
16334
16883
|
this.deps.log.write({ event: "remote_channel", channelId: wire.channelId, state: "active", browserKeyId: outcome.browser.keyId });
|
|
16335
16884
|
void this.deps.notifier.notify({ kind: "session", keyId: outcome.browser.keyId, browserName: outcome.browser.name });
|
|
16336
16885
|
await this.hooks.applyWatching();
|
|
16337
16886
|
return;
|
|
16338
16887
|
case "command":
|
|
16339
|
-
await this.
|
|
16888
|
+
if (outcome.command.kind === "device") await this.device(wire, outcome.command, outcome.browser);
|
|
16889
|
+
else await this.execute(wire, outcome.command, outcome.browser);
|
|
16340
16890
|
return;
|
|
16341
16891
|
}
|
|
16342
16892
|
}
|
|
16893
|
+
/** 기기 관리 명령(approve-new-device §3-4) — 답 봉투 {opId, kind:"device", ok, detail?, result}. 세션 없음(AAD session ""). */
|
|
16894
|
+
async device(wire, command, browser) {
|
|
16895
|
+
this.deps.log.write({
|
|
16896
|
+
event: "remote_command",
|
|
16897
|
+
type: "device",
|
|
16898
|
+
channelId: wire.channelId,
|
|
16899
|
+
n: wire.n,
|
|
16900
|
+
opId: command.opId,
|
|
16901
|
+
...wire.requestId ? { requestId: wire.requestId } : {}
|
|
16902
|
+
});
|
|
16903
|
+
const devices = this.hooks.devices();
|
|
16904
|
+
let failure2;
|
|
16905
|
+
let result = {};
|
|
16906
|
+
if (this.remote() !== "on") {
|
|
16907
|
+
failure2 = { code: "REMOTE_OFF", message: "Terminals from the web are turned off on this PC." };
|
|
16908
|
+
} else if (!devices) {
|
|
16909
|
+
failure2 = { code: "TERM_BAD_REQUEST", message: "This PC cannot manage devices (account unknown)." };
|
|
16910
|
+
} else {
|
|
16911
|
+
try {
|
|
16912
|
+
result = await devices.command(command.action, browser);
|
|
16913
|
+
} catch (error) {
|
|
16914
|
+
failure2 = { code: errorCode2(error), message: error instanceof Error ? error.message : String(error) };
|
|
16915
|
+
}
|
|
16916
|
+
}
|
|
16917
|
+
let box;
|
|
16918
|
+
try {
|
|
16919
|
+
box = await this.book.seal(wire.channelId, { kind: "answer", session: "", opId: command.opId }, {
|
|
16920
|
+
opId: command.opId,
|
|
16921
|
+
kind: "device",
|
|
16922
|
+
ok: failure2 === void 0,
|
|
16923
|
+
...failure2 ? { detail: `${failure2.code}: ${failure2.message}` } : {},
|
|
16924
|
+
result
|
|
16925
|
+
});
|
|
16926
|
+
} catch (error) {
|
|
16927
|
+
const reason = error instanceof ChannelSealError && error.reason !== "CHANNEL_GONE" ? error.reason : void 0;
|
|
16928
|
+
this.logResult(wire, "device", "", false, failure2?.code ?? reason ?? "CHANNEL_GONE");
|
|
16929
|
+
if (reason) await this.hooks.closeChannel(wire.channelId, reason);
|
|
16930
|
+
return;
|
|
16931
|
+
}
|
|
16932
|
+
if (wire.requestId) {
|
|
16933
|
+
try {
|
|
16934
|
+
await this.deps.http.call("answer", {
|
|
16935
|
+
linkId: this.linkId(),
|
|
16936
|
+
requestId: wire.requestId,
|
|
16937
|
+
channelId: wire.channelId,
|
|
16938
|
+
...box,
|
|
16939
|
+
ok: failure2 === void 0,
|
|
16940
|
+
...failure2 ? { code: answerCodeOf(failure2.code) } : {}
|
|
16941
|
+
}, { signal: this.stopSignal });
|
|
16942
|
+
} catch {
|
|
16943
|
+
}
|
|
16944
|
+
}
|
|
16945
|
+
const raised = this.book.executed(wire.channelId, wire.n);
|
|
16946
|
+
this.logResult(wire, "device", "", failure2 === void 0, failure2?.code, raised ? wire.n : void 0);
|
|
16947
|
+
if (raised) this.hooks.refreshChannel(wire.channelId);
|
|
16948
|
+
}
|
|
16343
16949
|
async execute(wire, command, browser) {
|
|
16344
16950
|
const session = command.kind === "create" ? command.name : command.session;
|
|
16345
16951
|
const opId = "opId" in command ? command.opId : void 0;
|
|
@@ -16599,6 +17205,8 @@ function pollItems(answer) {
|
|
|
16599
17205
|
}) : [] }];
|
|
16600
17206
|
case "channel-closed":
|
|
16601
17207
|
return channelId ? [{ type: "channel-closed", channelId }] : [];
|
|
17208
|
+
case "pair-request":
|
|
17209
|
+
return typeof item.requestId === "string" && item.requestId !== "" ? [{ type: "pair-request", requestId: item.requestId }] : [];
|
|
16602
17210
|
default:
|
|
16603
17211
|
return [];
|
|
16604
17212
|
}
|
|
@@ -16655,6 +17263,13 @@ function pcAction(running, cliVersion) {
|
|
|
16655
17263
|
}
|
|
16656
17264
|
return { kind: "replace", pcs: [...running] };
|
|
16657
17265
|
}
|
|
17266
|
+
function daemonUpgrade(daemonVersion, cliVersion, sessions, insideTermSession) {
|
|
17267
|
+
if (daemonVersion === void 0 || daemonVersion === cliVersion || insideTermSession) {
|
|
17268
|
+
return { kind: "keep" };
|
|
17269
|
+
}
|
|
17270
|
+
const user = sessions.filter((session) => !isPcCommand(session.command)).map((session) => session.name);
|
|
17271
|
+
return user.length === 0 ? { kind: "restart" } : { kind: "ask", sessions: user };
|
|
17272
|
+
}
|
|
16658
17273
|
function pcStopDeadlineMs() {
|
|
16659
17274
|
return AGENT_STOP_WAIT_MS * 4 + Math.max(AGENT_CALL_TIMEOUT_MS, CALL_TIMEOUT_MS);
|
|
16660
17275
|
}
|
|
@@ -16708,80 +17323,6 @@ function pcOutcome(lines) {
|
|
|
16708
17323
|
return failed === void 0 ? void 0 : { kind: "failed", line: failed };
|
|
16709
17324
|
}
|
|
16710
17325
|
|
|
16711
|
-
// src/core/pc/pcPairing.ts
|
|
16712
|
-
var PAIR_WAIT_MS = 5 * 6e4;
|
|
16713
|
-
async function runPairing(input) {
|
|
16714
|
-
const deadline = new AbortController();
|
|
16715
|
-
const timer = setTimeout(() => deadline.abort(), input.waitMs);
|
|
16716
|
-
let cancelled = false;
|
|
16717
|
-
const onCancel = () => {
|
|
16718
|
-
cancelled = true;
|
|
16719
|
-
deadline.abort();
|
|
16720
|
-
};
|
|
16721
|
-
input.cancel?.addEventListener("abort", onCancel, { once: true });
|
|
16722
|
-
if (input.cancel?.aborted) onCancel();
|
|
16723
|
-
const { signal } = deadline;
|
|
16724
|
-
const relayed = async (step) => {
|
|
16725
|
-
try {
|
|
16726
|
-
return await step();
|
|
16727
|
-
} catch (error) {
|
|
16728
|
-
if (signal.aborted) return "timeout";
|
|
16729
|
-
throw error;
|
|
16730
|
-
}
|
|
16731
|
-
};
|
|
16732
|
-
let outcome;
|
|
16733
|
-
try {
|
|
16734
|
-
outcome = await pairOnce();
|
|
16735
|
-
if (cancelled && outcome.kind === "timeout") outcome = { kind: "cancelled" };
|
|
16736
|
-
return outcome;
|
|
16737
|
-
} finally {
|
|
16738
|
-
clearTimeout(timer);
|
|
16739
|
-
input.cancel?.removeEventListener("abort", onCancel);
|
|
16740
|
-
if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
|
|
16741
|
-
}
|
|
16742
|
-
async function pairOnce() {
|
|
16743
|
-
const pcPublicRaw = publicRawFromJwk(input.pcKey);
|
|
16744
|
-
const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
|
|
16745
|
-
const commit = await pairCommitment(pcPublicRaw, nP);
|
|
16746
|
-
const offer = await relayed(() => input.transport.offer(commit, signal));
|
|
16747
|
-
if (offer === "timeout") return { kind: "timeout" };
|
|
16748
|
-
const publicJwk = publicJwkFromRaw(offer.publicRaw);
|
|
16749
|
-
await assertSigningPublicKey(publicJwk);
|
|
16750
|
-
if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
|
|
16751
|
-
throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 browser registration aborted.");
|
|
16752
|
-
}
|
|
16753
|
-
const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
|
|
16754
|
-
const transcript = () => pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
|
|
16755
|
-
const keys = await registerKeys(input.secret);
|
|
16756
|
-
const expected = await registerOfferMac(keys.browser, {
|
|
16757
|
-
userId: input.userId,
|
|
16758
|
-
pcId: input.pcId,
|
|
16759
|
-
attemptId: offer.attemptId,
|
|
16760
|
-
commit,
|
|
16761
|
-
browserPublicRaw: offer.publicRaw,
|
|
16762
|
-
keyId: offer.keyId,
|
|
16763
|
-
nB: offer.nB,
|
|
16764
|
-
name: offer.name
|
|
16765
|
-
});
|
|
16766
|
-
if (!offer.macB || !macEquals(offer.macB, expected)) return { kind: "code-mismatch" };
|
|
16767
|
-
const t = await transcript();
|
|
16768
|
-
await input.pin(browser);
|
|
16769
|
-
const macP = await registerRevealMac(keys.pc, { transcript: t, attemptId: offer.attemptId });
|
|
16770
|
-
return await finish(browser, t, () => input.transport.reveal(pcPublicRaw, nP, signal, macP));
|
|
16771
|
-
}
|
|
16772
|
-
async function finish(browser, transcript, before) {
|
|
16773
|
-
const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
|
|
16774
|
-
let doneError;
|
|
16775
|
-
try {
|
|
16776
|
-
await before();
|
|
16777
|
-
await input.transport.done(signature, signal);
|
|
16778
|
-
} catch (error) {
|
|
16779
|
-
doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
|
|
16780
|
-
}
|
|
16781
|
-
return { kind: "paired", browser, doneError };
|
|
16782
|
-
}
|
|
16783
|
-
}
|
|
16784
|
-
|
|
16785
17326
|
// src/adapters/cli/pcCommand.ts
|
|
16786
17327
|
import { readFile as readFile13 } from "fs/promises";
|
|
16787
17328
|
|
|
@@ -16962,6 +17503,7 @@ async function executePcStart(deps) {
|
|
|
16962
17503
|
settings = withConsent(settings, key, remote, /* @__PURE__ */ new Date());
|
|
16963
17504
|
await savePcSettings(deps.settingsPath, settings);
|
|
16964
17505
|
}
|
|
17506
|
+
await upgradeDaemon(deps, note);
|
|
16965
17507
|
const action = pcAction(runningPcs(await listed2(deps)), deps.cliVersion);
|
|
16966
17508
|
if (action.kind === "already") {
|
|
16967
17509
|
if (!remoteOffByWeb(await screenLines2(deps, action.pc.session))) {
|
|
@@ -16984,6 +17526,22 @@ async function executePcStart(deps) {
|
|
|
16984
17526
|
}
|
|
16985
17527
|
return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
|
|
16986
17528
|
}
|
|
17529
|
+
async function upgradeDaemon(deps, note) {
|
|
17530
|
+
const info = readDaemonInfo(deps.paths);
|
|
17531
|
+
if (!info) return;
|
|
17532
|
+
const plan = daemonUpgrade(info.version, deps.cliVersion, await listed2(deps), deps.register?.insideTermSession ?? false);
|
|
17533
|
+
if (plan.kind === "keep") return;
|
|
17534
|
+
if (plan.kind === "ask") {
|
|
17535
|
+
if (!deps.interactive) return;
|
|
17536
|
+
note(`This PC's terminal service is from an older AiNecto (${info.version}). Updating it to ${deps.cliVersion} closes ${plan.sessions.length} open terminal session(s): ${plan.sessions.join(", ")}.`);
|
|
17537
|
+
if (!yes(await promptLine(deps.io, "Update it now? [y/N]: "), false)) return;
|
|
17538
|
+
}
|
|
17539
|
+
note("Updating the AiNecto terminal service on this PC\u2026");
|
|
17540
|
+
await termRequest(deps.paths, { op: "kill-server" }, { start: false });
|
|
17541
|
+
if (!await waitForPidGone(info.pid, deps.stopDeadlineMs)) {
|
|
17542
|
+
throw new CliCommandError("PC_START_FAILED", `The old terminal service (pid ${info.pid}) did not stop. Restart this PC, then run \`npx -y ainecto@latest\` again.`);
|
|
17543
|
+
}
|
|
17544
|
+
}
|
|
16987
17545
|
async function withRegistration(deps, key, userId, code) {
|
|
16988
17546
|
if (code === 0) await registerBrowserOnStart(deps, { key, userId });
|
|
16989
17547
|
return code;
|
|
@@ -17012,6 +17570,7 @@ async function registerBrowserOnStart(deps, account2) {
|
|
|
17012
17570
|
const secret = randomBytes3(NONCE_SEED_BYTES);
|
|
17013
17571
|
const interrupt = register.interrupt();
|
|
17014
17572
|
let outcome;
|
|
17573
|
+
let writtenAt = "";
|
|
17015
17574
|
try {
|
|
17016
17575
|
const tag = await registerTag((await registerKeys(secret)).account, userId);
|
|
17017
17576
|
const url = `${new URL(deps.endpoint).origin}${REGISTER_PATH}#${registerFragment({ pcId: settings.pcId, tag, secret })}`;
|
|
@@ -17024,13 +17583,15 @@ async function registerBrowserOnStart(deps, account2) {
|
|
|
17024
17583
|
note("");
|
|
17025
17584
|
note(`Finish in the browser that just opened (up to ${Math.round(register.waitMs / 6e4)} min \xB7 Ctrl+C to skip)`);
|
|
17026
17585
|
const pcKey = stored?.pcKey ?? await generateSigningJwk();
|
|
17586
|
+
const pinnedAt = register.now();
|
|
17587
|
+
writtenAt = pinnedAt.toISOString();
|
|
17027
17588
|
outcome = await runPairing({
|
|
17028
17589
|
userId,
|
|
17029
17590
|
pcId: settings.pcId,
|
|
17030
17591
|
pcKey,
|
|
17031
17592
|
transport: await register.transport(settings.pcId),
|
|
17032
|
-
secret,
|
|
17033
|
-
pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now:
|
|
17593
|
+
confirm: { kind: "secret", secret },
|
|
17594
|
+
pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now: pinnedAt }),
|
|
17034
17595
|
waitMs: register.waitMs,
|
|
17035
17596
|
cancel: interrupt.signal
|
|
17036
17597
|
});
|
|
@@ -17049,8 +17610,12 @@ async function registerBrowserOnStart(deps, account2) {
|
|
|
17049
17610
|
const { browser, doneError } = outcome;
|
|
17050
17611
|
if (doneError !== void 0) {
|
|
17051
17612
|
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17052
|
-
const
|
|
17053
|
-
|
|
17613
|
+
const current = keys.accounts[account2.key];
|
|
17614
|
+
if (!current?.browsers.some((item) => item.keyId === browser.keyId && item.pairedAt === writtenAt)) return void 0;
|
|
17615
|
+
return { accounts: { ...keys.accounts, [account2.key]: {
|
|
17616
|
+
...current,
|
|
17617
|
+
browsers: current.browsers.filter((item) => !(item.keyId === browser.keyId && item.pairedAt === writtenAt))
|
|
17618
|
+
} } };
|
|
17054
17619
|
});
|
|
17055
17620
|
note(`The browser "${browser.name}" did not get the confirmation (${doneError}), so nothing was kept. ${REGISTER_AGAIN}`);
|
|
17056
17621
|
return;
|
|
@@ -17366,12 +17931,12 @@ function createPairRelay(input) {
|
|
|
17366
17931
|
};
|
|
17367
17932
|
return {
|
|
17368
17933
|
async offer(commit, signal) {
|
|
17369
|
-
const opened = await http.call("pair/open", { pcId: input.pcId }, { signal });
|
|
17934
|
+
const opened = await http.call("pair/open", { pcId: input.pcId, ...input.requestId ? { requestId: input.requestId } : {} }, { signal });
|
|
17370
17935
|
if (typeof opened.attemptId !== "string" || opened.attemptId === "") {
|
|
17371
17936
|
throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "AiNecto answered pair/open without an attemptId.");
|
|
17372
17937
|
}
|
|
17373
17938
|
attemptId = opened.attemptId;
|
|
17374
|
-
await send({ type: "commit", commit:
|
|
17939
|
+
await send({ type: "commit", commit: b64u3(commit) }, signal);
|
|
17375
17940
|
for (; ; ) {
|
|
17376
17941
|
const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
|
|
17377
17942
|
if (answer.closed === true) {
|
|
@@ -17387,10 +17952,26 @@ function createPairRelay(input) {
|
|
|
17387
17952
|
}
|
|
17388
17953
|
},
|
|
17389
17954
|
async reveal(pcPublicRaw, nP, signal, macP) {
|
|
17390
|
-
await send({ type: "reveal", publicKey:
|
|
17955
|
+
await send({ type: "reveal", publicKey: b64u3(pcPublicRaw), nP: b64u3(nP), ...macP ? { macP: b64u3(macP) } : {} }, signal);
|
|
17956
|
+
},
|
|
17957
|
+
async deviceConsent(signal) {
|
|
17958
|
+
if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The browser registration was not opened.");
|
|
17959
|
+
for (; ; ) {
|
|
17960
|
+
const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
|
|
17961
|
+
if (answer.closed === true) {
|
|
17962
|
+
finished = true;
|
|
17963
|
+
return void 0;
|
|
17964
|
+
}
|
|
17965
|
+
const consent = consentOf(Array.isArray(answer.msgs) ? answer.msgs : []);
|
|
17966
|
+
if (consent === "abort") {
|
|
17967
|
+
finished = true;
|
|
17968
|
+
return void 0;
|
|
17969
|
+
}
|
|
17970
|
+
if (consent) return consent;
|
|
17971
|
+
}
|
|
17391
17972
|
},
|
|
17392
17973
|
async done(signature, signal) {
|
|
17393
|
-
await send({ type: "done", signature:
|
|
17974
|
+
await send({ type: "done", signature: b64u3(signature) }, signal);
|
|
17394
17975
|
finished = true;
|
|
17395
17976
|
},
|
|
17396
17977
|
async abort(reason) {
|
|
@@ -17423,7 +18004,16 @@ function offerOf(msgs) {
|
|
|
17423
18004
|
}
|
|
17424
18005
|
return { keyId: item.keyId, publicRaw, nB, name: item.name, ...macB ? { macB } : {} };
|
|
17425
18006
|
}
|
|
17426
|
-
function
|
|
18007
|
+
function consentOf(msgs) {
|
|
18008
|
+
if (msgs.length === 0) return void 0;
|
|
18009
|
+
const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
|
|
18010
|
+
if (items.some((item) => item.type === "abort")) return "abort";
|
|
18011
|
+
if (items.length > 1) throw new PairRelayError("PAIR_DUPLICATE", "More than one device answer arrived \u2014 this try was ended.");
|
|
18012
|
+
const sig = items[0]?.type === "confirm" ? fromB64u2(items[0].sig, SIGNATURE_BYTES) : void 0;
|
|
18013
|
+
if (!sig) throw new PairRelayError("PAIR_BAD_MESSAGE", "AiNecto relayed a device answer this CLI does not understand \u2014 this try was ended.");
|
|
18014
|
+
return sig;
|
|
18015
|
+
}
|
|
18016
|
+
function b64u3(bytes) {
|
|
17427
18017
|
return Buffer.from(bytes).toString("base64url");
|
|
17428
18018
|
}
|
|
17429
18019
|
function fromB64u2(value, length) {
|
|
@@ -17432,111 +18022,6 @@ function fromB64u2(value, length) {
|
|
|
17432
18022
|
return bytes.length === length ? bytes : void 0;
|
|
17433
18023
|
}
|
|
17434
18024
|
|
|
17435
|
-
// src/core/pc/pcNotify.ts
|
|
17436
|
-
var NOTIFY_BATCH_MS = 6e4;
|
|
17437
|
-
var WHAT = {
|
|
17438
|
-
paired: "was registered with this PC",
|
|
17439
|
-
session: "opened a terminal connection to this PC",
|
|
17440
|
-
shell: "started a new shell on this PC",
|
|
17441
|
-
command: "started a command in a new terminal on this PC"
|
|
17442
|
-
};
|
|
17443
|
-
function notificationText(event, more) {
|
|
17444
|
-
const time = `${String(event.at.getHours()).padStart(2, "0")}:${String(event.at.getMinutes()).padStart(2, "0")}`;
|
|
17445
|
-
return {
|
|
17446
|
-
title: "AiNecto",
|
|
17447
|
-
body: `${event.browserName} ${WHAT[event.kind]} \u2014 ${time}${more > 0 ? ` (+${more} more)` : ""}. Not you? Run \`ainecto remote off\`.`
|
|
17448
|
-
};
|
|
17449
|
-
}
|
|
17450
|
-
var systemClock = {
|
|
17451
|
-
now: () => Date.now(),
|
|
17452
|
-
setTimer: (run, ms) => {
|
|
17453
|
-
const timer = setTimeout(run, ms);
|
|
17454
|
-
timer.unref?.();
|
|
17455
|
-
return timer;
|
|
17456
|
-
},
|
|
17457
|
-
clearTimer: (timer) => clearTimeout(timer)
|
|
17458
|
-
};
|
|
17459
|
-
var NotifyBatcher = class {
|
|
17460
|
-
constructor(show, clock = systemClock) {
|
|
17461
|
-
this.show = show;
|
|
17462
|
-
this.clock = clock;
|
|
17463
|
-
}
|
|
17464
|
-
show;
|
|
17465
|
-
clock;
|
|
17466
|
-
slots = /* @__PURE__ */ new Map();
|
|
17467
|
-
add(event) {
|
|
17468
|
-
const key = `${event.keyId}\0${event.kind}`;
|
|
17469
|
-
const now = this.clock.now();
|
|
17470
|
-
const slot = this.slots.get(key);
|
|
17471
|
-
if (!slot || now >= slot.endsAt) {
|
|
17472
|
-
this.show(event, 0);
|
|
17473
|
-
this.slots.set(key, { endsAt: now + NOTIFY_BATCH_MS, pending: void 0, timer: void 0 });
|
|
17474
|
-
return;
|
|
17475
|
-
}
|
|
17476
|
-
slot.pending = { event, count: (slot.pending?.count ?? 0) + 1 };
|
|
17477
|
-
slot.timer ??= this.clock.setTimer(() => this.close(key), slot.endsAt - now);
|
|
17478
|
-
}
|
|
17479
|
-
flush() {
|
|
17480
|
-
for (const [key, slot] of this.slots) {
|
|
17481
|
-
if (slot.timer !== void 0) this.clock.clearTimer(slot.timer);
|
|
17482
|
-
if (slot.pending) this.show(slot.pending.event, slot.pending.count - 1);
|
|
17483
|
-
this.slots.delete(key);
|
|
17484
|
-
}
|
|
17485
|
-
}
|
|
17486
|
-
close(key) {
|
|
17487
|
-
const slot = this.slots.get(key);
|
|
17488
|
-
if (!slot) return;
|
|
17489
|
-
slot.timer = void 0;
|
|
17490
|
-
if (!slot.pending) return;
|
|
17491
|
-
const { event, count } = slot.pending;
|
|
17492
|
-
slot.pending = void 0;
|
|
17493
|
-
slot.endsAt = this.clock.now() + NOTIFY_BATCH_MS;
|
|
17494
|
-
this.show(event, count - 1);
|
|
17495
|
-
}
|
|
17496
|
-
};
|
|
17497
|
-
function notifyFailureReason(error) {
|
|
17498
|
-
if (error && typeof error === "object") {
|
|
17499
|
-
const value = error;
|
|
17500
|
-
if (value.code === "ENOENT") return "not-found";
|
|
17501
|
-
if (value.code === "EACCES") return "no-permission";
|
|
17502
|
-
if (typeof value.signal === "string" && value.signal !== "") return "signal";
|
|
17503
|
-
if (typeof value.code === "number") return `exit-${value.code}`;
|
|
17504
|
-
}
|
|
17505
|
-
return "failed";
|
|
17506
|
-
}
|
|
17507
|
-
function createPcNotifier(input) {
|
|
17508
|
-
const tool = notifyTool(input.platform);
|
|
17509
|
-
const run = input.run ?? runQuiet;
|
|
17510
|
-
const clock = input.clock ?? systemClock;
|
|
17511
|
-
let last = Promise.resolve();
|
|
17512
|
-
const show = (event, more) => {
|
|
17513
|
-
input.log.write({ event: "pc_notify", kind: event.kind, browserKeyId: event.keyId, more, tool: tool?.name ?? "none" });
|
|
17514
|
-
if (!tool) {
|
|
17515
|
-
input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: "none", reason: "no-tool-on-this-os" });
|
|
17516
|
-
last = Promise.resolve();
|
|
17517
|
-
return;
|
|
17518
|
-
}
|
|
17519
|
-
const { title, body } = notificationText(event, more);
|
|
17520
|
-
last = run(tool.file, tool.args(title, body)).then(
|
|
17521
|
-
() => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: true, tool: tool.name }),
|
|
17522
|
-
(error) => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: tool.name, reason: notifyFailureReason(error) })
|
|
17523
|
-
);
|
|
17524
|
-
};
|
|
17525
|
-
const batcher = new NotifyBatcher(show, clock);
|
|
17526
|
-
return {
|
|
17527
|
-
async notify(event) {
|
|
17528
|
-
const before = last;
|
|
17529
|
-
batcher.add({ ...event, at: new Date(clock.now()) });
|
|
17530
|
-
if (last !== before) await last;
|
|
17531
|
-
},
|
|
17532
|
-
async flush() {
|
|
17533
|
-
const before = last;
|
|
17534
|
-
batcher.flush();
|
|
17535
|
-
if (last !== before) await last;
|
|
17536
|
-
}
|
|
17537
|
-
};
|
|
17538
|
-
}
|
|
17539
|
-
|
|
17540
18025
|
// src/adapters/cli/pcSwap.ts
|
|
17541
18026
|
import { randomUUID as randomUUID8 } from "crypto";
|
|
17542
18027
|
import { writeFile as writeFile7 } from "fs/promises";
|
|
@@ -18849,6 +19334,14 @@ async function runPcRemote(setup, signal, onAnswer) {
|
|
|
18849
19334
|
pcId: setup.pcId,
|
|
18850
19335
|
remote: setup.remoteEnabled ? "on" : "off"
|
|
18851
19336
|
});
|
|
19337
|
+
const bridgeLock = await acquirePcBridgeLock(setup.paths);
|
|
19338
|
+
if (!bridgeLock) {
|
|
19339
|
+
const reason = "Another AiNecto connection is already running on this PC.";
|
|
19340
|
+
log.write({ event: "remote_stop", pid: process.pid, reason });
|
|
19341
|
+
setup.io.stderr.write(`Remote terminal stopped: ${reason}
|
|
19342
|
+
`);
|
|
19343
|
+
return { exitCode: 1, reason };
|
|
19344
|
+
}
|
|
18852
19345
|
let result;
|
|
18853
19346
|
try {
|
|
18854
19347
|
result = await runRemoteBridge({
|
|
@@ -18861,6 +19354,14 @@ async function runPcRemote(setup, signal, onAnswer) {
|
|
|
18861
19354
|
remoteEnabled: setup.remoteEnabled,
|
|
18862
19355
|
trust: setup.trust,
|
|
18863
19356
|
notifier: createPcNotifier({ log }),
|
|
19357
|
+
pairRelay: (requestId) => createPairRelay({
|
|
19358
|
+
endpoint: setup.endpoint,
|
|
19359
|
+
tokenProvider: setup.auth,
|
|
19360
|
+
log,
|
|
19361
|
+
pcId: setup.pcId,
|
|
19362
|
+
requestId,
|
|
19363
|
+
holdMs: PAIR_WAIT_MS
|
|
19364
|
+
}),
|
|
18864
19365
|
exclude: [PC_SESSION_NAME],
|
|
18865
19366
|
sessionEnv: setup.env,
|
|
18866
19367
|
appHome: setup.appHome,
|
|
@@ -18875,6 +19376,8 @@ async function runPcRemote(setup, signal, onAnswer) {
|
|
|
18875
19376
|
setup.io.stderr.write(`Remote terminal stopped: ${reason}
|
|
18876
19377
|
`);
|
|
18877
19378
|
return { exitCode: 1, reason };
|
|
19379
|
+
} finally {
|
|
19380
|
+
bridgeLock.release();
|
|
18878
19381
|
}
|
|
18879
19382
|
log.write({ event: "remote_stop", pid: process.pid, reason: result.reason, exitCode: result.exitCode });
|
|
18880
19383
|
if (result.exitCode !== 0 || !signal.aborted) {
|