@chainlesschain/personal-data-hub 0.4.3 → 0.4.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.
Files changed (58) hide show
  1. package/__tests__/adapters/edu-huawei-learning-live.test.js +198 -0
  2. package/__tests__/adapters/edu-zuoyebang-live.test.js +226 -0
  3. package/__tests__/adapters/family-23-collectors-scaffold.test.js +5 -1
  4. package/__tests__/adapters/finance-alipay-live.test.js +258 -0
  5. package/__tests__/adapters/game-genshin-live.test.js +238 -0
  6. package/__tests__/adapters/game-genshin-scaffold.test.js +4 -3
  7. package/__tests__/adapters/game-honor-of-kings-live.test.js +230 -0
  8. package/__tests__/adapters/messaging-whatsapp.test.js +289 -0
  9. package/__tests__/adapters/netease-music-live.test.js +244 -0
  10. package/__tests__/adapters/shopping-base.test.js +179 -0
  11. package/__tests__/adapters/social-douyin-adb-aweme-detail.test.js +165 -0
  12. package/__tests__/adapters/social-douyin-adb-watch-history.test.js +192 -0
  13. package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +64 -0
  14. package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +11 -0
  15. package/__tests__/adapters/social-toutiao-adb-account-reader.test.js +135 -0
  16. package/__tests__/adapters/social-toutiao-adb-api-client.test.js +89 -0
  17. package/__tests__/adapters/social-toutiao-adb-collector.test.js +95 -2
  18. package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +30 -0
  19. package/__tests__/adapters/social-xiaohongshu-adb-api-client.test.js +431 -0
  20. package/__tests__/adapters/social-xiaohongshu-adb-cookies-extension.test.js +0 -0
  21. package/__tests__/adapters/social-xiaohongshu-adb-snapshot-builder.test.js +200 -0
  22. package/__tests__/adapters/travel-12306.test.js +279 -0
  23. package/__tests__/adapters/travel-amap.test.js +219 -0
  24. package/__tests__/adapters/travel-baidu-map.test.js +305 -0
  25. package/__tests__/adapters/travel-base.test.js +205 -0
  26. package/__tests__/adapters/travel-ctrip.test.js +203 -0
  27. package/__tests__/adapters/travel-tencent-map.test.js +207 -0
  28. package/lib/adapters/_live-json-helpers.js +50 -0
  29. package/lib/adapters/edu-huawei-learning/api-client.js +178 -5
  30. package/lib/adapters/edu-huawei-learning/index.js +83 -9
  31. package/lib/adapters/edu-zuoyebang/api-client.js +181 -6
  32. package/lib/adapters/edu-zuoyebang/index.js +83 -9
  33. package/lib/adapters/finance-alipay/api-client.js +268 -6
  34. package/lib/adapters/finance-alipay/index.js +85 -9
  35. package/lib/adapters/game-genshin/api-client.js +207 -6
  36. package/lib/adapters/game-genshin/index.js +90 -9
  37. package/lib/adapters/game-honor-of-kings/api-client.js +235 -12
  38. package/lib/adapters/game-honor-of-kings/index.js +80 -9
  39. package/lib/adapters/netease-music/api-client.js +284 -0
  40. package/lib/adapters/netease-music/index.js +85 -9
  41. package/lib/adapters/social-douyin/index.js +2 -0
  42. package/lib/adapters/social-douyin-adb/aweme-detail-client.js +119 -0
  43. package/lib/adapters/social-douyin-adb/collector.js +114 -0
  44. package/lib/adapters/social-douyin-adb/index.js +18 -1
  45. package/lib/adapters/social-douyin-adb/watch-history-reader.js +188 -0
  46. package/lib/adapters/social-kuaishou/index.js +7 -2
  47. package/lib/adapters/social-kuaishou-adb/api-client.js +38 -18
  48. package/lib/adapters/social-kuaishou-adb/cookies-extension.js +16 -15
  49. package/lib/adapters/social-toutiao/index.js +8 -4
  50. package/lib/adapters/social-toutiao-adb/account-reader.js +179 -0
  51. package/lib/adapters/social-toutiao-adb/api-client.js +41 -17
  52. package/lib/adapters/social-toutiao-adb/collector.js +55 -19
  53. package/lib/adapters/social-toutiao-adb/cookies-extension.js +21 -1
  54. package/lib/adapters/social-toutiao-adb/index.js +6 -0
  55. package/lib/adapters/social-xiaohongshu-adb/cookies-extension.js +19 -1
  56. package/lib/adapters/travel-base/index.js +9 -2
  57. package/lib/index.js +1 -1
  58. package/package.json +1 -1
