ainecto 0.15.4 → 0.16.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/README.md +1 -1
- package/dist/bin/ainecto.js +808 -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.1" : UNBUNDLED_VERSION;
|
|
5703
|
+
var CLI_BUILD = true ? "53ef619" : 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,41 @@ 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 waitForDaemonLockFree(paths, ms) {
|
|
11076
|
+
const until = Date.now() + ms;
|
|
11077
|
+
for (; ; ) {
|
|
11078
|
+
const lock = await acquireProcessLock(paths);
|
|
11079
|
+
if (lock) {
|
|
11080
|
+
lock.release();
|
|
11081
|
+
return true;
|
|
11082
|
+
}
|
|
11083
|
+
if (Date.now() >= until) return false;
|
|
11084
|
+
await new Promise((resolve4) => setTimeout(resolve4, 100));
|
|
11085
|
+
}
|
|
11086
|
+
}
|
|
11087
|
+
async function acquireProcessLock(paths) {
|
|
11065
11088
|
assertTermRuntime();
|
|
11066
11089
|
const fileLock = FILE_LOCK[process.platform];
|
|
11067
11090
|
if (fileLock) {
|
|
11068
11091
|
try {
|
|
11069
|
-
|
|
11070
|
-
return {
|
|
11092
|
+
const fd = openSync(paths.lockFile, fileLock.flags, PRIVATE_FILE_MODE);
|
|
11093
|
+
return { release: () => closeSync(fd) };
|
|
11071
11094
|
} catch (error) {
|
|
11072
11095
|
if (fileLock.busy.some((code) => isNodeError(error, code))) {
|
|
11073
|
-
return
|
|
11096
|
+
return void 0;
|
|
11074
11097
|
}
|
|
11075
11098
|
throw error;
|
|
11076
11099
|
}
|
|
@@ -11080,15 +11103,14 @@ async function acquireDaemonLock(paths) {
|
|
|
11080
11103
|
return await new Promise((resolve4, reject) => {
|
|
11081
11104
|
server.once("error", (error) => {
|
|
11082
11105
|
if (isNodeError(error, "EADDRINUSE")) {
|
|
11083
|
-
resolve4(
|
|
11106
|
+
resolve4(void 0);
|
|
11084
11107
|
return;
|
|
11085
11108
|
}
|
|
11086
11109
|
reject(error);
|
|
11087
11110
|
});
|
|
11088
11111
|
server.listen(paths.abstractLockName, () => {
|
|
11089
|
-
heldServer = server;
|
|
11090
11112
|
server.unref();
|
|
11091
|
-
resolve4({
|
|
11113
|
+
resolve4({ release: () => server.close() });
|
|
11092
11114
|
});
|
|
11093
11115
|
});
|
|
11094
11116
|
}
|
|
@@ -11668,7 +11690,7 @@ async function spawnDaemon(paths) {
|
|
|
11668
11690
|
env: process.env
|
|
11669
11691
|
});
|
|
11670
11692
|
} finally {
|
|
11671
|
-
|
|
11693
|
+
closeSync2(stderrFd);
|
|
11672
11694
|
}
|
|
11673
11695
|
const channel = child.stdio[3];
|
|
11674
11696
|
if (!(channel instanceof Readable)) {
|
|
@@ -11724,14 +11746,6 @@ function readDaemonInfo(paths) {
|
|
|
11724
11746
|
function daemonPid(paths) {
|
|
11725
11747
|
return readDaemonInfo(paths)?.pid;
|
|
11726
11748
|
}
|
|
11727
|
-
async function waitForPidGone(pid, ms) {
|
|
11728
|
-
const until = Date.now() + ms;
|
|
11729
|
-
while (isAlive(pid)) {
|
|
11730
|
-
if (Date.now() >= until) return false;
|
|
11731
|
-
await new Promise((resolve4) => setTimeout(resolve4, 100));
|
|
11732
|
-
}
|
|
11733
|
-
return true;
|
|
11734
|
-
}
|
|
11735
11749
|
function notListening(paths) {
|
|
11736
11750
|
const pid = daemonPid(paths);
|
|
11737
11751
|
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.";
|
|
@@ -12138,7 +12152,7 @@ var QueryFilter = class _QueryFilter {
|
|
|
12138
12152
|
}
|
|
12139
12153
|
const whole = this.held + terminator;
|
|
12140
12154
|
const meaning = DISPATCHES.has(action) ? this.meaning + terminator : this.meaning;
|
|
12141
|
-
const
|
|
12155
|
+
const held2 = this.held;
|
|
12142
12156
|
this.held = "";
|
|
12143
12157
|
this.meaning = "";
|
|
12144
12158
|
if (this.dropTerminator && action === VtAction.ESC_DISPATCH && meaning === "\\") {
|
|
@@ -12157,7 +12171,7 @@ var QueryFilter = class _QueryFilter {
|
|
|
12157
12171
|
if (pieces === void 0) {
|
|
12158
12172
|
return this.release(whole);
|
|
12159
12173
|
}
|
|
12160
|
-
const introducer =
|
|
12174
|
+
const introducer = held2.startsWith(C1_OSC) ? C1_OSC : `${ESC}]`;
|
|
12161
12175
|
return this.releaseString(pieces.map((payload) => `${introducer}${payload}${terminator}`).join(""), terminator);
|
|
12162
12176
|
}
|
|
12163
12177
|
case VtAction.DCS_UNHOOK:
|
|
@@ -13313,7 +13327,7 @@ async function daemonCommand(paths, argv) {
|
|
|
13313
13327
|
writeSync(readyFd, `${JSON.stringify(readiness)}
|
|
13314
13328
|
`);
|
|
13315
13329
|
} finally {
|
|
13316
|
-
|
|
13330
|
+
closeSync3(readyFd);
|
|
13317
13331
|
}
|
|
13318
13332
|
};
|
|
13319
13333
|
let code;
|
|
@@ -13570,6 +13584,7 @@ function createPcHttp(input) {
|
|
|
13570
13584
|
);
|
|
13571
13585
|
const onStop = () => controller.abort(new DOMException("stopped", "AbortError"));
|
|
13572
13586
|
options.signal?.addEventListener("abort", onStop, { once: true });
|
|
13587
|
+
if (options.signal?.aborted) onStop();
|
|
13573
13588
|
const headers = { "Content-Type": "application/json", Accept: "application/json" };
|
|
13574
13589
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
13575
13590
|
if (sessionToken && op !== "open") headers[input.sessionHeader] = sessionToken;
|
|
@@ -14851,16 +14866,20 @@ var subtle = webcrypto.subtle;
|
|
|
14851
14866
|
var VERSION = "ainecto-e2e-v1";
|
|
14852
14867
|
var PAIR_LABEL = "ainecto-pair-v1";
|
|
14853
14868
|
var PAIR_DONE_LABEL = "ainecto-pair-v1/done";
|
|
14869
|
+
var PAIR_APPROVE_LABEL = "ainecto-pair-v1/approve";
|
|
14870
|
+
var PAIR_CODE_INFO = { a: "ainecto-pair-code-A", b: "ainecto-pair-code-B" };
|
|
14854
14871
|
var REGISTER_INFO = { browser: "ainecto-register-v1 browser", pc: "ainecto-register-v1 pc", account: "ainecto-register-v1 account" };
|
|
14855
14872
|
var REGISTER_OFFER_LABEL = "ainecto-register-v1/offer";
|
|
14856
14873
|
var REGISTER_REVEAL_LABEL = "ainecto-register-v1/reveal";
|
|
14857
14874
|
var REGISTER_TAG_BYTES = 8;
|
|
14858
14875
|
var KEY_INFO = { browserToPc: "ainecto-e2e-v1 b2p", pcToBrowser: "ainecto-e2e-v1 p2b", connId: "ainecto-e2e-v1 conn-id" };
|
|
14876
|
+
var PAIR_CODE_LIMIT = 4294e6;
|
|
14859
14877
|
var MAX_MESSAGES_PER_KEY = 2 ** 32;
|
|
14860
14878
|
var PUBLIC_KEY_BYTES = 65;
|
|
14861
14879
|
var NONCE_SEED_BYTES = 32;
|
|
14862
14880
|
var SIGNATURE_BYTES = 64;
|
|
14863
14881
|
var CONN_ID_BYTES = 16;
|
|
14882
|
+
var PAIR_CODE_DIGITS = 6;
|
|
14864
14883
|
var E2eError = class extends Error {
|
|
14865
14884
|
constructor(code, message2) {
|
|
14866
14885
|
super(message2);
|
|
@@ -15015,10 +15034,38 @@ async function pairTranscript(input) {
|
|
|
15015
15034
|
expectLength("nB", input.nB, NONCE_SEED_BYTES);
|
|
15016
15035
|
return await sha256(enc(PAIR_LABEL, input.userId, input.pcId, input.pcPublicRaw, input.browserPublicRaw, input.nP, input.nB));
|
|
15017
15036
|
}
|
|
15037
|
+
function pairCodeFromBlock(block) {
|
|
15038
|
+
expectLength("code block", block, 32);
|
|
15039
|
+
const view = new DataView(block.buffer, block.byteOffset, block.byteLength);
|
|
15040
|
+
for (let offset = 0; offset < 32; offset += 4) {
|
|
15041
|
+
const value = view.getUint32(offset, false);
|
|
15042
|
+
if (value < PAIR_CODE_LIMIT) {
|
|
15043
|
+
return String(value % 10 ** PAIR_CODE_DIGITS).padStart(PAIR_CODE_DIGITS, "0");
|
|
15044
|
+
}
|
|
15045
|
+
}
|
|
15046
|
+
return void 0;
|
|
15047
|
+
}
|
|
15048
|
+
async function pairCodes(transcript) {
|
|
15049
|
+
expectLength("transcript", transcript, 32);
|
|
15050
|
+
const prk = await subtle.importKey("raw", transcript, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
15051
|
+
const code = async (info) => {
|
|
15052
|
+
const block = new Uint8Array(await subtle.sign("HMAC", prk, concatBytes(utf8(info), Uint8Array.of(1))));
|
|
15053
|
+
const value = pairCodeFromBlock(block);
|
|
15054
|
+
if (value === void 0) {
|
|
15055
|
+
throw new E2eError("E2E_PAIR_CODE_UNAVAILABLE", "No usable registration code in this attempt \u2014 run `npx -y ainecto@latest` again.");
|
|
15056
|
+
}
|
|
15057
|
+
return value;
|
|
15058
|
+
};
|
|
15059
|
+
return { a: await code(PAIR_CODE_INFO.a), b: await code(PAIR_CODE_INFO.b) };
|
|
15060
|
+
}
|
|
15018
15061
|
function pairDoneInput(transcript) {
|
|
15019
15062
|
expectLength("transcript", transcript, 32);
|
|
15020
15063
|
return enc(PAIR_DONE_LABEL, transcript);
|
|
15021
15064
|
}
|
|
15065
|
+
function pairApproveInput(transcript) {
|
|
15066
|
+
expectLength("transcript", transcript, 32);
|
|
15067
|
+
return enc(PAIR_APPROVE_LABEL, transcript);
|
|
15068
|
+
}
|
|
15022
15069
|
async function registerKeys(secret) {
|
|
15023
15070
|
expectLength("register secret", secret, NONCE_SEED_BYTES);
|
|
15024
15071
|
const ikm = await subtle.importKey("raw", secret, "HKDF", false, ["deriveBits"]);
|
|
@@ -15307,7 +15354,7 @@ var ANSWER_CODES = ["TERM_NO_SESSION", "TERM_SESSION_EXISTS", "TERM_BAD_REQUEST"
|
|
|
15307
15354
|
function answerCodeOf(code) {
|
|
15308
15355
|
return ANSWER_CODES.includes(code) ? code : "TERM_FAILED";
|
|
15309
15356
|
}
|
|
15310
|
-
var COMMAND_KINDS = ["confirm", "input", "key", "resize", "create", "kill", "label"];
|
|
15357
|
+
var COMMAND_KINDS = ["confirm", "input", "key", "resize", "create", "kill", "label", "device"];
|
|
15311
15358
|
var ChannelSealError = class extends Error {
|
|
15312
15359
|
constructor(reason, message2) {
|
|
15313
15360
|
super(message2);
|
|
@@ -15352,6 +15399,12 @@ var ChannelBook = class {
|
|
|
15352
15399
|
drop(channelId) {
|
|
15353
15400
|
return this.channels.delete(channelId);
|
|
15354
15401
|
}
|
|
15402
|
+
/** 그 브라우저 키의 채널을 모두 지운다(연결 중·활성 — 기기 지우기, approve-new-device §3-6) — 지운 id 들. */
|
|
15403
|
+
dropBrowser(keyId) {
|
|
15404
|
+
const ids = [...this.channels.values()].filter((channel) => channel.browser.keyId === keyId).map((channel) => channel.channelId);
|
|
15405
|
+
for (const id of ids) this.channels.delete(id);
|
|
15406
|
+
return ids;
|
|
15407
|
+
}
|
|
15355
15408
|
/** 모두 지운다(원격 끔·링크 다시 열기) — 지운 id 들. */
|
|
15356
15409
|
dropAll() {
|
|
15357
15410
|
const ids = [...this.channels.keys()];
|
|
@@ -15555,6 +15608,29 @@ function sealedCommand(wire, plaintext) {
|
|
|
15555
15608
|
const label = text(body.label);
|
|
15556
15609
|
return targets(true) && label ? { kind: "label", opId, session, instance, label } : void 0;
|
|
15557
15610
|
}
|
|
15611
|
+
case "device": {
|
|
15612
|
+
if (!opId || wire.opId !== opId || wire.session !== void 0 || wire.projectUuid !== void 0) return void 0;
|
|
15613
|
+
const action = deviceAction(body);
|
|
15614
|
+
return action ? { kind: "device", opId, action } : void 0;
|
|
15615
|
+
}
|
|
15616
|
+
}
|
|
15617
|
+
}
|
|
15618
|
+
function deviceAction(body) {
|
|
15619
|
+
switch (body.action) {
|
|
15620
|
+
case "pending":
|
|
15621
|
+
return { action: "pending" };
|
|
15622
|
+
case "list":
|
|
15623
|
+
return { action: "list" };
|
|
15624
|
+
case "approve": {
|
|
15625
|
+
const transcript = fromB64u(body.T, 32);
|
|
15626
|
+
return transcript && typeof body.accept === "boolean" ? { action: "approve", transcript, accept: body.accept } : void 0;
|
|
15627
|
+
}
|
|
15628
|
+
case "remove": {
|
|
15629
|
+
const keyId = text(body.keyId);
|
|
15630
|
+
return keyId ? { action: "remove", keyId } : void 0;
|
|
15631
|
+
}
|
|
15632
|
+
default:
|
|
15633
|
+
return void 0;
|
|
15558
15634
|
}
|
|
15559
15635
|
}
|
|
15560
15636
|
function record2(value) {
|
|
@@ -15751,6 +15827,7 @@ var RemoteViewer = class {
|
|
|
15751
15827
|
this.deps.onChannelEnded(error instanceof ChannelSealError ? error.reason : "CHANNEL_GONE");
|
|
15752
15828
|
return;
|
|
15753
15829
|
}
|
|
15830
|
+
if (this.stopped) return;
|
|
15754
15831
|
try {
|
|
15755
15832
|
await this.deps.http.call("frame", { ...outer, ...box }, { signal: this.stopper.signal });
|
|
15756
15833
|
sentKey = key;
|
|
@@ -15869,98 +15946,539 @@ function record3(value) {
|
|
|
15869
15946
|
return value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : void 0;
|
|
15870
15947
|
}
|
|
15871
15948
|
|
|
15872
|
-
// src/core/
|
|
15873
|
-
var
|
|
15874
|
-
var
|
|
15875
|
-
|
|
15876
|
-
|
|
15877
|
-
|
|
15878
|
-
|
|
15879
|
-
|
|
15880
|
-
|
|
15949
|
+
// src/core/pc/pcNotify.ts
|
|
15950
|
+
var NOTIFY_BATCH_MS = 6e4;
|
|
15951
|
+
var WHAT = {
|
|
15952
|
+
paired: "was registered with this PC",
|
|
15953
|
+
session: "opened a terminal connection to this PC",
|
|
15954
|
+
shell: "started a new shell on this PC",
|
|
15955
|
+
command: "started a command in a new terminal on this PC",
|
|
15956
|
+
"device-request": "asks to open this PC's terminal \u2014 open AiNecto Terminal in a browser you already use to allow or refuse it"
|
|
15957
|
+
};
|
|
15958
|
+
function notificationText(event, more) {
|
|
15959
|
+
const time = `${String(event.at.getHours()).padStart(2, "0")}:${String(event.at.getMinutes()).padStart(2, "0")}`;
|
|
15960
|
+
return {
|
|
15961
|
+
title: "AiNecto",
|
|
15962
|
+
body: `${event.browserName} ${WHAT[event.kind]} \u2014 ${time}${more > 0 ? ` (+${more} more)` : ""}. Not you? Run \`ainecto remote off\`.`
|
|
15963
|
+
};
|
|
15881
15964
|
}
|
|
15882
|
-
|
|
15883
|
-
|
|
15884
|
-
|
|
15885
|
-
|
|
15886
|
-
|
|
15887
|
-
|
|
15888
|
-
|
|
15889
|
-
|
|
15890
|
-
|
|
15891
|
-
|
|
15892
|
-
|
|
15893
|
-
|
|
15894
|
-
|
|
15895
|
-
|
|
15896
|
-
|
|
15897
|
-
|
|
15898
|
-
|
|
15899
|
-
|
|
15965
|
+
var systemClock = {
|
|
15966
|
+
now: () => Date.now(),
|
|
15967
|
+
setTimer: (run, ms) => {
|
|
15968
|
+
const timer = setTimeout(run, ms);
|
|
15969
|
+
timer.unref?.();
|
|
15970
|
+
return timer;
|
|
15971
|
+
},
|
|
15972
|
+
clearTimer: (timer) => clearTimeout(timer)
|
|
15973
|
+
};
|
|
15974
|
+
var NotifyBatcher = class {
|
|
15975
|
+
constructor(show, clock = systemClock) {
|
|
15976
|
+
this.show = show;
|
|
15977
|
+
this.clock = clock;
|
|
15978
|
+
}
|
|
15979
|
+
show;
|
|
15980
|
+
clock;
|
|
15981
|
+
slots = /* @__PURE__ */ new Map();
|
|
15982
|
+
add(event) {
|
|
15983
|
+
const key = `${event.keyId}\0${event.kind}`;
|
|
15984
|
+
const now = this.clock.now();
|
|
15985
|
+
const slot = this.slots.get(key);
|
|
15986
|
+
if (!slot || now >= slot.endsAt) {
|
|
15987
|
+
this.show(event, 0);
|
|
15988
|
+
this.slots.set(key, { endsAt: now + NOTIFY_BATCH_MS, pending: void 0, timer: void 0 });
|
|
15989
|
+
return;
|
|
15900
15990
|
}
|
|
15901
|
-
|
|
15991
|
+
slot.pending = { event, count: (slot.pending?.count ?? 0) + 1 };
|
|
15992
|
+
slot.timer ??= this.clock.setTimer(() => this.close(key), slot.endsAt - now);
|
|
15993
|
+
}
|
|
15994
|
+
flush() {
|
|
15995
|
+
for (const [key, slot] of this.slots) {
|
|
15996
|
+
if (slot.timer !== void 0) this.clock.clearTimer(slot.timer);
|
|
15997
|
+
if (slot.pending) this.show(slot.pending.event, slot.pending.count - 1);
|
|
15998
|
+
this.slots.delete(key);
|
|
15999
|
+
}
|
|
16000
|
+
}
|
|
16001
|
+
close(key) {
|
|
16002
|
+
const slot = this.slots.get(key);
|
|
16003
|
+
if (!slot) return;
|
|
16004
|
+
slot.timer = void 0;
|
|
16005
|
+
if (!slot.pending) return;
|
|
16006
|
+
const { event, count } = slot.pending;
|
|
16007
|
+
slot.pending = void 0;
|
|
16008
|
+
slot.endsAt = this.clock.now() + NOTIFY_BATCH_MS;
|
|
16009
|
+
this.show(event, count - 1);
|
|
16010
|
+
}
|
|
16011
|
+
};
|
|
16012
|
+
function notifyFailureReason(error) {
|
|
16013
|
+
if (error && typeof error === "object") {
|
|
16014
|
+
const value = error;
|
|
16015
|
+
if (value.code === "ENOENT") return "not-found";
|
|
16016
|
+
if (value.code === "EACCES") return "no-permission";
|
|
16017
|
+
if (typeof value.signal === "string" && value.signal !== "") return "signal";
|
|
16018
|
+
if (typeof value.code === "number") return `exit-${value.code}`;
|
|
16019
|
+
}
|
|
16020
|
+
return "failed";
|
|
15902
16021
|
}
|
|
15903
|
-
|
|
15904
|
-
|
|
15905
|
-
|
|
15906
|
-
const
|
|
15907
|
-
|
|
15908
|
-
const
|
|
15909
|
-
|
|
15910
|
-
if (
|
|
15911
|
-
|
|
15912
|
-
|
|
15913
|
-
|
|
15914
|
-
|
|
16022
|
+
function createPcNotifier(input) {
|
|
16023
|
+
const tool = notifyTool(input.platform);
|
|
16024
|
+
const run = input.run ?? runQuiet;
|
|
16025
|
+
const clock = input.clock ?? systemClock;
|
|
16026
|
+
let last = Promise.resolve();
|
|
16027
|
+
const show = (event, more) => {
|
|
16028
|
+
input.log.write({ event: "pc_notify", kind: event.kind, browserKeyId: event.keyId, more, tool: tool?.name ?? "none" });
|
|
16029
|
+
if (!tool) {
|
|
16030
|
+
input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: "none", reason: "no-tool-on-this-os" });
|
|
16031
|
+
last = Promise.resolve();
|
|
16032
|
+
return;
|
|
16033
|
+
}
|
|
16034
|
+
const { title, body } = notificationText(event, more);
|
|
16035
|
+
last = run(tool.file, tool.args(title, body)).then(
|
|
16036
|
+
() => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: true, tool: tool.name }),
|
|
16037
|
+
(error) => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: tool.name, reason: notifyFailureReason(error) })
|
|
16038
|
+
);
|
|
15915
16039
|
};
|
|
15916
|
-
const
|
|
15917
|
-
|
|
15918
|
-
|
|
15919
|
-
|
|
15920
|
-
|
|
15921
|
-
|
|
15922
|
-
|
|
15923
|
-
|
|
15924
|
-
|
|
16040
|
+
const batcher = new NotifyBatcher(show, clock);
|
|
16041
|
+
return {
|
|
16042
|
+
async notify(event) {
|
|
16043
|
+
const before = last;
|
|
16044
|
+
batcher.add({ ...event, at: new Date(clock.now()) });
|
|
16045
|
+
if (last !== before) await last;
|
|
16046
|
+
},
|
|
16047
|
+
async flush() {
|
|
16048
|
+
const before = last;
|
|
16049
|
+
batcher.flush();
|
|
16050
|
+
if (last !== before) await last;
|
|
16051
|
+
}
|
|
16052
|
+
};
|
|
16053
|
+
}
|
|
16054
|
+
|
|
16055
|
+
// src/core/pc/pcApproval.ts
|
|
16056
|
+
var ApprovalSlot = class {
|
|
16057
|
+
current;
|
|
16058
|
+
/** 대기 중인 것이 있나. */
|
|
16059
|
+
get busy() {
|
|
16060
|
+
return this.current !== void 0;
|
|
16061
|
+
}
|
|
16062
|
+
/** 등록 작업이 결정을 기다린다. signal 이 끝나면 대기를 비우고 거절(reject)한다. 이미 대기 중이면 거절한다(다리당 하나). */
|
|
16063
|
+
wait(request, at, signal) {
|
|
16064
|
+
if (this.current) return Promise.reject(new Error("Another device approval is already waiting."));
|
|
16065
|
+
return new Promise((resolve4, reject) => {
|
|
16066
|
+
const clear = () => {
|
|
16067
|
+
signal.removeEventListener("abort", onAbort);
|
|
16068
|
+
if (this.current?.request === request) this.current = void 0;
|
|
16069
|
+
};
|
|
16070
|
+
const onAbort = () => {
|
|
16071
|
+
clear();
|
|
16072
|
+
reject(new Error("The device approval ended before anyone answered."));
|
|
16073
|
+
};
|
|
16074
|
+
if (signal.aborted) {
|
|
16075
|
+
onAbort();
|
|
16076
|
+
return;
|
|
16077
|
+
}
|
|
16078
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
16079
|
+
this.current = {
|
|
16080
|
+
request,
|
|
16081
|
+
at,
|
|
16082
|
+
settle: (approval) => {
|
|
16083
|
+
clear();
|
|
16084
|
+
resolve4(approval);
|
|
16085
|
+
},
|
|
16086
|
+
fail: (error) => {
|
|
16087
|
+
clear();
|
|
16088
|
+
reject(error);
|
|
16089
|
+
}
|
|
16090
|
+
};
|
|
16091
|
+
});
|
|
16092
|
+
}
|
|
16093
|
+
/** 이미 믿는 브라우저가 물어 가져갈 것 — 없으면 undefined. */
|
|
16094
|
+
pending() {
|
|
16095
|
+
return this.current ? { request: this.current.request, at: this.current.at } : void 0;
|
|
16096
|
+
}
|
|
16097
|
+
/** 허용·거절 — T 가 지금 대기 중인 것과 같을 때만 한 번 소비한다. approverKeyId = 명령을 보낸 채널의 브라우저 키. */
|
|
16098
|
+
decide(transcript, accept, approverKeyId) {
|
|
16099
|
+
const current = this.current;
|
|
16100
|
+
if (!current || !macEquals(current.request.transcript, transcript)) return "stale";
|
|
16101
|
+
current.settle(accept ? { accepted: true, approverKeyId } : { accepted: false });
|
|
16102
|
+
return accept ? "recorded" : "rejected";
|
|
16103
|
+
}
|
|
16104
|
+
/** 그 키를 지웠다 — 그 키가 후보인 대기면 끝낸다(허용한 쪽 키는 핀을 쓰는 갱신에서 다시 본다). 끝냈으면 true. */
|
|
16105
|
+
cancelInvolving(keyId) {
|
|
16106
|
+
if (this.current?.request.keyId !== keyId) return false;
|
|
16107
|
+
this.current.fail(new Error("The device was removed while it was waiting for approval."));
|
|
16108
|
+
return true;
|
|
16109
|
+
}
|
|
16110
|
+
};
|
|
16111
|
+
|
|
16112
|
+
// src/core/pc/pcPairing.ts
|
|
16113
|
+
var PAIR_WAIT_MS = 5 * 6e4;
|
|
16114
|
+
async function runPairing(input) {
|
|
16115
|
+
const deadline = new AbortController();
|
|
16116
|
+
const timer = setTimeout(() => deadline.abort(), input.waitMs);
|
|
16117
|
+
let cancelled = false;
|
|
16118
|
+
const onCancel = () => {
|
|
16119
|
+
cancelled = true;
|
|
16120
|
+
deadline.abort();
|
|
16121
|
+
};
|
|
16122
|
+
input.cancel?.addEventListener("abort", onCancel, { once: true });
|
|
16123
|
+
if (input.cancel?.aborted) onCancel();
|
|
16124
|
+
const { signal } = deadline;
|
|
16125
|
+
const relayed = async (step) => {
|
|
15925
16126
|
try {
|
|
15926
|
-
|
|
16127
|
+
return await step();
|
|
15927
16128
|
} catch (error) {
|
|
15928
|
-
|
|
16129
|
+
if (signal.aborted) return "timeout";
|
|
16130
|
+
throw error;
|
|
15929
16131
|
}
|
|
15930
|
-
|
|
15931
|
-
|
|
15932
|
-
|
|
15933
|
-
|
|
15934
|
-
|
|
15935
|
-
|
|
15936
|
-
|
|
15937
|
-
|
|
15938
|
-
|
|
15939
|
-
|
|
15940
|
-
|
|
15941
|
-
|
|
15942
|
-
|
|
15943
|
-
const
|
|
15944
|
-
|
|
15945
|
-
|
|
15946
|
-
|
|
15947
|
-
|
|
15948
|
-
|
|
15949
|
-
|
|
15950
|
-
|
|
15951
|
-
|
|
15952
|
-
|
|
15953
|
-
|
|
15954
|
-
|
|
15955
|
-
|
|
15956
|
-
|
|
15957
|
-
|
|
15958
|
-
|
|
15959
|
-
|
|
15960
|
-
|
|
15961
|
-
|
|
15962
|
-
|
|
15963
|
-
|
|
16132
|
+
};
|
|
16133
|
+
let outcome;
|
|
16134
|
+
try {
|
|
16135
|
+
outcome = await pairOnce();
|
|
16136
|
+
if (cancelled && outcome.kind === "timeout") outcome = { kind: "cancelled" };
|
|
16137
|
+
return outcome;
|
|
16138
|
+
} finally {
|
|
16139
|
+
clearTimeout(timer);
|
|
16140
|
+
input.cancel?.removeEventListener("abort", onCancel);
|
|
16141
|
+
if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
|
|
16142
|
+
}
|
|
16143
|
+
async function pairOnce() {
|
|
16144
|
+
const pcPublicRaw = publicRawFromJwk(input.pcKey);
|
|
16145
|
+
const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
|
|
16146
|
+
const commit = await pairCommitment(pcPublicRaw, nP);
|
|
16147
|
+
const offer = await relayed(() => input.transport.offer(commit, signal));
|
|
16148
|
+
if (offer === "timeout") return { kind: "timeout" };
|
|
16149
|
+
const publicJwk = publicJwkFromRaw(offer.publicRaw);
|
|
16150
|
+
await assertSigningPublicKey(publicJwk);
|
|
16151
|
+
if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
|
|
16152
|
+
throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 browser registration aborted.");
|
|
16153
|
+
}
|
|
16154
|
+
const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
|
|
16155
|
+
const transcript = () => pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
|
|
16156
|
+
const confirm = input.confirm;
|
|
16157
|
+
if (confirm.kind === "approval") {
|
|
16158
|
+
const consent = input.transport.deviceConsent?.bind(input.transport);
|
|
16159
|
+
if (!consent) throw new E2eError("E2E_BAD_INPUT", "This relay cannot carry the new device's consent \u2014 device approval aborted.");
|
|
16160
|
+
const t2 = await transcript();
|
|
16161
|
+
const request = { transcript: t2, code: (await pairCodes(t2)).a, name: browser.name, keyId: browser.keyId };
|
|
16162
|
+
const step = new AbortController();
|
|
16163
|
+
const stop = () => step.abort();
|
|
16164
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
16165
|
+
let approverKeyId;
|
|
16166
|
+
let agreed;
|
|
16167
|
+
try {
|
|
16168
|
+
const byBrowser = confirm.approve(request, step.signal).then((approval) => {
|
|
16169
|
+
if (approval.accepted) approverKeyId = approval.approverKeyId;
|
|
16170
|
+
return approval.accepted;
|
|
16171
|
+
});
|
|
16172
|
+
const byDevice = input.transport.reveal(pcPublicRaw, nP, step.signal).then(() => consent(step.signal)).then((sig) => sig !== void 0 && verifyBytes(publicJwk, sig, pairApproveInput(t2)));
|
|
16173
|
+
agreed = await relayed(() => bothAgree(byBrowser, byDevice));
|
|
16174
|
+
} finally {
|
|
16175
|
+
signal.removeEventListener("abort", stop);
|
|
16176
|
+
step.abort();
|
|
16177
|
+
}
|
|
16178
|
+
if (agreed === "timeout") return { kind: "timeout" };
|
|
16179
|
+
if (!agreed || await input.pin(browser, approverKeyId) === false) return { kind: "code-mismatch" };
|
|
16180
|
+
return await finish(browser, t2, async () => {
|
|
16181
|
+
});
|
|
16182
|
+
}
|
|
16183
|
+
const keys = await registerKeys(confirm.secret);
|
|
16184
|
+
const expected = await registerOfferMac(keys.browser, {
|
|
16185
|
+
userId: input.userId,
|
|
16186
|
+
pcId: input.pcId,
|
|
16187
|
+
attemptId: offer.attemptId,
|
|
16188
|
+
commit,
|
|
16189
|
+
browserPublicRaw: offer.publicRaw,
|
|
16190
|
+
keyId: offer.keyId,
|
|
16191
|
+
nB: offer.nB,
|
|
16192
|
+
name: offer.name
|
|
16193
|
+
});
|
|
16194
|
+
if (!offer.macB || !macEquals(offer.macB, expected)) return { kind: "code-mismatch" };
|
|
16195
|
+
const t = await transcript();
|
|
16196
|
+
await input.pin(browser);
|
|
16197
|
+
const macP = await registerRevealMac(keys.pc, { transcript: t, attemptId: offer.attemptId });
|
|
16198
|
+
return await finish(browser, t, () => input.transport.reveal(pcPublicRaw, nP, signal, macP));
|
|
16199
|
+
}
|
|
16200
|
+
async function finish(browser, transcript, before) {
|
|
16201
|
+
const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
|
|
16202
|
+
let doneError;
|
|
16203
|
+
try {
|
|
16204
|
+
await before();
|
|
16205
|
+
await input.transport.done(signature, signal);
|
|
16206
|
+
} catch (error) {
|
|
16207
|
+
doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
|
|
16208
|
+
}
|
|
16209
|
+
return { kind: "paired", browser, doneError };
|
|
16210
|
+
}
|
|
16211
|
+
}
|
|
16212
|
+
function bothAgree(a, b) {
|
|
16213
|
+
return new Promise((resolve4, reject) => {
|
|
16214
|
+
let left = 2;
|
|
16215
|
+
let settled = false;
|
|
16216
|
+
const settle = (fn) => {
|
|
16217
|
+
if (settled) return;
|
|
16218
|
+
settled = true;
|
|
16219
|
+
fn();
|
|
16220
|
+
};
|
|
16221
|
+
for (const each of [a, b]) {
|
|
16222
|
+
each.then((ok) => {
|
|
16223
|
+
if (!ok) settle(() => resolve4(false));
|
|
16224
|
+
else if (--left === 0) settle(() => resolve4(true));
|
|
16225
|
+
}, (error) => settle(() => reject(error)));
|
|
16226
|
+
}
|
|
16227
|
+
});
|
|
16228
|
+
}
|
|
16229
|
+
|
|
16230
|
+
// src/core/pc/pcDevices.ts
|
|
16231
|
+
var DeviceManager = class {
|
|
16232
|
+
constructor(deps) {
|
|
16233
|
+
this.deps = deps;
|
|
16234
|
+
this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
16235
|
+
}
|
|
16236
|
+
deps;
|
|
16237
|
+
slot = new ApprovalSlot();
|
|
16238
|
+
running;
|
|
16239
|
+
/** 진행 중에 온 새 요청 — 앞 작업이 끝나면 이어서 받는다(마지막 것 하나). */
|
|
16240
|
+
next;
|
|
16241
|
+
quietUntil = 0;
|
|
16242
|
+
/** keyId → 지운 시각(ms). 그보다 먼저 시작한 등록은 그 키를 쓰지 못한다(다시 요청하면 새 등록이라 쓸 수 있다). */
|
|
16243
|
+
removedAt = /* @__PURE__ */ new Map();
|
|
16244
|
+
now;
|
|
16245
|
+
/** poll 의 pair-request — 받을 수 있으면 등록 작업을 백그라운드로 시작한다(기다리지 않는다). */
|
|
16246
|
+
async onPairRequest(requestId) {
|
|
16247
|
+
const refuse = async (reason) => {
|
|
16248
|
+
this.deps.log({ event: "pc_device", step: "request", requestId, result: "refused", reason });
|
|
16249
|
+
await this.deps.relay(requestId).refuse(reason);
|
|
16250
|
+
};
|
|
16251
|
+
if (!this.deps.remoteOn()) return await refuse("remote-off");
|
|
16252
|
+
if (this.running) {
|
|
16253
|
+
this.deps.log({ event: "pc_device", step: "request", requestId, result: "replacing", reason: this.running.requestId });
|
|
16254
|
+
this.next = requestId;
|
|
16255
|
+
this.running.replaced = true;
|
|
16256
|
+
this.running.stop.abort();
|
|
16257
|
+
return;
|
|
16258
|
+
}
|
|
16259
|
+
if (this.now().getTime() < this.quietUntil) return await refuse("quiet");
|
|
16260
|
+
const account2 = await this.account();
|
|
16261
|
+
if (!account2 || account2.browsers.length === 0) return await refuse("no-trusted-browser");
|
|
16262
|
+
const running = { requestId, stop: new AbortController(), replaced: false };
|
|
16263
|
+
this.running = running;
|
|
16264
|
+
this.deps.log({ event: "pc_device", step: "request", requestId, result: "started" });
|
|
16265
|
+
void this.pair(requestId, account2.pcKey, running).finally(() => {
|
|
16266
|
+
if (this.running === running) this.running = void 0;
|
|
16267
|
+
const next = this.next;
|
|
16268
|
+
if (next !== void 0 && this.running === void 0) {
|
|
16269
|
+
this.next = void 0;
|
|
16270
|
+
void this.onPairRequest(next);
|
|
16271
|
+
}
|
|
16272
|
+
});
|
|
16273
|
+
}
|
|
16274
|
+
/** 다리 끝·원격 꺼짐·링크 다시 열기 — 진행 중 등록을 끝낸다(abort 를 보낸다). */
|
|
16275
|
+
stop() {
|
|
16276
|
+
this.running?.stop.abort();
|
|
16277
|
+
}
|
|
16278
|
+
/** 이미 믿는 브라우저의 봉인 명령 하나 — 봉인 답의 result. browser = 명령을 보낸 채널의 브라우저. */
|
|
16279
|
+
async command(action, browser) {
|
|
16280
|
+
switch (action.action) {
|
|
16281
|
+
case "pending": {
|
|
16282
|
+
const pending = this.slot.pending();
|
|
16283
|
+
return {
|
|
16284
|
+
request: pending ? { T: b64u2(pending.request.transcript), code: pending.request.code, name: pending.request.name, at: pending.at.toISOString() } : null
|
|
16285
|
+
};
|
|
16286
|
+
}
|
|
16287
|
+
case "approve": {
|
|
16288
|
+
const result = this.slot.decide(action.transcript, action.accept, browser.keyId);
|
|
16289
|
+
this.deps.log({ event: "pc_device", step: "approve", keyId: browser.keyId, result });
|
|
16290
|
+
return { result };
|
|
16291
|
+
}
|
|
16292
|
+
case "list": {
|
|
16293
|
+
const account2 = await this.account();
|
|
16294
|
+
return {
|
|
16295
|
+
devices: (account2?.browsers ?? []).map((item) => ({
|
|
16296
|
+
keyId: item.keyId,
|
|
16297
|
+
name: item.name,
|
|
16298
|
+
pairedAt: item.pairedAt,
|
|
16299
|
+
current: item.keyId === browser.keyId
|
|
16300
|
+
}))
|
|
16301
|
+
};
|
|
16302
|
+
}
|
|
16303
|
+
case "remove": {
|
|
16304
|
+
this.removedAt.set(action.keyId, this.now().getTime());
|
|
16305
|
+
this.slot.cancelInvolving(action.keyId);
|
|
16306
|
+
let removed = false;
|
|
16307
|
+
await updatePcKeys(this.deps.keysPath, (keys) => {
|
|
16308
|
+
const account2 = keys.accounts[this.deps.accountKey];
|
|
16309
|
+
if (!account2?.browsers.some((item) => item.keyId === action.keyId)) return void 0;
|
|
16310
|
+
removed = true;
|
|
16311
|
+
return { accounts: { ...keys.accounts, [this.deps.accountKey]: {
|
|
16312
|
+
...account2,
|
|
16313
|
+
browsers: account2.browsers.filter((item) => item.keyId !== action.keyId)
|
|
16314
|
+
} } };
|
|
16315
|
+
});
|
|
16316
|
+
await this.deps.closeKey(action.keyId);
|
|
16317
|
+
this.deps.log({ event: "pc_device", step: "remove", keyId: action.keyId, result: removed ? "removed" : "absent" });
|
|
16318
|
+
return { removed };
|
|
16319
|
+
}
|
|
16320
|
+
}
|
|
16321
|
+
}
|
|
16322
|
+
async pair(requestId, pcKey, running) {
|
|
16323
|
+
const stop = running.stop;
|
|
16324
|
+
let outcome;
|
|
16325
|
+
let reason;
|
|
16326
|
+
const startedAt = this.now().getTime();
|
|
16327
|
+
try {
|
|
16328
|
+
outcome = await runPairing({
|
|
16329
|
+
userId: transcriptUserId(this.deps.userId),
|
|
16330
|
+
pcId: this.deps.pcId,
|
|
16331
|
+
pcKey,
|
|
16332
|
+
transport: this.deps.relay(requestId),
|
|
16333
|
+
confirm: {
|
|
16334
|
+
kind: "approval",
|
|
16335
|
+
approve: (request, signal) => {
|
|
16336
|
+
this.deps.notifyRequest(request.name);
|
|
16337
|
+
this.deps.log({ event: "pc_device", step: "waiting", requestId, keyId: request.keyId });
|
|
16338
|
+
return this.slot.wait(request, this.now(), signal);
|
|
16339
|
+
}
|
|
16340
|
+
},
|
|
16341
|
+
pin: async (browser, approverKeyId) => await this.pinApproved(browser, approverKeyId, pcKey, this.now().toISOString(), startedAt, stop.signal),
|
|
16342
|
+
waitMs: this.deps.waitMs ?? PAIR_WAIT_MS,
|
|
16343
|
+
cancel: stop.signal
|
|
16344
|
+
});
|
|
16345
|
+
} catch (error) {
|
|
16346
|
+
reason = error instanceof Error ? error.message : String(error);
|
|
16347
|
+
}
|
|
16348
|
+
if (outcome?.kind === "paired" && outcome.doneError !== void 0) reason = outcome.doneError;
|
|
16349
|
+
const result = outcome === void 0 ? "error" : outcome.kind === "paired" && outcome.doneError !== void 0 ? "done-failed" : outcome.kind;
|
|
16350
|
+
if (result !== "paired" && result !== "timeout" && !running.replaced) this.quietUntil = this.now().getTime() + NOTIFY_BATCH_MS;
|
|
16351
|
+
this.deps.log({
|
|
16352
|
+
event: "pc_device",
|
|
16353
|
+
step: "finished",
|
|
16354
|
+
requestId,
|
|
16355
|
+
result,
|
|
16356
|
+
...outcome?.kind === "paired" ? { keyId: outcome.browser.keyId } : {},
|
|
16357
|
+
...reason ? { reason } : {}
|
|
16358
|
+
});
|
|
16359
|
+
}
|
|
16360
|
+
/** 양쪽 동의 뒤 — 같은 갱신 안에서 «허용한 키가 아직 있음 · PC 키 그대로»를 다시 보고 쓴다. 아니면 false(핀 0). */
|
|
16361
|
+
async pinApproved(browser, approverKeyId, pcKey, pairedAt, startedAt, stopped) {
|
|
16362
|
+
let pinned = false;
|
|
16363
|
+
const deadline = startedAt + (this.deps.waitMs ?? PAIR_WAIT_MS);
|
|
16364
|
+
await updatePcKeys(this.deps.keysPath, (keys) => {
|
|
16365
|
+
if (stopped.aborted || this.now().getTime() >= deadline) return void 0;
|
|
16366
|
+
if ((this.removedAt.get(browser.keyId) ?? -1) >= startedAt) return void 0;
|
|
16367
|
+
if (approverKeyId !== void 0 && (this.removedAt.get(approverKeyId) ?? -1) >= startedAt) return void 0;
|
|
16368
|
+
const account2 = keys.accounts[this.deps.accountKey];
|
|
16369
|
+
if (!account2 || account2.pcKey.d !== pcKey.d || !account2.browsers.some((item) => item.keyId === approverKeyId)) return void 0;
|
|
16370
|
+
if (account2.pendingTurnOff?.removals.some((item) => item.keyId === browser.keyId)) return void 0;
|
|
16371
|
+
pinned = true;
|
|
16372
|
+
return withBrowser(keys, this.deps.accountKey, pcKey, { ...browser, pairedAt });
|
|
16373
|
+
});
|
|
16374
|
+
return pinned;
|
|
16375
|
+
}
|
|
16376
|
+
async account() {
|
|
16377
|
+
try {
|
|
16378
|
+
return (await loadPcKeys(this.deps.keysPath)).accounts[this.deps.accountKey];
|
|
16379
|
+
} catch {
|
|
16380
|
+
return void 0;
|
|
16381
|
+
}
|
|
16382
|
+
}
|
|
16383
|
+
};
|
|
16384
|
+
function b64u2(bytes) {
|
|
16385
|
+
return Buffer.from(bytes).toString("base64url");
|
|
16386
|
+
}
|
|
16387
|
+
|
|
16388
|
+
// src/core/term/remote.ts
|
|
16389
|
+
var REMOTE_STATE_PREFIX = "Remote terminal: ";
|
|
16390
|
+
var REMOTE_OFF_BY_WEB_LINE = `${REMOTE_STATE_PREFIX}turned off from the web.`;
|
|
16391
|
+
var REMOTE_NOT_FOUND = "REMOTE_NOT_FOUND";
|
|
16392
|
+
var E2E_VERSION = 1;
|
|
16393
|
+
function openRemoteLog(paths) {
|
|
16394
|
+
const log = new DaemonLog(paths.remoteLog, paths.previousRemoteLog);
|
|
16395
|
+
log.enableRotation();
|
|
16396
|
+
return log;
|
|
16397
|
+
}
|
|
16398
|
+
function createRemoteHttp(input) {
|
|
16399
|
+
return createPcHttp({
|
|
16400
|
+
endpoint: input.endpoint,
|
|
16401
|
+
path: "term/pc",
|
|
16402
|
+
tokenProvider: input.tokenProvider,
|
|
16403
|
+
timeoutMs: CALL_TIMEOUT_MS,
|
|
16404
|
+
sessionHeader: "X-Remote-Token",
|
|
16405
|
+
fetchImpl: input.fetchImpl,
|
|
16406
|
+
logging: {
|
|
16407
|
+
log: input.log,
|
|
16408
|
+
request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
|
|
16409
|
+
response: ({ callId, op, ms }, outcome) => ({
|
|
16410
|
+
event: "remote_call_response",
|
|
16411
|
+
callId,
|
|
16412
|
+
op,
|
|
16413
|
+
...outcome.ok ? { ok: true, status: outcome.status, ...answerSummary(outcome.body) } : outcome,
|
|
16414
|
+
ms
|
|
16415
|
+
})
|
|
16416
|
+
}
|
|
16417
|
+
});
|
|
16418
|
+
}
|
|
16419
|
+
var viewerKey = (watch) => `${watch.channelId}\0${watch.session}`;
|
|
16420
|
+
async function runRemoteBridge(deps) {
|
|
16421
|
+
let ending;
|
|
16422
|
+
const stopper = new AbortController();
|
|
16423
|
+
const viewers = /* @__PURE__ */ new Map();
|
|
16424
|
+
const book = new ChannelBook(deps.pcId);
|
|
16425
|
+
let devices;
|
|
16426
|
+
const end = (outcome) => {
|
|
16427
|
+
if (ending) return;
|
|
16428
|
+
ending = outcome;
|
|
16429
|
+
devices?.stop();
|
|
16430
|
+
stopper.abort();
|
|
16431
|
+
for (const { viewer } of viewers.values()) viewer.stop();
|
|
16432
|
+
viewers.clear();
|
|
16433
|
+
};
|
|
16434
|
+
const onUserStop = () => end({ exitCode: 0, reason: "Stopped.", close: true });
|
|
16435
|
+
if (deps.signal.aborted) onUserStop();
|
|
16436
|
+
deps.signal.addEventListener("abort", onUserStop, { once: true });
|
|
16437
|
+
const control = new DaemonControl(deps.paths);
|
|
16438
|
+
let listWatch;
|
|
16439
|
+
try {
|
|
16440
|
+
const first = await currentSessions(deps);
|
|
16441
|
+
if (ending) return { exitCode: ending.exitCode, reason: ending.reason };
|
|
16442
|
+
let link2;
|
|
16443
|
+
try {
|
|
16444
|
+
link2 = await openLink2(deps, 1, deps.remoteEnabled, deps.remoteEnabled ? first : [], void 0);
|
|
16445
|
+
} catch (error) {
|
|
16446
|
+
return { exitCode: 1, reason: refused(error).reason };
|
|
16447
|
+
}
|
|
16448
|
+
let remote = startState(deps.remoteEnabled);
|
|
16449
|
+
let uploaded = deps.remoteEnabled ? sessionsKey(first) : void 0;
|
|
16450
|
+
let watchList = [];
|
|
16451
|
+
deps.log.write({
|
|
16452
|
+
event: "remote_opened",
|
|
16453
|
+
linkId: link2.linkId,
|
|
16454
|
+
sessions: deps.remoteEnabled ? first.length : 0,
|
|
16455
|
+
remote,
|
|
16456
|
+
pollHoldSeconds: link2.pollHoldSeconds,
|
|
16457
|
+
frameMaxBytes: link2.frameMaxBytes
|
|
16458
|
+
});
|
|
16459
|
+
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).`);
|
|
16460
|
+
let syncing = Promise.resolve();
|
|
16461
|
+
const syncList = () => {
|
|
16462
|
+
syncing = syncing.then(async () => {
|
|
16463
|
+
if (ending || remote !== "on") return;
|
|
16464
|
+
let sessions;
|
|
16465
|
+
try {
|
|
16466
|
+
sessions = await currentSessions(deps);
|
|
16467
|
+
} catch (error) {
|
|
16468
|
+
daemonFailed(deps, "ls", void 0, error);
|
|
16469
|
+
return;
|
|
16470
|
+
}
|
|
16471
|
+
const key = sessionsKey(sessions);
|
|
16472
|
+
if (key === uploaded) return;
|
|
16473
|
+
try {
|
|
16474
|
+
await deps.http.call("sessions", { linkId: link2.linkId, sessions }, { signal: stopper.signal });
|
|
16475
|
+
uploaded = key;
|
|
16476
|
+
for (const { viewer } of viewers.values()) viewer.refresh();
|
|
16477
|
+
} catch {
|
|
16478
|
+
}
|
|
16479
|
+
});
|
|
16480
|
+
return syncing;
|
|
16481
|
+
};
|
|
15964
16482
|
listWatch = await openTermClient(deps.paths, { start: false });
|
|
15965
16483
|
if (listWatch) {
|
|
15966
16484
|
listWatch.onEvent((event) => {
|
|
@@ -16067,6 +16585,7 @@ async function runRemoteBridge(deps) {
|
|
|
16067
16585
|
void syncList();
|
|
16068
16586
|
deps.print(`${REMOTE_STATE_PREFIX}on.`);
|
|
16069
16587
|
} else {
|
|
16588
|
+
devices?.stop();
|
|
16070
16589
|
await closeAllChannels("REMOTE_OFF");
|
|
16071
16590
|
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).`);
|
|
16072
16591
|
}
|
|
@@ -16104,7 +16623,36 @@ async function runRemoteBridge(deps) {
|
|
|
16104
16623
|
return;
|
|
16105
16624
|
}
|
|
16106
16625
|
};
|
|
16626
|
+
const closeKey = async (keyId) => {
|
|
16627
|
+
for (const channelId of book.dropBrowser(keyId)) {
|
|
16628
|
+
stopViewers(channelId);
|
|
16629
|
+
commands.forgetChannel(channelId);
|
|
16630
|
+
deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "pc", reason: "PAIRING_REQUIRED", browserKeyId: keyId });
|
|
16631
|
+
try {
|
|
16632
|
+
await deps.http.call("channel/close", { linkId: link2.linkId, channelId, reason: "PAIRING_REQUIRED" }, { signal: stopper.signal });
|
|
16633
|
+
} catch {
|
|
16634
|
+
}
|
|
16635
|
+
}
|
|
16636
|
+
};
|
|
16637
|
+
if (deps.trust && deps.pairRelay) {
|
|
16638
|
+
const trust = deps.trust;
|
|
16639
|
+
const relay = deps.pairRelay;
|
|
16640
|
+
devices = new DeviceManager({
|
|
16641
|
+
keysPath: trust.keysPath,
|
|
16642
|
+
accountKey: trust.accountKey,
|
|
16643
|
+
userId: trust.userId,
|
|
16644
|
+
pcId: deps.pcId,
|
|
16645
|
+
relay,
|
|
16646
|
+
notifyRequest: (name) => void deps.notifier.notify({ kind: "device-request", keyId: "device-request", browserName: name }),
|
|
16647
|
+
log: (record4) => deps.log.write(record4),
|
|
16648
|
+
closeKey,
|
|
16649
|
+
// ★PC 설정이 먼저다 — 서버 poll 의 remote 로는 줄일 수만 있다(서버가 «켜짐»을 보내도 PC 에서 끈 원격은 열리지 않는다).
|
|
16650
|
+
remoteOn: () => deps.remoteEnabled && remote === "on" && !ending
|
|
16651
|
+
});
|
|
16652
|
+
}
|
|
16107
16653
|
const commands = new CommandRunner(deps, control, book, () => remote, () => link2.linkId, stopper.signal, {
|
|
16654
|
+
devices: () => devices,
|
|
16655
|
+
trusted: async (keyId) => (await loadTrust(deps))?.browsers.some((item) => item.keyId === keyId) === true,
|
|
16108
16656
|
closeChannel,
|
|
16109
16657
|
refreshChannel,
|
|
16110
16658
|
resized: (session, size) => {
|
|
@@ -16139,6 +16687,7 @@ async function runRemoteBridge(deps) {
|
|
|
16139
16687
|
end(refused(reopenError));
|
|
16140
16688
|
break;
|
|
16141
16689
|
}
|
|
16690
|
+
devices?.stop();
|
|
16142
16691
|
const dropped = book.dropAll();
|
|
16143
16692
|
for (const channelId of dropped) {
|
|
16144
16693
|
stopViewers(channelId);
|
|
@@ -16194,6 +16743,9 @@ async function runRemoteBridge(deps) {
|
|
|
16194
16743
|
case "watch":
|
|
16195
16744
|
watchList = item.channels;
|
|
16196
16745
|
break;
|
|
16746
|
+
case "pair-request":
|
|
16747
|
+
await devices?.onPairRequest(item.requestId);
|
|
16748
|
+
break;
|
|
16197
16749
|
case "channel-closed":
|
|
16198
16750
|
if (book.drop(item.channelId)) {
|
|
16199
16751
|
deps.log.write({ event: "remote_channel", channelId: item.channelId, state: "closed", by: "web" });
|
|
@@ -16230,14 +16782,16 @@ function startState(remoteEnabled) {
|
|
|
16230
16782
|
return remoteEnabled ? "on" : "off-by-pc";
|
|
16231
16783
|
}
|
|
16232
16784
|
async function openLink2(deps, generation, remoteEnabled, sessions, signal) {
|
|
16233
|
-
const
|
|
16234
|
-
|
|
16235
|
-
|
|
16236
|
-
|
|
16237
|
-
|
|
16238
|
-
|
|
16239
|
-
|
|
16240
|
-
|
|
16785
|
+
const base = { pcId: deps.pcId, hostName: deps.hostName, cliVersion: deps.cliVersion, remoteEnabled, sessions, e2e: E2E_VERSION };
|
|
16786
|
+
const devices = deps.trust !== void 0 && deps.pairRelay !== void 0;
|
|
16787
|
+
let opened;
|
|
16788
|
+
try {
|
|
16789
|
+
opened = await deps.http.call("open", devices ? { ...base, devices: true } : base, signal ? { signal } : void 0);
|
|
16790
|
+
} catch (error) {
|
|
16791
|
+
if (!devices || !(error instanceof PcCallError && error.status === 400 && error.code === "INVALID")) throw error;
|
|
16792
|
+
deps.log.write({ event: "remote_open_without_devices", reason: "server refused the devices field" });
|
|
16793
|
+
opened = await deps.http.call("open", base, signal ? { signal } : void 0);
|
|
16794
|
+
}
|
|
16241
16795
|
const limits = serverLimits2(opened.limits);
|
|
16242
16796
|
if (typeof opened.linkId !== "string" || typeof opened.linkToken !== "string" || !limits) {
|
|
16243
16797
|
throw new TermError("TERM_REMOTE_BAD_RESPONSE", "AiNecto answered open without linkId, linkToken or limits.");
|
|
@@ -16343,15 +16897,76 @@ var CommandRunner = class {
|
|
|
16343
16897
|
await this.hooks.closeChannel(wire.channelId, outcome.reason);
|
|
16344
16898
|
return;
|
|
16345
16899
|
case "confirmed":
|
|
16900
|
+
if (!await this.hooks.trusted(outcome.browser.keyId)) {
|
|
16901
|
+
await this.hooks.closeChannel(wire.channelId, "PAIRING_REQUIRED", outcome.browser);
|
|
16902
|
+
return;
|
|
16903
|
+
}
|
|
16346
16904
|
this.deps.log.write({ event: "remote_channel", channelId: wire.channelId, state: "active", browserKeyId: outcome.browser.keyId });
|
|
16347
16905
|
void this.deps.notifier.notify({ kind: "session", keyId: outcome.browser.keyId, browserName: outcome.browser.name });
|
|
16348
16906
|
await this.hooks.applyWatching();
|
|
16349
16907
|
return;
|
|
16350
16908
|
case "command":
|
|
16351
|
-
await this.
|
|
16909
|
+
if (outcome.command.kind === "device") await this.device(wire, outcome.command, outcome.browser);
|
|
16910
|
+
else await this.execute(wire, outcome.command, outcome.browser);
|
|
16352
16911
|
return;
|
|
16353
16912
|
}
|
|
16354
16913
|
}
|
|
16914
|
+
/** 기기 관리 명령(approve-new-device §3-4) — 답 봉투 {opId, kind:"device", ok, detail?, result}. 세션 없음(AAD session ""). */
|
|
16915
|
+
async device(wire, command, browser) {
|
|
16916
|
+
this.deps.log.write({
|
|
16917
|
+
event: "remote_command",
|
|
16918
|
+
type: "device",
|
|
16919
|
+
channelId: wire.channelId,
|
|
16920
|
+
n: wire.n,
|
|
16921
|
+
opId: command.opId,
|
|
16922
|
+
...wire.requestId ? { requestId: wire.requestId } : {}
|
|
16923
|
+
});
|
|
16924
|
+
const devices = this.hooks.devices();
|
|
16925
|
+
let failure2;
|
|
16926
|
+
let result = {};
|
|
16927
|
+
if (this.remote() !== "on") {
|
|
16928
|
+
failure2 = { code: "REMOTE_OFF", message: "Terminals from the web are turned off on this PC." };
|
|
16929
|
+
} else if (!devices) {
|
|
16930
|
+
failure2 = { code: "TERM_BAD_REQUEST", message: "This PC cannot manage devices (account unknown)." };
|
|
16931
|
+
} else {
|
|
16932
|
+
try {
|
|
16933
|
+
result = await devices.command(command.action, browser);
|
|
16934
|
+
} catch (error) {
|
|
16935
|
+
failure2 = { code: errorCode2(error), message: error instanceof Error ? error.message : String(error) };
|
|
16936
|
+
}
|
|
16937
|
+
}
|
|
16938
|
+
let box;
|
|
16939
|
+
try {
|
|
16940
|
+
box = await this.book.seal(wire.channelId, { kind: "answer", session: "", opId: command.opId }, {
|
|
16941
|
+
opId: command.opId,
|
|
16942
|
+
kind: "device",
|
|
16943
|
+
ok: failure2 === void 0,
|
|
16944
|
+
...failure2 ? { detail: `${failure2.code}: ${failure2.message}` } : {},
|
|
16945
|
+
result
|
|
16946
|
+
});
|
|
16947
|
+
} catch (error) {
|
|
16948
|
+
const reason = error instanceof ChannelSealError && error.reason !== "CHANNEL_GONE" ? error.reason : void 0;
|
|
16949
|
+
this.logResult(wire, "device", "", false, failure2?.code ?? reason ?? "CHANNEL_GONE");
|
|
16950
|
+
if (reason) await this.hooks.closeChannel(wire.channelId, reason);
|
|
16951
|
+
return;
|
|
16952
|
+
}
|
|
16953
|
+
if (wire.requestId) {
|
|
16954
|
+
try {
|
|
16955
|
+
await this.deps.http.call("answer", {
|
|
16956
|
+
linkId: this.linkId(),
|
|
16957
|
+
requestId: wire.requestId,
|
|
16958
|
+
channelId: wire.channelId,
|
|
16959
|
+
...box,
|
|
16960
|
+
ok: failure2 === void 0,
|
|
16961
|
+
...failure2 ? { code: answerCodeOf(failure2.code) } : {}
|
|
16962
|
+
}, { signal: this.stopSignal });
|
|
16963
|
+
} catch {
|
|
16964
|
+
}
|
|
16965
|
+
}
|
|
16966
|
+
const raised = this.book.executed(wire.channelId, wire.n);
|
|
16967
|
+
this.logResult(wire, "device", "", failure2 === void 0, failure2?.code, raised ? wire.n : void 0);
|
|
16968
|
+
if (raised) this.hooks.refreshChannel(wire.channelId);
|
|
16969
|
+
}
|
|
16355
16970
|
async execute(wire, command, browser) {
|
|
16356
16971
|
const session = command.kind === "create" ? command.name : command.session;
|
|
16357
16972
|
const opId = "opId" in command ? command.opId : void 0;
|
|
@@ -16611,6 +17226,8 @@ function pollItems(answer) {
|
|
|
16611
17226
|
}) : [] }];
|
|
16612
17227
|
case "channel-closed":
|
|
16613
17228
|
return channelId ? [{ type: "channel-closed", channelId }] : [];
|
|
17229
|
+
case "pair-request":
|
|
17230
|
+
return typeof item.requestId === "string" && item.requestId !== "" ? [{ type: "pair-request", requestId: item.requestId }] : [];
|
|
16614
17231
|
default:
|
|
16615
17232
|
return [];
|
|
16616
17233
|
}
|
|
@@ -16727,80 +17344,6 @@ function pcOutcome(lines) {
|
|
|
16727
17344
|
return failed === void 0 ? void 0 : { kind: "failed", line: failed };
|
|
16728
17345
|
}
|
|
16729
17346
|
|
|
16730
|
-
// src/core/pc/pcPairing.ts
|
|
16731
|
-
var PAIR_WAIT_MS = 5 * 6e4;
|
|
16732
|
-
async function runPairing(input) {
|
|
16733
|
-
const deadline = new AbortController();
|
|
16734
|
-
const timer = setTimeout(() => deadline.abort(), input.waitMs);
|
|
16735
|
-
let cancelled = false;
|
|
16736
|
-
const onCancel = () => {
|
|
16737
|
-
cancelled = true;
|
|
16738
|
-
deadline.abort();
|
|
16739
|
-
};
|
|
16740
|
-
input.cancel?.addEventListener("abort", onCancel, { once: true });
|
|
16741
|
-
if (input.cancel?.aborted) onCancel();
|
|
16742
|
-
const { signal } = deadline;
|
|
16743
|
-
const relayed = async (step) => {
|
|
16744
|
-
try {
|
|
16745
|
-
return await step();
|
|
16746
|
-
} catch (error) {
|
|
16747
|
-
if (signal.aborted) return "timeout";
|
|
16748
|
-
throw error;
|
|
16749
|
-
}
|
|
16750
|
-
};
|
|
16751
|
-
let outcome;
|
|
16752
|
-
try {
|
|
16753
|
-
outcome = await pairOnce();
|
|
16754
|
-
if (cancelled && outcome.kind === "timeout") outcome = { kind: "cancelled" };
|
|
16755
|
-
return outcome;
|
|
16756
|
-
} finally {
|
|
16757
|
-
clearTimeout(timer);
|
|
16758
|
-
input.cancel?.removeEventListener("abort", onCancel);
|
|
16759
|
-
if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
|
|
16760
|
-
}
|
|
16761
|
-
async function pairOnce() {
|
|
16762
|
-
const pcPublicRaw = publicRawFromJwk(input.pcKey);
|
|
16763
|
-
const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
|
|
16764
|
-
const commit = await pairCommitment(pcPublicRaw, nP);
|
|
16765
|
-
const offer = await relayed(() => input.transport.offer(commit, signal));
|
|
16766
|
-
if (offer === "timeout") return { kind: "timeout" };
|
|
16767
|
-
const publicJwk = publicJwkFromRaw(offer.publicRaw);
|
|
16768
|
-
await assertSigningPublicKey(publicJwk);
|
|
16769
|
-
if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
|
|
16770
|
-
throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 browser registration aborted.");
|
|
16771
|
-
}
|
|
16772
|
-
const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
|
|
16773
|
-
const transcript = () => pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
|
|
16774
|
-
const keys = await registerKeys(input.secret);
|
|
16775
|
-
const expected = await registerOfferMac(keys.browser, {
|
|
16776
|
-
userId: input.userId,
|
|
16777
|
-
pcId: input.pcId,
|
|
16778
|
-
attemptId: offer.attemptId,
|
|
16779
|
-
commit,
|
|
16780
|
-
browserPublicRaw: offer.publicRaw,
|
|
16781
|
-
keyId: offer.keyId,
|
|
16782
|
-
nB: offer.nB,
|
|
16783
|
-
name: offer.name
|
|
16784
|
-
});
|
|
16785
|
-
if (!offer.macB || !macEquals(offer.macB, expected)) return { kind: "code-mismatch" };
|
|
16786
|
-
const t = await transcript();
|
|
16787
|
-
await input.pin(browser);
|
|
16788
|
-
const macP = await registerRevealMac(keys.pc, { transcript: t, attemptId: offer.attemptId });
|
|
16789
|
-
return await finish(browser, t, () => input.transport.reveal(pcPublicRaw, nP, signal, macP));
|
|
16790
|
-
}
|
|
16791
|
-
async function finish(browser, transcript, before) {
|
|
16792
|
-
const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
|
|
16793
|
-
let doneError;
|
|
16794
|
-
try {
|
|
16795
|
-
await before();
|
|
16796
|
-
await input.transport.done(signature, signal);
|
|
16797
|
-
} catch (error) {
|
|
16798
|
-
doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
|
|
16799
|
-
}
|
|
16800
|
-
return { kind: "paired", browser, doneError };
|
|
16801
|
-
}
|
|
16802
|
-
}
|
|
16803
|
-
|
|
16804
17347
|
// src/adapters/cli/pcCommand.ts
|
|
16805
17348
|
import { readFile as readFile13 } from "fs/promises";
|
|
16806
17349
|
|
|
@@ -17016,8 +17559,8 @@ async function upgradeDaemon(deps, note) {
|
|
|
17016
17559
|
}
|
|
17017
17560
|
note("Updating the AiNecto terminal service on this PC\u2026");
|
|
17018
17561
|
await termRequest(deps.paths, { op: "kill-server" }, { start: false });
|
|
17019
|
-
if (!await
|
|
17020
|
-
throw new CliCommandError("PC_START_FAILED", `The old terminal service (pid ${info.pid}) did not stop.
|
|
17562
|
+
if (!await waitForDaemonLockFree(deps.paths, deps.stopDeadlineMs)) {
|
|
17563
|
+
throw new CliCommandError("PC_START_FAILED", `The old AiNecto terminal service (${info.version}, started as pid ${info.pid}) is still running and did not stop within ${Math.round(deps.stopDeadlineMs / 1e3)} s. End it \u2014 on Windows: Task Manager \u203A Details \u203A the node.exe whose command line has "term daemon"; on macOS/Linux: \`kill ${info.pid}\` if that pid is still the daemon \u2014 or restart this PC, then run \`npx -y ainecto@latest\` again.`);
|
|
17021
17564
|
}
|
|
17022
17565
|
}
|
|
17023
17566
|
async function withRegistration(deps, key, userId, code) {
|
|
@@ -17048,6 +17591,7 @@ async function registerBrowserOnStart(deps, account2) {
|
|
|
17048
17591
|
const secret = randomBytes3(NONCE_SEED_BYTES);
|
|
17049
17592
|
const interrupt = register.interrupt();
|
|
17050
17593
|
let outcome;
|
|
17594
|
+
let writtenAt = "";
|
|
17051
17595
|
try {
|
|
17052
17596
|
const tag = await registerTag((await registerKeys(secret)).account, userId);
|
|
17053
17597
|
const url = `${new URL(deps.endpoint).origin}${REGISTER_PATH}#${registerFragment({ pcId: settings.pcId, tag, secret })}`;
|
|
@@ -17060,13 +17604,15 @@ async function registerBrowserOnStart(deps, account2) {
|
|
|
17060
17604
|
note("");
|
|
17061
17605
|
note(`Finish in the browser that just opened (up to ${Math.round(register.waitMs / 6e4)} min \xB7 Ctrl+C to skip)`);
|
|
17062
17606
|
const pcKey = stored?.pcKey ?? await generateSigningJwk();
|
|
17607
|
+
const pinnedAt = register.now();
|
|
17608
|
+
writtenAt = pinnedAt.toISOString();
|
|
17063
17609
|
outcome = await runPairing({
|
|
17064
17610
|
userId,
|
|
17065
17611
|
pcId: settings.pcId,
|
|
17066
17612
|
pcKey,
|
|
17067
17613
|
transport: await register.transport(settings.pcId),
|
|
17068
|
-
secret,
|
|
17069
|
-
pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now:
|
|
17614
|
+
confirm: { kind: "secret", secret },
|
|
17615
|
+
pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now: pinnedAt }),
|
|
17070
17616
|
waitMs: register.waitMs,
|
|
17071
17617
|
cancel: interrupt.signal
|
|
17072
17618
|
});
|
|
@@ -17085,8 +17631,12 @@ async function registerBrowserOnStart(deps, account2) {
|
|
|
17085
17631
|
const { browser, doneError } = outcome;
|
|
17086
17632
|
if (doneError !== void 0) {
|
|
17087
17633
|
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17088
|
-
const
|
|
17089
|
-
|
|
17634
|
+
const current = keys.accounts[account2.key];
|
|
17635
|
+
if (!current?.browsers.some((item) => item.keyId === browser.keyId && item.pairedAt === writtenAt)) return void 0;
|
|
17636
|
+
return { accounts: { ...keys.accounts, [account2.key]: {
|
|
17637
|
+
...current,
|
|
17638
|
+
browsers: current.browsers.filter((item) => !(item.keyId === browser.keyId && item.pairedAt === writtenAt))
|
|
17639
|
+
} } };
|
|
17090
17640
|
});
|
|
17091
17641
|
note(`The browser "${browser.name}" did not get the confirmation (${doneError}), so nothing was kept. ${REGISTER_AGAIN}`);
|
|
17092
17642
|
return;
|
|
@@ -17402,12 +17952,12 @@ function createPairRelay(input) {
|
|
|
17402
17952
|
};
|
|
17403
17953
|
return {
|
|
17404
17954
|
async offer(commit, signal) {
|
|
17405
|
-
const opened = await http.call("pair/open", { pcId: input.pcId }, { signal });
|
|
17955
|
+
const opened = await http.call("pair/open", { pcId: input.pcId, ...input.requestId ? { requestId: input.requestId } : {} }, { signal });
|
|
17406
17956
|
if (typeof opened.attemptId !== "string" || opened.attemptId === "") {
|
|
17407
17957
|
throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "AiNecto answered pair/open without an attemptId.");
|
|
17408
17958
|
}
|
|
17409
17959
|
attemptId = opened.attemptId;
|
|
17410
|
-
await send({ type: "commit", commit:
|
|
17960
|
+
await send({ type: "commit", commit: b64u3(commit) }, signal);
|
|
17411
17961
|
for (; ; ) {
|
|
17412
17962
|
const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
|
|
17413
17963
|
if (answer.closed === true) {
|
|
@@ -17423,12 +17973,38 @@ function createPairRelay(input) {
|
|
|
17423
17973
|
}
|
|
17424
17974
|
},
|
|
17425
17975
|
async reveal(pcPublicRaw, nP, signal, macP) {
|
|
17426
|
-
await send({ type: "reveal", publicKey:
|
|
17976
|
+
await send({ type: "reveal", publicKey: b64u3(pcPublicRaw), nP: b64u3(nP), ...macP ? { macP: b64u3(macP) } : {} }, signal);
|
|
17977
|
+
},
|
|
17978
|
+
async deviceConsent(signal) {
|
|
17979
|
+
if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The browser registration was not opened.");
|
|
17980
|
+
for (; ; ) {
|
|
17981
|
+
const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
|
|
17982
|
+
if (answer.closed === true) {
|
|
17983
|
+
finished = true;
|
|
17984
|
+
return void 0;
|
|
17985
|
+
}
|
|
17986
|
+
const consent = consentOf(Array.isArray(answer.msgs) ? answer.msgs : []);
|
|
17987
|
+
if (consent === "abort") {
|
|
17988
|
+
finished = true;
|
|
17989
|
+
return void 0;
|
|
17990
|
+
}
|
|
17991
|
+
if (consent) return consent;
|
|
17992
|
+
}
|
|
17427
17993
|
},
|
|
17428
17994
|
async done(signature, signal) {
|
|
17429
|
-
await send({ type: "done", signature:
|
|
17995
|
+
await send({ type: "done", signature: b64u3(signature) }, signal);
|
|
17430
17996
|
finished = true;
|
|
17431
17997
|
},
|
|
17998
|
+
async refuse(reason) {
|
|
17999
|
+
try {
|
|
18000
|
+
const opened = await http.call("pair/open", { pcId: input.pcId, ...input.requestId ? { requestId: input.requestId } : {} });
|
|
18001
|
+
if (typeof opened.attemptId !== "string" || opened.attemptId === "") return;
|
|
18002
|
+
attemptId = opened.attemptId;
|
|
18003
|
+
finished = true;
|
|
18004
|
+
await http.call("pair/send", { attemptId, msg: { type: "abort", reason } });
|
|
18005
|
+
} catch {
|
|
18006
|
+
}
|
|
18007
|
+
},
|
|
17432
18008
|
async abort(reason) {
|
|
17433
18009
|
if (!attemptId || finished) return;
|
|
17434
18010
|
finished = true;
|
|
@@ -17459,7 +18035,16 @@ function offerOf(msgs) {
|
|
|
17459
18035
|
}
|
|
17460
18036
|
return { keyId: item.keyId, publicRaw, nB, name: item.name, ...macB ? { macB } : {} };
|
|
17461
18037
|
}
|
|
17462
|
-
function
|
|
18038
|
+
function consentOf(msgs) {
|
|
18039
|
+
if (msgs.length === 0) return void 0;
|
|
18040
|
+
const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
|
|
18041
|
+
if (items.some((item) => item.type === "abort")) return "abort";
|
|
18042
|
+
if (items.length > 1) throw new PairRelayError("PAIR_DUPLICATE", "More than one device answer arrived \u2014 this try was ended.");
|
|
18043
|
+
const sig = items[0]?.type === "confirm" ? fromB64u2(items[0].sig, SIGNATURE_BYTES) : void 0;
|
|
18044
|
+
if (!sig) throw new PairRelayError("PAIR_BAD_MESSAGE", "AiNecto relayed a device answer this CLI does not understand \u2014 this try was ended.");
|
|
18045
|
+
return sig;
|
|
18046
|
+
}
|
|
18047
|
+
function b64u3(bytes) {
|
|
17463
18048
|
return Buffer.from(bytes).toString("base64url");
|
|
17464
18049
|
}
|
|
17465
18050
|
function fromB64u2(value, length) {
|
|
@@ -17468,111 +18053,6 @@ function fromB64u2(value, length) {
|
|
|
17468
18053
|
return bytes.length === length ? bytes : void 0;
|
|
17469
18054
|
}
|
|
17470
18055
|
|
|
17471
|
-
// src/core/pc/pcNotify.ts
|
|
17472
|
-
var NOTIFY_BATCH_MS = 6e4;
|
|
17473
|
-
var WHAT = {
|
|
17474
|
-
paired: "was registered with this PC",
|
|
17475
|
-
session: "opened a terminal connection to this PC",
|
|
17476
|
-
shell: "started a new shell on this PC",
|
|
17477
|
-
command: "started a command in a new terminal on this PC"
|
|
17478
|
-
};
|
|
17479
|
-
function notificationText(event, more) {
|
|
17480
|
-
const time = `${String(event.at.getHours()).padStart(2, "0")}:${String(event.at.getMinutes()).padStart(2, "0")}`;
|
|
17481
|
-
return {
|
|
17482
|
-
title: "AiNecto",
|
|
17483
|
-
body: `${event.browserName} ${WHAT[event.kind]} \u2014 ${time}${more > 0 ? ` (+${more} more)` : ""}. Not you? Run \`ainecto remote off\`.`
|
|
17484
|
-
};
|
|
17485
|
-
}
|
|
17486
|
-
var systemClock = {
|
|
17487
|
-
now: () => Date.now(),
|
|
17488
|
-
setTimer: (run, ms) => {
|
|
17489
|
-
const timer = setTimeout(run, ms);
|
|
17490
|
-
timer.unref?.();
|
|
17491
|
-
return timer;
|
|
17492
|
-
},
|
|
17493
|
-
clearTimer: (timer) => clearTimeout(timer)
|
|
17494
|
-
};
|
|
17495
|
-
var NotifyBatcher = class {
|
|
17496
|
-
constructor(show, clock = systemClock) {
|
|
17497
|
-
this.show = show;
|
|
17498
|
-
this.clock = clock;
|
|
17499
|
-
}
|
|
17500
|
-
show;
|
|
17501
|
-
clock;
|
|
17502
|
-
slots = /* @__PURE__ */ new Map();
|
|
17503
|
-
add(event) {
|
|
17504
|
-
const key = `${event.keyId}\0${event.kind}`;
|
|
17505
|
-
const now = this.clock.now();
|
|
17506
|
-
const slot = this.slots.get(key);
|
|
17507
|
-
if (!slot || now >= slot.endsAt) {
|
|
17508
|
-
this.show(event, 0);
|
|
17509
|
-
this.slots.set(key, { endsAt: now + NOTIFY_BATCH_MS, pending: void 0, timer: void 0 });
|
|
17510
|
-
return;
|
|
17511
|
-
}
|
|
17512
|
-
slot.pending = { event, count: (slot.pending?.count ?? 0) + 1 };
|
|
17513
|
-
slot.timer ??= this.clock.setTimer(() => this.close(key), slot.endsAt - now);
|
|
17514
|
-
}
|
|
17515
|
-
flush() {
|
|
17516
|
-
for (const [key, slot] of this.slots) {
|
|
17517
|
-
if (slot.timer !== void 0) this.clock.clearTimer(slot.timer);
|
|
17518
|
-
if (slot.pending) this.show(slot.pending.event, slot.pending.count - 1);
|
|
17519
|
-
this.slots.delete(key);
|
|
17520
|
-
}
|
|
17521
|
-
}
|
|
17522
|
-
close(key) {
|
|
17523
|
-
const slot = this.slots.get(key);
|
|
17524
|
-
if (!slot) return;
|
|
17525
|
-
slot.timer = void 0;
|
|
17526
|
-
if (!slot.pending) return;
|
|
17527
|
-
const { event, count } = slot.pending;
|
|
17528
|
-
slot.pending = void 0;
|
|
17529
|
-
slot.endsAt = this.clock.now() + NOTIFY_BATCH_MS;
|
|
17530
|
-
this.show(event, count - 1);
|
|
17531
|
-
}
|
|
17532
|
-
};
|
|
17533
|
-
function notifyFailureReason(error) {
|
|
17534
|
-
if (error && typeof error === "object") {
|
|
17535
|
-
const value = error;
|
|
17536
|
-
if (value.code === "ENOENT") return "not-found";
|
|
17537
|
-
if (value.code === "EACCES") return "no-permission";
|
|
17538
|
-
if (typeof value.signal === "string" && value.signal !== "") return "signal";
|
|
17539
|
-
if (typeof value.code === "number") return `exit-${value.code}`;
|
|
17540
|
-
}
|
|
17541
|
-
return "failed";
|
|
17542
|
-
}
|
|
17543
|
-
function createPcNotifier(input) {
|
|
17544
|
-
const tool = notifyTool(input.platform);
|
|
17545
|
-
const run = input.run ?? runQuiet;
|
|
17546
|
-
const clock = input.clock ?? systemClock;
|
|
17547
|
-
let last = Promise.resolve();
|
|
17548
|
-
const show = (event, more) => {
|
|
17549
|
-
input.log.write({ event: "pc_notify", kind: event.kind, browserKeyId: event.keyId, more, tool: tool?.name ?? "none" });
|
|
17550
|
-
if (!tool) {
|
|
17551
|
-
input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: "none", reason: "no-tool-on-this-os" });
|
|
17552
|
-
last = Promise.resolve();
|
|
17553
|
-
return;
|
|
17554
|
-
}
|
|
17555
|
-
const { title, body } = notificationText(event, more);
|
|
17556
|
-
last = run(tool.file, tool.args(title, body)).then(
|
|
17557
|
-
() => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: true, tool: tool.name }),
|
|
17558
|
-
(error) => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: tool.name, reason: notifyFailureReason(error) })
|
|
17559
|
-
);
|
|
17560
|
-
};
|
|
17561
|
-
const batcher = new NotifyBatcher(show, clock);
|
|
17562
|
-
return {
|
|
17563
|
-
async notify(event) {
|
|
17564
|
-
const before = last;
|
|
17565
|
-
batcher.add({ ...event, at: new Date(clock.now()) });
|
|
17566
|
-
if (last !== before) await last;
|
|
17567
|
-
},
|
|
17568
|
-
async flush() {
|
|
17569
|
-
const before = last;
|
|
17570
|
-
batcher.flush();
|
|
17571
|
-
if (last !== before) await last;
|
|
17572
|
-
}
|
|
17573
|
-
};
|
|
17574
|
-
}
|
|
17575
|
-
|
|
17576
18056
|
// src/adapters/cli/pcSwap.ts
|
|
17577
18057
|
import { randomUUID as randomUUID8 } from "crypto";
|
|
17578
18058
|
import { writeFile as writeFile7 } from "fs/promises";
|
|
@@ -18885,6 +19365,14 @@ async function runPcRemote(setup, signal, onAnswer) {
|
|
|
18885
19365
|
pcId: setup.pcId,
|
|
18886
19366
|
remote: setup.remoteEnabled ? "on" : "off"
|
|
18887
19367
|
});
|
|
19368
|
+
const bridgeLock = await acquirePcBridgeLock(setup.paths);
|
|
19369
|
+
if (!bridgeLock) {
|
|
19370
|
+
const reason = "Another AiNecto connection is already running on this PC.";
|
|
19371
|
+
log.write({ event: "remote_stop", pid: process.pid, reason });
|
|
19372
|
+
setup.io.stderr.write(`Remote terminal stopped: ${reason}
|
|
19373
|
+
`);
|
|
19374
|
+
return { exitCode: 1, reason };
|
|
19375
|
+
}
|
|
18888
19376
|
let result;
|
|
18889
19377
|
try {
|
|
18890
19378
|
result = await runRemoteBridge({
|
|
@@ -18897,6 +19385,14 @@ async function runPcRemote(setup, signal, onAnswer) {
|
|
|
18897
19385
|
remoteEnabled: setup.remoteEnabled,
|
|
18898
19386
|
trust: setup.trust,
|
|
18899
19387
|
notifier: createPcNotifier({ log }),
|
|
19388
|
+
pairRelay: (requestId) => createPairRelay({
|
|
19389
|
+
endpoint: setup.endpoint,
|
|
19390
|
+
tokenProvider: setup.auth,
|
|
19391
|
+
log,
|
|
19392
|
+
pcId: setup.pcId,
|
|
19393
|
+
requestId,
|
|
19394
|
+
holdMs: PAIR_WAIT_MS
|
|
19395
|
+
}),
|
|
18900
19396
|
exclude: [PC_SESSION_NAME],
|
|
18901
19397
|
sessionEnv: setup.env,
|
|
18902
19398
|
appHome: setup.appHome,
|
|
@@ -18911,6 +19407,8 @@ async function runPcRemote(setup, signal, onAnswer) {
|
|
|
18911
19407
|
setup.io.stderr.write(`Remote terminal stopped: ${reason}
|
|
18912
19408
|
`);
|
|
18913
19409
|
return { exitCode: 1, reason };
|
|
19410
|
+
} finally {
|
|
19411
|
+
bridgeLock.release();
|
|
18914
19412
|
}
|
|
18915
19413
|
log.write({ event: "remote_stop", pid: process.pid, reason: result.reason, exitCode: result.exitCode });
|
|
18916
19414
|
if (result.exitCode !== 0 || !signal.aborted) {
|