@dsh-mobile/mobile-remote 0.0.0-stage → 3.2.5
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/CHANGELOG.md +1273 -0
- package/CONTRIBUTING.md +59 -0
- package/FAQ.md +115 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/cordis.patch.yml +22 -0
- package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +121 -0
- package/docs/01-PRD.md +148 -0
- package/docs/02-architecture.md +249 -0
- package/docs/03-api.md +882 -0
- package/docs/04-security.md +109 -0
- package/docs/05-test-cases.md +376 -0
- package/docs/06-install-run.md +349 -0
- package/docs/07-user-manual.md +92 -0
- package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +86 -0
- package/docs/09-compatibility.md +201 -0
- package/docs/10-remote-access-and-launch-plan.md +216 -0
- package/docs/11-remote-relay-guide.md +82 -0
- package/docs/APP-ENCRYPTION-DESCRIPTION.md +50 -0
- package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
- package/docs/ARCHITECTURE-CURRENT.md +229 -0
- package/docs/AUDIT-2026-11-node.md +181 -0
- package/docs/AUDIT-2026-11.md +167 -0
- package/docs/BRAND-ASSETS.md +142 -0
- package/docs/BUILD-ENVIRONMENT.md +180 -0
- package/docs/FEATURE-PARITY.md +195 -0
- package/docs/PRIVACY-POLICY.en.md +143 -0
- package/docs/PRIVACY-POLICY.md +143 -0
- package/docs/REA-UNDERSTANDING.md +246 -0
- package/docs/STORE-LAUNCH.md +278 -0
- package/docs/STORE-LISTING.md +150 -0
- package/docs/SUPPORT.md +43 -0
- package/docs/TERMS-OF-SERVICE.en.md +70 -0
- package/docs/TERMS-OF-SERVICE.md +70 -0
- package/docs/screenshots/01-home.png +0 -0
- package/docs/screenshots/02-notifications.png +0 -0
- package/docs/screenshots/03-sessions.png +0 -0
- package/docs/screenshots/04-chat.png +0 -0
- package/docs/screenshots/05-settings.png +0 -0
- package/docs/screenshots/06-new-session.png +0 -0
- package/docs/screenshots/07-connect.png +0 -0
- package/docs/screenshots/pgy-appstore.jpg +0 -0
- package/docs/screenshots/pgy-mobile-app.jpg +0 -0
- package/docs/screenshots/pgy-pc-client.jpg +0 -0
- package/lib/account-usage-query.js +278 -0
- package/lib/account-usage.js +145 -0
- package/lib/api-helpers.js +333 -0
- package/lib/auto-config.js +107 -0
- package/lib/client.js +586 -0
- package/lib/config.js +211 -0
- package/lib/git-read-bundled-provider.js +255 -0
- package/lib/git-read-service.js +322 -0
- package/lib/host-compat.js +133 -0
- package/lib/http-util.js +69 -0
- package/lib/index.js +5729 -0
- package/lib/push.js +73 -0
- package/lib/rate-limit.js +46 -0
- package/lib/relay/connector.js +300 -0
- package/lib/relay/crypto.js +117 -0
- package/lib/relay/devices.js +138 -0
- package/lib/relay/identity.js +60 -0
- package/lib/relay/mux.js +411 -0
- package/lib/relay/noise.js +178 -0
- package/lib/relay/pairing.js +64 -0
- package/lib/relay/phone.js +114 -0
- package/lib/relay/serve.js +105 -0
- package/lib/rpc-adapter.js +88 -0
- package/lib/session-list.js +77 -0
- package/lib/session-title-cache.js +123 -0
- package/lib/session-title-refresh.js +261 -0
- package/lib/timeline.js +476 -0
- package/lib/turn-outline.js +289 -0
- package/package.json +62 -4
package/lib/push.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 第三方推送通道的请求构造。
|
|
3
|
+
* 从 lib/index.js 原样拆出(行为不变)。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* ntfy 发布请求(v3.1.4,issue #14 Bug3)。
|
|
8
|
+
*
|
|
9
|
+
* ntfy 的 JSON 发布契约:`POST /`(或自托管服务器的 base path 根)**且 body 内带 `topic`**;
|
|
10
|
+
* 把 JSON 发到主题地址(`POST /<topic>`)时服务端按**纯文本**处理整段 JSON ——
|
|
11
|
+
* 实测返回体中无 `title` 字段、`message` 为 `{"title":…,"message":…}` 原文,
|
|
12
|
+
* 于是手机通知没有标题、正文是一坨 JSON(用户 12 小时 ntfy 历史里按标题搜不到任何提醒)。
|
|
13
|
+
*
|
|
14
|
+
* 兼容自托管带 base path 的部署:`https://host/ntfy/topic` → POST `https://host/ntfy/`。
|
|
15
|
+
*
|
|
16
|
+
* @param {string} url - 配置里的通道地址(形如 `https://ntfy.sh/<topic>`)
|
|
17
|
+
* @param {object} payload - 消息字段(title / message / priority …)
|
|
18
|
+
* @returns {{url: string, body: string}} 发布地址与 JSON body(已含 topic)
|
|
19
|
+
*/
|
|
20
|
+
export function ntfyPublish(url, payload = {}) {
|
|
21
|
+
const parsed = new URL(url);
|
|
22
|
+
const segments = parsed.pathname.split("/").filter((segment) => segment !== "");
|
|
23
|
+
const topic = segments.length > 0 ? segments[segments.length - 1] : parsed.hostname;
|
|
24
|
+
const basePath = segments.slice(0, -1).join("/");
|
|
25
|
+
return {
|
|
26
|
+
url: `${parsed.origin}/${basePath}${basePath === "" ? "" : "/"}`,
|
|
27
|
+
body: JSON.stringify({ ...payload, topic }),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 按通道格式(serverchan / ntfy / bark / wecom / generic)构造并发送一次推送;失败抛错,由调用方记录。 */
|
|
32
|
+
export async function pushToChannel(logger, target, kind, kindLabel, title, detail, sessionId) {
|
|
33
|
+
const desp = detail || "详情请在 DSH Remote App 中查看";
|
|
34
|
+
let url = target.url;
|
|
35
|
+
const headers = { "user-agent": "dsh-mobile-remote" };
|
|
36
|
+
let init;
|
|
37
|
+
if (target.format === "serverchan") {
|
|
38
|
+
// Server酱³:POST form,title/desp
|
|
39
|
+
const params = new URLSearchParams({ title: `${kindLabel} · ${title}`, desp });
|
|
40
|
+
init = { method: "POST", headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, body: params.toString() };
|
|
41
|
+
} else if (target.format === "ntfy") {
|
|
42
|
+
// ntfy JSON 格式:标题走 body(x-title 头只接受 Latin-1,中文/emoji 会抛错)
|
|
43
|
+
// v3.1.4(issue #14 Bug3):必须 POST 根地址且 body 带 topic——发到主题地址时
|
|
44
|
+
// ntfy 把整段 JSON 当纯文本消息,标题丢失(详见 ntfyPublish 注释与实测结论)。
|
|
45
|
+
const publish = ntfyPublish(url, { title: `${kindLabel} · ${title}`, message: desp });
|
|
46
|
+
url = publish.url;
|
|
47
|
+
init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: publish.body };
|
|
48
|
+
} else if (target.format === "bark") {
|
|
49
|
+
init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify({ title: `${kindLabel} · ${title}`, body: desp }) };
|
|
50
|
+
} else if (target.format === "wecom") {
|
|
51
|
+
// 企业微信群机器人 Webhook(国内稳定、免登录态;约 20 条/分钟限额)
|
|
52
|
+
init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify({ msgtype: "text", text: { content: `${kindLabel} · ${title}\n${desp}` } }) };
|
|
53
|
+
} else {
|
|
54
|
+
init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify({ kind, title, detail: desp, sessionId, time: Date.now() }) };
|
|
55
|
+
}
|
|
56
|
+
// v3.1.2:超时 10s→15s,并针对间歇性网络失败(DNS 抖动等)重试一次——
|
|
57
|
+
// 只重试 fetch 传输失败(timeout/DNS/ECONNRESET),HTTP 4xx/5xx(配额/参数错)不重试
|
|
58
|
+
const pushOnce = async () => {
|
|
59
|
+
try {
|
|
60
|
+
return await fetch(url, { ...init, signal: AbortSignal.timeout(15_000) });
|
|
61
|
+
} catch (err) {
|
|
62
|
+
logger.info?.(`mobile-remote: push 首试失败(${target.name}):${err?.message ?? err},重试一次`);
|
|
63
|
+
return await fetch(url, { ...init, signal: AbortSignal.timeout(15_000) });
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const response = await pushOnce();
|
|
67
|
+
if (!response.ok) {
|
|
68
|
+
// v3.0.0:失败带上响应体(截断)——Server酱/Turbo 400 常带原因说明(额度/参数/转发),
|
|
69
|
+
// 裸 "HTTP 400" 无法定位;空 body 则可能为网络中间层拦截
|
|
70
|
+
const text = (await response.text().catch(() => "")).trim().slice(0, 300);
|
|
71
|
+
throw new Error(`HTTP ${response.status}${text ? `: ${text}` : "(空响应体)"}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 登录限流(v2.6.0):按来源 IP 固定窗口计数,防弱口令爆破。从 lib/index.js 原样拆出(行为不变)。
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @param {{ maxFailures?: number, windowMs?: number, blockMs?: number }} [overrides] 即 `config.rateLimit`
|
|
7
|
+
* @returns {{ cfg: object, blocked: (ip: string) => boolean, fail: (ip: string) => void, reset: (ip: string) => boolean }}
|
|
8
|
+
*/
|
|
9
|
+
export function createLoginRateLimiter(overrides) {
|
|
10
|
+
// 正常用户一次成功即重置计数;frp 等中继场景所有外部请求同源(中继 IP),
|
|
11
|
+
// 阈值 10 次/60s 对单用户足够宽裕(见 docs/04-security.md §2)。
|
|
12
|
+
const rateLimitCfg = { maxFailures: 10, windowMs: 60_000, blockMs: 60_000, ...(overrides ?? {}) };
|
|
13
|
+
const rateBuckets = new Map(); // ip -> { count, windowStart, blockedUntil? }
|
|
14
|
+
// 封锁用显式的 blockedUntil 计时:到阈值那一刻起算 blockMs,与 windowMs 无关。
|
|
15
|
+
// 旧实现用 `now - windowStart < blockMs` 判定——blockMs < windowMs 时封锁提前结束,
|
|
16
|
+
// 而失败计数仍 ≥ 阈值,窗口剩余时间内每次猜口令都被放行(blockMs 形同虚设);
|
|
17
|
+
// blockMs > windowMs 时又被 windowStart 截短。封锁到期即整桶清零,下一个周期重新给 maxFailures 次额度。
|
|
18
|
+
const rateBlocked = (ip) => {
|
|
19
|
+
const b = rateBuckets.get(ip);
|
|
20
|
+
if (b === undefined || b.blockedUntil === undefined) return false;
|
|
21
|
+
if (Date.now() < b.blockedUntil) return true;
|
|
22
|
+
rateBuckets.delete(ip);
|
|
23
|
+
return false;
|
|
24
|
+
};
|
|
25
|
+
const rateFail = (ip) => {
|
|
26
|
+
const now = Date.now();
|
|
27
|
+
let b = rateBuckets.get(ip);
|
|
28
|
+
if (!b || now - b.windowStart >= rateLimitCfg.windowMs) {
|
|
29
|
+
b = { count: 0, windowStart: now };
|
|
30
|
+
rateBuckets.set(ip, b);
|
|
31
|
+
}
|
|
32
|
+
b.count++;
|
|
33
|
+
if (b.count >= rateLimitCfg.maxFailures) b.blockedUntil = now + rateLimitCfg.blockMs;
|
|
34
|
+
// 防内存膨胀:超过 512 个来源时清掉最旧的一半
|
|
35
|
+
if (rateBuckets.size > 512) {
|
|
36
|
+
const oldest = [...rateBuckets.entries()]
|
|
37
|
+
.sort((x, y) => x[1].windowStart - y[1].windowStart)
|
|
38
|
+
.slice(0, 256)
|
|
39
|
+
.map(([k]) => k);
|
|
40
|
+
for (const k of oldest) rateBuckets.delete(k);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const rateReset = (ip) => rateBuckets.delete(ip);
|
|
44
|
+
|
|
45
|
+
return { cfg: rateLimitCfg, blocked: rateBlocked, fail: rateFail, reset: rateReset };
|
|
46
|
+
}
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 电脑端的中继连接器:常驻**出站**连接到中继(电脑不开任何入站端口),把中继转来的手机会话落地。
|
|
3
|
+
*
|
|
4
|
+
* 每个中继地址一条 WebSocket(断了按指数退避 + 抖动重连):
|
|
5
|
+
* 1. 中继发来挑战 → 用 Ed25519 签名证明房间所有权 → 收到 `ready`;
|
|
6
|
+
* 2. 手机来了(`guest{c}`)→ 为它建一个 GuestSession:Noise 响应方握手(消息 1 → 消息 2);
|
|
7
|
+
* 3. 握手消息 1 里的静态公钥交给 DeviceStore 核对(已配对 / 带有效一次性配对码)→ 不认识就踢掉,**不回应**;
|
|
8
|
+
* 4. 通过后告诉中继 `verified`(解除未确认限额),之后的传输消息解密后交给 MuxSession → serve() 回放给本机 HTTP。
|
|
9
|
+
*
|
|
10
|
+
* 防重放:握手之后 15 秒内必须收到一条能解密的传输数据,否则踢掉——重放者拿不到会话密钥,发不出来。
|
|
11
|
+
*/
|
|
12
|
+
import { b64u, concat, ed25519Sign, hex } from "./crypto.js";
|
|
13
|
+
import { MuxError, MuxSession } from "./mux.js";
|
|
14
|
+
import { NoiseResponder } from "./noise.js";
|
|
15
|
+
|
|
16
|
+
const enc = new TextEncoder();
|
|
17
|
+
const dec = new TextDecoder();
|
|
18
|
+
const fromHex = (h) => Uint8Array.from(h.match(/../g) ?? [], (x) => parseInt(x, 16));
|
|
19
|
+
|
|
20
|
+
export const AUTH_CONTEXT = "dsh-relay-host-v1";
|
|
21
|
+
|
|
22
|
+
export class RelayConnector {
|
|
23
|
+
/**
|
|
24
|
+
* @param {{ identity:object, devices:object, urls:string[], serve:(stream:object, device:object)=>unknown,
|
|
25
|
+
* serverName?:string, WebSocketImpl?:Function, log?:(m:string)=>void, now?:()=>number,
|
|
26
|
+
* timing?:Partial<typeof RelayConnector.TIMING> }} o
|
|
27
|
+
*/
|
|
28
|
+
constructor({ identity, devices, urls, serve, serverName = "dsh-mobile-remote", WebSocketImpl = globalThis.WebSocket, log = () => {}, timing = {} }) {
|
|
29
|
+
if (typeof WebSocketImpl !== "function") throw new Error("需要全局 WebSocket(Node ≥ 22),或传入 WebSocketImpl");
|
|
30
|
+
this.identity = identity;
|
|
31
|
+
this.devices = devices;
|
|
32
|
+
this.serve = serve;
|
|
33
|
+
this.serverName = serverName;
|
|
34
|
+
this.WS = WebSocketImpl;
|
|
35
|
+
this.log = log;
|
|
36
|
+
this.timing = { ...RelayConnector.TIMING, ...timing };
|
|
37
|
+
this.links = urls.map((url) => new RelayLink(this, url.replace(/\/+$/, "")));
|
|
38
|
+
this.stopped = true;
|
|
39
|
+
this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
|
|
40
|
+
}
|
|
41
|
+
static TIMING = Object.freeze({ handshakeMs: 15_000, pingMs: 20_000, deadMs: 50_000, firstFrameMs: 15_000, backoffMinMs: 1_000, backoffMaxMs: 30_000, maxSessionsPerLink: 16 });
|
|
42
|
+
|
|
43
|
+
start() {
|
|
44
|
+
if (!this.stopped) return;
|
|
45
|
+
this.stopped = false;
|
|
46
|
+
// stop() 取消了订阅;重新 start() 必须再订阅,否则撤销设备不再踢掉它的在线会话
|
|
47
|
+
this.unsubscribe ??= this.devices.onRevoke((id) => this.dropDevice(id));
|
|
48
|
+
for (const l of this.links) l.connect();
|
|
49
|
+
}
|
|
50
|
+
stop() {
|
|
51
|
+
this.stopped = true;
|
|
52
|
+
this.unsubscribe?.();
|
|
53
|
+
this.unsubscribe = null;
|
|
54
|
+
for (const l of this.links) l.shutdown();
|
|
55
|
+
}
|
|
56
|
+
status() {
|
|
57
|
+
return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: l.sessions.size }));
|
|
58
|
+
}
|
|
59
|
+
/** 设备被撤销:立刻踢掉它所有在线的会话。 */
|
|
60
|
+
dropDevice(deviceId) {
|
|
61
|
+
for (const l of this.links) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
class RelayLink {
|
|
66
|
+
constructor(owner, url) {
|
|
67
|
+
this.o = owner;
|
|
68
|
+
this.url = url;
|
|
69
|
+
this.state = "idle";
|
|
70
|
+
this.since = Date.now();
|
|
71
|
+
this.lastError = "";
|
|
72
|
+
this.ws = null;
|
|
73
|
+
this.sessions = new Map();
|
|
74
|
+
this.attempt = 0;
|
|
75
|
+
this.timers = new Set();
|
|
76
|
+
this.lastHeard = 0;
|
|
77
|
+
}
|
|
78
|
+
#set(state) {
|
|
79
|
+
this.state = state;
|
|
80
|
+
this.since = Date.now();
|
|
81
|
+
}
|
|
82
|
+
after(ms, fn) {
|
|
83
|
+
const t = setTimeout(() => {
|
|
84
|
+
this.timers.delete(t);
|
|
85
|
+
fn();
|
|
86
|
+
}, ms);
|
|
87
|
+
t.unref?.();
|
|
88
|
+
this.timers.add(t);
|
|
89
|
+
return t;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
connect() {
|
|
93
|
+
if (this.o.stopped) return;
|
|
94
|
+
this.#set("connecting");
|
|
95
|
+
let ws;
|
|
96
|
+
try {
|
|
97
|
+
ws = new this.o.WS(`${this.url}/v1/host/${this.o.identity.roomId}`);
|
|
98
|
+
} catch (err) {
|
|
99
|
+
this.lastError = String(err?.message ?? err);
|
|
100
|
+
return this.#scheduleReconnect();
|
|
101
|
+
}
|
|
102
|
+
ws.binaryType = "arraybuffer";
|
|
103
|
+
this.ws = ws;
|
|
104
|
+
this.lastHeard = Date.now();
|
|
105
|
+
ws.addEventListener("message", (e) => this.#onMessage(ws, e.data));
|
|
106
|
+
ws.addEventListener("close", (e) => this.#onClose(ws, e));
|
|
107
|
+
ws.addEventListener("error", () => {
|
|
108
|
+
if (ws === this.ws) this.lastError = "connection error";
|
|
109
|
+
});
|
|
110
|
+
// HTTP 升级成功不代表房间认证完成;ready 前也必须有截止时间。
|
|
111
|
+
this.handshakeTimer = this.after(this.o.timing.handshakeMs, () => {
|
|
112
|
+
if (ws !== this.ws || this.state !== "connecting") return;
|
|
113
|
+
this.lastError = "relay handshake timeout";
|
|
114
|
+
ws.close();
|
|
115
|
+
// 不等对端确认关闭:失联的中继可能连 close 也不回。
|
|
116
|
+
this.#onClose(ws, {});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
#onMessage(ws, data) {
|
|
121
|
+
if (ws !== this.ws) return;
|
|
122
|
+
this.lastHeard = Date.now();
|
|
123
|
+
try {
|
|
124
|
+
if (typeof data === "string") return this.#onControl(JSON.parse(data));
|
|
125
|
+
const bytes = new Uint8Array(data);
|
|
126
|
+
if (bytes.length < 9) return;
|
|
127
|
+
this.sessions.get(hex(bytes.subarray(0, 8)))?.onFrame(bytes.subarray(8));
|
|
128
|
+
} catch (err) {
|
|
129
|
+
this.o.log(`relay: 处理消息出错(${this.url}):${err?.message ?? err}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
#onControl(msg) {
|
|
133
|
+
switch (msg.t) {
|
|
134
|
+
case "challenge": {
|
|
135
|
+
const { identity } = this.o;
|
|
136
|
+
const sig = ed25519Sign(identity.ed.priv, enc.encode(`${AUTH_CONTEXT}|${identity.roomId}|${msg.nonce}`));
|
|
137
|
+
return this.send(JSON.stringify({ t: "auth", pub: b64u.enc(identity.ed.pub), sig: b64u.enc(sig) }));
|
|
138
|
+
}
|
|
139
|
+
case "ready":
|
|
140
|
+
if (this.state !== "connecting") return;
|
|
141
|
+
clearTimeout(this.handshakeTimer);
|
|
142
|
+
this.timers.delete(this.handshakeTimer);
|
|
143
|
+
this.#set("online");
|
|
144
|
+
this.attempt = 0;
|
|
145
|
+
this.lastError = "";
|
|
146
|
+
this.#startPing();
|
|
147
|
+
return this.o.log(`relay: 已连上 ${this.url}`);
|
|
148
|
+
case "guest":
|
|
149
|
+
if (typeof msg.c !== "string" || !/^[0-9a-f]{16}$/.test(msg.c)) return;
|
|
150
|
+
if (this.sessions.size >= this.o.timing.maxSessionsPerLink) return this.control({ t: "kick", c: msg.c });
|
|
151
|
+
this.sessions.set(msg.c, new GuestSession(this, msg.c));
|
|
152
|
+
return;
|
|
153
|
+
case "guest-close":
|
|
154
|
+
return void this.sessions.get(msg.c)?.dispose();
|
|
155
|
+
case "pong":
|
|
156
|
+
case "error":
|
|
157
|
+
return;
|
|
158
|
+
default:
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
#startPing() {
|
|
162
|
+
const { pingMs, deadMs } = this.o.timing;
|
|
163
|
+
const tick = () => {
|
|
164
|
+
if (this.o.stopped || this.state !== "online") return;
|
|
165
|
+
if (Date.now() - this.lastHeard > deadMs) {
|
|
166
|
+
this.lastError = "relay went silent";
|
|
167
|
+
return void this.ws?.close();
|
|
168
|
+
}
|
|
169
|
+
this.send(JSON.stringify({ t: "ping" }));
|
|
170
|
+
this.after(pingMs, tick);
|
|
171
|
+
};
|
|
172
|
+
this.after(pingMs, tick);
|
|
173
|
+
}
|
|
174
|
+
#onClose(ws, event) {
|
|
175
|
+
if (ws !== this.ws) return;
|
|
176
|
+
this.ws = null;
|
|
177
|
+
for (const t of this.timers) clearTimeout(t);
|
|
178
|
+
this.timers.clear();
|
|
179
|
+
for (const s of [...this.sessions.values()]) s.dispose();
|
|
180
|
+
const code = event?.code ?? 0;
|
|
181
|
+
if (code === 4401) this.lastError = "relay rejected our identity (4401)";
|
|
182
|
+
else if (code && code !== 1000 && code !== 1005 && !this.lastError) this.lastError = `closed (${code})`;
|
|
183
|
+
this.#set("offline");
|
|
184
|
+
this.#scheduleReconnect();
|
|
185
|
+
}
|
|
186
|
+
#scheduleReconnect() {
|
|
187
|
+
if (this.o.stopped) return;
|
|
188
|
+
const { backoffMinMs, backoffMaxMs } = this.o.timing;
|
|
189
|
+
const base = Math.min(backoffMaxMs, backoffMinMs * 2 ** Math.min(this.attempt, 10));
|
|
190
|
+
this.attempt++;
|
|
191
|
+
this.after(base / 2 + Math.random() * (base / 2), () => this.connect()); // 抖动:避免大家同时重连
|
|
192
|
+
}
|
|
193
|
+
shutdown() {
|
|
194
|
+
for (const t of this.timers) clearTimeout(t);
|
|
195
|
+
this.timers.clear();
|
|
196
|
+
for (const s of [...this.sessions.values()]) s.dispose();
|
|
197
|
+
const ws = this.ws;
|
|
198
|
+
this.ws = null;
|
|
199
|
+
try {
|
|
200
|
+
ws?.close(1000, "shutdown");
|
|
201
|
+
} catch {
|
|
202
|
+
/* 已断开 */
|
|
203
|
+
}
|
|
204
|
+
this.#set("idle");
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
send(data) {
|
|
208
|
+
try {
|
|
209
|
+
if (this.ws && this.ws.readyState === 1) {
|
|
210
|
+
this.ws.send(data);
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
} catch {
|
|
214
|
+
/* 连接正在断开 */
|
|
215
|
+
}
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
control(obj) {
|
|
219
|
+
return this.send(JSON.stringify(obj));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 一台手机在一条中继连接上的会话。 */
|
|
224
|
+
class GuestSession {
|
|
225
|
+
constructor(link, connId) {
|
|
226
|
+
this.link = link;
|
|
227
|
+
this.connId = connId;
|
|
228
|
+
this.idBytes = fromHex(connId);
|
|
229
|
+
this.state = "handshake";
|
|
230
|
+
this.noise = new NoiseResponder({ s: link.o.identity.x, prologue: enc.encode(`DSH-RELAY/1|${link.o.identity.roomId}`) });
|
|
231
|
+
this.device = null;
|
|
232
|
+
this.mux = null;
|
|
233
|
+
this.cipherOut = null;
|
|
234
|
+
this.cipherIn = null;
|
|
235
|
+
this.timer = link.after(link.o.timing.firstFrameMs, () => {
|
|
236
|
+
if (this.state !== "open") this.kick("handshake timeout");
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
onFrame(bytes) {
|
|
241
|
+
try {
|
|
242
|
+
if (this.state === "handshake") return this.#handshake(bytes);
|
|
243
|
+
if (this.state === "closed") return;
|
|
244
|
+
const plain = this.cipherIn.decrypt(bytes); // 认证失败抛错
|
|
245
|
+
if (this.state === "await-first") {
|
|
246
|
+
this.state = "open";
|
|
247
|
+
clearTimeout(this.timer);
|
|
248
|
+
}
|
|
249
|
+
this.mux.receive(plain);
|
|
250
|
+
} catch (err) {
|
|
251
|
+
this.kick(err instanceof MuxError ? `protocol: ${err.message}` : "bad frame");
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#handshake(bytes) {
|
|
256
|
+
const { devices, serverName } = this.link.o;
|
|
257
|
+
const { payload, rs } = this.noise.readMessage1(bytes);
|
|
258
|
+
let info = {};
|
|
259
|
+
try {
|
|
260
|
+
info = JSON.parse(dec.decode(payload));
|
|
261
|
+
} catch {
|
|
262
|
+
return this.kick("bad handshake payload");
|
|
263
|
+
}
|
|
264
|
+
if (info?.v !== 1) return this.kick("unsupported version");
|
|
265
|
+
const result = devices.authorize(rs, info);
|
|
266
|
+
if (!result) return this.kick("unauthorized device"); // 不回应:别给陌生人任何东西
|
|
267
|
+
this.device = result.device;
|
|
268
|
+
const reply = this.noise.writeMessage2(enc.encode(JSON.stringify({ v: 1, ok: true, server: serverName, device: { id: result.device.id, name: result.device.name }, newlyPaired: result.newlyPaired })));
|
|
269
|
+
this.cipherOut = reply.send;
|
|
270
|
+
this.cipherIn = reply.recv;
|
|
271
|
+
this.mux = new MuxSession({
|
|
272
|
+
role: "server",
|
|
273
|
+
send: (frame) => this.#sendPlain(frame),
|
|
274
|
+
onRequest: (stream) => this.link.o.serve(stream, this.device),
|
|
275
|
+
});
|
|
276
|
+
this.link.send(concat(this.idBytes, reply.msg));
|
|
277
|
+
this.link.control({ t: "verified", c: this.connId });
|
|
278
|
+
this.state = "await-first";
|
|
279
|
+
this.link.o.log(`relay: 设备「${this.device.name}」${result.newlyPaired ? "完成配对" : "已连接"}`);
|
|
280
|
+
}
|
|
281
|
+
#sendPlain(frame) {
|
|
282
|
+
if (this.state === "closed") return;
|
|
283
|
+
this.link.send(concat(this.idBytes, this.cipherOut.encrypt(frame)));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** 拒绝并断开这个访客(同时让中继关掉它)。 */
|
|
287
|
+
kick(reason = "kicked") {
|
|
288
|
+
if (this.state === "closed") return;
|
|
289
|
+
this.link.o.log(`relay: 断开访客 ${this.connId.slice(0, 6)}…(${reason})`);
|
|
290
|
+
this.link.control({ t: "kick", c: this.connId });
|
|
291
|
+
this.dispose();
|
|
292
|
+
}
|
|
293
|
+
dispose() {
|
|
294
|
+
if (this.state === "closed") return;
|
|
295
|
+
this.state = "closed";
|
|
296
|
+
clearTimeout(this.timer);
|
|
297
|
+
this.mux?.close("session closed");
|
|
298
|
+
this.link.sessions.delete(this.connId);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 中继用到的密码学原语,**只用 Node 内置的 crypto**(零依赖,插件包保持小)。
|
|
3
|
+
* 这里不实现任何原语,只是把 Node 的 KeyObject 接口包成「裸 32 字节」的形态,供 Noise 与配对使用。
|
|
4
|
+
*
|
|
5
|
+
* 原语:X25519(DH)、Ed25519(中继侧证明房间所有权)、ChaCha20-Poly1305(AEAD)、SHA-256 / HMAC-SHA256。
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey,
|
|
9
|
+
diffieHellman, generateKeyPairSync, randomBytes, sign as edSign, verify as edVerify, timingSafeEqual,
|
|
10
|
+
} from "node:crypto";
|
|
11
|
+
|
|
12
|
+
export const EMPTY = new Uint8Array(0);
|
|
13
|
+
|
|
14
|
+
const X25519_SPKI = Buffer.from("302a300506032b656e032100", "hex");
|
|
15
|
+
const X25519_PKCS8 = Buffer.from("302e020100300506032b656e04220420", "hex");
|
|
16
|
+
const ED25519_SPKI = Buffer.from("302a300506032b6570032100", "hex");
|
|
17
|
+
const ED25519_PKCS8 = Buffer.from("302e020100300506032b657004220420", "hex");
|
|
18
|
+
|
|
19
|
+
const u8 = (b) => new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
|
|
20
|
+
|
|
21
|
+
export const b64u = {
|
|
22
|
+
enc: (bytes) => Buffer.from(bytes).toString("base64url"),
|
|
23
|
+
dec: (s) => {
|
|
24
|
+
if (typeof s !== "string" || !/^[A-Za-z0-9_-]*$/.test(s)) throw new Error("bad base64url");
|
|
25
|
+
return new Uint8Array(Buffer.from(s, "base64url"));
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
export const hex = (bytes) => Buffer.from(bytes).toString("hex");
|
|
29
|
+
export const concat = (...parts) => u8(Buffer.concat(parts.map((p) => Buffer.from(p))));
|
|
30
|
+
export const randomBytesU8 = (n) => u8(randomBytes(n));
|
|
31
|
+
|
|
32
|
+
/** 常量时间比较(长度不同直接 false)。 */
|
|
33
|
+
export const equalBytes = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
34
|
+
|
|
35
|
+
// ── X25519 ──────────────────────────────────────────────────────────────────
|
|
36
|
+
const x25519Priv = (raw) => {
|
|
37
|
+
if (raw.length !== 32) throw new Error("x25519 private key must be 32 bytes");
|
|
38
|
+
return createPrivateKey({ key: Buffer.concat([X25519_PKCS8, Buffer.from(raw)]), format: "der", type: "pkcs8" });
|
|
39
|
+
};
|
|
40
|
+
const x25519Pub = (raw) => {
|
|
41
|
+
if (raw.length !== 32) throw new Error("x25519 public key must be 32 bytes");
|
|
42
|
+
return createPublicKey({ key: Buffer.concat([X25519_SPKI, Buffer.from(raw)]), format: "der", type: "spki" });
|
|
43
|
+
};
|
|
44
|
+
/** 由私钥算公钥。 */
|
|
45
|
+
export const x25519PublicOf = (priv) => b64uToU8(createPublicKey(x25519Priv(priv)).export({ format: "jwk" }).x);
|
|
46
|
+
const b64uToU8 = (s) => new Uint8Array(Buffer.from(s, "base64url"));
|
|
47
|
+
|
|
48
|
+
export function x25519Generate() {
|
|
49
|
+
const { privateKey } = generateKeyPairSync("x25519");
|
|
50
|
+
const jwk = privateKey.export({ format: "jwk" });
|
|
51
|
+
return { priv: b64uToU8(jwk.d), pub: b64uToU8(jwk.x) };
|
|
52
|
+
}
|
|
53
|
+
/** 32 字节共享密钥;对端是低阶点时 OpenSSL 会抛错,调用方当握手失败处理。 */
|
|
54
|
+
export function x25519Dh(priv, pub) {
|
|
55
|
+
return u8(diffieHellman({ privateKey: x25519Priv(priv), publicKey: x25519Pub(pub) }));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ── Ed25519(只用于中继侧证明「这个房间是我的」)──────────────────────────────────
|
|
59
|
+
export function ed25519Generate() {
|
|
60
|
+
const { privateKey } = generateKeyPairSync("ed25519");
|
|
61
|
+
const jwk = privateKey.export({ format: "jwk" });
|
|
62
|
+
return { priv: b64uToU8(jwk.d), pub: b64uToU8(jwk.x) };
|
|
63
|
+
}
|
|
64
|
+
export function ed25519Sign(priv, message) {
|
|
65
|
+
return u8(edSign(null, Buffer.from(message), createPrivateKey({ key: Buffer.concat([ED25519_PKCS8, Buffer.from(priv)]), format: "der", type: "pkcs8" })));
|
|
66
|
+
}
|
|
67
|
+
export function ed25519Verify(pub, message, signature) {
|
|
68
|
+
try {
|
|
69
|
+
if (pub.length !== 32 || signature.length !== 64) return false;
|
|
70
|
+
const key = createPublicKey({ key: Buffer.concat([ED25519_SPKI, Buffer.from(pub)]), format: "der", type: "spki" });
|
|
71
|
+
return edVerify(null, Buffer.from(message), key, Buffer.from(signature));
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ── 哈希 / HMAC / HKDF(Noise 规范 §4.3 的 HKDF,基于 HMAC)──────────────────────
|
|
78
|
+
export const sha256 = (...parts) => {
|
|
79
|
+
const h = createHash("sha256");
|
|
80
|
+
for (const p of parts) h.update(p);
|
|
81
|
+
return u8(h.digest());
|
|
82
|
+
};
|
|
83
|
+
const hmac = (key, ...parts) => {
|
|
84
|
+
const h = createHmac("sha256", key);
|
|
85
|
+
for (const p of parts) h.update(p);
|
|
86
|
+
return u8(h.digest());
|
|
87
|
+
};
|
|
88
|
+
/** Noise HKDF:返回 n(2 或 3)个 32 字节输出。 */
|
|
89
|
+
export function hkdf(chainingKey, inputKeyMaterial, n) {
|
|
90
|
+
const tempKey = hmac(chainingKey, inputKeyMaterial);
|
|
91
|
+
const out1 = hmac(tempKey, Uint8Array.of(1));
|
|
92
|
+
const out2 = hmac(tempKey, out1, Uint8Array.of(2));
|
|
93
|
+
if (n === 2) return [out1, out2];
|
|
94
|
+
return [out1, out2, hmac(tempKey, out2, Uint8Array.of(3))];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ── ChaCha20-Poly1305(Noise 的 nonce:4 字节 0 + 8 字节小端计数)──────────────────
|
|
98
|
+
const nonceFor = (counter) => {
|
|
99
|
+
const n = Buffer.alloc(12);
|
|
100
|
+
n.writeBigUInt64LE(BigInt(counter), 4);
|
|
101
|
+
return n;
|
|
102
|
+
};
|
|
103
|
+
export function aeadEncrypt(key, counter, ad, plaintext) {
|
|
104
|
+
const c = createCipheriv("chacha20-poly1305", Buffer.from(key), nonceFor(counter), { authTagLength: 16 });
|
|
105
|
+
c.setAAD(Buffer.from(ad), { plaintextLength: plaintext.length });
|
|
106
|
+
return concat(c.update(Buffer.from(plaintext)), c.final(), c.getAuthTag());
|
|
107
|
+
}
|
|
108
|
+
/** 认证失败抛错(不泄漏原因)。 */
|
|
109
|
+
export function aeadDecrypt(key, counter, ad, ciphertext) {
|
|
110
|
+
if (ciphertext.length < 16) throw new Error("ciphertext too short");
|
|
111
|
+
const body = ciphertext.subarray(0, ciphertext.length - 16);
|
|
112
|
+
const tag = ciphertext.subarray(ciphertext.length - 16);
|
|
113
|
+
const d = createDecipheriv("chacha20-poly1305", Buffer.from(key), nonceFor(counter), { authTagLength: 16 });
|
|
114
|
+
d.setAAD(Buffer.from(ad), { plaintextLength: body.length });
|
|
115
|
+
d.setAuthTag(Buffer.from(tag));
|
|
116
|
+
return concat(d.update(Buffer.from(body)), d.final());
|
|
117
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 已配对设备 + 一次性配对码。
|
|
3
|
+
*
|
|
4
|
+
* 取代「一个共享口令授权所有手机」:每台手机一把自己的 X25519 静态密钥,电脑只放行名单里的密钥,
|
|
5
|
+
* 丢了手机在桌面上「撤销」即可,其它手机不受影响。口令不再经过网络。
|
|
6
|
+
*
|
|
7
|
+
* 配对:桌面生成一次性配对码(5 分钟内有效、只能用一次、最多同时 5 个),放进二维码。手机第一次握手时
|
|
8
|
+
* 在加密负载里带上它;电脑核对通过就把这台手机的公钥登记进名单。以后重连只认公钥。
|
|
9
|
+
*/
|
|
10
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { b64u, equalBytes, hex, randomBytesU8, sha256 } from "./crypto.js";
|
|
13
|
+
|
|
14
|
+
export const OTP_TTL_MS = 5 * 60_000;
|
|
15
|
+
export const MAX_PENDING_OTPS = 5;
|
|
16
|
+
export const MAX_DEVICES = 16;
|
|
17
|
+
const NAME_MAX = 40;
|
|
18
|
+
|
|
19
|
+
const cleanName = (s) => {
|
|
20
|
+
const name = String(s ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, NAME_MAX);
|
|
21
|
+
return name === "" ? "Phone" : name;
|
|
22
|
+
};
|
|
23
|
+
const fingerprint = (pub) => hex(sha256(pub)).slice(0, 16);
|
|
24
|
+
|
|
25
|
+
export class DeviceStore {
|
|
26
|
+
constructor({ dir, now = Date.now, otpTtlMs = OTP_TTL_MS, maxDevices = MAX_DEVICES } = {}) {
|
|
27
|
+
this.file = join(dir, "devices.json");
|
|
28
|
+
this.dir = dir;
|
|
29
|
+
this.now = now;
|
|
30
|
+
this.otpTtlMs = otpTtlMs;
|
|
31
|
+
this.maxDevices = maxDevices;
|
|
32
|
+
this.devices = [];
|
|
33
|
+
this.otps = new Map(); // sha256(otp) hex -> { expiresAt, name }
|
|
34
|
+
this.revokeListeners = new Set();
|
|
35
|
+
this.lastPersist = 0;
|
|
36
|
+
this.#load();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
#load() {
|
|
40
|
+
if (!existsSync(this.file)) return;
|
|
41
|
+
try {
|
|
42
|
+
const raw = JSON.parse(readFileSync(this.file, "utf8"));
|
|
43
|
+
if (raw?.v !== 1 || !Array.isArray(raw.devices)) return;
|
|
44
|
+
this.devices = raw.devices
|
|
45
|
+
.map((d) => ({ id: String(d.id), name: cleanName(d.name), pub: b64u.dec(d.pub), createdAt: Number(d.createdAt) || 0, lastSeen: Number(d.lastSeen) || 0 }))
|
|
46
|
+
.filter((d) => d.pub.length === 32 && d.id === fingerprint(d.pub));
|
|
47
|
+
} catch {
|
|
48
|
+
/* 损坏的名单 = 没有已配对设备(宁可让人重新配对,也不放行不认识的东西) */
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
#persist() {
|
|
52
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
53
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
54
|
+
const body = { v: 1, devices: this.devices.map((d) => ({ id: d.id, name: d.name, pub: b64u.enc(d.pub), createdAt: d.createdAt, lastSeen: d.lastSeen })) };
|
|
55
|
+
writeFileSync(tmp, `${JSON.stringify(body)}\n`, { mode: 0o600 });
|
|
56
|
+
renameSync(tmp, this.file);
|
|
57
|
+
try {
|
|
58
|
+
chmodSync(this.file, 0o600);
|
|
59
|
+
} catch {
|
|
60
|
+
/* Windows */
|
|
61
|
+
}
|
|
62
|
+
this.lastPersist = this.now();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 给 UI 看的列表:不含公钥全文,只有稳定的 id(公钥指纹)。 */
|
|
66
|
+
list() {
|
|
67
|
+
return this.devices.map(({ id, name, createdAt, lastSeen }) => ({ id, name, createdAt, lastSeen }));
|
|
68
|
+
}
|
|
69
|
+
find(pub) {
|
|
70
|
+
return this.devices.find((d) => equalBytes(d.pub, pub)) ?? null;
|
|
71
|
+
}
|
|
72
|
+
touch(device) {
|
|
73
|
+
device.lastSeen = this.now();
|
|
74
|
+
if (this.now() - this.lastPersist > 60_000) this.#persist();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 撤销设备;返回是否真的删掉了。监听者(连接器)据此踢掉它正在用的连接。 */
|
|
78
|
+
revoke(id) {
|
|
79
|
+
const i = this.devices.findIndex((d) => d.id === id);
|
|
80
|
+
if (i < 0) return false;
|
|
81
|
+
const [gone] = this.devices.splice(i, 1);
|
|
82
|
+
this.#persist();
|
|
83
|
+
for (const fn of this.revokeListeners) fn(gone.id);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
onRevoke(fn) {
|
|
87
|
+
this.revokeListeners.add(fn);
|
|
88
|
+
return () => this.revokeListeners.delete(fn);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 生成一次性配对码。返回明文码(只此一次)与过期时间。 */
|
|
92
|
+
createPairing(name) {
|
|
93
|
+
this.#sweep();
|
|
94
|
+
while (this.otps.size >= MAX_PENDING_OTPS) this.otps.delete(this.otps.keys().next().value); // 最旧的让位
|
|
95
|
+
const otp = b64u.enc(randomBytesU8(16));
|
|
96
|
+
const expiresAt = this.now() + this.otpTtlMs;
|
|
97
|
+
this.otps.set(hex(sha256(otp)), { expiresAt, name: name ? cleanName(name) : undefined });
|
|
98
|
+
return { otp, expiresAt };
|
|
99
|
+
}
|
|
100
|
+
#sweep() {
|
|
101
|
+
const t = this.now();
|
|
102
|
+
for (const [k, v] of this.otps) if (v.expiresAt <= t) this.otps.delete(k);
|
|
103
|
+
}
|
|
104
|
+
pendingPairings() {
|
|
105
|
+
this.#sweep();
|
|
106
|
+
return this.otps.size;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 握手成功之后、放行之前的最后一道关:这把公钥是不是我们认的?
|
|
111
|
+
* @returns {{ device, newlyPaired:boolean } | null} null = 拒绝(不要回应、直接踢掉)
|
|
112
|
+
*/
|
|
113
|
+
authorize(pub, info = {}) {
|
|
114
|
+
const known = this.find(pub);
|
|
115
|
+
if (known) {
|
|
116
|
+
this.touch(known);
|
|
117
|
+
return { device: known, newlyPaired: false };
|
|
118
|
+
}
|
|
119
|
+
const otp = typeof info.otp === "string" ? info.otp : "";
|
|
120
|
+
if (otp === "" || otp.length > 64) return null;
|
|
121
|
+
this.#sweep();
|
|
122
|
+
const key = hex(sha256(otp));
|
|
123
|
+
const entry = this.otps.get(key);
|
|
124
|
+
if (!entry) return null;
|
|
125
|
+
this.otps.delete(key); // 一次性:无论后面成不成功,这个码都作废
|
|
126
|
+
if (this.devices.length >= this.maxDevices) return null;
|
|
127
|
+
const device = {
|
|
128
|
+
id: fingerprint(pub),
|
|
129
|
+
name: cleanName(info.name ?? entry.name),
|
|
130
|
+
pub: pub.slice(),
|
|
131
|
+
createdAt: this.now(),
|
|
132
|
+
lastSeen: this.now(),
|
|
133
|
+
};
|
|
134
|
+
this.devices.push(device);
|
|
135
|
+
this.#persist();
|
|
136
|
+
return { device, newlyPaired: true };
|
|
137
|
+
}
|
|
138
|
+
}
|