@@ -0,0 +1,258 @@
1
+ /**
2
+ * FAMILY-23 v0.2 — finance-alipay LIVE mobilegw fetcher tests.
3
+ * cookie (支付宝会话) → mgw.htm bill-list → snapshot-shaped events + adapter
4
+ * live sync + signProvider seam + amount/direction derivation + error mapping.
5
+ * All network via injected fetch. Endpoint shapes are best-effort (see
6
+ * api-client header) — these tests pin the REQUEST CONSTRUCTION + PARSING
7
+ * contract, not the live server, which can't be verified here.
8
+ */
9
+ "use strict";
10
+
11
+ import { describe, it, expect } from "vitest";
12
+
13
+ const { AlipayAdapter } = require("../../lib");
14
+ const {
15
+ AlipayApiClient,
16
+ parseAmountYuan,
17
+ deriveDirection,
18
+ } = require("../../lib/adapters/finance-alipay/api-client");
19
+ const { validateBatch } = require("../../lib/batch");
20
+
21
+ const COOKIE = "ALIPAYJSESSIONID=sess-abc; userId=2088123";
22
+ const COOKIE_TOKEN_ONLY = "ALIPAYJSESSIONID=sess-abc";
23
+
24
+ function makeFetch(routes, calls) {
25
+ return async (url, init) => {
26
+ calls.push({
27
+ url,
28
+ body: (init && init.body) || null,
29
+ headers: (init && init.headers) || {},
30
+ });
31
+ const route = routes.find((r) => url.includes(r.match));
32
+ if (!route) return { ok: false, status: 404, text: async () => "not mapped" };
33
+ return {
34
+ ok: route.status ? route.status >= 200 && route.status < 300 : true,
35
+ status: route.status || 200,
36
+ text: async () =>
37
+ typeof route.body === "string" ? route.body : JSON.stringify(route.body),
38
+ };
39
+ };
40
+ }
41
+
42
+ async function collect(iter) {
43
+ const out = [];
44
+ for await (const r of iter) out.push(r);
45
+ return out;
46
+ }
47
+
48
+ describe("alipay amount/direction derivation", () => {
49
+ it("parseAmountYuan handles number / signed string / currency noise", () => {
50
+ expect(parseAmountYuan(12.5)).toEqual({ amountFen: 1250, sign: 1 });
51
+ expect(parseAmountYuan("-25.00")).toEqual({ amountFen: 2500, sign: -1 });
52
+ expect(parseAmountYuan("+3.50")).toEqual({ amountFen: 350, sign: 1 });
53
+ expect(parseAmountYuan("¥ 1,200.00")).toEqual({ amountFen: 120000, sign: 1 });
54
+ expect(parseAmountYuan("abc")).toBeNull();
55
+ expect(parseAmountYuan(null)).toBeNull();
56
+ });
57
+
58
+ it("deriveDirection: explicit field wins, then amount sign, default out", () => {
59
+ expect(deriveDirection("收入", -1)).toBe("in");
60
+ expect(deriveDirection("支出", 1)).toBe("out");
61
+ expect(deriveDirection("INCOME", 0)).toBe("in");
62
+ expect(deriveDirection(null, 1)).toBe("in");
63
+ expect(deriveDirection(null, -1)).toBe("out");
64
+ expect(deriveDirection(null, 0)).toBe("out");
65
+ });
66
+ });
67
+
68
+ describe("AlipayApiClient session probe", () => {
69
+ it("hasSession accepts session token or numeric uid; rejects neither", () => {
70
+ const c = new AlipayApiClient();
71
+ expect(c.hasSession(COOKIE_TOKEN_ONLY)).toBe(true);
72
+ expect(c.hasSession("userId=2088123")).toBe(true);
73
+ expect(c.hasSession("foo=bar")).toBe(false);
74
+ expect(c.lastError.code).toBe(-7);
75
+ });
76
+ });
77
+
78
+ describe("AlipayApiClient.fetchSnapshot — live (mocked fetch)", () => {
79
+ it("POSTs form-encoded operationType+requestData with cookie; parses bills", async () => {
80
+ const calls = [];
81
+ const fetch = makeFetch(
82
+ [
83
+ {
84
+ match: "/mgw.htm",
85
+ body: {
86
+ resultStatus: 1000,
87
+ result: {
88
+ success: true,
89
+ billList: [
90
+ { billId: "b1", displayName: "便利店", amount: "-12.50", gmtCreate: 1700000000 },
91
+ { tradeNo: "b2", merchantName: "红包", amount: "+5.00", inOut: "收入", createTime: "1700003600" },
92
+ ],
93
+ },
94
+ },
95
+ },
96
+ ],
97
+ calls,
98
+ );
99
+ const client = new AlipayApiClient({ fetch });
100
+ const result = await client.fetchSnapshot(COOKIE);
101
+ // profile derived from cookie scrape (no extra op)
102
+ expect(result.account).toEqual({ uid: "2088123", displayName: null });
103
+ const profile = result.events.find((e) => e.kind === "profile");
104
+ expect(profile).toMatchObject({ uid: "2088123" });
105
+ const orders = result.events.filter((e) => e.kind === "order");
106
+ expect(orders).toHaveLength(2);
107
+ expect(orders[0]).toMatchObject({
108
+ id: "order-b1",
109
+ merchant: "便利店",
110
+ amountFen: 1250,
111
+ direction: "out",
112
+ startAt: 1700000000000,
113
+ });
114
+ expect(orders[1]).toMatchObject({
115
+ id: "order-b2",
116
+ merchant: "红包",
117
+ amountFen: 500,
118
+ direction: "in",
119
+ startAt: 1700003600000,
120
+ });
121
+ const call = calls[0];
122
+ expect(call.headers.Cookie).toBe(COOKIE);
123
+ expect(call.headers["Content-Type"]).toContain("application/x-www-form-urlencoded");
124
+ expect(call.body).toContain("operationType=alipay.mobile.bill.list");
125
+ expect(call.body).toContain("requestData=");
126
+ });
127
+
128
+ it("parses result-as-JSON-string envelope (mgw double-encoding)", async () => {
129
+ const fetch = makeFetch(
130
+ [
131
+ {
132
+ match: "/mgw.htm",
133
+ body: {
134
+ resultStatus: 1000,
135
+ result: JSON.stringify({ success: true, list: [{ id: "s1", title: "公交", amount: "-2.00", tradeTime: 1700000000 }] }),
136
+ },
137
+ },
138
+ ],
139
+ [],
140
+ );
141
+ const client = new AlipayApiClient({ fetch });
142
+ const result = await client.fetchSnapshot(COOKIE_TOKEN_ONLY);
143
+ // token-only cookie → no profile event, account null, orders still flow
144
+ expect(result.account).toBeNull();
145
+ expect(result.events.every((e) => e.kind === "order")).toBe(true);
146
+ expect(result.events[0]).toMatchObject({ merchant: "公交", amountFen: 200, direction: "out" });
147
+ });
148
+
149
+ it("signProvider headers are merged into the request", async () => {
150
+ const calls = [];
151
+ const fetch = makeFetch(
152
+ [{ match: "/mgw.htm", body: { resultStatus: 1000, result: { success: true, billList: [] } } }],
153
+ calls,
154
+ );
155
+ const signProvider = {
156
+ buildHeaders: async ({ operationType }) => ({ "X-Sign": `sig-of-${operationType}` }),
157
+ };
158
+ const client = new AlipayApiClient({ fetch, signProvider });
159
+ await client.fetchSnapshot(COOKIE);
160
+ expect(calls[0].headers["X-Sign"]).toBe("sig-of-alipay.mobile.bill.list");
161
+ });
162
+
163
+ it("maps mgw gateway error (resultStatus != 1000) to null + lastError", async () => {
164
+ const fetch = makeFetch(
165
+ [{ match: "/mgw.htm", body: { resultStatus: 2000, memo: "登录超时" } }],
166
+ [],
167
+ );
168
+ const client = new AlipayApiClient({ fetch });
169
+ expect(await client.fetchSnapshot(COOKIE)).toBeNull();
170
+ expect(client.lastError.code).toBe(2000);
171
+ expect(client.lastError.message).toContain("登录超时");
172
+ });
173
+
174
+ it("maps business failure (success:false) to null + lastError -6", async () => {
175
+ const fetch = makeFetch(
176
+ [{ match: "/mgw.htm", body: { resultStatus: 1000, result: { success: false, resultMessage: "无权限" } } }],
177
+ [],
178
+ );
179
+ const client = new AlipayApiClient({ fetch });
180
+ expect(await client.fetchSnapshot(COOKIE)).toBeNull();
181
+ expect(client.lastError.code).toBe(-6);
182
+ expect(client.lastError.message).toContain("无权限");
183
+ });
184
+
185
+ it("no session cookie → null + lastError -7 (no network)", async () => {
186
+ const calls = [];
187
+ const client = new AlipayApiClient({ fetch: makeFetch([], calls) });
188
+ expect(await client.fetchSnapshot("foo=bar")).toBeNull();
189
+ expect(client.lastError.code).toBe(-7);
190
+ expect(calls).toHaveLength(0);
191
+ });
192
+
193
+ it("sign failure → null + lastError -5 (no network)", async () => {
194
+ const calls = [];
195
+ const client = new AlipayApiClient({
196
+ fetch: makeFetch([], calls),
197
+ signProvider: { buildHeaders: () => { throw new Error("key missing"); } },
198
+ });
199
+ expect(await client.fetchSnapshot(COOKIE)).toBeNull();
200
+ expect(client.lastError.code).toBe(-5);
201
+ expect(calls).toHaveLength(0);
202
+ });
203
+ });
204
+
205
+ describe("AlipayAdapter — cookie (live) sync mode", () => {
206
+ it("authenticate accepts session cookie; rejects sessionless", async () => {
207
+ const a = new AlipayAdapter();
208
+ expect((await a.authenticate({ cookie: COOKIE })).mode).toBe("cookie");
209
+ const bad = await a.authenticate({ cookie: "foo=bar" });
210
+ expect(bad.ok).toBe(false);
211
+ expect(bad.reason).toBe("INVALID_COOKIE");
212
+ });
213
+
214
+ it("version/capabilities reflect v0.2 live mode", () => {
215
+ const a = new AlipayAdapter();
216
+ expect(a.version).toBe("0.2.0");
217
+ expect(a.capabilities).toContain("sync:cookie");
218
+ });
219
+
220
+ it("sync via cookie yields profile+order raws → valid normalized batch", async () => {
221
+ const fetch = makeFetch(
222
+ [
223
+ {
224
+ match: "/mgw.htm",
225
+ body: {
226
+ resultStatus: 1000,
227
+ result: { success: true, billList: [{ billId: "b1", displayName: "便利店", amount: "-12.50", gmtCreate: 1700000000 }] },
228
+ },
229
+ },
230
+ ],
231
+ [],
232
+ );
233
+ const a = new AlipayAdapter();
234
+ const raws = await collect(a.sync({ cookie: COOKIE, fetch }));
235
+ expect(raws.map((r) => r.kind).sort()).toEqual(["order", "profile"]);
236
+ const profileRaw = raws.find((r) => r.kind === "profile");
237
+ expect(profileRaw.originalId).toBe("alipay:profile:profile-2088123");
238
+
239
+ for (const raw of raws) {
240
+ expect(validateBatch(a.normalize(raw)).valid).toBe(true);
241
+ }
242
+ const profileBatch = a.normalize(profileRaw);
243
+ expect(profileBatch.persons[0].identifiers["alipay-uid"]).toEqual(["2088123"]);
244
+ const orderBatch = a.normalize(raws.find((r) => r.kind === "order"));
245
+ expect(orderBatch.events[0].subtype).toBe("payment");
246
+ expect(orderBatch.events[0].extra.amountFen).toBe(1250);
247
+ expect(orderBatch.events[0].extra.direction).toBe("out");
248
+ });
249
+
250
+ it("sync via cookie throws (mapped lastError) on gateway error", async () => {
251
+ const fetch = makeFetch(
252
+ [{ match: "/mgw.htm", body: { resultStatus: 2000, memo: "登录超时" } }],
253
+ [],
254
+ );
255
+ const a = new AlipayAdapter();
256
+ await expect(collect(a.sync({ cookie: COOKIE, fetch }))).rejects.toThrow(/登录超时|code 2000/);
257
+ });
258
+ });
@@ -0,0 +1,238 @@
1
+ /**
2
+ * FAMILY-23 v0.2 — game-genshin LIVE HoYoLAB fetcher tests.
3
+ * DS v1 signing determinism + takumi role fetch + game-record stats fold-in
4
+ * + adapter cookie-mode sync + error mapping. All network via injected fetch.
5
+ */
6
+ import { describe, it, expect } from "vitest";
7
+ const { GenshinAdapter } = require("../../lib");
8
+ const {
9
+ GenshinApiClient,
10
+ genDs,
11
+ md5Hex,
12
+ DEFAULT_DS_SALT,
13
+ } = require("../../lib/adapters/game-genshin/api-client");
14
+ const { validateBatch } = require("../../lib/batch");
15
+
16
+ // Deterministic clock + RNG seams.
17
+ const FIXED_NOW = () => 1700000000000; // → t = 1700000000
18
+ const FIXED_RAND = () => 0.5; // → r = 100001 + floor(0.5 * 99999) = 150000
19
+
20
+ /**
21
+ * Build a fake fetch that maps URL substrings to JSON responses.
22
+ * Each entry: { match, status?, body }. body is auto-JSON.stringify'd.
23
+ * Records every requested URL + headers into `calls`.
24
+ */
25
+ function makeFetch(routes, calls) {
26
+ return async (url, init) => {
27
+ calls.push({ url, headers: (init && init.headers) || {} });
28
+ const route = routes.find((r) => url.includes(r.match));
29
+ if (!route) {
30
+ return { ok: false, status: 404, text: async () => "not mapped" };
31
+ }
32
+ return {
33
+ ok: route.status ? route.status >= 200 && route.status < 300 : true,
34
+ status: route.status || 200,
35
+ text: async () =>
36
+ typeof route.body === "string" ? route.body : JSON.stringify(route.body),
37
+ };
38
+ };
39
+ }
40
+
41
+ const COOKIE = "account_id_v2=809199; cookie_token_v2=abc; ltoken_v2=xyz";
42
+
43
+ describe("genDs — DS v1 dynamic-secret signing", () => {
44
+ it("produces `${t},${r},${c}` with c = md5(salt&t&r), deterministic under seams", () => {
45
+ const ds = genDs(DEFAULT_DS_SALT, FIXED_NOW, FIXED_RAND);
46
+ const [t, r, c] = ds.split(",");
47
+ expect(t).toBe("1700000000");
48
+ expect(r).toBe("150000");
49
+ expect(c).toBe(md5Hex(`salt=${DEFAULT_DS_SALT}&t=1700000000&r=150000`));
50
+ expect(c).toMatch(/^[0-9a-f]{32}$/);
51
+ });
52
+
53
+ it("r stays within the 6-digit [100001,200000) window at RNG extremes", () => {
54
+ const low = genDs("s", FIXED_NOW, () => 0).split(",")[1];
55
+ const high = genDs("s", FIXED_NOW, () => 0.9999999).split(",")[1];
56
+ expect(Number(low)).toBe(100001);
57
+ expect(Number(high)).toBeLessThan(200000);
58
+ expect(Number(high)).toBeGreaterThanOrEqual(100001);
59
+ });
60
+ });
61
+
62
+ describe("GenshinApiClient.fetchProfiles — live (mocked fetch)", () => {
63
+ it("resolves bound roles + folds in active_day_number; sends DS-signed mihoyo headers", async () => {
64
+ const calls = [];
65
+ const fetch = makeFetch(
66
+ [
67
+ {
68
+ match: "getUserGameRolesByCookie",
69
+ body: {
70
+ retcode: 0,
71
+ message: "OK",
72
+ data: {
73
+ list: [
74
+ {
75
+ game_uid: "800000001",
76
+ nickname: "旅行者",
77
+ level: 58,
78
+ region: "cn_gf01",
79
+ region_name: "天空岛",
80
+ },
81
+ ],
82
+ },
83
+ },
84
+ },
85
+ {
86
+ match: "game_record/app/genshin/api/index",
87
+ body: { retcode: 0, message: "OK", data: { stats: { active_day_number: 421 } } },
88
+ },
89
+ ],
90
+ calls,
91
+ );
92
+ const client = new GenshinApiClient({ fetch, now: FIXED_NOW, rand: FIXED_RAND });
93
+ const profiles = await client.fetchProfiles(COOKIE);
94
+ expect(profiles).toHaveLength(1);
95
+ expect(profiles[0]).toMatchObject({
96
+ uid: "800000001",
97
+ nickname: "旅行者",
98
+ level: 58,
99
+ region: "cn_gf01",
100
+ regionName: "天空岛",
101
+ activeDayNumber: 421,
102
+ });
103
+ // DS header present + well-formed on every call; client_type=5, version set.
104
+ for (const c of calls) {
105
+ expect(c.headers.DS).toMatch(/^\d+,\d+,[0-9a-f]{32}$/);
106
+ expect(c.headers["x-rpc-client_type"]).toBe("5");
107
+ expect(c.headers["x-rpc-app_version"]).toBeTruthy();
108
+ expect(c.headers.Cookie).toBe(COOKIE);
109
+ }
110
+ // index request carried role_id + server from the role.
111
+ const idx = calls.find((c) => c.url.includes("/index"));
112
+ expect(idx.url).toContain("role_id=800000001");
113
+ expect(idx.url).toContain("server=cn_gf01");
114
+ });
115
+
116
+ it("fetchStats:false skips the game-record index call", async () => {
117
+ const calls = [];
118
+ const fetch = makeFetch(
119
+ [
120
+ {
121
+ match: "getUserGameRolesByCookie",
122
+ body: {
123
+ retcode: 0,
124
+ data: { list: [{ game_uid: "1", nickname: "a", level: 1, region: "cn_qd01" }] },
125
+ },
126
+ },
127
+ ],
128
+ calls,
129
+ );
130
+ const client = new GenshinApiClient({ fetch, now: FIXED_NOW, rand: FIXED_RAND });
131
+ const profiles = await client.fetchProfiles(COOKIE, { fetchStats: false });
132
+ expect(profiles[0].activeDayNumber).toBeNull();
133
+ expect(calls.some((c) => c.url.includes("/index"))).toBe(false);
134
+ });
135
+
136
+ it("maps mihoyo retcode != 0 to null + lastError (e.g. 1034 risk-control)", async () => {
137
+ const calls = [];
138
+ const fetch = makeFetch(
139
+ [{ match: "getUserGameRolesByCookie", body: { retcode: 1034, message: "请进行验证" } }],
140
+ calls,
141
+ );
142
+ const client = new GenshinApiClient({ fetch, now: FIXED_NOW, rand: FIXED_RAND });
143
+ const profiles = await client.fetchProfiles(COOKIE);
144
+ expect(profiles).toBeNull();
145
+ expect(client.lastError.code).toBe(1034);
146
+ expect(client.lastError.message).toContain("验证");
147
+ });
148
+
149
+ it("empty cookie → null + lastError -1 (no network)", async () => {
150
+ const calls = [];
151
+ const client = new GenshinApiClient({
152
+ fetch: makeFetch([], calls),
153
+ now: FIXED_NOW,
154
+ rand: FIXED_RAND,
155
+ });
156
+ expect(await client.fetchProfiles("")).toBeNull();
157
+ expect(client.lastError.code).toBe(-1);
158
+ expect(calls).toHaveLength(0);
159
+ });
160
+
161
+ it("HTTP non-2xx → null + lastError with status code", async () => {
162
+ const calls = [];
163
+ const fetch = makeFetch(
164
+ [{ match: "getUserGameRolesByCookie", status: 503, body: "down" }],
165
+ calls,
166
+ );
167
+ const client = new GenshinApiClient({ fetch, now: FIXED_NOW, rand: FIXED_RAND });
168
+ expect(await client.fetchProfiles(COOKIE)).toBeNull();
169
+ expect(client.lastError.code).toBe(503);
170
+ });
171
+ });
172
+
173
+ describe("GenshinAdapter — cookie (live) sync mode", () => {
174
+ it("authenticate accepts a valid cookie (mode: cookie)", async () => {
175
+ const a = new GenshinAdapter();
176
+ const r = await a.authenticate({ cookie: COOKIE });
177
+ expect(r.ok).toBe(true);
178
+ expect(r.mode).toBe("cookie");
179
+ });
180
+
181
+ it("authenticate rejects guest cookie (no uid)", async () => {
182
+ const a = new GenshinAdapter();
183
+ const r = await a.authenticate({ cookie: "foo=bar" });
184
+ expect(r.ok).toBe(false);
185
+ expect(r.reason).toBe("INVALID_COOKIE");
186
+ });
187
+
188
+ it("sync via cookie yields profile raws → valid normalized batch with region/activeDays", async () => {
189
+ const calls = [];
190
+ const fetch = makeFetch(
191
+ [
192
+ {
193
+ match: "getUserGameRolesByCookie",
194
+ body: {
195
+ retcode: 0,
196
+ data: {
197
+ list: [
198
+ { game_uid: "800000001", nickname: "旅行者", level: 58, region: "cn_gf01", region_name: "天空岛" },
199
+ ],
200
+ },
201
+ },
202
+ },
203
+ {
204
+ match: "/index",
205
+ body: { retcode: 0, data: { stats: { active_day_number: 421 } } },
206
+ },
207
+ ],
208
+ calls,
209
+ );
210
+ const a = new GenshinAdapter();
211
+ const raws = [];
212
+ for await (const r of a.sync({ cookie: COOKIE, fetch, now: FIXED_NOW, rand: FIXED_RAND })) {
213
+ raws.push(r);
214
+ }
215
+ expect(raws).toHaveLength(1);
216
+ expect(raws[0].kind).toBe("profile");
217
+ expect(raws[0].originalId).toBe("genshin:profile:800000001");
218
+
219
+ const batch = a.normalize(raws[0]);
220
+ expect(validateBatch(batch).valid).toBe(true);
221
+ const person = batch.persons[0];
222
+ expect(person.identifiers["genshin-uid"]).toEqual(["800000001"]);
223
+ expect(person.extra.region).toBe("cn_gf01");
224
+ expect(person.extra.activeDayNumber).toBe(421);
225
+ });
226
+
227
+ it("sync via cookie throws (mapped lastError) on API risk-control", async () => {
228
+ const calls = [];
229
+ const fetch = makeFetch(
230
+ [{ match: "getUserGameRolesByCookie", body: { retcode: 10001, message: "登录失效" } }],
231
+ calls,
232
+ );
233
+ const a = new GenshinAdapter();
234
+ await expect(async () => {
235
+ for await (const _ of a.sync({ cookie: COOKIE, fetch, now: FIXED_NOW, rand: FIXED_RAND })) void _;
236
+ }).rejects.toThrow(/登录失效|code 10001/);
237
+ });
238
+ });
@@ -25,10 +25,11 @@ describe("GenshinAdapter — FAMILY-23 v0.1 cookie-scrape placeholder", () => {
25
25
  const a = new GenshinAdapter();
26
26
  expect(assertAdapter(a).ok).toBe(true);
27
27
  expect(a.name).toBe("game-genshin");
28
- expect(a.version).toBe("0.1.0");
28
+ expect(a.version).toBe("0.2.0");
29
29
  expect(a.extractMode).toBe("web-api");
30
30
  expect(a.dataDisclosure.sensitivity).toBe("medium");
31
31
  expect(a.capabilities).toContain("sync:snapshot");
32
+ expect(a.capabilities).toContain("sync:cookie");
32
33
  });
33
34
 
34
35
  it("extractUid parses HoYoLAB cookie keys (priority + null)", () => {
@@ -45,11 +46,11 @@ describe("GenshinAdapter — FAMILY-23 v0.1 cookie-scrape placeholder", () => {
45
46
  expect(c.lastError.code).toBe(-1);
46
47
  });
47
48
 
48
- it("sync throws NO_INPUT without inputPath (v0.1 no live HTTP)", async () => {
49
+ it("sync throws without inputPath or cookie", async () => {
49
50
  const a = new GenshinAdapter();
50
51
  await expect(async () => {
51
52
  for await (const _ of a.sync({})) void _;
52
- }).rejects.toThrow(/inputPath/);
53
+ }).rejects.toThrow(/inputPath.*cookie|cookie.*inputPath/);
53
54
  });
54
55
 
55
56
  it("sync via snapshot yields profile + play raws", async () => {