dsh-coding-subscription-oauth 0.6.4 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +280 -255
  2. package/CONTRIBUTING.md +138 -129
  3. package/INSTALL.md +256 -255
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +303 -303
  7. package/README.es.md +304 -304
  8. package/README.fr.md +304 -304
  9. package/README.ja.md +304 -304
  10. package/README.ko.md +304 -304
  11. package/README.md +320 -320
  12. package/README.pt-BR.md +304 -304
  13. package/README.ru.md +304 -304
  14. package/README.zh-CN.md +318 -318
  15. package/compatibility/dsh-bom.json +30 -30
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -212
  18. package/docs/02-architecture.md +141 -137
  19. package/docs/02-architecture.zh-CN.md +141 -137
  20. package/lib/bin.js.map +1 -1
  21. package/lib/client.js +1 -1
  22. package/lib/client.js.map +1 -1
  23. package/lib/gateway-protocol.d.ts +3 -46
  24. package/lib/gateway-protocol.d.ts.map +1 -1
  25. package/lib/gateway-routes.d.ts.map +1 -1
  26. package/lib/grok-errors.d.ts +2 -12
  27. package/lib/grok-errors.d.ts.map +1 -1
  28. package/lib/grok-imagine/client.d.ts +73 -0
  29. package/lib/grok-imagine/client.d.ts.map +1 -0
  30. package/lib/grok-imagine/index.d.ts +8 -0
  31. package/lib/grok-imagine/index.d.ts.map +1 -0
  32. package/lib/grok-imagine/net.d.ts +10 -0
  33. package/lib/grok-imagine/net.d.ts.map +1 -0
  34. package/lib/grok-imagine/parse.d.ts +20 -0
  35. package/lib/grok-imagine/parse.d.ts.map +1 -0
  36. package/lib/grok-imagine/types.d.ts +191 -0
  37. package/lib/grok-imagine/types.d.ts.map +1 -0
  38. package/lib/grok-imagine.d.ts +3 -263
  39. package/lib/grok-imagine.d.ts.map +1 -1
  40. package/lib/http-json.d.ts +2 -9
  41. package/lib/http-json.d.ts.map +1 -1
  42. package/lib/index.js +57 -37
  43. package/lib/index.js.map +4 -4
  44. package/lib/invariant.js.map +1 -1
  45. package/lib/kimi-errors.d.ts +2 -12
  46. package/lib/kimi-errors.d.ts.map +1 -1
  47. package/lib/runtime/gateway-protocol.d.ts +47 -0
  48. package/lib/runtime/gateway-protocol.d.ts.map +1 -0
  49. package/lib/runtime/grok-errors.d.ts +13 -0
  50. package/lib/runtime/grok-errors.d.ts.map +1 -0
  51. package/lib/runtime/http-json.d.ts +10 -0
  52. package/lib/runtime/http-json.d.ts.map +1 -0
  53. package/lib/runtime/kimi-errors.d.ts +13 -0
  54. package/lib/runtime/kimi-errors.d.ts.map +1 -0
  55. package/media/en/settings_accounts.png +0 -0
  56. package/media/en/settings_capabilities.png +0 -0
  57. package/media/en/settings_gateway.png +0 -0
  58. package/media/settings_accounts.png +0 -0
  59. package/media/settings_capabilities.png +0 -0
  60. package/media/settings_gateway.png +0 -0
  61. package/media/settings_overview.png +0 -0
  62. package/media/zh-CN/settings_accounts.png +0 -0
  63. package/media/zh-CN/settings_capabilities.png +0 -0
  64. package/media/zh-CN/settings_gateway.png +0 -0
  65. package/package.json +225 -220
  66. package/patches/dsh-agy@0.1.2.patch +25 -25
  67. package/scripts/release.mjs +187 -186
  68. package/scripts/smoke-deployed-routes.mjs +146 -146
  69. package/scripts/verify-deployed-catalog.mjs +87 -87
  70. package/src/adapter.ts +0 -348
  71. package/src/alias-adapter.ts +0 -147
  72. package/src/auth-routes.ts +0 -921
  73. package/src/auth.ts +0 -67
  74. package/src/bin.ts +0 -350
  75. package/src/capability-routes.ts +0 -279
  76. package/src/capability-runtime.ts +0 -314
  77. package/src/capability-settings.ts +0 -671
  78. package/src/capability-tools.ts +0 -685
  79. package/src/catalog.ts +0 -271
  80. package/src/client/GrokBuildSettings.tsx +0 -771
  81. package/src/client/api.ts +0 -88
  82. package/src/client/components/AboutTab.tsx +0 -30
  83. package/src/client/components/AccountsTab.tsx +0 -241
  84. package/src/client/components/Badge.tsx +0 -33
  85. package/src/client/components/CapabilitiesTab.tsx +0 -265
  86. package/src/client/components/CliPullPreview.tsx +0 -116
  87. package/src/client/components/CopyButton.tsx +0 -57
  88. package/src/client/components/GatewayTab.tsx +0 -469
  89. package/src/client/components/NoticeBanner.tsx +0 -46
  90. package/src/client/components/ProgressBar.tsx +0 -53
  91. package/src/client/components/ProviderCard.tsx +0 -606
  92. package/src/client/components/SettingsTabs.tsx +0 -75
  93. package/src/client/components/ToggleSwitch.tsx +0 -71
  94. package/src/client/constants.ts +0 -230
  95. package/src/client/display.ts +0 -61
  96. package/src/client/dshClientAdapter.ts +0 -127
  97. package/src/client/gatewaySnippets.ts +0 -37
  98. package/src/client/index.tsx +0 -156
  99. package/src/client/locales.ts +0 -540
  100. package/src/client/microStyles.ts +0 -52
  101. package/src/client/parsers.ts +0 -398
  102. package/src/client/styles.ts +0 -325
  103. package/src/client/types.ts +0 -199
  104. package/src/codex-http.ts +0 -447
  105. package/src/codex-images.ts +0 -503
  106. package/src/codex-model-capabilities.ts +0 -320
  107. package/src/codex-search.ts +0 -245
  108. package/src/codex-usage.ts +0 -263
  109. package/src/compatibility.ts +0 -55
  110. package/src/dsh-host-adapter.ts +0 -173
  111. package/src/gateway-anthropic-messages.ts +0 -84
  112. package/src/gateway-auth.ts +0 -102
  113. package/src/gateway-backend.ts +0 -274
  114. package/src/gateway-body.ts +0 -49
  115. package/src/gateway-config.ts +0 -76
  116. package/src/gateway-http.ts +0 -104
  117. package/src/gateway-openai-chat.ts +0 -124
  118. package/src/gateway-openai-responses.ts +0 -53
  119. package/src/gateway-parse.ts +0 -224
  120. package/src/gateway-protocol.ts +0 -52
  121. package/src/gateway-routes.ts +0 -158
  122. package/src/gateway.ts +0 -258
  123. package/src/grok-errors.ts +0 -24
  124. package/src/grok-imagine.ts +0 -1627
  125. package/src/grok-import.ts +0 -151
  126. package/src/http-json.ts +0 -82
  127. package/src/ids.ts +0 -59
  128. package/src/imagine-routes.ts +0 -463
  129. package/src/index.ts +0 -735
  130. package/src/invariant.ts +0 -17
  131. package/src/kimi-errors.ts +0 -26
  132. package/src/media-store.ts +0 -927
  133. package/src/oauth-import-routes.ts +0 -324
  134. package/src/oauth-providers.ts +0 -152
  135. package/src/oauth-session.ts +0 -183
  136. package/src/oauth-sources.ts +0 -1104
  137. package/src/oauth.ts +0 -620
  138. package/src/provider.ts +0 -128
  139. package/src/proxy.ts +0 -11
  140. package/src/redact.ts +0 -72
  141. package/src/session.ts +0 -218
  142. package/src/store.ts +0 -217
  143. package/src/web-origin.ts +0 -296
  144. package/src/web-routes.ts +0 -38
