dsh-coding-subscription-oauth 0.5.8 → 0.6.2

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