pwish-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,348 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * 直接从浏览器磁盘上读 localStorage —— 用户只要在浏览器里登录过佐糖,
7
+ * 就不需要复制 token、也不需要点书签(这是「从已登录网页取凭据」的零交互实现)。
8
+ *
9
+ * 原理:Chromium 把 localStorage 存在 <profile>/Local Storage/leveldb 下。
10
+ * - .ldb 是 SSTable:data block 可能被 snappy 压缩,块尾 5 字节为 [压缩类型][CRC32]
11
+ * - .log 是 WAL:物理记录 [CRC(4)][len(2)][type(1)][payload],逻辑记录可能分片
12
+ * 这里只做只读解析,不写原目录,因此可以在浏览器运行中读取(读到的是最新落盘值)。
13
+ *
14
+ * 注意:本模块刻意不实现严格的 key/value 边界解析 —— Chromium 会在 key 末尾附加
15
+ * 内部元数据,跨版本会变。改为在解压后的字节里做定向提取,格式漂移时更抗打。
16
+ */
17
+
18
+ /** LEB128 varint 解码。返回 { value, next }。 */
19
+ export function decodeVarint(buf, pos = 0) {
20
+ let value = 0;
21
+ let shift = 0;
22
+ while (pos < buf.length && shift < 63) {
23
+ const b = buf[pos++];
24
+ value += (b & 0x7f) * 2 ** shift;
25
+ if (!(b & 0x80)) return { value, next: pos };
26
+ shift += 7;
27
+ }
28
+ throw new Error("varint 溢出");
29
+ }
30
+
31
+ /** Snappy 原始块解压。 */
32
+ export function snappyDecompress(src) {
33
+ let pos = 0;
34
+ let len = 0;
35
+ let shift = 0;
36
+ while (pos < src.length) {
37
+ const b = src[pos++];
38
+ len += (b & 0x7f) * 2 ** shift;
39
+ if (!(b & 0x80)) break;
40
+ shift += 7;
41
+ }
42
+ if (len === 0 || len > 64 * 1024 * 1024) throw new Error(`snappy 长度非法: ${len}`);
43
+ const out = Buffer.alloc(len);
44
+ let op = 0;
45
+ while (pos < src.length) {
46
+ const tag = src[pos++];
47
+ const type = tag & 0x03;
48
+ let copyLen;
49
+ let offset;
50
+ if (type === 0) {
51
+ copyLen = tag >>> 2;
52
+ if (copyLen >= 60) {
53
+ const n = copyLen - 59;
54
+ copyLen = 0;
55
+ for (let i = 0; i < n; i++) copyLen += src[pos++] * 2 ** (8 * i);
56
+ }
57
+ copyLen += 1;
58
+ if (pos + copyLen > src.length || op + copyLen > len) throw new Error("snappy literal 越界");
59
+ src.copy(out, op, pos, pos + copyLen);
60
+ pos += copyLen;
61
+ op += copyLen;
62
+ continue;
63
+ }
64
+ if (type === 1) {
65
+ copyLen = 4 + ((tag >>> 2) & 0x07);
66
+ offset = ((tag >>> 5) << 8) | src[pos++];
67
+ } else if (type === 2) {
68
+ copyLen = 1 + (tag >>> 2);
69
+ offset = src[pos++] | (src[pos++] << 8);
70
+ } else {
71
+ copyLen = 1 + (tag >>> 2);
72
+ offset = src.readUInt32LE(pos);
73
+ pos += 4;
74
+ }
75
+ if (offset === 0 || offset > op || op + copyLen > len) throw new Error("snappy backref 越界");
76
+ for (let i = 0; i < copyLen; i++) {
77
+ out[op] = out[op - offset];
78
+ op++;
79
+ }
80
+ }
81
+ if (op !== len) throw new Error(`snappy 输出长度不符: ${op} != ${len}`);
82
+ return out;
83
+ }
84
+
85
+ const TABLE_MAGIC = 0xdb4775248b80fb57n;
86
+
87
+ function readBlockOf(buf, offset, size) {
88
+ const body = buf.slice(offset, offset + size);
89
+ const compression = buf[offset + size];
90
+ if (compression === 0) return body;
91
+ if (compression === 1) return snappyDecompress(body);
92
+ throw new Error(`不支持的 block 压缩类型: ${compression}`);
93
+ }
94
+
95
+ /** 解析 .ldb(SSTable)里所有 data block 的解压内容。 */
96
+ export function ldbBlocks(buf) {
97
+ if (buf.length < 48 || buf.readBigUInt64LE(buf.length - 8) !== TABLE_MAGIC) {
98
+ throw new Error("不是 LevelDB .ldb 文件");
99
+ }
100
+ const footer = buf.length - 48;
101
+ const meta = decodeVarint(buf, footer);
102
+ const metaSize = decodeVarint(buf, meta.next);
103
+ const index = decodeVarint(buf, metaSize.next);
104
+ const indexSize = decodeVarint(buf, index.next);
105
+
106
+ const blocks = [];
107
+ let indexBlock;
108
+ try {
109
+ indexBlock = readBlockOf(buf, index.value, indexSize.value);
110
+ } catch {
111
+ return blocks;
112
+ }
113
+ const restartCount = indexBlock.readUInt32LE(indexBlock.length - 4);
114
+ const bodyEnd = indexBlock.length - 4 - restartCount * 4;
115
+ let pos = 0;
116
+ let last = Buffer.alloc(0);
117
+ while (pos < bodyEnd) {
118
+ let shared;
119
+ let nonShared;
120
+ let valueLen;
121
+ try {
122
+ shared = decodeVarint(indexBlock, pos);
123
+ nonShared = decodeVarint(indexBlock, shared.next);
124
+ valueLen = decodeVarint(indexBlock, nonShared.next);
125
+ } catch {
126
+ break;
127
+ }
128
+ const keyStart = valueLen.next;
129
+ const key = Buffer.concat([
130
+ last.slice(0, shared.value),
131
+ indexBlock.slice(keyStart, keyStart + nonShared.value),
132
+ ]);
133
+ const valueStart = keyStart + nonShared.value;
134
+ const value = indexBlock.slice(valueStart, valueStart + valueLen.value);
135
+ pos = valueStart + valueLen.value;
136
+ last = key;
137
+ try {
138
+ const offset = decodeVarint(value, 0);
139
+ const size = decodeVarint(value, offset.next);
140
+ blocks.push(readBlockOf(buf, offset.value, size.value));
141
+ } catch {
142
+ /* 跳过坏块 */
143
+ }
144
+ }
145
+ return blocks;
146
+ }
147
+
148
+ /** 解析 .log(WAL)里的记录 payload。 */
149
+ export function logBlocks(buf) {
150
+ const out = [];
151
+ let pos = 0;
152
+ let pending = Buffer.alloc(0);
153
+ while (pos + 7 <= buf.length) {
154
+ const length = buf.readUInt16LE(pos + 4);
155
+ const type = buf[pos + 6];
156
+ if (pos + 7 + length > buf.length) break;
157
+ const payload = buf.slice(pos + 7, pos + 7 + length);
158
+ pos += 7 + length;
159
+ if (type === 1) {
160
+ out.push(Buffer.concat([pending, payload]));
161
+ pending = Buffer.alloc(0);
162
+ } else if (type === 2 || type === 3) {
163
+ pending = Buffer.concat([pending, payload]);
164
+ } else if (type === 0) {
165
+ pending = Buffer.alloc(0);
166
+ }
167
+ }
168
+ if (pending.length) out.push(pending);
169
+ return out;
170
+ }
171
+
172
+ /** 把 origin 编码成 Chromium localStorage 的 key 前缀。 */
173
+ function originPrefix(origin) {
174
+ return `_${origin}${String.fromCharCode(0)}${String.fromCharCode(1)}`;
175
+ }
176
+
177
+ const PRINTABLE = /^[\x20-\x7e\u00a0-\uffff]*$/;
178
+
179
+ /**
180
+ * 在一个已解压的 block 里,提取指定 key 之后的值文本。
181
+ * Chromium 在 key 与 value 之间会插入内部元数据,所以取 key 之后的一段窗口,
182
+ * 再从里面挑出「看起来像值」的连续可打印串。
183
+ */
184
+ function extractValue(block, keyName, origin) {
185
+ const text = block.toString("latin1");
186
+ const needle = keyName;
187
+ let from = 0;
188
+ for (;;) {
189
+ const idx = text.indexOf(needle, from);
190
+ if (idx < 0) return null;
191
+ from = idx + needle.length;
192
+
193
+ // 确认这个 key 属于目标 origin:向前找最近的 origin 前缀(同一 block 内紧邻)
194
+ const before = text.slice(Math.max(0, idx - 200), idx);
195
+ const prefixAt = before.lastIndexOf(originPrefix(origin));
196
+ const hasOrigin = prefixAt >= 0;
197
+
198
+ const window = block.slice(idx + needle.length, idx + needle.length + 512);
199
+ // 值以 0x01 开头(UTF-8 标记)或 UTF-16(字符间夹 0x00)
200
+ for (let i = 0; i < Math.min(window.length, 96); i++) {
201
+ if (window[i] !== 0x01) continue;
202
+ const chunk = window.slice(i + 1);
203
+ // UTF-16LE:第 2 个字节是 0x00
204
+ if (chunk.length > 2 && chunk[1] === 0x00 && chunk[0] !== 0x00) {
205
+ const chars = [];
206
+ for (let j = 0; j + 1 < chunk.length; j += 2) {
207
+ const code = chunk[j] | (chunk[j + 1] << 8);
208
+ if (code === 0) break;
209
+ chars.push(String.fromCharCode(code));
210
+ }
211
+ const s = chars.join("");
212
+ if (s && PRINTABLE.test(s)) return { value: s, hasOrigin };
213
+ continue;
214
+ }
215
+ // UTF-8 / latin1:取到不可打印字符为止
216
+ const bytes = [];
217
+ for (let j = 0; j < chunk.length; j++) {
218
+ const b = chunk[j];
219
+ if (b === 0 || b === 0x1e || b === 0x1d) break;
220
+ bytes.push(b);
221
+ }
222
+ const s = Buffer.from(bytes).toString("utf8");
223
+ if (s && PRINTABLE.test(s)) return { value: s, hasOrigin };
224
+ }
225
+ }
226
+ }
227
+
228
+ /** 读取某 origin 下的所有 localStorage 键值。 */
229
+ export function readLocalStorage(dir, origin) {
230
+ const result = {};
231
+ if (!fs.existsSync(dir)) return result;
232
+
233
+ const files = fs.readdirSync(dir).filter((f) => f.endsWith(".ldb") || f.endsWith(".log"));
234
+ // 先读 .ldb(旧值),再用 .log(WAL,最新值)覆盖
235
+ files.sort((a, b) => (a.endsWith(".log") ? 1 : 0) - (b.endsWith(".log") ? 1 : 0));
236
+
237
+ const wanted = [
238
+ "passport_api_token",
239
+ "passport_user_info",
240
+ "last_login",
241
+ "user_id",
242
+ ];
243
+
244
+ for (const file of files) {
245
+ const full = path.join(dir, file);
246
+ let blocks;
247
+ try {
248
+ const buf = fs.readFileSync(full);
249
+ blocks = file.endsWith(".ldb") ? ldbBlocks(buf) : logBlocks(buf);
250
+ } catch {
251
+ continue;
252
+ }
253
+ const joined = Buffer.concat(blocks);
254
+ if (!joined.includes(originPrefix(origin))) continue;
255
+
256
+ for (const key of wanted) {
257
+ const found = extractValue(joined, key, origin);
258
+ if (found?.value) result[key] = found.value;
259
+ }
260
+
261
+ // 兜底:直接正则捞 token(防止 key 名或结构微调)
262
+ if (!result.passport_api_token) {
263
+ const m = joined.toString("latin1").match(/v2,\d+,\d+,[0-9a-f]{16,}/);
264
+ if (m && joined.includes(originPrefix(origin))) result.passport_api_token = m[0];
265
+ }
266
+ }
267
+ return result;
268
+ }
269
+
270
+ /** 各平台的 Chromium 系浏览器数据根目录。 */
271
+ function chromiumRoots() {
272
+ const home = os.homedir();
273
+ const platform = process.platform;
274
+
275
+ if (platform === "darwin") {
276
+ const base = path.join(home, "Library", "Application Support");
277
+ return [
278
+ ["Chrome", path.join(base, "Google", "Chrome")],
279
+ ["Edge", path.join(base, "Microsoft Edge")],
280
+ ["Brave", path.join(base, "BraveSoftware", "Brave-Browser")],
281
+ ["Chromium", path.join(base, "Chromium")],
282
+ ["Arc", path.join(base, "Arc", "User Data")],
283
+ ["Vivaldi", path.join(base, "Vivaldi")],
284
+ ];
285
+ }
286
+
287
+ if (platform === "win32") {
288
+ const local = process.env.LOCALAPPDATA || path.join(home, "AppData", "Local");
289
+ return [
290
+ ["Chrome", path.join(local, "Google", "Chrome", "User Data")],
291
+ ["Edge", path.join(local, "Microsoft", "Edge", "User Data")],
292
+ ["Brave", path.join(local, "BraveSoftware", "Brave-Browser", "User Data")],
293
+ ["Chromium", path.join(local, "Chromium", "User Data")],
294
+ ["Vivaldi", path.join(local, "Vivaldi", "User Data")],
295
+ ];
296
+ }
297
+
298
+ // Linux 及其他:XDG
299
+ const config = process.env.XDG_CONFIG_HOME || path.join(home, ".config");
300
+ return [
301
+ ["Chrome", path.join(config, "google-chrome")],
302
+ ["Chrome Beta", path.join(config, "google-chrome-beta")],
303
+ ["Chromium", path.join(config, "chromium")],
304
+ ["Edge", path.join(config, "microsoft-edge")],
305
+ ["Brave", path.join(config, "BraveSoftware", "Brave-Browser")],
306
+ ["Vivaldi", path.join(config, "vivaldi")],
307
+ ];
308
+ }
309
+
310
+ /** 常见 Chromium 浏览器的 Local Storage leveldb 目录(macOS / Windows / Linux)。 */
311
+ export function browserProfiles() {
312
+ const found = [];
313
+
314
+ const add = (browser, profile) => {
315
+ const leveldb = path.join(profile, "Local Storage", "leveldb");
316
+ if (fs.existsSync(leveldb)) found.push({ browser, profile, leveldb });
317
+ };
318
+
319
+ for (const [browser, root] of chromiumRoots()) {
320
+ if (!fs.existsSync(root)) continue;
321
+ add(browser, path.join(root, "Default"));
322
+ try {
323
+ for (const d of fs.readdirSync(root, { withFileTypes: true })) {
324
+ if (d.isDirectory() && /^Profile \d+$/.test(d.name)) add(browser, path.join(root, d.name));
325
+ }
326
+ } catch {
327
+ /* 无权限或不可读时跳过 */
328
+ }
329
+ }
330
+
331
+ return found;
332
+ }
333
+
334
+ /** 扫描所有 profile,返回所有找到的 picwish token。 */
335
+ export function findPassportToken(origin = "https://picwish.cn") {
336
+ const hits = [];
337
+ for (const p of browserProfiles()) {
338
+ let storage;
339
+ try {
340
+ storage = readLocalStorage(p.leveldb, origin);
341
+ } catch {
342
+ continue;
343
+ }
344
+ const token = (storage.passport_api_token || "").trim();
345
+ if (token) hits.push({ browser: p.browser, profile: p.profile, token, storage });
346
+ }
347
+ return hits;
348
+ }