@@ -1,324 +0,0 @@
1
- /**
2
- * Same-origin Web API for allowlisted CLI OAuth source discovery and
3
- * two-phase import into destination stores. Preview tickets live only in the
4
- * process-local session; `peekPreview` supplies ticket.kind as the destination
5
- * authority before the store lock. Persist happens inside that lock.
6
- * @module dsh-coding-subscription-oauth/oauth-import-routes
7
- */
8
-
9
- import type { IncomingMessage, ServerResponse } from "node:http";
10
- import { readJsonRequest, requestErrorStatus } from "./http-json.ts";
11
- import {
12
- OAUTH_IMPORT_CANCEL_PATH,
13
- OAUTH_IMPORT_COMMIT_PATH,
14
- OAUTH_IMPORT_PREVIEW_PATH,
15
- OAUTH_IMPORT_SOURCES_PATH,
16
- } from "./ids.ts";
17
- import {
18
- createOAuthImportSession,
19
- isOAuthSourceError,
20
- isOAuthSourceKind,
21
- type OAuthImportCommitAction,
22
- type OAuthImportCommitResult,
23
- type OAuthImportPreview,
24
- type OAuthImportSession,
25
- type OAuthImportSessionOptions,
26
- type OAuthSourceCredential,
27
- type OAuthSourceDiscovery,
28
- OAuthSourceError,
29
- type OAuthSourceErrorCode,
30
- type OAuthSourceKind,
31
- type OAuthSourcePathOptions,
32
- } from "./oauth-sources.ts";
33
- import { safeMessage } from "./redact.ts";
34
- import { LOOPBACK_OWNER_REQUEST_POLICY, type OwnerRequestPolicy } from "./web-origin.ts";
35
- import { registerWebRouteSetupAtomically } from "./web-routes.ts";
36
-
37
- export {
38
- OAUTH_IMPORT_CANCEL_PATH,
39
- OAUTH_IMPORT_COMMIT_PATH,
40
- OAUTH_IMPORT_PREVIEW_PATH,
41
- OAUTH_IMPORT_SOURCES_PATH,
42
- } from "./ids.ts";
43
-
44
- export interface OAuthImportRouteContext {
45
- webServer: {
46
- register(route: {
47
- kind: "exact";
48
- path: string;
49
- handler: (request: IncomingMessage, response: ServerResponse) => void | Promise<void>;
50
- }): () => void;
51
- };
52
- effect?(setup: () => () => void | Promise<void>, label?: string): void;
53
- }
54
-
55
- export interface OAuthImportDestinationStore {
56
- readonly filename: string;
57
- modify(
58
- providerId: string,
59
- fn: (current: OAuthSourceCredential | undefined) => Promise<OAuthSourceCredential | undefined>,
60
- ): Promise<OAuthSourceCredential | undefined>;
61
- }
62
-
63
- export interface OAuthImportDestination {
64
- providerId: string;
65
- store: OAuthImportDestinationStore;
66
- }
67
-
68
- export type OAuthImportDestinations = { [K in OAuthSourceKind]: OAuthImportDestination };
69
-
70
- export interface OAuthImportAppliedEvent {
71
- kind: OAuthSourceKind;
72
- action: Extract<OAuthImportCommitAction, "imported" | "overwritten">;
73
- }
74
-
75
- export interface OAuthImportRouteOptions extends OAuthImportSessionOptions, OAuthSourcePathOptions {
76
- onImported?: (event: OAuthImportAppliedEvent) => void | Promise<void>;
77
- ownerRequestPolicy?: OwnerRequestPolicy;
78
- }
79
-
80
- export interface OAuthImportSourcesResponse {
81
- sources: OAuthSourceDiscovery[];
82
- }
83
-
84
- export interface OAuthImportCancelResult {
85
- ok: true;
86
- cancelled: boolean;
87
- }
88
-
89
- /** Register same-origin CLI source import routes when the Web server is composed. */
90
- export function registerOAuthImportRoutes(
91
- ctx: OAuthImportRouteContext,
92
- destinations: OAuthImportDestinations,
93
- options: OAuthImportRouteOptions = {},
94
- ): () => void {
95
- const importer = createOAuthImportSession({
96
- ...(options.now === undefined ? {} : { now: options.now }),
97
- ...(options.ttlMs === undefined ? {} : { ttlMs: options.ttlMs }),
98
- });
99
- const pathOptions: OAuthSourcePathOptions = {
100
- ...(options.home === undefined ? {} : { home: options.home }),
101
- ...(options.env === undefined ? {} : { env: options.env }),
102
- };
103
- const ownerRequestPolicy = options.ownerRequestPolicy ?? LOOPBACK_OWNER_REQUEST_POLICY;
104
-
105
- const attach = (): (() => void) =>
106
- registerWebRouteSetupAtomically(ctx.webServer, (webServer) => [
107
- webServer.register({
108
- kind: "exact",
109
- path: OAUTH_IMPORT_SOURCES_PATH,
110
- handler: async (req, res) => {
111
- if (req.method !== "GET") return json(res, 405, { error: "method not allowed" });
112
- if (!ownerRequestPolicy.authorize(req).authorized) return json(res, 403, { error: "forbidden" });
113
- try {
114
- json(res, 200, await discoverSources(importer, pathOptions));
115
- } catch (error: unknown) {
116
- writeError(res, error);
117
- }
118
- },
119
- }),
120
- webServer.register({
121
- kind: "exact",
122
- path: OAUTH_IMPORT_PREVIEW_PATH,
123
- handler: async (req, res) => {
124
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
125
- if (!ownerRequestPolicy.authorize(req).authorized) return json(res, 403, { error: "forbidden" });
126
- try {
127
- const kind = readExactKind(await readJsonRequest(req));
128
- if (kind === undefined) {
129
- return json(res, 400, { error: "kind must be grok, codex, kimi, or claude" });
130
- }
131
- json(res, 200, await previewSource(importer, destinations[kind], kind, pathOptions));
132
- } catch (error: unknown) {
133
- writeError(res, error);
134
- }
135
- },
136
- }),
137
- webServer.register({
138
- kind: "exact",
139
- path: OAUTH_IMPORT_COMMIT_PATH,
140
- handler: async (req, res) => {
141
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
142
- if (!ownerRequestPolicy.authorize(req).authorized) return json(res, 403, { error: "forbidden" });
143
- try {
144
- const parsed = readCommitBody(await readJsonRequest(req));
145
- if (parsed.error !== undefined) {
146
- return json(res, 400, { error: parsed.error });
147
- }
148
- const claim = importer.peekPreview(parsed.previewId);
149
- if (claim.kind !== parsed.kind) {
150
- throw new OAuthSourceError("unsupported", "oauth import: kind does not match the preview");
151
- }
152
- json(
153
- res,
154
- 200,
155
- await commitSource(
156
- importer,
157
- destinations[claim.kind],
158
- { ...parsed, kind: claim.kind },
159
- pathOptions,
160
- options.onImported,
161
- ),
162
- );
163
- } catch (error: unknown) {
164
- writeError(res, error);
165
- }
166
- },
167
- }),
168
- webServer.register({
169
- kind: "exact",
170
- path: OAUTH_IMPORT_CANCEL_PATH,
171
- handler: async (req, res) => {
172
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
173
- if (!ownerRequestPolicy.authorize(req).authorized) return json(res, 403, { error: "forbidden" });
174
- try {
175
- const previewId = readPreviewId(await readJsonRequest(req));
176
- if (previewId === undefined) {
177
- return json(res, 400, { error: "previewId must be a non-empty string" });
178
- }
179
- json(res, 200, { ok: true, cancelled: importer.cancel(previewId) } satisfies OAuthImportCancelResult);
180
- } catch (error: unknown) {
181
- writeError(res, error);
182
- }
183
- },
184
- }),
185
- ]);
186
-
187
- if (typeof ctx.effect === "function") {
188
- ctx.effect(attach, "dsh-coding-subscription-oauth: OAuth source import routes");
189
- return () => undefined;
190
- }
191
- return attach();
192
- }
193
-
194
- async function discoverSources(
195
- importer: OAuthImportSession,
196
- pathOptions: OAuthSourcePathOptions,
197
- ): Promise<OAuthImportSourcesResponse> {
198
- return { sources: await importer.discover(pathOptions) };
199
- }
200
-
201
- async function previewSource(
202
- importer: OAuthImportSession,
203
- destination: OAuthImportDestination,
204
- kind: OAuthSourceKind,
205
- pathOptions: OAuthSourcePathOptions,
206
- ): Promise<OAuthImportPreview> {
207
- return importer.preview({
208
- kind,
209
- ...pathOptions,
210
- destination: { path: destination.store.filename },
211
- });
212
- }
213
-
214
- async function commitSource(
215
- importer: OAuthImportSession,
216
- destination: OAuthImportDestination,
217
- input: { kind: OAuthSourceKind; previewId: string; confirmOverwrite?: boolean },
218
- pathOptions: OAuthSourcePathOptions,
219
- onImported: OAuthImportRouteOptions["onImported"],
220
- ): Promise<OAuthImportCommitResult> {
221
- let result: OAuthImportCommitResult | undefined;
222
- await destination.store.modify(destination.providerId, async (current) => {
223
- const outcome = await importer.commit({
224
- previewId: input.previewId,
225
- kind: input.kind,
226
- ...(input.confirmOverwrite === undefined ? {} : { confirmOverwrite: input.confirmOverwrite }),
227
- ...pathOptions,
228
- destination: { path: destination.store.filename },
229
- });
230
- result = outcome.result;
231
- return outcome.takePersist() ?? current;
232
- });
233
- if (result === undefined) {
234
- throw new Error("oauth import: destination store did not complete commit");
235
- }
236
- if (result.action === "imported" || result.action === "overwritten") {
237
- try {
238
- await onImported?.({ kind: input.kind, action: result.action });
239
- } catch {
240
- // Adapter notification is advisory; persist already succeeded.
241
- }
242
- }
243
- return result;
244
- }
245
-
246
- function json(res: ServerResponse, status: number, value: unknown): void {
247
- res.writeHead(status, {
248
- "content-type": "application/json; charset=utf-8",
249
- "cache-control": "no-store",
250
- "x-content-type-options": "nosniff",
251
- });
252
- res.end(JSON.stringify(value));
253
- }
254
-
255
- function writeError(res: ServerResponse, error: unknown): void {
256
- const status = oauthImportErrorStatus(error);
257
- const payload: { error: string; code?: OAuthSourceErrorCode } = {
258
- error: status >= 500 ? "request failed" : safeMessage(error),
259
- };
260
- if (isOAuthSourceError(error)) payload.code = error.code;
261
- json(res, status, payload);
262
- }
263
-
264
- export function oauthImportErrorStatus(error: unknown): number {
265
- if (isOAuthSourceError(error)) {
266
- switch (error.code) {
267
- case "not_found":
268
- case "preview_invalid":
269
- return 404;
270
- case "too_large":
271
- return 413;
272
- case "preview_expired":
273
- return 410;
274
- case "source_changed":
275
- case "destination_changed":
276
- case "confirm_required":
277
- case "unsafe_destination":
278
- return 409;
279
- case "unsafe_source":
280
- case "invalid_document":
281
- case "unsupported":
282
- return 400;
283
- }
284
- }
285
- return requestErrorStatus(error, 500);
286
- }
287
-
288
- function readExactKind(body: unknown): OAuthSourceKind | undefined {
289
- const record = asRecord(body);
290
- if (record === undefined) return undefined;
291
- const kind = record["kind"];
292
- return typeof kind === "string" && isOAuthSourceKind(kind) ? kind : undefined;
293
- }
294
-
295
- function readPreviewId(body: unknown): string | undefined {
296
- const record = asRecord(body);
297
- if (record === undefined) return undefined;
298
- const previewId = record["previewId"];
299
- return typeof previewId === "string" && previewId.length > 0 ? previewId : undefined;
300
- }
301
-
302
- function readCommitBody(
303
- body: unknown,
304
- ): { kind: OAuthSourceKind; previewId: string; confirmOverwrite?: boolean; error?: undefined } | { error: string } {
305
- const kind = readExactKind(body);
306
- if (kind === undefined) return { error: "kind must be grok, codex, kimi, or claude" };
307
- const previewId = readPreviewId(body);
308
- if (previewId === undefined) return { error: "previewId must be a non-empty string" };
309
- const record = asRecord(body);
310
- if (record === undefined) return { error: "request body must be a JSON object" };
311
- if (!("confirmOverwrite" in record) || record["confirmOverwrite"] === undefined) {
312
- return { kind, previewId };
313
- }
314
- if (typeof record["confirmOverwrite"] !== "boolean") {
315
- return { error: "confirmOverwrite must be a boolean" };
316
- }
317
- return { kind, previewId, confirmOverwrite: record["confirmOverwrite"] };
318
- }
319
-
320
- function asRecord(value: unknown): Record<string, unknown> | undefined {
321
- return typeof value === "object" && value !== null && !Array.isArray(value)
322
- ? (value as Record<string, unknown>)
323
- : undefined;
324
- }
@@ -1,152 +0,0 @@
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 +0,0 @@
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
- }