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,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
+ }