pi-hub-server 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +516 -2
- package/bin/pi-hub.mjs +473 -0
- package/docs/AUTH.md +260 -0
- package/package.json +45 -4
- package/src/config.mjs +60 -0
- package/src/listen.mjs +207 -0
- package/src/net-allow.mjs +134 -0
- package/src/otp.mjs +162 -0
- package/src/pairing.mjs +653 -0
- package/src/pi-args.mjs +74 -0
- package/src/pi-session.mjs +638 -0
- package/src/proxy-auth.mjs +238 -0
- package/src/registry.mjs +145 -0
- package/src/rpc-once.mjs +83 -0
- package/src/server.mjs +1603 -0
- package/src/session-lock.mjs +42 -0
- package/src/sessions-index.mjs +179 -0
- package/src/static.mjs +148 -0
- package/src/totp.mjs +151 -0
- package/src/update-check.mjs +218 -0
- package/src/web-auth.mjs +450 -0
- package/systemd/pi-hub.service +40 -0
- package/web/app.js +1699 -0
- package/web/icons/icon.svg +7 -0
- package/web/index.html +131 -0
- package/web/manifest.webmanifest +20 -0
- package/web/style.css +982 -0
- package/web/sw.js +41 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// 入站来源网段白名单(只做「谁能连到这个 hub」这一件事,与鉴权正交)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要:hub 经常以 `PI_HUB_HOST=0.0.0.0` 起在笔记本上,而笔记本会同时挂在
|
|
4
|
+
// 校园网/宿舍网/咖啡厅 Wi-Fi 上。pi 以当前用户全权限执行模型生成的命令,明文 HTTP
|
|
5
|
+
// 一旦被同网段的人拿到就等 RCE;而 Tailscale/私有网/USB 网络共享这些正常路径全部
|
|
6
|
+
// 落在私有地址段里。所以默认只放行「不可能直接路由到公网」的来源:
|
|
7
|
+
// 本机回环 + RFC1918 + CGNAT(Tailscale 100.64/10)+ 链路本地
|
|
8
|
+
// 真要放开(例如放在已配好的反代后面、或自己的公网测试机)就设 `PI_HUB_ALLOW_CIDRS=*`。
|
|
9
|
+
import net from "node:net";
|
|
10
|
+
|
|
11
|
+
/** 默认放行集合:回环 + RFC1918 + CGNAT + 链路本地(IPv4/IPv6 各一套)。 */
|
|
12
|
+
export const DEFAULT_ALLOW_CIDRS = Object.freeze([
|
|
13
|
+
"127.0.0.0/8",
|
|
14
|
+
"::1/128",
|
|
15
|
+
"10.0.0.0/8",
|
|
16
|
+
"172.16.0.0/12",
|
|
17
|
+
"192.168.0.0/16",
|
|
18
|
+
"169.254.0.0/16",
|
|
19
|
+
"100.64.0.0/10",
|
|
20
|
+
"fc00::/7",
|
|
21
|
+
"fe80::/10",
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 解析 `PI_HUB_ALLOW_CIDRS`:逗号分隔,裸 IP 当 /32(v4)或 /128(v6)。
|
|
26
|
+
* `*` 表示不限制(返回 `null`);解析不了的条目抛错(宁可起不来,也不要静默变成"全放行")。
|
|
27
|
+
*/
|
|
28
|
+
export function parseAllowCidrs(raw) {
|
|
29
|
+
if (raw === undefined || raw === null) return DEFAULT_ALLOW_CIDRS.map((c) => parseCidr(c));
|
|
30
|
+
const text = String(raw).trim();
|
|
31
|
+
if (text === "*") return null;
|
|
32
|
+
if (!text) return [];
|
|
33
|
+
return text
|
|
34
|
+
.split(",")
|
|
35
|
+
.map((s) => s.trim())
|
|
36
|
+
.filter(Boolean)
|
|
37
|
+
.map((s) => {
|
|
38
|
+
try {
|
|
39
|
+
return parseCidr(s);
|
|
40
|
+
} catch (err) {
|
|
41
|
+
throw new Error(`PI_HUB_ALLOW_CIDRS 里的 "${s}" 不是合法网段:${err.message}`);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 单条 CIDR → `{bits, network(BigInt), family}`。 */
|
|
47
|
+
export function parseCidr(token) {
|
|
48
|
+
const [addr, prefixRaw] = String(token).split("/");
|
|
49
|
+
const family = net.isIP(addr);
|
|
50
|
+
if (family === 0) throw new Error(`不是 IP:${addr}`);
|
|
51
|
+
const width = family === 4 ? 32 : 128;
|
|
52
|
+
const prefix = prefixRaw === undefined ? width : Number(prefixRaw);
|
|
53
|
+
if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) {
|
|
54
|
+
throw new Error(`掩码位数不合法:${prefixRaw}`);
|
|
55
|
+
}
|
|
56
|
+
const value = family === 4 ? ipv4ToBigInt(addr) : ipv6ToBigInt(addr);
|
|
57
|
+
const shift = BigInt(width - prefix);
|
|
58
|
+
const network = shift === 0n ? value : (value >> shift) << shift;
|
|
59
|
+
return { family, prefix, network, width };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function ipv4ToBigInt(addr) {
|
|
63
|
+
const parts = addr.split(".").map(Number);
|
|
64
|
+
let out = 0n;
|
|
65
|
+
for (const p of parts) out = (out << 8n) | BigInt(p);
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** IPv6 → BigInt(支持 `::` 压缩与末尾内嵌 IPv4)。 */
|
|
70
|
+
function ipv6ToBigInt(addr) {
|
|
71
|
+
let text = addr.toLowerCase();
|
|
72
|
+
// 末尾内嵌 IPv4:`::ffff:127.0.0.1` 之类
|
|
73
|
+
if (text.includes(".")) {
|
|
74
|
+
const lastColon = text.lastIndexOf(":");
|
|
75
|
+
const v4 = text.slice(lastColon + 1);
|
|
76
|
+
const hex = ipv4ToBigInt(v4).toString(16).padStart(8, "0");
|
|
77
|
+
text = `${text.slice(0, lastColon + 1)}${hex.slice(0, 4)}:${hex.slice(4)}`;
|
|
78
|
+
}
|
|
79
|
+
const [head, tail] = text.split("::");
|
|
80
|
+
const headParts = head ? head.split(":") : [];
|
|
81
|
+
const tailParts = tail === undefined ? [] : tail ? tail.split(":") : [];
|
|
82
|
+
const missing = 8 - headParts.length - tailParts.length;
|
|
83
|
+
if (tail === undefined ? headParts.length !== 8 : missing < 0) throw new Error(`IPv6 形态不合法:${addr}`);
|
|
84
|
+
const groups = [...headParts, ...Array(tail === undefined ? 0 : missing).fill("0"), ...tailParts];
|
|
85
|
+
let out = 0n;
|
|
86
|
+
for (const g of groups) {
|
|
87
|
+
if (!/^[0-9a-f]{1,4}$/.test(g)) throw new Error(`IPv6 段不合法:${g}`);
|
|
88
|
+
out = (out << 16n) | BigInt(parseInt(g, 16));
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 归一化 socket 里拿到的远端地址:去掉 zone、把 IPv4-mapped IPv6 折叠回 IPv4。
|
|
95
|
+
* 返回 `{family, value(BigInt)}`,无法解析返回 null。
|
|
96
|
+
*/
|
|
97
|
+
export function normalizePeer(raw) {
|
|
98
|
+
if (!raw) return null;
|
|
99
|
+
let addr = String(raw).trim();
|
|
100
|
+
const zoneAt = addr.indexOf("%");
|
|
101
|
+
if (zoneAt >= 0) addr = addr.slice(0, zoneAt);
|
|
102
|
+
if (addr.toLowerCase().startsWith("::ffff:")) {
|
|
103
|
+
const v4 = addr.slice(7);
|
|
104
|
+
if (net.isIP(v4) === 4) return { family: 4, value: ipv4ToBigInt(v4) };
|
|
105
|
+
}
|
|
106
|
+
const family = net.isIP(addr);
|
|
107
|
+
if (family === 0) return null;
|
|
108
|
+
try {
|
|
109
|
+
return family === 4
|
|
110
|
+
? { family: 4, value: ipv4ToBigInt(addr) }
|
|
111
|
+
: { family: 6, value: ipv6ToBigInt(addr) };
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 该来源地址是否在白名单里(`cidrs === null` 表示不限制)。解析不了的地址一律拒绝。 */
|
|
118
|
+
export function isPeerAllowed(rawAddr, cidrs) {
|
|
119
|
+
if (cidrs === null) return true;
|
|
120
|
+
const peer = normalizePeer(rawAddr);
|
|
121
|
+
if (!peer) return false;
|
|
122
|
+
for (const c of cidrs) {
|
|
123
|
+
if (c.family !== peer.family) continue;
|
|
124
|
+
const shift = BigInt(c.width - c.prefix);
|
|
125
|
+
const masked = shift === 0n ? peer.value : (peer.value >> shift) << shift;
|
|
126
|
+
if (masked === c.network) return true;
|
|
127
|
+
}
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** env → 放行集合(`null` = 不限制)。非法配置直接抛错,由调用方决定是否致命。 */
|
|
132
|
+
export function allowCidrsFromEnv(env = process.env) {
|
|
133
|
+
return parseAllowCidrs(env.PI_HUB_ALLOW_CIDRS);
|
|
134
|
+
}
|
package/src/otp.mjs
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// 一次性登录码(PLAN M4):主机 TTY 生成、2 min TTL、单次消费、可选 meta(如 UA hash)绑定。
|
|
2
|
+
// 纯模块:零依赖、不碰 HTTP;只用 node: 内置模块。接线见 W1(src/server.mjs 的 /v1/web/otp)。
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
/** Crockford base32:去掉 I/L/O/U,避免 0/O、1/I/L 认错。 */
|
|
6
|
+
export const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
7
|
+
export const OTP_CODE_LENGTH = 8;
|
|
8
|
+
/** 展示为 XXXX-XXXX。 */
|
|
9
|
+
export const OTP_CODE_GROUP = 4;
|
|
10
|
+
export const OTP_TTL_MS = 2 * 60 * 1000;
|
|
11
|
+
export const OTP_MAX_FAILURES = 5;
|
|
12
|
+
export const OTP_MAX_ENTRIES = 64;
|
|
13
|
+
|
|
14
|
+
const ALPHABET_SET = new Set(CROCKFORD_ALPHABET);
|
|
15
|
+
|
|
16
|
+
function sha256hex(data) {
|
|
17
|
+
return createHash("sha256").update(data).digest("hex");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 用户输入 → 内部码:去掉 `-` 与空白、转大写。
|
|
22
|
+
* 不做 0/O、1/I/L 的模糊映射:字符集外的输入直接当未知码处理,避免把错码猜成对码。
|
|
23
|
+
*/
|
|
24
|
+
export function normalizeOtpCode(input) {
|
|
25
|
+
if (typeof input !== "string") return "";
|
|
26
|
+
return input.replace(/[\s-]/g, "").toUpperCase();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 内部码 → 展示形式 XXXX-XXXX。 */
|
|
30
|
+
export function formatOtpCode(code) {
|
|
31
|
+
const normalized = normalizeOtpCode(code);
|
|
32
|
+
const groups = [];
|
|
33
|
+
for (let i = 0; i < normalized.length; i += OTP_CODE_GROUP) {
|
|
34
|
+
groups.push(normalized.slice(i, i + OTP_CODE_GROUP));
|
|
35
|
+
}
|
|
36
|
+
return groups.join("-");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 8 位 Crockford base32:每字节 % 32(256 是 32 的整数倍,无取模偏置)→ 40 bit 随机码。 */
|
|
40
|
+
function generateCode() {
|
|
41
|
+
const bytes = randomBytes(OTP_CODE_LENGTH);
|
|
42
|
+
let code = "";
|
|
43
|
+
for (const byte of bytes) code += CROCKFORD_ALPHABET[byte % 32];
|
|
44
|
+
return code;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isValidCode(normalized) {
|
|
48
|
+
if (normalized.length !== OTP_CODE_LENGTH) return false;
|
|
49
|
+
for (const char of normalized) if (!ALPHABET_SET.has(char)) return false;
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sameValue(a, b) {
|
|
54
|
+
if (a === b) return true;
|
|
55
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
56
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 绑定键全部命中才算通过;记录有绑定但调用方没给 meta → 拒绝(fail closed)。 */
|
|
60
|
+
function metaMatches(bound, provided) {
|
|
61
|
+
const keys = Object.keys(bound ?? {});
|
|
62
|
+
if (keys.length === 0) return true;
|
|
63
|
+
if (provided === null || typeof provided !== "object") return false;
|
|
64
|
+
return keys.every((key) => sameValue(bound[key], provided[key]));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 内存态 OTP 存储。内部只留 sha256(code) 与元数据,明文码仅在 `create()` 返回值里出现一次。
|
|
69
|
+
* 淘汰口径:先删已过期,再按插入顺序(最旧)删到 maxEntries 以内。
|
|
70
|
+
*/
|
|
71
|
+
export function createOtpStore({
|
|
72
|
+
now = Date.now,
|
|
73
|
+
ttlMs = OTP_TTL_MS,
|
|
74
|
+
maxFailures = OTP_MAX_FAILURES,
|
|
75
|
+
maxEntries = OTP_MAX_ENTRIES,
|
|
76
|
+
} = {}) {
|
|
77
|
+
/** sha256(code) → { id, createdAt, expiresAt, usedAt, failures, meta },Map 插入顺序即生成顺序。 */
|
|
78
|
+
const entries = new Map();
|
|
79
|
+
let seq = 0;
|
|
80
|
+
|
|
81
|
+
function prune() {
|
|
82
|
+
const at = now();
|
|
83
|
+
let removed = 0;
|
|
84
|
+
for (const [hash, record] of entries) {
|
|
85
|
+
if (at >= record.expiresAt) {
|
|
86
|
+
entries.delete(hash);
|
|
87
|
+
removed += 1;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return removed;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function enforceMaxEntries(keepHash) {
|
|
94
|
+
prune();
|
|
95
|
+
while (entries.size > maxEntries) {
|
|
96
|
+
let victim = null;
|
|
97
|
+
for (const hash of entries.keys()) {
|
|
98
|
+
if (hash !== keepHash) {
|
|
99
|
+
victim = hash;
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (victim === null) break;
|
|
104
|
+
entries.delete(victim);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 生成一次性码。返回值里的 `code` 是明文展示形式,只此一次。 */
|
|
109
|
+
function create({ meta = {} } = {}) {
|
|
110
|
+
const code = generateCode();
|
|
111
|
+
const hash = sha256hex(code);
|
|
112
|
+
const createdAt = now();
|
|
113
|
+
seq += 1;
|
|
114
|
+
const record = {
|
|
115
|
+
id: `otp_${seq.toString(36)}${randomBytes(4).toString("hex")}`,
|
|
116
|
+
createdAt,
|
|
117
|
+
expiresAt: createdAt + ttlMs,
|
|
118
|
+
usedAt: null,
|
|
119
|
+
failures: 0,
|
|
120
|
+
meta: { ...meta },
|
|
121
|
+
};
|
|
122
|
+
entries.set(hash, record);
|
|
123
|
+
enforceMaxEntries(hash);
|
|
124
|
+
return { id: record.id, code: formatOtpCode(code), expiresAt: record.expiresAt };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 兑换。reason 取值:`unknown`(不存在/格式非法)、`used`、`expired`、
|
|
129
|
+
* `too_many`(该码失败次数用尽,码作废)、`meta_mismatch`(绑定不符,计入 failures)。
|
|
130
|
+
*/
|
|
131
|
+
function redeem(code, { meta } = {}) {
|
|
132
|
+
const normalized = normalizeOtpCode(code);
|
|
133
|
+
if (!isValidCode(normalized)) return { ok: false, reason: "unknown" };
|
|
134
|
+
const record = entries.get(sha256hex(normalized));
|
|
135
|
+
if (!record) return { ok: false, reason: "unknown" };
|
|
136
|
+
if (record.failures >= maxFailures) return { ok: false, reason: "too_many" };
|
|
137
|
+
if (record.usedAt !== null) return { ok: false, reason: "used" };
|
|
138
|
+
if (now() >= record.expiresAt) return { ok: false, reason: "expired" };
|
|
139
|
+
if (!metaMatches(record.meta, meta)) {
|
|
140
|
+
record.failures += 1;
|
|
141
|
+
return { ok: false, reason: record.failures >= maxFailures ? "too_many" : "meta_mismatch" };
|
|
142
|
+
}
|
|
143
|
+
record.usedAt = now();
|
|
144
|
+
return { ok: true, meta: { ...record.meta }, expiresAt: record.expiresAt };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 管理视图:不含明文码、不含 hash。 */
|
|
148
|
+
function list() {
|
|
149
|
+
const at = now();
|
|
150
|
+
return [...entries.values()].map((record) => ({
|
|
151
|
+
id: record.id,
|
|
152
|
+
createdAt: record.createdAt,
|
|
153
|
+
expiresAt: record.expiresAt,
|
|
154
|
+
usedAt: record.usedAt,
|
|
155
|
+
failures: record.failures,
|
|
156
|
+
expired: at >= record.expiresAt,
|
|
157
|
+
meta: { ...record.meta },
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return { create, redeem, list, prune };
|
|
162
|
+
}
|