dsh-coding-subscription-oauth 0.5.7 → 0.6.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.
Files changed (141) hide show
  1. package/CHANGELOG.md +211 -182
  2. package/CONTRIBUTING.md +120 -109
  3. package/INSTALL.md +240 -209
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +298 -293
  7. package/README.es.md +299 -294
  8. package/README.fr.md +299 -294
  9. package/README.ja.md +299 -294
  10. package/README.ko.md +299 -294
  11. package/README.md +313 -306
  12. package/README.pt-BR.md +299 -294
  13. package/README.ru.md +299 -294
  14. package/README.zh-CN.md +311 -304
  15. package/compatibility/dsh-bom.json +43 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +195 -195
  18. package/docs/02-architecture.md +134 -129
  19. package/docs/02-architecture.zh-CN.md +134 -129
  20. package/lib/auth-routes.d.ts +8 -15
  21. package/lib/auth-routes.d.ts.map +1 -1
  22. package/lib/bin.js +746 -1402
  23. package/lib/bin.js.map +4 -4
  24. package/lib/capability-routes.d.ts +3 -3
  25. package/lib/capability-routes.d.ts.map +1 -1
  26. package/lib/capability-settings.d.ts +5 -4
  27. package/lib/capability-settings.d.ts.map +1 -1
  28. package/lib/client.js +27 -8
  29. package/lib/client.js.map +4 -4
  30. package/lib/compatibility.d.ts +46 -0
  31. package/lib/compatibility.d.ts.map +1 -0
  32. package/lib/dsh-host-adapter.d.ts +18 -0
  33. package/lib/dsh-host-adapter.d.ts.map +1 -0
  34. package/lib/gateway-auth.d.ts +1 -2
  35. package/lib/gateway-auth.d.ts.map +1 -1
  36. package/lib/gateway-routes.d.ts +3 -4
  37. package/lib/gateway-routes.d.ts.map +1 -1
  38. package/lib/gateway.d.ts +4 -0
  39. package/lib/gateway.d.ts.map +1 -1
  40. package/lib/ids.d.ts +3 -32
  41. package/lib/ids.d.ts.map +1 -1
  42. package/lib/imagine-routes.d.ts +2 -0
  43. package/lib/imagine-routes.d.ts.map +1 -1
  44. package/lib/index.d.ts +19 -4
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +26573 -1023
  47. package/lib/index.js.map +4 -4
  48. package/lib/invariant.js.map +1 -1
  49. package/lib/oauth-import-routes.d.ts +3 -4
  50. package/lib/oauth-import-routes.d.ts.map +1 -1
  51. package/lib/proxy.d.ts +3 -16
  52. package/lib/proxy.d.ts.map +1 -1
  53. package/lib/web-origin.d.ts +28 -4
  54. package/lib/web-origin.d.ts.map +1 -1
  55. package/lib/web-routes.d.ts.map +1 -1
  56. package/media/en/settings_accounts.png +0 -0
  57. package/media/en/settings_capabilities.png +0 -0
  58. package/media/en/settings_gateway.png +0 -0
  59. package/media/zh-CN/settings_accounts.png +0 -0
  60. package/media/zh-CN/settings_capabilities.png +0 -0
  61. package/media/zh-CN/settings_gateway.png +0 -0
  62. package/package.json +209 -172
  63. package/patches/dsh-agy@0.1.2.patch +25 -25
  64. package/scripts/release.mjs +186 -166
  65. package/scripts/smoke-deployed-routes.mjs +146 -146
  66. package/scripts/verify-deployed-catalog.mjs +87 -87
  67. package/src/adapter.ts +287 -287
  68. package/src/alias-adapter.ts +153 -153
  69. package/src/auth-routes.ts +921 -871
  70. package/src/auth.ts +67 -67
  71. package/src/bin.ts +350 -350
  72. package/src/capability-routes.ts +279 -275
  73. package/src/capability-runtime.ts +313 -313
  74. package/src/capability-settings.ts +658 -657
  75. package/src/capability-tools.ts +666 -666
  76. package/src/catalog.ts +271 -271
  77. package/src/client/GrokBuildSettings.tsx +770 -718
  78. package/src/client/api.ts +88 -88
  79. package/src/client/components/AboutTab.tsx +30 -20
  80. package/src/client/components/AccountsTab.tsx +241 -224
  81. package/src/client/components/Badge.tsx +33 -33
  82. package/src/client/components/CapabilitiesTab.tsx +265 -227
  83. package/src/client/components/CliPullPreview.tsx +116 -107
  84. package/src/client/components/CopyButton.tsx +57 -57
  85. package/src/client/components/GatewayTab.tsx +469 -364
  86. package/src/client/components/NoticeBanner.tsx +46 -46
  87. package/src/client/components/ProgressBar.tsx +53 -52
  88. package/src/client/components/ProviderCard.tsx +606 -502
  89. package/src/client/components/SettingsTabs.tsx +75 -75
  90. package/src/client/components/ToggleSwitch.tsx +71 -62
  91. package/src/client/constants.ts +224 -206
  92. package/src/client/display.ts +61 -61
  93. package/src/client/dshClientAdapter.ts +109 -0
  94. package/src/client/gatewaySnippets.ts +37 -36
  95. package/src/client/index.tsx +156 -37
  96. package/src/client/locales.ts +535 -487
  97. package/src/client/microStyles.ts +52 -33
  98. package/src/client/parsers.ts +396 -386
  99. package/src/client/styles.ts +325 -312
  100. package/src/client/types.ts +197 -185
  101. package/src/codex-http.ts +447 -447
  102. package/src/codex-images.ts +485 -485
  103. package/src/codex-model-capabilities.ts +320 -320
  104. package/src/codex-search.ts +245 -245
  105. package/src/codex-usage.ts +263 -263
  106. package/src/compatibility.ts +55 -0
  107. package/src/dsh-host-adapter.ts +171 -0
  108. package/src/gateway-anthropic-messages.ts +84 -84
  109. package/src/gateway-auth.ts +102 -100
  110. package/src/gateway-backend.ts +274 -274
  111. package/src/gateway-body.ts +49 -49
  112. package/src/gateway-config.ts +76 -76
  113. package/src/gateway-http.ts +104 -104
  114. package/src/gateway-openai-chat.ts +124 -124
  115. package/src/gateway-openai-responses.ts +53 -53
  116. package/src/gateway-parse.ts +224 -224
  117. package/src/gateway-protocol.ts +52 -52
  118. package/src/gateway-routes.ts +158 -152
  119. package/src/gateway.ts +258 -242
  120. package/src/grok-errors.ts +24 -24
  121. package/src/grok-imagine.ts +1627 -1627
  122. package/src/grok-import.ts +151 -151
  123. package/src/http-json.ts +82 -82
  124. package/src/ids.ts +59 -45
  125. package/src/imagine-routes.ts +463 -461
  126. package/src/index.ts +748 -598
  127. package/src/invariant.ts +17 -17
  128. package/src/kimi-errors.ts +26 -26
  129. package/src/media-store.ts +927 -927
  130. package/src/oauth-import-routes.ts +324 -314
  131. package/src/oauth-providers.ts +152 -152
  132. package/src/oauth-session.ts +183 -183
  133. package/src/oauth-sources.ts +1104 -1104
  134. package/src/oauth.ts +620 -620
  135. package/src/provider.ts +128 -128
  136. package/src/proxy.ts +11 -99
  137. package/src/redact.ts +72 -72
  138. package/src/session.ts +218 -218
  139. package/src/store.ts +217 -217
  140. package/src/web-origin.ts +296 -60
  141. package/src/web-routes.ts +38 -75
