@lks347/dsh-oauth 0.0.0-stage → 1.0.2

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 (67) hide show
  1. package/README.en.md +155 -0
  2. package/README.md +101 -2
  3. package/app.js +1045 -0
  4. package/auth.html +80 -0
  5. package/client.js +31 -0
  6. package/cordis.patch.yml +4 -0
  7. package/docs/CONNECTIONS.md +77 -0
  8. package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
  9. package/docs/RELEASE-1.0.1.md +48 -0
  10. package/docs/RELEASE-1.0.2.md +8 -0
  11. package/docs/VALIDATION.md +59 -0
  12. package/docs/evidence/live-1.0.1.json +135 -0
  13. package/docs/evidence/release-1.0.1.json +38 -0
  14. package/index.html +43 -0
  15. package/package.json +64 -4
  16. package/providers.js +73 -0
  17. package/scripts/check-upstreams.mjs +27 -0
  18. package/scripts/link-peers.js +38 -0
  19. package/scripts/verify-browser.mjs +297 -0
  20. package/scripts/verify-host.mjs +431 -0
  21. package/scripts/verify-live.mjs +268 -0
  22. package/scripts/verify-package.mjs +168 -0
  23. package/scripts/verify-persistence.mjs +307 -0
  24. package/scripts/verify-subscriptions-ui.mjs +321 -0
  25. package/src/account.js +85 -0
  26. package/src/account.test.js +52 -0
  27. package/src/authorization.js +199 -0
  28. package/src/authorization.test.js +332 -0
  29. package/src/catalog.js +180 -0
  30. package/src/catalog.test.js +146 -0
  31. package/src/chat-recovery.js +110 -0
  32. package/src/chat-recovery.test.js +261 -0
  33. package/src/connection-runtime.js +129 -0
  34. package/src/connection-runtime.test.js +244 -0
  35. package/src/connections.js +70 -0
  36. package/src/grants.js +104 -0
  37. package/src/grants.test.js +340 -0
  38. package/src/index.js +676 -0
  39. package/src/local-imports.js +263 -0
  40. package/src/local-imports.test.js +201 -0
  41. package/src/media.js +152 -0
  42. package/src/models.js +610 -0
  43. package/src/models.test.js +503 -0
  44. package/src/profile-store.js +51 -0
  45. package/src/pulls.js +100 -0
  46. package/src/pulls.test.js +156 -0
  47. package/src/qwen.js +141 -0
  48. package/src/qwen.test.js +35 -0
  49. package/src/request-errors.js +50 -0
  50. package/src/request-errors.test.js +131 -0
  51. package/src/routes.js +47 -0
  52. package/src/routes.test.js +136 -0
  53. package/src/subscription-models.test.js +160 -0
  54. package/src/usage/aggregators.js +292 -0
  55. package/src/usage/aggregators.test.js +316 -0
  56. package/src/usage/core.js +68 -0
  57. package/src/usage/index.js +93 -0
  58. package/src/usage/official.js +339 -0
  59. package/src/usage/official.test.js +273 -0
  60. package/src/usage/service.test.js +89 -0
  61. package/src/xai-browser.js +272 -0
  62. package/src/xai-browser.test.js +256 -0
  63. package/src/xai-login.js +121 -0
  64. package/src/xai-login.test.js +259 -0
  65. package/styles.css +364 -0
  66. package/theme.js +118 -0
  67. package/upstreams.json +10 -0
