dsh-coding-subscription-oauth 0.6.2 → 0.6.3

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 (121) hide show
  1. package/CHANGELOG.md +222 -206
  2. package/CONTRIBUTING.md +129 -120
  3. package/INSTALL.md +218 -218
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +289 -289
  7. package/README.es.md +290 -290
  8. package/README.fr.md +290 -290
  9. package/README.ja.md +290 -290
  10. package/README.ko.md +290 -290
  11. package/README.md +304 -304
  12. package/README.pt-BR.md +290 -290
  13. package/README.ru.md +290 -290
  14. package/README.zh-CN.md +302 -302
  15. package/compatibility/dsh-bom.json +0 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -195
  18. package/docs/02-architecture.md +130 -130
  19. package/docs/02-architecture.zh-CN.md +130 -130
  20. package/lib/bin.js.map +1 -1
  21. package/lib/capability-settings.d.ts +8 -2
  22. package/lib/capability-settings.d.ts.map +1 -1
  23. package/lib/capability-tools.d.ts +7 -2
  24. package/lib/capability-tools.d.ts.map +1 -1
  25. package/lib/client.js +3 -3
  26. package/lib/client.js.map +2 -2
  27. package/lib/codex-images.d.ts +8 -0
  28. package/lib/codex-images.d.ts.map +1 -1
  29. package/lib/index.js +32 -7
  30. package/lib/index.js.map +2 -2
  31. package/lib/invariant.js.map +1 -1
  32. package/media/en/settings_accounts.png +0 -0
  33. package/media/en/settings_capabilities.png +0 -0
  34. package/media/en/settings_gateway.png +0 -0
  35. package/media/settings_accounts.png +0 -0
  36. package/media/settings_capabilities.png +0 -0
  37. package/media/settings_gateway.png +0 -0
  38. package/media/settings_overview.png +0 -0
  39. package/media/zh-CN/settings_accounts.png +0 -0
  40. package/media/zh-CN/settings_capabilities.png +0 -0
  41. package/media/zh-CN/settings_gateway.png +0 -0
  42. package/package.json +148 -148
  43. package/patches/dsh-agy@0.1.2.patch +25 -25
  44. package/scripts/release.mjs +186 -186
  45. package/scripts/smoke-deployed-routes.mjs +146 -146
  46. package/scripts/verify-deployed-catalog.mjs +87 -87
  47. package/src/adapter.ts +273 -273
  48. package/src/alias-adapter.ts +130 -130
  49. package/src/auth-routes.ts +921 -921
  50. package/src/auth.ts +67 -67
  51. package/src/bin.ts +350 -350
  52. package/src/capability-routes.ts +279 -279
  53. package/src/capability-runtime.ts +314 -313
  54. package/src/capability-settings.ts +671 -658
  55. package/src/capability-tools.ts +685 -666
  56. package/src/catalog.ts +271 -271
  57. package/src/client/GrokBuildSettings.tsx +771 -770
  58. package/src/client/api.ts +88 -88
  59. package/src/client/components/AboutTab.tsx +30 -30
  60. package/src/client/components/AccountsTab.tsx +241 -241
  61. package/src/client/components/Badge.tsx +33 -33
  62. package/src/client/components/CapabilitiesTab.tsx +265 -265
  63. package/src/client/components/CliPullPreview.tsx +116 -116
  64. package/src/client/components/CopyButton.tsx +57 -57
  65. package/src/client/components/GatewayTab.tsx +469 -469
  66. package/src/client/components/NoticeBanner.tsx +46 -46
  67. package/src/client/components/ProgressBar.tsx +53 -53
  68. package/src/client/components/ProviderCard.tsx +606 -606
  69. package/src/client/components/SettingsTabs.tsx +75 -75
  70. package/src/client/components/ToggleSwitch.tsx +71 -71
  71. package/src/client/constants.ts +230 -224
  72. package/src/client/display.ts +61 -61
  73. package/src/client/dshClientAdapter.ts +127 -127
  74. package/src/client/gatewaySnippets.ts +37 -37
  75. package/src/client/index.tsx +156 -156
  76. package/src/client/locales.ts +540 -535
  77. package/src/client/microStyles.ts +52 -52
  78. package/src/client/parsers.ts +398 -396
  79. package/src/client/styles.ts +325 -325
  80. package/src/client/types.ts +199 -197
  81. package/src/codex-http.ts +447 -447
  82. package/src/codex-images.ts +503 -485
  83. package/src/codex-model-capabilities.ts +320 -320
  84. package/src/codex-search.ts +245 -245
  85. package/src/codex-usage.ts +263 -263
  86. package/src/compatibility.ts +41 -41
  87. package/src/dsh-host-adapter.ts +173 -173
  88. package/src/gateway-anthropic-messages.ts +84 -84
  89. package/src/gateway-auth.ts +102 -102
  90. package/src/gateway-backend.ts +274 -274
  91. package/src/gateway-body.ts +49 -49
  92. package/src/gateway-config.ts +76 -76
  93. package/src/gateway-http.ts +104 -104
  94. package/src/gateway-openai-chat.ts +124 -124
  95. package/src/gateway-openai-responses.ts +53 -53
  96. package/src/gateway-parse.ts +224 -224
  97. package/src/gateway-protocol.ts +52 -52
  98. package/src/gateway-routes.ts +158 -158
  99. package/src/gateway.ts +258 -258
  100. package/src/grok-errors.ts +24 -24
  101. package/src/grok-imagine.ts +1627 -1627
  102. package/src/grok-import.ts +151 -151
  103. package/src/http-json.ts +82 -82
  104. package/src/ids.ts +59 -59
  105. package/src/imagine-routes.ts +463 -463
  106. package/src/index.ts +709 -709
  107. package/src/invariant.ts +17 -17
  108. package/src/kimi-errors.ts +26 -26
  109. package/src/media-store.ts +927 -927
  110. package/src/oauth-import-routes.ts +324 -324
  111. package/src/oauth-providers.ts +152 -152
  112. package/src/oauth-session.ts +183 -183
  113. package/src/oauth-sources.ts +1104 -1104
  114. package/src/oauth.ts +620 -620
  115. package/src/provider.ts +128 -128
  116. package/src/proxy.ts +11 -11
  117. package/src/redact.ts +72 -72
  118. package/src/session.ts +218 -218
  119. package/src/store.ts +217 -217
  120. package/src/web-origin.ts +296 -296
  121. package/src/web-routes.ts +38 -38
@@ -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
+ }