dsh-coding-subscription-oauth 0.6.3 → 0.6.4

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