@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
package/src/catalog.js ADDED
@@ -0,0 +1,180 @@
1
+ import { isIP } from 'node:net';
2
+
3
+ // Fixed supplier endpoints verified against the official contracts recorded in
4
+ // the 2026-11-16 quota research. A model catalog is not a funding guarantee.
5
+ const bearerKey = Object.freeze({ header: 'Authorization', scheme: 'Bearer' });
6
+ const definitions = [
7
+ { id: 'openai-codex', name: 'ChatGPT / Codex', group: 'official', keyConnect: false,
8
+ baseURL: 'https://chatgpt.com/backend-api/codex',
9
+ modelsURL: 'https://chatgpt.com/backend-api/codex/models',
10
+ modelSource: 'account', entitlement: 'account', usageHosts: ['chatgpt.com'] },
11
+ { id: 'anthropic', name: 'Claude API', group: 'official', keyConnect: true, oauthConnect: false,
12
+ baseURL: 'https://api.anthropic.com', modelsURL: 'https://api.anthropic.com/v1/models?limit=1000',
13
+ modelHeaders: { 'anthropic-version': '2023-06-01' }, docs: 'https://platform.claude.com/docs/en/api/models/list',
14
+ modelSource: 'account', entitlement: 'account', usageHosts: [] },
15
+ { id: 'github-copilot', name: 'GitHub Copilot', group: 'official', keyConnect: false,
16
+ baseURL: 'https://api.individual.githubcopilot.com', modelsURL: 'https://api.individual.githubcopilot.com/models',
17
+ modelHeaders: { 'user-agent': 'GitHubCopilotChat/0.35.0', 'editor-version': 'vscode/1.107.0', 'editor-plugin-version': 'copilot-chat/0.35.0', 'copilot-integration-id': 'vscode-chat', 'x-github-api-version': '2026-06-01' },
18
+ modelSource: 'account', entitlement: 'account', usageHosts: ['api.github.com'] },
19
+ { id: 'kimi-coding', name: 'Kimi Code', group: 'official', keyConnect: true,
20
+ modelHeaders: { 'user-agent': 'KimiCLI/1.0' }, modelSource: 'account', entitlement: 'account',
21
+ regions: {
22
+ global: { baseURL: 'https://api.kimi.ai/coding/v1', modelsURL: 'https://api.kimi.ai/coding/v1/models', usageHosts: ['api.kimi.ai'] },
23
+ cn: { baseURL: 'https://api.kimi.com/coding/v1', modelsURL: 'https://api.kimi.com/coding/v1/models', usageHosts: ['api.kimi.com'] },
24
+ } },
25
+ { id: 'minimax', name: 'MiniMax', group: 'official', keyConnect: true,
26
+ modelSource: 'catalog', entitlement: 'unknown', reason: 'installed-catalog-only', api: 'anthropic-messages',
27
+ regions: {
28
+ global: { baseURL: 'https://api.minimax.io/anthropic', catalogProvider: 'minimax', usageHosts: ['api.minimax.io'] },
29
+ cn: { baseURL: 'https://api.minimaxi.com/anthropic', catalogProvider: 'minimax-cn', usageHosts: ['api.minimax.cn'] },
30
+ } },
31
+ { id: 'zai', name: 'Z.AI / GLM Coding Plan', group: 'official', keyConnect: true,
32
+ modelSource: 'catalog', entitlement: 'unknown', reason: 'installed-catalog-only',
33
+ regions: {
34
+ global: { baseURL: 'https://api.z.ai/api/coding/paas/v4', catalogProvider: 'zai', usageHosts: ['api.z.ai'] },
35
+ cn: { baseURL: 'https://open.bigmodel.cn/api/coding/paas/v4', catalogProvider: 'zai-coding-cn', usageHosts: ['bigmodel.cn'] },
36
+ } },
37
+ // https://help.aliyun.com/en/model-studio/base-url: new Token Plan and
38
+ // legacy Coding Plan use different keys and domains. Never use PAYG as fallback.
39
+ { id: 'aliyun-token-plan', name: 'Alibaba Cloud Token Plan', group: 'official', keyConnect: true,
40
+ modelSource: 'catalog', entitlement: 'unknown', reason: 'installed-catalog-only',
41
+ regions: {
42
+ cn: { baseURL: 'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1', catalogProvider: 'qwen-token-plan-cn', usageHosts: ['bailian-cs.console.aliyun.com'] },
43
+ global: { baseURL: 'https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1', catalogProvider: 'qwen-token-plan-individual', usageHosts: ['bailian-singapore-cs.alibabacloud.com'] },
44
+ } },
45
+ { id: 'google-antigravity', name: 'Google Antigravity', group: 'official', keyConnect: false,
46
+ modelSource: 'account', entitlement: 'unknown', usageHosts: ['daily-cloudcode-pa.googleapis.com'], reason: 'host-oauth-model-integration-unavailable',
47
+ docs: 'https://antigravity.google/docs/cli/commands/usage' },
48
+ { id: 'google-gemini-cli', name: 'Google Gemini CLI', group: 'official', keyConnect: false,
49
+ modelSource: 'account', entitlement: 'unknown', usageHosts: ['cloudcode-pa.googleapis.com'], reason: 'gemini-consumer-retired',
50
+ docs: 'https://developers.google.com/gemini-code-assist/docs/deprecations/code-assist-individuals' },
51
+ { id: 'xai', name: 'xAI Grok', group: 'official', keyConnect: false,
52
+ baseURL: 'https://cli-chat-proxy.grok.com/v1', modelsURL: 'https://cli-chat-proxy.grok.com/v1/models',
53
+ modelHeaders: { 'x-xai-token-auth': 'xai-grok-cli' }, modelSource: 'account', entitlement: 'account', usageHosts: ['cli-chat-proxy.grok.com'] },
54
+ // Authenticated /v1/models is the org's reachability allowlist in Hermes:
55
+ // NousResearch/hermes-agent@f8acc268.../hermes_cli/models_pricing.py.
56
+ { id: 'nous', name: 'Nous Portal', group: 'aggregator', keyConnect: true,
57
+ baseURL: 'https://inference-api.nousresearch.com/v1', modelsURL: 'https://inference-api.nousresearch.com/v1/models',
58
+ modelSource: 'account', entitlement: 'account', usageHosts: ['portal.nousresearch.com'], reason: 'usage-requires-portal-oauth' },
59
+ { id: 'qwen', name: 'Qwen Code subscription', group: 'official', keyConnect: false,
60
+ baseURL: 'https://api.qwen.ai/compatible-mode/v1', modelsURL: 'https://api.qwen.ai/compatible-mode/v1/models',
61
+ modelSource: 'account', entitlement: 'account', usageHosts: [], reason: 'qwen-legacy-oauth',
62
+ docs: 'https://help.aliyun.com/en/model-studio/qwen-code' },
63
+ { id: 'deepseek', name: 'DeepSeek API', group: 'official', keyConnect: true,
64
+ baseURL: 'https://api.deepseek.com', modelsURL: 'https://api.deepseek.com/models',
65
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: ['api.deepseek.com'] },
66
+ { id: 'openrouter', name: 'OpenRouter', group: 'aggregator', keyConnect: true,
67
+ baseURL: 'https://openrouter.ai/api/v1', modelsURL: 'https://openrouter.ai/api/v1/models/user',
68
+ modelSource: 'account', entitlement: 'account', usageHosts: ['openrouter.ai'] },
69
+ // NanoGPT's total /api/v1/models catalog is deliberately not substituted for
70
+ // the subscription-specific list, and inference uses the matching channel.
71
+ { id: 'nanogpt', name: 'NanoGPT', group: 'aggregator', keyConnect: true,
72
+ baseURL: 'https://api.nano-gpt.com/api/subscription/v1', modelsURL: 'https://api.nano-gpt.com/api/subscription/v1/models?detailed=true',
73
+ modelSource: 'catalog', entitlement: 'subscription', usageHosts: ['api.nano-gpt.com', 'nano-gpt.com'] },
74
+ { id: 'zenmux', name: 'ZenMux', group: 'aggregator', keyConnect: true,
75
+ baseURL: 'https://zenmux.ai/api/v1', modelsURL: 'https://zenmux.ai/api/v1/models',
76
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: ['zenmux.ai'] },
77
+ { id: 'opencode-go', name: 'OpenCode Go', group: 'aggregator', keyConnect: true,
78
+ baseURL: 'https://opencode.ai/inference/go/v1', modelsURL: 'https://opencode.ai/inference/go/v1/models',
79
+ modelSource: 'catalog', entitlement: 'subscription', usageHosts: ['opencode.ai'] },
80
+ { id: 'opencode-zen', name: 'OpenCode Console / Zen', group: 'aggregator', keyConnect: true,
81
+ baseURL: 'https://opencode.ai/inference/v1', modelsURL: 'https://opencode.ai/inference/v1/models',
82
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: ['opencode.ai'] },
83
+ { id: 'kilo', name: 'Kilo Gateway / Pass', group: 'aggregator', keyConnect: true,
84
+ baseURL: 'https://ai-gateway.kilo.ai/api/v1', modelsURL: 'https://ai-gateway.kilo.ai/api/v1/models',
85
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: ['app.kilo.ai'] },
86
+ { id: 'poe', name: 'Poe', group: 'aggregator', keyConnect: true,
87
+ baseURL: 'https://api.poe.com/v1', modelsURL: 'https://api.poe.com/v1/models',
88
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: ['api.poe.com'] },
89
+ { id: 'synthetic', name: 'Synthetic', group: 'aggregator', keyConnect: true,
90
+ baseURL: 'https://api.synthetic.new/openai/v1', modelsURL: 'https://api.synthetic.new/openai/v1/models',
91
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: ['api.synthetic.new'] },
92
+ { id: 'chutes', name: 'Chutes', group: 'aggregator', keyConnect: true,
93
+ baseURL: 'https://llm.chutes.ai/v1', modelsURL: 'https://llm.chutes.ai/v1/models',
94
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: ['api.chutes.ai'] },
95
+ { id: 'new-api', name: 'New API gateway', group: 'gateway', keyConnect: false,
96
+ modelSource: 'catalog', entitlement: 'unknown', usageHosts: [], reason: 'instance-url-required' },
97
+ ];
98
+
99
+ const byId = new Map(definitions.map(definition => [definition.id, definition]));
100
+ const safeScope = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined;
101
+
102
+ function gatewayBase(value) {
103
+ if (typeof value !== 'string' || value.length > 2048 || /\s/.test(value)) return undefined;
104
+ let url;
105
+ try { url = new URL(value); } catch { return undefined; }
106
+ const host = url.hostname.toLowerCase();
107
+ // A custom gateway must be an explicit public HTTPS instance. Local callback,
108
+ // metadata-service and LAN addresses are not automatic credential targets.
109
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.port && url.port !== '443'
110
+ || !host.includes('.') || host.endsWith('.') || host.endsWith('.localhost') || host.endsWith('.local')
111
+ || host.endsWith('.internal') || isIP(host.replace(/^\[|\]$/g, ''))) return undefined;
112
+ return url.toString().replace(/\/+$/, '');
113
+ }
114
+
115
+ /** Endpoint and capability metadata only. This function never handles secrets. */
116
+ export function getProviderDefinition(id, metadata = {}) {
117
+ const source = byId.get(id);
118
+ if (!source) return undefined;
119
+ metadata = metadata && typeof metadata === 'object' && !Array.isArray(metadata) ? metadata : {};
120
+ const { regions, ...base } = source;
121
+ const region = metadata.region ?? 'global';
122
+ const regional = regions && typeof region === 'string' && Object.hasOwn(regions, region) ? regions[region] : undefined;
123
+ const out = {
124
+ api: 'openai-completions', ...base, ...(regional ?? {}),
125
+ modelHeaders: { Accept: 'application/json', ...source.modelHeaders },
126
+ routeHeaders: {},
127
+ usageHosts: [...(regional?.usageHosts ?? source.usageHosts ?? [])],
128
+ ...(source.keyConnect ? { keyAuth: { ...bearerKey } } : {}),
129
+ };
130
+ if (regions) {
131
+ out.region = region;
132
+ out.regions = Object.keys(regions);
133
+ if (!regional) {
134
+ out.keyConnect = false;
135
+ delete out.baseURL; delete out.modelsURL;
136
+ out.usageHosts = [];
137
+ out.reason = 'unsupported-region';
138
+ }
139
+ }
140
+ if (id === 'openai-codex') {
141
+ out.api = 'openai-codex-responses';
142
+ const accountId = safeScope(metadata.accountId);
143
+ if (accountId) out.modelHeaders['chatgpt-account-id'] = accountId;
144
+ }
145
+ if (id === 'anthropic') out.api = 'anthropic-messages';
146
+ if (id === 'kimi-coding') out.routeHeaders['user-agent'] = 'KimiCLI/1.0';
147
+ if (out.api === 'anthropic-messages' && out.keyConnect) out.keyAuth = { header: 'x-api-key' };
148
+ if (id === 'opencode-go' || id === 'opencode-zen') {
149
+ const org = safeScope(metadata.workspaceId) || safeScope(metadata.organizationId);
150
+ if (org) { out.modelHeaders['x-opencode-org-id'] = org; out.routeHeaders['x-opencode-org-id'] = org; }
151
+ }
152
+ if (id === 'kilo') {
153
+ const org = safeScope(metadata.organizationId);
154
+ if (org) { out.modelHeaders['X-KiloCode-OrganizationId'] = org; out.routeHeaders['X-KiloCode-OrganizationId'] = org; }
155
+ }
156
+ if (id === 'new-api') {
157
+ const baseURL = gatewayBase(metadata.baseURL);
158
+ if (baseURL) {
159
+ out.baseURL = baseURL;
160
+ out.modelsURL = `${baseURL}/models`;
161
+ out.usageHosts = [new URL(baseURL).hostname];
162
+ out.keyConnect = true;
163
+ out.keyAuth = { ...bearerKey };
164
+ delete out.reason;
165
+ }
166
+ }
167
+ if (!out.keyConnect) delete out.keyAuth;
168
+ return out;
169
+ }
170
+
171
+ // Safe for UI enumeration: contains no tokens, imported config or mutable arrays.
172
+ export const providerDefinitions = Object.freeze(definitions.map(({ id }) => {
173
+ const row = getProviderDefinition(id);
174
+ Object.freeze(row.usageHosts);
175
+ Object.freeze(row.modelHeaders);
176
+ Object.freeze(row.routeHeaders);
177
+ if (row.keyAuth) Object.freeze(row.keyAuth);
178
+ if (row.regions) Object.freeze(row.regions);
179
+ return Object.freeze(row);
180
+ }));
@@ -0,0 +1,146 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { getProviderDefinition, providerDefinitions } from './catalog.js';
4
+ import { aggregatorUsageIds } from './usage/aggregators.js';
5
+ import { officialUsageIds } from './usage/official.js';
6
+ import { builtinModels } from '@earendil-works/pi-ai/providers/all';
7
+
8
+ test('catalog covers all quota adapters plus explicit model-only and gateway connections', () => {
9
+ const ids = providerDefinitions.map(row => row.id);
10
+ assert.equal(new Set(ids).size, ids.length);
11
+ for (const id of [...aggregatorUsageIds, ...officialUsageIds, 'qwen', 'deepseek', 'new-api']) assert.ok(ids.includes(id), id);
12
+ assert.equal(getProviderDefinition('__proto__'), undefined);
13
+ assert.equal(getProviderDefinition('unknown'), undefined);
14
+ });
15
+
16
+ test('fixed supplier endpoints ignore arbitrary metadata URL and request headers', () => {
17
+ for (const source of providerDefinitions.filter(row => row.id !== 'new-api')) {
18
+ const normal = getProviderDefinition(source.id);
19
+ const row = getProviderDefinition(source.id, { baseURL: 'https://evil.example', apiBase: 'https://evil.example', modelsURL: 'https://evil.example/models', requestHeaders: { Authorization: 'secret' }, access: 'secret', billingAccess: 'billing-secret' });
20
+ assert.equal(row.baseURL, normal.baseURL);
21
+ assert.equal(row.modelsURL, normal.modelsURL);
22
+ assert.deepEqual(row.usageHosts, normal.usageHosts);
23
+ assert.equal(JSON.stringify(row).includes('secret'), false);
24
+ }
25
+ });
26
+
27
+ test('region-bound endpoints and usage hosts stay paired without cross-region probing', () => {
28
+ for (const id of ['kimi-coding', 'minimax', 'zai', 'aliyun-token-plan']) {
29
+ const cn = getProviderDefinition(id, { region: 'cn' });
30
+ const global = getProviderDefinition(id, { region: 'global' });
31
+ assert.notEqual(cn.baseURL, global.baseURL, id);
32
+ assert.notDeepEqual(cn.usageHosts, global.usageHosts, id);
33
+ for (const region of ['moon', '__proto__', 'constructor']) {
34
+ const invalid = getProviderDefinition(id, { region });
35
+ assert.equal(invalid.keyConnect, false);
36
+ assert.equal(invalid.baseURL, undefined);
37
+ assert.equal(invalid.modelsURL, undefined);
38
+ assert.deepEqual(invalid.usageHosts, []);
39
+ }
40
+ }
41
+ assert.equal(getProviderDefinition('kimi-coding', { region: 'cn' }).modelsURL, 'https://api.kimi.com/coding/v1/models');
42
+ assert.equal(getProviderDefinition('kimi-coding', { region: 'global' }).modelsURL, 'https://api.kimi.ai/coding/v1/models');
43
+ });
44
+
45
+ test('unverified model listing and unsupported Google login are explicit', () => {
46
+ for (const id of ['minimax', 'zai', 'aliyun-token-plan']) {
47
+ const row = getProviderDefinition(id, { region: 'cn' });
48
+ assert.equal(row.modelsURL, undefined);
49
+ assert.equal(row.reason, 'installed-catalog-only');
50
+ assert.ok(row.catalogProvider);
51
+ assert.equal(row.entitlement, 'unknown');
52
+ }
53
+ for (const id of ['google-antigravity', 'google-gemini-cli']) {
54
+ const row = getProviderDefinition(id);
55
+ assert.equal(row.keyConnect, false);
56
+ assert.equal(row.modelsURL, undefined);
57
+ assert.equal(row.reason, id === 'google-gemini-cli' ? 'gemini-consumer-retired' : 'host-oauth-model-integration-unavailable');
58
+ }
59
+ const internationalAli = getProviderDefinition('aliyun-token-plan');
60
+ assert.equal(internationalAli.keyConnect, true);
61
+ assert.equal(internationalAli.baseURL, 'https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1');
62
+ assert.equal(internationalAli.catalogProvider, 'qwen-token-plan-individual');
63
+ });
64
+
65
+ test('installed catalog mappings use the actual provider protocol and base URL', () => {
66
+ const catalog = builtinModels();
67
+ for (const id of ['minimax', 'zai', 'aliyun-token-plan']) for (const region of ['cn', 'global']) {
68
+ const definition = getProviderDefinition(id, { region });
69
+ const installed = catalog.getProvider(definition.catalogProvider);
70
+ assert.ok(installed, definition.catalogProvider);
71
+ assert.equal(definition.baseURL, installed.baseUrl);
72
+ const models = catalog.getModels(definition.catalogProvider);
73
+ assert.ok(models.length > 0);
74
+ assert.ok(models.every(model => model.api === definition.api), `${id}/${region} protocol`);
75
+ assert.equal(definition.entitlement, 'unknown');
76
+ }
77
+ assert.equal(getProviderDefinition('aliyun-token-plan', { region: 'global', planKind: 'team' }).catalogProvider, 'qwen-token-plan-individual');
78
+ assert.equal(getProviderDefinition('minimax').keyAuth.header, 'x-api-key');
79
+ });
80
+
81
+ test('subscription, account-filtered and public catalogs preserve different entitlements', () => {
82
+ const openrouter = getProviderDefinition('openrouter');
83
+ assert.equal(openrouter.modelsURL, 'https://openrouter.ai/api/v1/models/user');
84
+ assert.equal(openrouter.modelSource, 'account');
85
+ const nano = getProviderDefinition('nanogpt');
86
+ assert.equal(nano.entitlement, 'subscription');
87
+ assert.equal(nano.baseURL, 'https://api.nano-gpt.com/api/subscription/v1');
88
+ assert.equal(nano.modelsURL, 'https://api.nano-gpt.com/api/subscription/v1/models?detailed=true');
89
+ assert.equal(getProviderDefinition('nous').modelSource, 'account');
90
+ for (const id of ['zenmux', 'poe', 'kilo', 'synthetic', 'chutes']) {
91
+ assert.equal(getProviderDefinition(id).modelSource, 'catalog');
92
+ assert.equal(getProviderDefinition(id).entitlement, 'unknown');
93
+ }
94
+ });
95
+
96
+ test('scope headers are explicitly selected and never copied from arbitrary metadata', () => {
97
+ assert.equal(getProviderDefinition('openai-codex', { accountId: 'account_123' }).modelHeaders['chatgpt-account-id'], 'account_123');
98
+ assert.equal(getProviderDefinition('kilo', { organizationId: 'org_123' }).modelHeaders['X-KiloCode-OrganizationId'], 'org_123');
99
+ assert.equal(getProviderDefinition('opencode-go', { workspaceId: 'workspace_1' }).modelHeaders['x-opencode-org-id'], 'workspace_1');
100
+ assert.equal(getProviderDefinition('opencode-go', { workspaceId: 'workspace_1' }).routeHeaders['x-opencode-org-id'], 'workspace_1');
101
+ assert.equal(getProviderDefinition('kilo', { organizationId: 'org_123' }).routeHeaders['X-KiloCode-OrganizationId'], 'org_123');
102
+ assert.equal(getProviderDefinition('kimi-coding').routeHeaders['user-agent'], 'KimiCLI/1.0');
103
+ assert.equal(getProviderDefinition('openai-codex', { accountId: 'value\nheader' }).modelHeaders['chatgpt-account-id'], undefined);
104
+ assert.equal(getProviderDefinition('kilo', { organizationId: 'value\nheader' }).modelHeaders['X-KiloCode-OrganizationId'], undefined);
105
+ });
106
+
107
+ test('definitions and independent resolutions cannot mutate shared policy', () => {
108
+ assert.equal(Object.isFrozen(providerDefinitions), true);
109
+ assert.equal(Object.isFrozen(providerDefinitions[0].usageHosts), true);
110
+ const first = getProviderDefinition('kimi-coding', { region: 'cn' });
111
+ first.usageHosts.push('evil.example');
112
+ first.modelHeaders.Accept = 'text/plain';
113
+ first.keyAuth.header = 'Cookie';
114
+ const second = getProviderDefinition('kimi-coding', { region: 'cn' });
115
+ assert.deepEqual(second.usageHosts, ['api.kimi.com']);
116
+ assert.equal(second.modelHeaders.Accept, 'application/json');
117
+ assert.equal(second.keyAuth.header, 'Authorization');
118
+ });
119
+
120
+ test('custom gateway is opt-in, issuer-bound and requires an explicit public HTTPS base', () => {
121
+ assert.equal(getProviderDefinition('new-api').keyConnect, false);
122
+ for (const baseURL of ['http://gateway.example/v1', 'https://user:secret@gateway.example/v1', 'https://gateway.example/v1?key=secret', 'https://gateway.example/v1#secret', 'https://localhost/v1', 'https://127.0.0.1/v1', 'https://[::1]/v1', 'https://169.254.169.254/v1', 'https://service.internal/v1', 'https://service.local/v1', 'https://gateway.example:444/v1']) {
123
+ const row = getProviderDefinition('new-api', { baseURL });
124
+ assert.equal(row.keyConnect, false, baseURL);
125
+ assert.equal(row.modelsURL, undefined);
126
+ assert.deepEqual(row.usageHosts, []);
127
+ }
128
+ const row = getProviderDefinition('new-api', { baseURL: 'https://gateway.example/v1/' });
129
+ assert.equal(row.keyConnect, true);
130
+ assert.equal(row.baseURL, 'https://gateway.example/v1');
131
+ assert.equal(row.modelsURL, 'https://gateway.example/v1/models');
132
+ assert.deepEqual(row.usageHosts, ['gateway.example']);
133
+ assert.equal(row.entitlement, 'unknown');
134
+ });
135
+
136
+ test('all built-in URLs are HTTPS and never include credentials or mutable caller domains', () => {
137
+ for (const row of providerDefinitions) {
138
+ for (const value of [row.baseURL, row.modelsURL].filter(Boolean)) {
139
+ const url = new URL(value);
140
+ assert.equal(url.protocol, 'https:');
141
+ assert.equal(url.username, '');
142
+ assert.equal(url.password, '');
143
+ }
144
+ for (const host of row.usageHosts) assert.match(host, /^[a-z0-9.-]+$/);
145
+ }
146
+ });
@@ -0,0 +1,110 @@
1
+ /** Recover one explicitly rejected xAI OAuth chat attempt through public DSH events. */
2
+ import { OAuthRequestError } from "./request-errors.js";
3
+
4
+ const usableGrant = (grant) => grant?.type === "oauth" && typeof grant.access === "string" && grant.access.length > 0 &&
5
+ typeof grant.refresh === "string" && grant.refresh.length > 0;
6
+
7
+ function authenticationRejected(failure) {
8
+ if (!failure || failure.code === "ABORTED") return false;
9
+ if (failure.status === 401) return true;
10
+ // pi-ai exposes this provider/status prefix after normalizing an SDK error.
11
+ // A number or credential-related word elsewhere in the body is insufficient.
12
+ const match = /^xai API error \((401|403)\):\s?([\s\S]*)$/.exec(failure.message ?? "");
13
+ return match !== null && new OAuthRequestError("xai", Number(match[1]), match[2]).authenticationRejected;
14
+ }
15
+
16
+ /**
17
+ * Observe a grant before a normal loop request, then refresh it at most once per
18
+ * agent/turn/step. This is a pre-request observation, not proof of the credential
19
+ * pi-ai subsequently selected; resolveGrant compares it again under the store
20
+ * lock so an intervening refresh is reused rather than rotated a second time.
21
+ */
22
+ export function registerChatRecovery(ctx, resolveGrant) {
23
+ const steps = new WeakMap();
24
+ const active = new Map();
25
+ const removers = [];
26
+ let disposed = false;
27
+
28
+ const oauthRoute = () => {
29
+ try {
30
+ const row = ctx.settings.describe({ redactSecrets: false }).find((entry) => entry.ns === "llm-pi-ai");
31
+ const route = row?.value?.providers?.xai;
32
+ return route !== null && typeof route === "object" && route.apiKeyEnv === undefined;
33
+ } catch { return false; }
34
+ };
35
+ const clearAgent = (agent) => {
36
+ const id = agent?.session?.id;
37
+ if (active.get(id)?.agent === agent) active.delete(id);
38
+ if (agent && typeof agent === "object") steps.delete(agent);
39
+ };
40
+
41
+ removers.push(ctx.on("agent/request", async (payload, next) => {
42
+ const config = await next();
43
+ const { agent, turn, step, signal } = payload;
44
+ const id = agent?.session?.id;
45
+ if (disposed || !agent || typeof agent !== "object" || typeof id !== "string" || !signal || signal.aborted ||
46
+ config?.provider !== "xai" || !oauthRoute()) {
47
+ if (active.get(id)?.agent === agent) active.delete(id);
48
+ return config;
49
+ }
50
+ let state = steps.get(agent);
51
+ if (!state || state.turn !== turn || state.step !== step || state.signal !== signal) {
52
+ state = { turn, step, signal, recovered: false };
53
+ steps.set(agent, state);
54
+ }
55
+ active.set(id, { agent, state, started: false, observed: undefined });
56
+ return config;
57
+ }));
58
+
59
+ removers.push(ctx.on("llm/stream", (options, next) => {
60
+ const entry = active.get(options.sessionId);
61
+ if (disposed || options.provider !== "xai" || options.purpose !== undefined ||
62
+ !entry || entry.started || options.signal !== entry.state.signal || options.signal?.aborted || !oauthRoute()) return next();
63
+ entry.started = true;
64
+ return (async function* () {
65
+ try {
66
+ const observed = await resolveGrant("xai");
67
+ if (!disposed && active.get(options.sessionId) === entry && !options.signal.aborted && oauthRoute() && usableGrant(observed)) {
68
+ entry.observed = observed;
69
+ }
70
+ } catch {
71
+ // The host retains ownership of an unconfigured/failed auth request.
72
+ // Do not replace its stream or force a refresh without an observation.
73
+ }
74
+ if (disposed || options.signal.aborted) return;
75
+ yield* next();
76
+ })();
77
+ }));
78
+
79
+ removers.push(ctx.on("agent/request-error", async (payload, next) => {
80
+ if (disposed) return;
81
+ const { agent, turn, step, provider, signal, failure } = payload;
82
+ const entry = active.get(agent?.session?.id);
83
+ if (provider !== "xai" || !entry || entry.agent !== agent || entry.state.turn !== turn || entry.state.step !== step ||
84
+ entry.state.signal !== signal || !usableGrant(entry.observed) || !oauthRoute() || !authenticationRejected(failure) || entry.state.recovered) return next();
85
+ if (signal.aborted) return;
86
+ entry.state.recovered = true;
87
+ const observed = entry.observed;
88
+ entry.observed = undefined;
89
+ try {
90
+ await resolveGrant("xai", { rejectedGrant: observed });
91
+ } catch {
92
+ if (disposed || signal.aborted) return;
93
+ ctx.logger?.warn("dsh-oauth: xAI chat OAuth recovery failed; stored authorization was retained");
94
+ return next();
95
+ }
96
+ if (disposed || signal.aborted) return;
97
+ return { kind: "retry" };
98
+ }));
99
+
100
+ removers.push(ctx.on("agent/status", ({ agent, status }) => { if (status === "idle") clearAgent(agent); }));
101
+ removers.push(ctx.on("agent/disposed", ({ agent }) => clearAgent(agent)));
102
+ const dispose = () => {
103
+ if (disposed) return;
104
+ disposed = true;
105
+ active.clear();
106
+ for (const remove of removers.splice(0)) remove();
107
+ };
108
+ removers.push(ctx.on("dispose", dispose));
109
+ return dispose;
110
+ }