@@ -1,152 +1,152 @@
1
- /**
2
- * Native pi-ai OAuth providers and their stable Harness route aliases.
3
- * @module dsh-coding-subscription-oauth/oauth-providers
4
- */
5
-
6
- import type { Api, ApiKeyAuth, Provider } from "@earendil-works/pi-ai";
7
- import { anthropicProvider } from "@earendil-works/pi-ai/providers/anthropic";
8
- import { kimiCodingProvider } from "@earendil-works/pi-ai/providers/kimi-coding";
9
- import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
10
- import {
11
- CLAUDE_CODE_OAUTH_AUTH_FILENAME,
12
- CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
13
- CLAUDE_CODE_OAUTH_ROUTE,
14
- CLAUDE_PI_PROVIDER,
15
- CODEX_OAUTH_AUTH_FILENAME,
16
- CODEX_OAUTH_MODELS_CACHE_FILENAME,
17
- CODEX_OAUTH_ROUTE,
18
- CODEX_PI_PROVIDER,
19
- type CodingOAuthProviderSlug,
20
- KIMI_CODE_OAUTH_AUTH_FILENAME,
21
- KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
22
- KIMI_CODE_OAUTH_ROUTE,
23
- KIMI_PI_PROVIDER,
24
- } from "./ids.ts";
25
-
26
- export type SubscriptionProviderSlug = Exclude<CodingOAuthProviderSlug, "grok">;
27
- export type SubscriptionLoginMethod = "browser" | "device";
28
-
29
- export interface OAuthProviderDefinition {
30
- slug: SubscriptionProviderSlug;
31
- route: string;
32
- nativeProviderId: string;
33
- displayName: string;
34
- authFilename: string;
35
- modelsCacheFilename: string;
36
- loginMethods: readonly SubscriptionLoginMethod[];
37
- recommendedLoginMethod: SubscriptionLoginMethod;
38
- providerFactory(): Provider<Api>;
39
- requestProvider(selectedIds?: readonly string[]): Provider<Api>;
40
- }
41
-
42
- function requestTokenAuth(name: string, bearerHeader: boolean): ApiKeyAuth {
43
- return {
44
- name,
45
- resolve: async ({ credential }) => {
46
- const token = credential?.key?.trim();
47
- if (token === undefined || token.length === 0) return undefined;
48
- return bearerHeader
49
- ? { auth: { headers: { Authorization: `Bearer ${token}` } }, source: "OAuth bridge" }
50
- : { auth: { apiKey: token }, source: "OAuth bridge" };
51
- },
52
- };
53
- }
54
-
55
- function selectedProvider(
56
- base: Provider<Api>,
57
- selectedIds: readonly string[] | undefined,
58
- apiKey: ApiKeyAuth | undefined,
59
- ): Provider<Api> {
60
- const selected = selectedIds === undefined || selectedIds.length === 0 ? undefined : new Set(selectedIds);
61
- return {
62
- ...base,
63
- auth: apiKey === undefined ? base.auth : { ...base.auth, apiKey },
64
- getModels: () => {
65
- const models = base.getModels();
66
- return selected === undefined ? models : models.filter((model) => selected.has(model.id));
67
- },
68
- };
69
- }
70
-
71
- /** Remove the transport-only `apiKey` carrier without reintroducing it as an explicit undefined. */
72
- function withoutApiKey<T extends { apiKey?: unknown }>(options: T): T {
73
- const { apiKey: _dropped, ...rest } = options;
74
- return rest as T;
75
- }
76
-
77
- /**
78
- * PiAiAdapter's api-key resolver seam necessarily populates `options.apiKey`.
79
- * Kimi OAuth is header-owned Bearer auth, so remove that transport-only carrier
80
- * after Models has derived Authorization and before the Anthropic client sees
81
- * it (otherwise the SDK also emits an invalid x-api-key header).
82
- */
83
- function stripApiKeyBeforeStream(provider: Provider<Api>): Provider<Api> {
84
- return {
85
- ...provider,
86
- stream: (model, context, options) =>
87
- provider.stream(model, context, options === undefined ? undefined : withoutApiKey(options)),
88
- streamSimple: (model, context, options) =>
89
- provider.streamSimple(model, context, options === undefined ? undefined : withoutApiKey(options)),
90
- };
91
- }
92
-
93
- function asProvider(factory: () => Provider): () => Provider<Api> {
94
- return factory as () => Provider<Api>;
95
- }
96
-
97
- const createCodexProvider = asProvider(openaiCodexProvider);
98
- const createKimiProvider = asProvider(kimiCodingProvider);
99
- const createClaudeProvider = asProvider(anthropicProvider);
100
-
101
- export const CODEX_OAUTH_PROVIDER: OAuthProviderDefinition = {
102
- slug: "codex",
103
- route: CODEX_OAUTH_ROUTE,
104
- nativeProviderId: CODEX_PI_PROVIDER,
105
- displayName: "OpenAI Codex (ChatGPT Plus/Pro)",
106
- authFilename: CODEX_OAUTH_AUTH_FILENAME,
107
- modelsCacheFilename: CODEX_OAUTH_MODELS_CACHE_FILENAME,
108
- loginMethods: ["device", "browser"],
109
- recommendedLoginMethod: "device",
110
- providerFactory: createCodexProvider,
111
- requestProvider: (selectedIds) =>
112
- selectedProvider(createCodexProvider(), selectedIds, requestTokenAuth("OpenAI Codex OAuth token", false)),
113
- };
114
-
115
- export const KIMI_CODE_OAUTH_PROVIDER: OAuthProviderDefinition = {
116
- slug: "kimi",
117
- route: KIMI_CODE_OAUTH_ROUTE,
118
- nativeProviderId: KIMI_PI_PROVIDER,
119
- displayName: "Kimi Code (subscription)",
120
- authFilename: KIMI_CODE_OAUTH_AUTH_FILENAME,
121
- modelsCacheFilename: KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
122
- loginMethods: ["device"],
123
- recommendedLoginMethod: "device",
124
- providerFactory: createKimiProvider,
125
- requestProvider: (selectedIds) =>
126
- stripApiKeyBeforeStream(
127
- selectedProvider(createKimiProvider(), selectedIds, requestTokenAuth("Kimi Code OAuth token", true)),
128
- ),
129
- };
130
-
131
- export const CLAUDE_CODE_OAUTH_PROVIDER: OAuthProviderDefinition = {
132
- slug: "claude",
133
- route: CLAUDE_CODE_OAUTH_ROUTE,
134
- nativeProviderId: CLAUDE_PI_PROVIDER,
135
- displayName: "Claude Code (Pro/Max)",
136
- authFilename: CLAUDE_CODE_OAUTH_AUTH_FILENAME,
137
- modelsCacheFilename: CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
138
- loginMethods: ["browser"],
139
- recommendedLoginMethod: "browser",
140
- providerFactory: createClaudeProvider,
141
- requestProvider: (selectedIds) => selectedProvider(createClaudeProvider(), selectedIds, undefined),
142
- };
143
-
144
- export const OAUTH_PROVIDER_DEFINITIONS = [
145
- CODEX_OAUTH_PROVIDER,
146
- KIMI_CODE_OAUTH_PROVIDER,
147
- CLAUDE_CODE_OAUTH_PROVIDER,
148
- ] as const;
149
-
150
- export function oauthProviderDefinition(slug: string): OAuthProviderDefinition | undefined {
151
- return OAUTH_PROVIDER_DEFINITIONS.find((provider) => provider.slug === slug);
152
- }
1
+ /**
2
+ * Native pi-ai OAuth providers and their stable Harness route aliases.
3
+ * @module dsh-coding-subscription-oauth/oauth-providers
4
+ */
5
+
6
+ import type { Api, ApiKeyAuth, Provider } from "@earendil-works/pi-ai";
7
+ import { anthropicProvider } from "@earendil-works/pi-ai/providers/anthropic";
8
+ import { kimiCodingProvider } from "@earendil-works/pi-ai/providers/kimi-coding";
9
+ import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
10
+ import {
11
+ CLAUDE_CODE_OAUTH_AUTH_FILENAME,
12
+ CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
13
+ CLAUDE_CODE_OAUTH_ROUTE,
14
+ CLAUDE_PI_PROVIDER,
15
+ CODEX_OAUTH_AUTH_FILENAME,
16
+ CODEX_OAUTH_MODELS_CACHE_FILENAME,
17
+ CODEX_OAUTH_ROUTE,
18
+ CODEX_PI_PROVIDER,
19
+ type CodingOAuthProviderSlug,
20
+ KIMI_CODE_OAUTH_AUTH_FILENAME,
21
+ KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
22
+ KIMI_CODE_OAUTH_ROUTE,
23
+ KIMI_PI_PROVIDER,
24
+ } from "./ids.ts";
25
+
26
+ export type SubscriptionProviderSlug = Exclude<CodingOAuthProviderSlug, "grok">;
27
+ export type SubscriptionLoginMethod = "browser" | "device";
28
+
29
+ export interface OAuthProviderDefinition {
30
+ slug: SubscriptionProviderSlug;
31
+ route: string;
32
+ nativeProviderId: string;
33
+ displayName: string;
34
+ authFilename: string;
35
+ modelsCacheFilename: string;
36
+ loginMethods: readonly SubscriptionLoginMethod[];
37
+ recommendedLoginMethod: SubscriptionLoginMethod;
38
+ providerFactory(): Provider<Api>;
39
+ requestProvider(selectedIds?: readonly string[]): Provider<Api>;
40
+ }
41
+
42
+ function requestTokenAuth(name: string, bearerHeader: boolean): ApiKeyAuth {
43
+ return {
44
+ name,
45
+ resolve: async ({ credential }) => {
46
+ const token = credential?.key?.trim();
47
+ if (token === undefined || token.length === 0) return undefined;
48
+ return bearerHeader
49
+ ? { auth: { headers: { Authorization: `Bearer ${token}` } }, source: "OAuth bridge" }
50
+ : { auth: { apiKey: token }, source: "OAuth bridge" };
51
+ },
52
+ };
53
+ }
54
+
55
+ function selectedProvider(
56
+ base: Provider<Api>,
57
+ selectedIds: readonly string[] | undefined,
58
+ apiKey: ApiKeyAuth | undefined,
59
+ ): Provider<Api> {
60
+ const selected = selectedIds === undefined || selectedIds.length === 0 ? undefined : new Set(selectedIds);
61
+ return {
62
+ ...base,
63
+ auth: apiKey === undefined ? base.auth : { ...base.auth, apiKey },
64
+ getModels: () => {
65
+ const models = base.getModels();
66
+ return selected === undefined ? models : models.filter((model) => selected.has(model.id));
67
+ },
68
+ };
69
+ }
70
+
71
+ /** Remove the transport-only `apiKey` carrier without reintroducing it as an explicit undefined. */
72
+ function withoutApiKey<T extends { apiKey?: unknown }>(options: T): T {
73
+ const { apiKey: _dropped, ...rest } = options;
74
+ return rest as T;
75
+ }
76
+
77
+ /**
78
+ * PiAiAdapter's api-key resolver seam necessarily populates `options.apiKey`.
79
+ * Kimi OAuth is header-owned Bearer auth, so remove that transport-only carrier
80
+ * after Models has derived Authorization and before the Anthropic client sees
81
+ * it (otherwise the SDK also emits an invalid x-api-key header).
82
+ */
83
+ function stripApiKeyBeforeStream(provider: Provider<Api>): Provider<Api> {
84
+ return {
85
+ ...provider,
86
+ stream: (model, context, options) =>
87
+ provider.stream(model, context, options === undefined ? undefined : withoutApiKey(options)),
88
+ streamSimple: (model, context, options) =>
89
+ provider.streamSimple(model, context, options === undefined ? undefined : withoutApiKey(options)),
90
+ };
91
+ }
92
+
93
+ function asProvider(factory: () => Provider): () => Provider<Api> {
94
+ return factory as () => Provider<Api>;
95
+ }
96
+
97
+ const createCodexProvider = asProvider(openaiCodexProvider);
98
+ const createKimiProvider = asProvider(kimiCodingProvider);
99
+ const createClaudeProvider = asProvider(anthropicProvider);
100
+
101
+ export const CODEX_OAUTH_PROVIDER: OAuthProviderDefinition = {
102
+ slug: "codex",
103
+ route: CODEX_OAUTH_ROUTE,
104
+ nativeProviderId: CODEX_PI_PROVIDER,
105
+ displayName: "OpenAI Codex (ChatGPT Plus/Pro)",
106
+ authFilename: CODEX_OAUTH_AUTH_FILENAME,
107
+ modelsCacheFilename: CODEX_OAUTH_MODELS_CACHE_FILENAME,
108
+ loginMethods: ["device", "browser"],
109
+ recommendedLoginMethod: "device",
110
+ providerFactory: createCodexProvider,
111
+ requestProvider: (selectedIds) =>
112
+ selectedProvider(createCodexProvider(), selectedIds, requestTokenAuth("OpenAI Codex OAuth token", false)),
113
+ };
114
+
115
+ export const KIMI_CODE_OAUTH_PROVIDER: OAuthProviderDefinition = {
116
+ slug: "kimi",
117
+ route: KIMI_CODE_OAUTH_ROUTE,
118
+ nativeProviderId: KIMI_PI_PROVIDER,
119
+ displayName: "Kimi Code (subscription)",
120
+ authFilename: KIMI_CODE_OAUTH_AUTH_FILENAME,
121
+ modelsCacheFilename: KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
122
+ loginMethods: ["device"],
123
+ recommendedLoginMethod: "device",
124
+ providerFactory: createKimiProvider,
125
+ requestProvider: (selectedIds) =>
126
+ stripApiKeyBeforeStream(
127
+ selectedProvider(createKimiProvider(), selectedIds, requestTokenAuth("Kimi Code OAuth token", true)),
128
+ ),
129
+ };
130
+
131
+ export const CLAUDE_CODE_OAUTH_PROVIDER: OAuthProviderDefinition = {
132
+ slug: "claude",
133
+ route: CLAUDE_CODE_OAUTH_ROUTE,
134
+ nativeProviderId: CLAUDE_PI_PROVIDER,
135
+ displayName: "Claude Code (Pro/Max)",
136
+ authFilename: CLAUDE_CODE_OAUTH_AUTH_FILENAME,
137
+ modelsCacheFilename: CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
138
+ loginMethods: ["browser"],
139
+ recommendedLoginMethod: "browser",
140
+ providerFactory: createClaudeProvider,
141
+ requestProvider: (selectedIds) => selectedProvider(createClaudeProvider(), selectedIds, undefined),
142
+ };
143
+
144
+ export const OAUTH_PROVIDER_DEFINITIONS = [
145
+ CODEX_OAUTH_PROVIDER,
146
+ KIMI_CODE_OAUTH_PROVIDER,
147
+ CLAUDE_CODE_OAUTH_PROVIDER,
148
+ ] as const;
149
+
150
+ export function oauthProviderDefinition(slug: string): OAuthProviderDefinition | undefined {
151
+ return OAUTH_PROVIDER_DEFINITIONS.find((provider) => provider.slug === slug);
152
+ }
@@ -1,183 +1,183 @@
1
- /**
2
- * Persistent OAuth session and static model selection for one subscription provider.
3
- * @module dsh-coding-subscription-oauth/oauth-session
4
- */
5
-
6
- import { mkdir, readFile, rm } from "node:fs/promises";
7
- import { dirname, join, resolve } from "node:path";
8
- import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
9
- import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
10
- import type {
11
- Api,
12
- AuthInteraction,
13
- Credential,
14
- Model,
15
- MutableModels,
16
- OAuthCredential,
17
- Provider,
18
- } from "@earendil-works/pi-ai";
19
- import { createModels } from "@earendil-works/pi-ai";
20
- import type { OAuthProviderDefinition } from "./oauth-providers.ts";
21
- import { OAuthCredentialFileStore, oauthCredentialPath } from "./store.ts";
22
-
23
- const MODELS_CACHE_VERSION = 1;
24
-
25
- interface ModelsCacheDocument {
26
- version: typeof MODELS_CACHE_VERSION;
27
- selected: string[];
28
- }
29
-
30
- function isENOENT(error: unknown): boolean {
31
- return (error as NodeJS.ErrnoException | null)?.code === "ENOENT";
32
- }
33
-
34
- function parseIdList(value: unknown): string[] {
35
- if (!Array.isArray(value)) return [];
36
- return [...new Set(value.filter((id): id is string => typeof id === "string" && id.length > 0))];
37
- }
38
-
39
- function parseCache(text: string): string[] | undefined {
40
- let value: unknown;
41
- try {
42
- value = JSON.parse(text);
43
- } catch {
44
- return undefined;
45
- }
46
- if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
47
- const document = value as Record<string, unknown>;
48
- if (document["version"] !== MODELS_CACHE_VERSION) return undefined;
49
- const selected = parseIdList(document["selected"]);
50
- return selected.length === 0 ? undefined : selected;
51
- }
52
-
53
- export function oauthModelsCachePath(basename: string, dshHome?: string): string {
54
- return resolve(join(resolveDshHome(dshHome), basename));
55
- }
56
-
57
- export interface OAuthProviderStatus {
58
- authenticated: boolean;
59
- expiresAt?: number;
60
- }
61
-
62
- export class OAuthProviderSession {
63
- readonly store: OAuthCredentialFileStore;
64
- readonly models: MutableModels;
65
- private readonly catalog: readonly Model<Api>[];
66
- private readonly cacheFile: string;
67
- private selectedIds: string[] | undefined;
68
-
69
- constructor(
70
- readonly definition: OAuthProviderDefinition,
71
- onCatalogChange?: () => void,
72
- store: OAuthCredentialFileStore = new OAuthCredentialFileStore(
73
- definition.nativeProviderId,
74
- oauthCredentialPath(definition.authFilename),
75
- definition.route,
76
- ),
77
- cacheFile: string = oauthModelsCachePath(definition.modelsCacheFilename),
78
- ) {
79
- this.store = store;
80
- this.cacheFile = resolve(cacheFile);
81
- const provider = definition.providerFactory();
82
- this.catalog = [...provider.getModels()];
83
- this.models = createModels({ credentials: store });
84
- this.models.setProvider(provider);
85
- this.onCatalogChange = onCatalogChange;
86
- }
87
-
88
- private onCatalogChange: (() => void) | undefined;
89
-
90
- availableModels(): Model<Api>[] {
91
- return [...this.catalog];
92
- }
93
-
94
- selectedModelIds(): string[] | undefined {
95
- return this.selectedIds === undefined ? undefined : [...this.selectedIds];
96
- }
97
-
98
- visibleModels(): Model<Api>[] {
99
- if (this.selectedIds === undefined || this.selectedIds.length === 0) return this.availableModels();
100
- const byId = new Map(this.catalog.map((model) => [model.id, model]));
101
- return this.selectedIds.flatMap((id) => {
102
- const model = byId.get(id);
103
- return model === undefined ? [] : [model];
104
- });
105
- }
106
-
107
- provider(): Provider {
108
- return this.definition.requestProvider(this.visibleModels().map((model) => model.id));
109
- }
110
-
111
- async loadCachedModels(): Promise<void> {
112
- try {
113
- this.selectedIds = parseCache(await readFile(this.cacheFile, "utf8"));
114
- } catch (error) {
115
- if (!isENOENT(error)) throw error;
116
- }
117
- }
118
-
119
- async setSelectedModels(ids: readonly string[]): Promise<void> {
120
- const available = new Set(this.catalog.map((model) => model.id));
121
- const selected = [...new Set(ids.filter((id) => available.has(id)))];
122
- this.selectedIds = selected.length === 0 ? undefined : selected;
123
- await this.writeCache();
124
- this.onCatalogChange?.();
125
- }
126
-
127
- async status(): Promise<OAuthProviderStatus> {
128
- const credential = await this.store.read(this.definition.nativeProviderId);
129
- if (credential?.type !== "oauth") return { authenticated: false };
130
- return { authenticated: true, expiresAt: credential.expires };
131
- }
132
-
133
- async login(interaction: AuthInteraction): Promise<Credential> {
134
- const credential = await this.models.login(this.definition.nativeProviderId, "oauth", interaction);
135
- this.onCatalogChange?.();
136
- return credential;
137
- }
138
-
139
- async resolveAccessToken(): Promise<string | undefined> {
140
- const resolved = await this.models.getAuth(this.definition.nativeProviderId);
141
- if (resolved === undefined) return undefined;
142
- const credential = await this.store.read(this.definition.nativeProviderId);
143
- return credential?.type === "oauth" ? credential.access : undefined;
144
- }
145
-
146
- /**
147
- * Backdate the stored token's expiry so the next `getAuth()` refreshes.
148
- * Called after an upstream 401 rejected a locally-valid token.
149
- */
150
- async invalidateAccessToken(): Promise<void> {
151
- await this.store.invalidate(this.definition.nativeProviderId);
152
- }
153
-
154
- async storedCredential(): Promise<OAuthCredential | undefined> {
155
- const credential = await this.store.read(this.definition.nativeProviderId);
156
- return credential?.type === "oauth" ? credential : undefined;
157
- }
158
-
159
- async logout(): Promise<void> {
160
- try {
161
- await this.models.logout(this.definition.nativeProviderId);
162
- this.selectedIds = undefined;
163
- await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
164
- await rm(this.cacheFile, { force: true });
165
- } finally {
166
- // Credential deletion may succeed before cache cleanup fails. Always
167
- // refresh discovery so an open selector cannot retain stale models.
168
- this.onCatalogChange?.();
169
- }
170
- }
171
-
172
- private async writeCache(): Promise<void> {
173
- const document: ModelsCacheDocument = {
174
- version: MODELS_CACHE_VERSION,
175
- selected: this.selectedIds === undefined ? [] : [...this.selectedIds],
176
- };
177
- await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
178
- await writeFileAtomic(this.cacheFile, `${JSON.stringify(document)}\n`, {
179
- mode: 0o600,
180
- dirMode: 0o700,
181
- });
182
- }
183
- }
1
+ /**
2
+ * Persistent OAuth session and static model selection for one subscription provider.
3
+ * @module dsh-coding-subscription-oauth/oauth-session
4
+ */
5
+
6
+ import { mkdir, readFile, rm } from "node:fs/promises";
7
+ import { dirname, join, resolve } from "node:path";
8
+ import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
9
+ import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
10
+ import type {
11
+ Api,
12
+ AuthInteraction,
13
+ Credential,
14
+ Model,
15
+ MutableModels,
16
+ OAuthCredential,
17
+ Provider,
18
+ } from "@earendil-works/pi-ai";
19
+ import { createModels } from "@earendil-works/pi-ai";
20
+ import type { OAuthProviderDefinition } from "./oauth-providers.ts";
21
+ import { OAuthCredentialFileStore, oauthCredentialPath } from "./store.ts";
22
+
23
+ const MODELS_CACHE_VERSION = 1;
24
+
25
+ interface ModelsCacheDocument {
26
+ version: typeof MODELS_CACHE_VERSION;
27
+ selected: string[];
28
+ }
29
+
30
+ function isENOENT(error: unknown): boolean {
31
+ return (error as NodeJS.ErrnoException | null)?.code === "ENOENT";
32
+ }
33
+
34
+ function parseIdList(value: unknown): string[] {
35
+ if (!Array.isArray(value)) return [];
36
+ return [...new Set(value.filter((id): id is string => typeof id === "string" && id.length > 0))];
37
+ }
38
+
39
+ function parseCache(text: string): string[] | undefined {
40
+ let value: unknown;
41
+ try {
42
+ value = JSON.parse(text);
43
+ } catch {
44
+ return undefined;
45
+ }
46
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
47
+ const document = value as Record<string, unknown>;
48
+ if (document["version"] !== MODELS_CACHE_VERSION) return undefined;
49
+ const selected = parseIdList(document["selected"]);
50
+ return selected.length === 0 ? undefined : selected;
51
+ }
52
+
53
+ export function oauthModelsCachePath(basename: string, dshHome?: string): string {
54
+ return resolve(join(resolveDshHome(dshHome), basename));
55
+ }
56
+
57
+ export interface OAuthProviderStatus {
58
+ authenticated: boolean;
59
+ expiresAt?: number;
60
+ }
61
+
62
+ export class OAuthProviderSession {
63
+ readonly store: OAuthCredentialFileStore;
64
+ readonly models: MutableModels;
65
+ private readonly catalog: readonly Model<Api>[];
66
+ private readonly cacheFile: string;
67
+ private selectedIds: string[] | undefined;
68
+
69
+ constructor(
70
+ readonly definition: OAuthProviderDefinition,
71
+ onCatalogChange?: () => void,
72
+ store: OAuthCredentialFileStore = new OAuthCredentialFileStore(
73
+ definition.nativeProviderId,
74
+ oauthCredentialPath(definition.authFilename),
75
+ definition.route,
76
+ ),
77
+ cacheFile: string = oauthModelsCachePath(definition.modelsCacheFilename),
78
+ ) {
79
+ this.store = store;
80
+ this.cacheFile = resolve(cacheFile);
81
+ const provider = definition.providerFactory();
82
+ this.catalog = [...provider.getModels()];
83
+ this.models = createModels({ credentials: store });
84
+ this.models.setProvider(provider);
85
+ this.onCatalogChange = onCatalogChange;
86
+ }
87
+
88
+ private onCatalogChange: (() => void) | undefined;
89
+
90
+ availableModels(): Model<Api>[] {
91
+ return [...this.catalog];
92
+ }
93
+
94
+ selectedModelIds(): string[] | undefined {
95
+ return this.selectedIds === undefined ? undefined : [...this.selectedIds];
96
+ }
97
+
98
+ visibleModels(): Model<Api>[] {
99
+ if (this.selectedIds === undefined || this.selectedIds.length === 0) return this.availableModels();
100
+ const byId = new Map(this.catalog.map((model) => [model.id, model]));
101
+ return this.selectedIds.flatMap((id) => {
102
+ const model = byId.get(id);
103
+ return model === undefined ? [] : [model];
104
+ });
105
+ }
106
+
107
+ provider(): Provider {
108
+ return this.definition.requestProvider(this.visibleModels().map((model) => model.id));
109
+ }
110
+
111
+ async loadCachedModels(): Promise<void> {
112
+ try {
113
+ this.selectedIds = parseCache(await readFile(this.cacheFile, "utf8"));
114
+ } catch (error) {
115
+ if (!isENOENT(error)) throw error;
116
+ }
117
+ }
118
+
119
+ async setSelectedModels(ids: readonly string[]): Promise<void> {
120
+ const available = new Set(this.catalog.map((model) => model.id));
121
+ const selected = [...new Set(ids.filter((id) => available.has(id)))];
122
+ this.selectedIds = selected.length === 0 ? undefined : selected;
123
+ await this.writeCache();
124
+ this.onCatalogChange?.();
125
+ }
126
+
127
+ async status(): Promise<OAuthProviderStatus> {
128
+ const credential = await this.store.read(this.definition.nativeProviderId);
129
+ if (credential?.type !== "oauth") return { authenticated: false };
130
+ return { authenticated: true, expiresAt: credential.expires };
131
+ }
132
+
133
+ async login(interaction: AuthInteraction): Promise<Credential> {
134
+ const credential = await this.models.login(this.definition.nativeProviderId, "oauth", interaction);
135
+ this.onCatalogChange?.();
136
+ return credential;
137
+ }
138
+
139
+ async resolveAccessToken(): Promise<string | undefined> {
140
+ const resolved = await this.models.getAuth(this.definition.nativeProviderId);
141
+ if (resolved === undefined) return undefined;
142
+ const credential = await this.store.read(this.definition.nativeProviderId);
143
+ return credential?.type === "oauth" ? credential.access : undefined;
144
+ }
145
+
146
+ /**
147
+ * Backdate the stored token's expiry so the next `getAuth()` refreshes.
148
+ * Called after an upstream 401 rejected a locally-valid token.
149
+ */
150
+ async invalidateAccessToken(): Promise<void> {
151
+ await this.store.invalidate(this.definition.nativeProviderId);
152
+ }
153
+
154
+ async storedCredential(): Promise<OAuthCredential | undefined> {
155
+ const credential = await this.store.read(this.definition.nativeProviderId);
156
+ return credential?.type === "oauth" ? credential : undefined;
157
+ }
158
+
159
+ async logout(): Promise<void> {
160
+ try {
161
+ await this.models.logout(this.definition.nativeProviderId);
162
+ this.selectedIds = undefined;
163
+ await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
164
+ await rm(this.cacheFile, { force: true });
165
+ } finally {
166
+ // Credential deletion may succeed before cache cleanup fails. Always
167
+ // refresh discovery so an open selector cannot retain stale models.
168
+ this.onCatalogChange?.();
169
+ }
170
+ }
171
+
172
+ private async writeCache(): Promise<void> {
173
+ const document: ModelsCacheDocument = {
174
+ version: MODELS_CACHE_VERSION,
175
+ selected: this.selectedIds === undefined ? [] : [...this.selectedIds],
176
+ };
177
+ await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
178
+ await writeFileAtomic(this.cacheFile, `${JSON.stringify(document)}\n`, {
179
+ mode: 0o600,
180
+ dirMode: 0o700,
181
+ });
182
+ }
183
+ }