@@ -0,0 +1,321 @@
1
+ /** Subscription UI acceptance against local mocks. Never contacts a provider or reads credentials. */
2
+ import assert from 'node:assert/strict';
3
+ import { createServer } from 'node:http';
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join, resolve } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ const require = createRequire(import.meta.url);
10
+ let playwright;
11
+ try { playwright = require('playwright'); }
12
+ catch { playwright = require(process.env.DSH_PLAYWRIGHT_MODULE || join(homedir(), '.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright')); }
13
+ const root = dirname(dirname(fileURLToPath(import.meta.url)));
14
+ const outArg = process.argv.indexOf('--out-dir');
15
+ const outDir = resolve(outArg >= 0 ? process.argv[outArg + 1] : join(root, 'artifacts/subscriptions-ui'));
16
+ await mkdir(outDir, { recursive: true });
17
+ const completed = [], pageErrors = [], blockedRequests = [], calls = [];
18
+ let usageMode = 'fresh', lateUsage, releaseLate;
19
+ const providers = [
20
+ { id: 'google-antigravity', name: 'Google Antigravity', cliCatalog: true, flow: 'pkce', authMethods: ['oauth', 'local'], usageSupported: true, loggedIn: true, pullable: false, supportReason: 'host-oauth-model-integration-unavailable', pulledModels: [] },
21
+ { id: 'qwen', name: 'Qwen CLI', flow: 'device_code', authMethods: ['oauth'], usageSupported: false, loggedIn: true, pullable: true, pulledModels: [] },
22
+ { id: 'new-api', name: 'New API', flow: 'key', authMethods: ['key'], keyConnect: true, usageSupported: true, loggedIn: false, pulledModels: [] },
23
+ { id: 'zenmux', name: 'ZenMux', flow: 'key', authMethods: ['key'], keyConnect: true, usageSupported: true, loggedIn: false, pulledModels: [] },
24
+ { id: 'openai-codex', name: 'ChatGPT / Codex', flow: 'pkce', authMethods: ['oauth', 'local'], usageSupported: true, loggedIn: true, tokenPreview: 'DO-NOT-DISPLAY-TOKEN', pulledModels: [] },
25
+ { id: 'anthropic', name: 'Claude Pro/Max', flow: 'pkce', authMethods: ['oauth'], usageSupported: true, loggedIn: false, pullable: false },
26
+ ];
27
+ const models = [{ id: 'mock-model', name: 'Mock <img src=x onerror=alert(1)>', role: 'chat', input: ['text', 'image'], output: ['text'], tools: true, contextWindow: 200000, maxTokens: 32000, reasoningEfforts: { low: 'low', high: 'high' }, source: 'public-catalog', entitlement: 'unknown' }, { id: 'mock-image', name: 'Image model', role: 'image', input: ['text'], output: ['image'], source: 'account', entitlement: 'account' }];
28
+ const snapshot = { plan: { name: 'Mock subscription', renewsAt: '2026-12-01T00:00:00Z' }, source: 'provider-api', observedAt: '2026-11-16T12:00:00Z', windows: [
29
+ { id: 'five-hour', label: 'Five-hour window', unit: 'percent', usedPercent: 25, resetAt: '2026-11-16T17:00:00Z', scope: 'account' },
30
+ { id: 'monthly', label: 'Monthly cap', unit: 'credits', limit: '500', scope: 'account', nextRegenAt: '2026-11-17T00:00:00Z', nextRegenPercent: 10 },
31
+ ], balances: [{ id: 'payg', label: 'PAYG', amount: '-2.5', currency: 'USD', unit: 'money' }], notes: [] };
32
+ let auth = { attemptId: 'mock-attempt', status: 'pending', prompt: { id: 'code', kind: 'text', message: 'Paste authorization code', placeholder: 'code' } };
33
+ const server = createServer(async (req, res) => {
34
+ const pathname = new URL(req.url, 'http://localhost').pathname;
35
+ const json = (body, status = 200) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
36
+ try {
37
+ if (pathname.startsWith('/oauth/api/')) {
38
+ const chunks = []; for await (const chunk of req) chunks.push(chunk);
39
+ const raw = Buffer.concat(chunks).toString(); const body = raw ? JSON.parse(raw) : {};
40
+ calls.push({ pathname, body });
41
+ if (pathname.endsWith('/providers')) return json({ providers });
42
+ if (pathname.endsWith('/connect') || pathname.endsWith('/connection')) {
43
+ const item = providers.find((item) => item.id === body.provider);
44
+ assert.ok(item);
45
+ item.loggedIn = true; item.credentialConfigured = true;
46
+ if (body.billingAccess) item.billingCredentialConfigured = true;
47
+ item.connection = { ...item.connection, ...Object.fromEntries(Object.entries(body).filter(([key]) => !['provider', 'access', 'billingAccess'].includes(key))) };
48
+ return json({ ok: true });
49
+ }
50
+ if (pathname.endsWith('/models')) return json({ models });
51
+ if (pathname.endsWith('/pull')) {
52
+ const item = providers.find((item) => item.id === body.provider);
53
+ item.pulledModels = models.filter((item) => body.models.includes(item.id));
54
+ item.pullPermanent = body.expiresAt === null; item.pullExpiresAt = body.expiresAt;
55
+ return json({ models: item.pulledModels });
56
+ }
57
+ if (pathname.endsWith('/usage')) {
58
+ if (usageMode === 'failure') return json({ error: 'Mock usage service offline' }, 503);
59
+ if (usageMode === 'late') { lateUsage?.(); await new Promise((resolve) => { releaseLate = resolve; }); }
60
+ if (['needs-permission', 'needs-configuration', 'rate-limited', 'reauth-required'].includes(usageMode)) return json({ status: usageMode, message: 'Management key required', lastAttemptAt: new Date().toISOString() });
61
+ return json({ status: usageMode === 'partial' ? 'partial' : 'fresh', snapshot, lastAttemptAt: new Date().toISOString() });
62
+ }
63
+ if (pathname.endsWith('/import/sources')) return json({ sources: [
64
+ { id: 'codex', label: 'Codex CLI', available: true, providers: [{ provider: 'openai-codex', authType: 'oauth', available: true }] },
65
+ { id: 'opencode', label: 'OpenCode', available: false, providers: [{ provider: 'openai-codex', authType: 'oauth', available: false }] },
66
+ { id: 'agy', label: 'Antigravity CLI (agy)', available: false, providers: [{ provider: 'google-antigravity', authType: 'oauth', available: false, reasonCode: 'source-does-not-export-credentials' }] },
67
+ ] });
68
+ if (pathname.endsWith('/import')) return json({ ok: true });
69
+ if (pathname.endsWith('/logout')) { providers.find((item) => item.id === body.provider).loggedIn = false; return json({ ok: true }); }
70
+ if (pathname.endsWith('/login')) return json(auth);
71
+ if (pathname.endsWith('/login/status')) return json(auth);
72
+ if (pathname.endsWith('/login/answer')) { assert.equal(body.value, 'mock-authorization-input'); providers.find((item) => item.id === body.provider).loggedIn = true; auth = { attemptId: 'mock-attempt', status: 'authorized' }; return json(auth); }
73
+ if (pathname.endsWith('/login/cancel')) { auth = { ...auth, status: 'cancelled' }; return json(auth); }
74
+ return json({ error: 'Unexpected mock API route' }, 404);
75
+ }
76
+ const name = pathname.replace(/^\/oauth\/?|^\//, '') || 'index.html';
77
+ if (!['index.html', 'app.js', 'styles.css', 'providers.js', 'theme.js', 'auth.html'].includes(name)) { res.writeHead(404); res.end(); return; }
78
+ res.writeHead(200, { 'content-type': name.endsWith('.html') ? 'text/html' : name.endsWith('.css') ? 'text/css' : 'text/javascript' });
79
+ res.end(await readFile(join(root, name)));
80
+ } catch (error) { json({ error: error.message }, 500); }
81
+ });
82
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
83
+ const origin = `http://127.0.0.1:${server.address().port}`;
84
+ const browser = await playwright.chromium.launch({ headless: true });
85
+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, reducedMotion: 'reduce' });
86
+ await context.route('**/*', (route) => {
87
+ if (route.request().url().startsWith(origin)) return route.continue();
88
+ blockedRequests.push(route.request().url()); return route.abort();
89
+ });
90
+ context.on('page', (page) => page.on('pageerror', (error) => pageErrors.push(error.message)));
91
+ const page = await context.newPage();
92
+ page.setDefaultTimeout(7000);
93
+ const row = (id) => page.locator(`[data-provider="${id}"]`);
94
+ try {
95
+ await page.goto(`${origin}/oauth/`);
96
+ await row('zenmux').getByRole('button', { name: '连接密钥', exact: true }).waitFor();
97
+ assert.equal(await page.locator('.nav').isVisible(), true);
98
+ assert.equal(await page.getByText('DO-NOT-DISPLAY-TOKEN').count(), 0);
99
+ assert.equal(calls.filter((item) => item.pathname.endsWith('/usage')).length, 0);
100
+ completed.push('Original sidebar and rows retained; credentials hidden; no automatic quota calls');
101
+ assert.equal(await row('google-antigravity').getByRole('button', { name: '拉取模型', exact: true }).count(), 0);
102
+ await row('google-antigravity').getByText('可查询套餐用量;当前宿主尚未接入此来源的模型调用。', { exact: true }).waitFor();
103
+ await row('google-antigravity').getByRole('button', { name: '连接配置', exact: true }).click();
104
+ await page.getByRole('button', { name: '改用本机 CLI 管理的授权', exact: true }).click();
105
+ await page.getByText('AGY 通过系统钥匙串管理登录,暂无法在此导入。请在 agy 中输入 /usage 查看套餐用量。', { exact: true }).waitFor();
106
+ assert.equal(await page.locator('#local-source-agy').isDisabled(), true);
107
+ assert.equal(await page.getByRole('button', { name: '确认复用此来源', exact: true }).isDisabled(), true);
108
+ await page.getByRole('button', { name: '取消', exact: true }).click();
109
+ completed.push('AGY shows the system-keyring limitation and links the user to the CLI usage command');
110
+ await row('google-antigravity').getByRole('button', { name: '查看 AGY CLI 模型', exact: true }).click();
111
+ await page.getByRole('heading', { name: 'AGY CLI 模型目录' }).waitFor();
112
+ assert.ok(calls.some(item => item.pathname.endsWith('/models') && item.body.provider === 'google-antigravity' && item.body.source === 'agy'));
113
+ assert.equal(await page.locator('#confirm-pull').count(), 0);
114
+ await page.getByRole('button', { name: '关闭', exact: true }).click();
115
+
116
+ await row('qwen').getByRole('button', { name: '套餐与用量', exact: true }).click();
117
+ await row('qwen').getByText('此来源暂不提供用量', { exact: true }).waitFor();
118
+ assert.equal(calls.filter((item) => item.pathname.endsWith('/usage')).length, 0);
119
+ completed.push('Google usage-only integration does not promise model access; unsupported usage makes no API request');
120
+
121
+ await row('zenmux').getByRole('button', { name: '连接密钥', exact: true }).click();
122
+ await page.locator('#connection-access').fill('mock-inference-secret');
123
+ await page.locator('#connection-billing').fill('mock-management-secret');
124
+ await page.locator('#connection-label').fill('My subscription');
125
+ assert.equal(await page.locator('#connection-access').getAttribute('type'), 'password');
126
+ await page.locator('[data-modal-locale]').selectOption('en');
127
+ assert.equal(await page.locator('#connection-access').inputValue(), 'mock-inference-secret');
128
+ assert.equal(await page.locator('#connection-label').inputValue(), 'My subscription');
129
+ assert.ok(!(await page.evaluate(() => JSON.stringify(localStorage))).includes('mock-inference-secret'));
130
+ await page.getByRole('button', { name: 'Save and connect', exact: true }).click();
131
+ await row('zenmux').getByText('Connected', { exact: true }).waitFor();
132
+ assert.equal(calls.find((item) => item.pathname.endsWith('/connect')).body.billingAccess, 'mock-management-secret');
133
+ assert.equal(await page.locator('#connection-access').count(), 0);
134
+ completed.push('Key connection and distinct billing credential; locale preserves draft without persistence');
135
+
136
+ await row('zenmux').getByRole('button', { name: 'Connection settings', exact: true }).click();
137
+ assert.equal(await page.locator('#connection-access').count(), 0);
138
+ assert.equal(await page.locator('#connection-billing').inputValue(), '');
139
+ await page.getByRole('button', { name: 'Save settings', exact: true }).click();
140
+ await page.locator('#modal').waitFor({ state: 'hidden' });
141
+ assert.deepEqual(calls.find((item) => item.pathname.endsWith('/connection')).body, { provider: 'zenmux' });
142
+ completed.push('Saved authorization never echoed; blank billing field retains existing credential');
143
+ for (const region of ['cn', 'global']) {
144
+ await row('zenmux').getByRole('button', { name: 'Connection settings', exact: true }).click();
145
+ if (!(await page.locator('#connection-region').isVisible())) await page.locator('.scope-fields summary').click();
146
+ await page.locator('#connection-region').selectOption(region);
147
+ await page.getByRole('button', { name: 'Save settings', exact: true }).click();
148
+ await page.locator('#modal').waitFor({ state: 'hidden' });
149
+ assert.equal(calls.filter((item) => item.pathname.endsWith('/connection')).at(-1).body.region, region);
150
+ }
151
+ completed.push('Region changes use global/cn and can return to the global default without sending an empty region');
152
+
153
+ await row('zenmux').getByRole('button', { name: 'Fetch models', exact: true }).click();
154
+ await page.locator('.model-capabilities').getByText(/Tools supported/).waitFor();
155
+ await page.locator('.model-capabilities').getByText(/Reasoning: low \/ high/).waitFor();
156
+ await page.locator('.model-capabilities').getByText(/Plan entitlement unconfirmed/).waitFor();
157
+ assert.equal(await page.locator('#modal img').count(), 0);
158
+ assert.equal(await page.locator('#pull-permanent').isChecked(), true);
159
+ await page.getByRole('button', { name: 'Select all / clear', exact: true }).click();
160
+ assert.equal(await page.locator('.choice input').isChecked(), false);
161
+ await page.getByRole('button', { name: 'Save selected models', exact: true }).click();
162
+ await page.getByText('Select at least one chat model.', { exact: true }).waitFor();
163
+ await page.getByRole('button', { name: 'Select all / clear', exact: true }).click();
164
+ models[0].name = 'Mock reasoning model';
165
+ await page.getByRole('button', { name: 'Save selected models', exact: true }).click();
166
+ await row('zenmux').getByText('Models stay enabled', { exact: true }).waitFor();
167
+ assert.equal(calls.find((item) => item.pathname.endsWith('/pull')).body.expiresAt, null);
168
+ completed.push('Capabilities and entitlement provenance; malicious model name escaped; single-model selection; permanent default');
169
+
170
+ await row('zenmux').getByRole('button', { name: 'Fetch models', exact: true }).click();
171
+ await page.locator('#pull-title').waitFor();
172
+ await page.locator('#toast').waitFor({ state: 'hidden', timeout: 4000 });
173
+ await page.screenshot({ path: join(outDir, 'models-en.png') });
174
+ await page.locator('#pull-until').check();
175
+ await page.locator('#pull-expiry').fill('2030-01-01T12:00');
176
+ await page.getByRole('button', { name: 'Save selected models', exact: true }).click();
177
+ await page.getByText('Choose an expiry date within the next 366 days.', { exact: true }).waitFor();
178
+ await page.getByRole('button', { name: '7 days', exact: true }).click();
179
+ assert.equal(await page.locator('#pull-until').isChecked(), true);
180
+ await page.locator('[data-modal-locale]').selectOption('zh');
181
+ assert.equal(await page.locator('#pull-until').isChecked(), true);
182
+ assert.equal(await page.locator('.choice input').isChecked(), true);
183
+ await page.getByRole('button', { name: '写入所选模型', exact: true }).click();
184
+ await page.locator('#modal').waitFor({ state: 'hidden' });
185
+ assert.ok(calls.filter((item) => item.pathname.endsWith('/pull')).at(-1).body.expiresAt > Date.now());
186
+ await row('zenmux').getByRole('button', { name: '拉取模型', exact: true }).click();
187
+ assert.equal(await page.locator('#pull-until').isChecked(), true);
188
+ await page.keyboard.press('Escape');
189
+ completed.push('Optional expiry remains selectable, survives locale change and reopening');
190
+
191
+ await row('zenmux').getByRole('button', { name: '套餐与用量', exact: true }).click();
192
+ await row('zenmux').getByText('Mock subscription', { exact: true }).waitFor();
193
+ assert.equal(await row('zenmux').getByRole('meter').count(), 1);
194
+ await row('zenmux').getByText('用量比例未知', { exact: true }).waitFor();
195
+ await row('zenmux').getByText('-2.5 USD', { exact: false }).waitFor();
196
+ await row('zenmux').getByText(/下次部分恢复/).waitFor();
197
+ await row('zenmux').getByText(/provider-api/).waitFor();
198
+ completed.push('Real quota windows, unknown percentages, signed balances, partial recovery and timestamp/source');
199
+
200
+ usageMode = 'failure';
201
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
202
+ await row('zenmux').getByText('上次成功数据 · 本次更新失败', { exact: true }).waitFor();
203
+ assert.equal(await row('zenmux').getByRole('meter').count(), 1);
204
+ completed.push('Transient usage failure preserves a clearly stale last-good snapshot');
205
+ await page.locator('#toast').waitFor({ state: 'hidden', timeout: 4000 });
206
+ await page.screenshot({ path: join(outDir, 'subscriptions-zh-desktop.png'), fullPage: true });
207
+
208
+ usageMode = 'needs-permission';
209
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
210
+ await row('zenmux').getByText('需要查询权限', { exact: true }).waitFor();
211
+ assert.equal(await row('zenmux').getByRole('meter').count(), 0);
212
+ assert.equal(await row('zenmux').getByText('已连接', { exact: true }).count(), 1);
213
+ completed.push('Usage permission failure does not claim disconnected or exhausted');
214
+ usageMode = 'needs-configuration';
215
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
216
+ await row('zenmux').getByText('需要补充查询配置', { exact: true }).waitFor();
217
+ await row('zenmux').getByText(/请在「连接配置」中补充查询授权/).waitFor();
218
+ assert.equal(await row('zenmux').getByRole('meter').count(), 0);
219
+ usageMode = 'partial';
220
+ snapshot.notes = ['subscription-split-and-reset-not-provided'];
221
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
222
+ await row('zenmux').getByText('部分数据可用', { exact: true }).waitFor();
223
+ await row('zenmux').getByText('未提供订阅与充值分项或重置时间。', { exact: true }).waitFor();
224
+ assert.equal(await row('zenmux').getByRole('meter').count(), 1);
225
+ snapshot.notes = [];
226
+ completed.push('Missing query configuration remains actionable; partial quota data retains known values and translated limitations');
227
+
228
+ await row('openai-codex').getByRole('button', { name: '连接配置', exact: true }).click();
229
+ await page.getByRole('button', { name: '改用本机 CLI 管理的授权', exact: true }).click();
230
+ await page.getByText('Codex CLI', { exact: true }).waitFor();
231
+ assert.equal(await page.locator('input[name="source"][value="opencode"]').isDisabled(), true);
232
+ await page.locator('input[name="source"][value="codex"]').check();
233
+ await page.getByRole('button', { name: '确认复用此来源', exact: true }).click();
234
+ await page.locator('#modal').waitFor({ state: 'hidden' });
235
+ assert.deepEqual(calls.find((item) => item.pathname.endsWith('/import')).body, { source: 'codex', provider: 'openai-codex' });
236
+ completed.push('Fixed local CLI sources reflect actual availability and selected provider');
237
+
238
+ await row('anthropic').getByRole('button', { name: '登录', exact: true }).click();
239
+ await page.locator('#authorization-answer').fill('mock-authorization-input');
240
+ await page.locator('[data-modal-locale]').selectOption('en');
241
+ assert.equal(await page.locator('#authorization-answer').inputValue(), 'mock-authorization-input');
242
+ await page.getByRole('button', { name: 'Submit authorization input', exact: true }).click();
243
+ await row('anthropic').getByText('Connected', { exact: true }).waitFor();
244
+ completed.push('Existing OAuth manual-input flow survives locale switch and confirms local credentials');
245
+
246
+ usageMode = 'fresh';
247
+ await row('zenmux').getByRole('button', { name: 'Refresh usage', exact: true }).click();
248
+ await row('zenmux').getByText('Updated', { exact: true }).waitFor();
249
+ await page.locator('#toast').waitFor({ state: 'hidden', timeout: 4000 });
250
+ await page.screenshot({ path: join(outDir, 'subscriptions-en-desktop.png'), fullPage: true });
251
+ for (const width of [390, 320]) {
252
+ await page.setViewportSize({ width, height: 844 });
253
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true);
254
+ await row('zenmux').getByRole('button', { name: 'Connection settings', exact: true }).click();
255
+ await page.keyboard.press('Tab');
256
+ assert.equal(await page.evaluate(() => document.querySelector('#modal').contains(document.activeElement)), true);
257
+ for (let i = 0; i < 14; i++) await page.keyboard.press('Tab');
258
+ assert.equal(await page.evaluate(() => document.querySelector('#modal').contains(document.activeElement)), true);
259
+ await page.screenshot({ path: join(outDir, `connection-en-${width}.png`) });
260
+ await page.keyboard.press('Escape');
261
+ assert.equal(await page.locator('#modal').isHidden(), true);
262
+ await page.screenshot({ path: join(outDir, `subscriptions-en-${width}.png`), fullPage: true });
263
+ }
264
+ await page.locator('#locale').selectOption('zh');
265
+ await page.setViewportSize({ width: 390, height: 844 });
266
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true);
267
+ await page.screenshot({ path: join(outDir, 'subscriptions-zh-390.png'), fullPage: true });
268
+ await row('zenmux').getByRole('button', { name: '连接配置', exact: true }).click();
269
+ await page.screenshot({ path: join(outDir, 'connection-zh-390.png') });
270
+ await page.keyboard.press('Escape');
271
+ await page.locator('#locale').selectOption('en');
272
+ completed.push('390px and 320px layouts in both locales; modal focus trap, Escape and reduced-motion environment');
273
+
274
+ await page.reload();
275
+ await page.getByText('OAuth authentication', { exact: true }).waitFor();
276
+ assert.equal(await page.locator('#locale').inputValue(), 'en');
277
+ completed.push('Locale preference persists independently of authorization');
278
+
279
+ await row('new-api').getByRole('button', { name: 'Connect key', exact: true }).click();
280
+ await page.locator('#connection-access').fill('mock-custom-gateway-key');
281
+ await page.locator('#connection-baseURL').fill('http://api.example.test/v1');
282
+ await page.getByRole('button', { name: 'Save and connect', exact: true }).click();
283
+ await page.getByText('Enter an HTTPS API URL without credentials, query parameters or a fragment.', { exact: true }).waitFor();
284
+ await page.locator('#connection-baseURL').fill('https://api.example.test/v1');
285
+ await page.getByRole('button', { name: 'Save and connect', exact: true }).click();
286
+ await row('new-api').getByText('Connected', { exact: true }).waitFor();
287
+ assert.equal(calls.filter((call) => call.pathname.endsWith('/connect')).at(-1).body.baseURL, 'https://api.example.test/v1');
288
+ completed.push('New API requires explicit HTTPS API root and stores it only for that provider');
289
+
290
+ const startPage = await context.newPage();
291
+ await startPage.goto(`${origin}/oauth/auth.html?provider=anthropic&locale=en`);
292
+ await startPage.getByText('Starting Claude Pro/Max sign-in', { exact: true }).waitFor();
293
+ await startPage.close();
294
+ completed.push('Authorization startup page follows selected locale');
295
+
296
+ await page.setViewportSize({ width: 1280, height: 900 });
297
+ usageMode = 'late';
298
+ const waiting = new Promise((resolve) => { lateUsage = resolve; });
299
+ await row('zenmux').getByRole('button', { name: 'Plan & usage', exact: true }).click();
300
+ await waiting;
301
+ await row('zenmux').getByRole('button', { name: 'Disconnect', exact: true }).click();
302
+ await page.getByText(/same shared credential/).waitFor();
303
+ await page.locator('#confirm-disconnect').click();
304
+ await row('zenmux').getByRole('button', { name: 'Connect key', exact: true }).waitFor();
305
+ releaseLate();
306
+ await page.waitForTimeout(120);
307
+ assert.equal(await row('zenmux').locator('[data-usage-panel]').count(), 0);
308
+ completed.push('Late quota response cannot restore data after disconnect; shared credential impact is explicit');
309
+
310
+ const stored = await page.evaluate(() => JSON.stringify(localStorage));
311
+ assert.ok(!stored.includes('mock-management-secret') && !stored.includes('mock-inference-secret'));
312
+ assert.ok(!calls.some((call) => /chat\/completions|generate|messages/.test(call.pathname)));
313
+ assert.deepEqual(pageErrors, []);
314
+ assert.deepEqual(blockedRequests, []);
315
+ completed.push('No credential persistence in browser, no inference requests, no browser errors or external network');
316
+ await writeFile(join(outDir, 'report.json'), JSON.stringify({ passed: completed.length, completed, pageErrors, blockedRequests, endpoints: [...new Set(calls.map((call) => call.pathname))] }, null, 2));
317
+ process.stdout.write(JSON.stringify({ passed: completed.length, outDir, completed }, null, 2) + '\n');
318
+ } finally {
319
+ releaseLate?.();
320
+ await context.close(); await browser.close(); await new Promise((resolve) => server.close(resolve));
321
+ }
package/src/account.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * DeepSeek official-account calls for Harness 0.2.
3
+ * startSignIn and signOut take AccountClientMetadata, and the callback
4
+ * origin must be a loopback http URL with an explicit port.
5
+ */
6
+
7
+ const LOOPBACK = /^(?:localhost|127\.0\.0\.1|\[::1\])$/i;
8
+ const FALLBACK_VERSION = "0.2.0-rc.2";
9
+ const TERMINAL_FAILURE = new Set(["failed", "expired", "cancelled"]);
10
+
11
+ /**
12
+ * @param {unknown} value
13
+ * @returns {string | undefined}
14
+ */
15
+ function nonEmpty(value) {
16
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
17
+ }
18
+
19
+ /**
20
+ * @param {unknown} header
21
+ * @returns {string | undefined}
22
+ */
23
+ export function localeFromAcceptLanguage(header) {
24
+ if (typeof header !== "string") return undefined;
25
+ return nonEmpty(header.split(",")[0]?.split(";")[0]);
26
+ }
27
+
28
+ /**
29
+ * Identity the 0.2 account service puts on Platform request headers.
30
+ * @param {{ version?: string, locale?: string, timezoneOffsetSeconds?: number }} [input]
31
+ * @param {NodeJS.ProcessEnv} [env]
32
+ */
33
+ export function accountClientMetadata(input = {}, env = process.env) {
34
+ const offset = input.timezoneOffsetSeconds;
35
+ return {
36
+ version: nonEmpty(input.version) ?? nonEmpty(env.DSH_CLIENT_VERSION) ?? FALLBACK_VERSION,
37
+ locale: nonEmpty(input.locale) ?? "zh-CN",
38
+ timezoneOffsetSeconds: Number.isInteger(offset) ? offset : -new Date().getTimezoneOffset() * 60,
39
+ };
40
+ }
41
+
42
+ /**
43
+ * @param {import("node:http").IncomingMessage | { headers?: Record<string, unknown> } | undefined} req
44
+ * @param {NodeJS.ProcessEnv} [env]
45
+ */
46
+ export function accountClientFrom(req, env = process.env) {
47
+ const header = req?.headers?.["accept-language"];
48
+ return accountClientMetadata({ locale: localeFromAcceptLanguage(header) }, env);
49
+ }
50
+
51
+ /**
52
+ * Origin accepted by the account service's loginOrigin check.
53
+ * @param {unknown} host
54
+ * @returns {string}
55
+ */
56
+ export function loginCallbackOrigin(host) {
57
+ const raw = nonEmpty(host) ?? "127.0.0.1:19387";
58
+ let url;
59
+ try {
60
+ url = new URL(`http://${raw}`);
61
+ } catch {
62
+ throw new Error("登录回调地址必须是本机 http 端口");
63
+ }
64
+ const bare = url.hostname;
65
+ const hostname = bare.startsWith("[") ? bare : bare.includes(":") ? `[${bare}]` : bare;
66
+ if (!LOOPBACK.test(hostname) || url.port.length === 0 || Number(url.port) === 0 || url.username || url.password) {
67
+ throw new Error("登录回调地址必须是本机 http 端口");
68
+ }
69
+ return `http://${hostname}:${Number(url.port)}`;
70
+ }
71
+
72
+ /**
73
+ * Desktop listens on 19387. Any other loopback port is the web profile.
74
+ * @param {string} origin
75
+ */
76
+ export function loginSource(origin) {
77
+ return origin.endsWith(":19387") ? "desktop" : "web";
78
+ }
79
+
80
+ /**
81
+ * @param {unknown} phase
82
+ */
83
+ export function signInFailed(phase) {
84
+ return typeof phase === "string" && TERMINAL_FAILURE.has(phase);
85
+ }
@@ -0,0 +1,52 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import {
4
+ accountClientFrom,
5
+ accountClientMetadata,
6
+ localeFromAcceptLanguage,
7
+ loginCallbackOrigin,
8
+ loginSource,
9
+ signInFailed,
10
+ } from "./account.js";
11
+
12
+ test("account client metadata prefers the running harness version", () => {
13
+ assert.deepEqual(
14
+ accountClientMetadata(
15
+ { locale: "en", timezoneOffsetSeconds: -28_800 },
16
+ { DSH_CLIENT_VERSION: "0.2.0-rc.2" },
17
+ ),
18
+ { version: "0.2.0-rc.2", locale: "en", timezoneOffsetSeconds: -28_800 },
19
+ );
20
+ });
21
+
22
+ test("account client metadata falls back when the process has no client version", () => {
23
+ assert.equal(accountClientMetadata({}, {}).version, "0.2.0-rc.2");
24
+ assert.equal(accountClientMetadata({}, {}).locale, "zh-CN");
25
+ });
26
+
27
+ test("accept-language supplies the account locale", () => {
28
+ assert.equal(localeFromAcceptLanguage("en-US,en;q=0.8"), "en-US");
29
+ assert.deepEqual(
30
+ accountClientFrom({ headers: { "accept-language": "zh-CN,zh;q=0.9" } }, { DSH_CLIENT_VERSION: "0.2.0-rc.2" }),
31
+ { version: "0.2.0-rc.2", locale: "zh-CN", timezoneOffsetSeconds: accountClientMetadata().timezoneOffsetSeconds },
32
+ );
33
+ });
34
+
35
+ test("login callback origin is a loopback http URL with an explicit port", () => {
36
+ assert.equal(loginCallbackOrigin("127.0.0.1:19387"), "http://127.0.0.1:19387");
37
+ assert.equal(loginCallbackOrigin("localhost:3081"), "http://localhost:3081");
38
+ assert.equal(loginCallbackOrigin("[::1]:19387"), "http://[::1]:19387");
39
+ assert.equal(loginCallbackOrigin(""), "http://127.0.0.1:19387");
40
+ assert.equal(loginSource("http://127.0.0.1:19387"), "desktop");
41
+ assert.equal(loginSource("http://127.0.0.1:3081"), "web");
42
+ assert.throws(() => loginCallbackOrigin("example.com:19387"), /本机 http 端口/);
43
+ assert.throws(() => loginCallbackOrigin("127.0.0.1"), /本机 http 端口/);
44
+ });
45
+
46
+ test("cancelled, failed, and expired sign-in attempts stop the wait", () => {
47
+ assert.equal(signInFailed("failed"), true);
48
+ assert.equal(signInFailed("expired"), true);
49
+ assert.equal(signInFailed("cancelled"), true);
50
+ assert.equal(signInFailed("waiting-browser"), false);
51
+ assert.equal(signInFailed("succeeded"), false);
52
+ });