dsh-coding-subscription-oauth 0.5.0
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.
- package/CHANGELOG.md +136 -0
- package/CONTRIBUTING.md +109 -0
- package/INSTALL.md +220 -0
- package/LICENSE +19 -0
- package/NOTICE +11 -0
- package/README.de.md +254 -0
- package/README.es.md +254 -0
- package/README.fr.md +254 -0
- package/README.ja.md +254 -0
- package/README.ko.md +254 -0
- package/README.md +286 -0
- package/README.pt-BR.md +254 -0
- package/README.ru.md +254 -0
- package/README.zh-CN.md +271 -0
- package/cordis.patch.yml +13 -0
- package/docs/00-project-rules.md +195 -0
- package/docs/02-architecture.md +132 -0
- package/docs/02-architecture.zh-CN.md +128 -0
- package/lib/adapter.d.ts +24 -0
- package/lib/adapter.d.ts.map +1 -0
- package/lib/alias-adapter.d.ts +43 -0
- package/lib/alias-adapter.d.ts.map +1 -0
- package/lib/auth-routes.d.ts +155 -0
- package/lib/auth-routes.d.ts.map +1 -0
- package/lib/auth.d.ts +29 -0
- package/lib/auth.d.ts.map +1 -0
- package/lib/bin.d.ts +6 -0
- package/lib/bin.d.ts.map +1 -0
- package/lib/bin.js +27591 -0
- package/lib/bin.js.map +7 -0
- package/lib/capability-routes.d.ts +43 -0
- package/lib/capability-routes.d.ts.map +1 -0
- package/lib/capability-runtime.d.ts +56 -0
- package/lib/capability-runtime.d.ts.map +1 -0
- package/lib/capability-settings.d.ts +263 -0
- package/lib/capability-settings.d.ts.map +1 -0
- package/lib/capability-tools.d.ts +50 -0
- package/lib/capability-tools.d.ts.map +1 -0
- package/lib/catalog.d.ts +53 -0
- package/lib/catalog.d.ts.map +1 -0
- package/lib/client.js +3 -0
- package/lib/client.js.map +7 -0
- package/lib/codex-http.d.ts +77 -0
- package/lib/codex-http.d.ts.map +1 -0
- package/lib/codex-images.d.ts +109 -0
- package/lib/codex-images.d.ts.map +1 -0
- package/lib/codex-model-capabilities.d.ts +112 -0
- package/lib/codex-model-capabilities.d.ts.map +1 -0
- package/lib/codex-search.d.ts +96 -0
- package/lib/codex-search.d.ts.map +1 -0
- package/lib/codex-usage.d.ts +79 -0
- package/lib/codex-usage.d.ts.map +1 -0
- package/lib/gateway-anthropic-messages.d.ts +8 -0
- package/lib/gateway-anthropic-messages.d.ts.map +1 -0
- package/lib/gateway-auth.d.ts +22 -0
- package/lib/gateway-auth.d.ts.map +1 -0
- package/lib/gateway-backend.d.ts +62 -0
- package/lib/gateway-backend.d.ts.map +1 -0
- package/lib/gateway-body.d.ts +9 -0
- package/lib/gateway-body.d.ts.map +1 -0
- package/lib/gateway-config.d.ts +24 -0
- package/lib/gateway-config.d.ts.map +1 -0
- package/lib/gateway-http.d.ts +16 -0
- package/lib/gateway-http.d.ts.map +1 -0
- package/lib/gateway-openai-chat.d.ts +8 -0
- package/lib/gateway-openai-chat.d.ts.map +1 -0
- package/lib/gateway-openai-responses.d.ts +8 -0
- package/lib/gateway-openai-responses.d.ts.map +1 -0
- package/lib/gateway-parse.d.ts +10 -0
- package/lib/gateway-parse.d.ts.map +1 -0
- package/lib/gateway-protocol.d.ts +47 -0
- package/lib/gateway-protocol.d.ts.map +1 -0
- package/lib/gateway-routes.d.ts +21 -0
- package/lib/gateway-routes.d.ts.map +1 -0
- package/lib/gateway.d.ts +48 -0
- package/lib/gateway.d.ts.map +1 -0
- package/lib/grok-imagine.d.ts +271 -0
- package/lib/grok-imagine.d.ts.map +1 -0
- package/lib/grok-import.d.ts +21 -0
- package/lib/grok-import.d.ts.map +1 -0
- package/lib/http-json.d.ts +10 -0
- package/lib/http-json.d.ts.map +1 -0
- package/lib/ids.d.ts +33 -0
- package/lib/ids.d.ts.map +1 -0
- package/lib/imagine-routes.d.ts +59 -0
- package/lib/imagine-routes.d.ts.map +1 -0
- package/lib/index.d.ts +69 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +35355 -0
- package/lib/index.js.map +7 -0
- package/lib/invariant.d.ts +9 -0
- package/lib/invariant.d.ts.map +1 -0
- package/lib/invariant.js +14 -0
- package/lib/invariant.js.map +7 -0
- package/lib/kimi-errors.d.ts +13 -0
- package/lib/kimi-errors.d.ts.map +1 -0
- package/lib/media-store.d.ts +130 -0
- package/lib/media-store.d.ts.map +1 -0
- package/lib/oauth-import-routes.d.ts +52 -0
- package/lib/oauth-import-routes.d.ts.map +1 -0
- package/lib/oauth-providers.d.ts +26 -0
- package/lib/oauth-providers.d.ts.map +1 -0
- package/lib/oauth-session.d.ts +40 -0
- package/lib/oauth-session.d.ts.map +1 -0
- package/lib/oauth-sources.d.ts +205 -0
- package/lib/oauth-sources.d.ts.map +1 -0
- package/lib/oauth.d.ts +79 -0
- package/lib/oauth.d.ts.map +1 -0
- package/lib/provider.d.ts +38 -0
- package/lib/provider.d.ts.map +1 -0
- package/lib/proxy.d.ts +17 -0
- package/lib/proxy.d.ts.map +1 -0
- package/lib/redact.d.ts +5 -0
- package/lib/redact.d.ts.map +1 -0
- package/lib/session.d.ts +40 -0
- package/lib/session.d.ts.map +1 -0
- package/lib/store.d.ts +46 -0
- package/lib/store.d.ts.map +1 -0
- package/lib/web-origin.d.ts +10 -0
- package/lib/web-origin.d.ts.map +1 -0
- package/lib/web-routes.d.ts +20 -0
- package/lib/web-routes.d.ts.map +1 -0
- package/package.json +185 -0
- package/patches/dsh-agy@0.1.2.patch +25 -0
- package/scripts/release.mjs +166 -0
- package/scripts/smoke-deployed-routes.mjs +146 -0
- package/scripts/verify-deployed-catalog.mjs +87 -0
- package/src/adapter.ts +282 -0
- package/src/alias-adapter.ts +152 -0
- package/src/auth-routes.ts +871 -0
- package/src/auth.ts +67 -0
- package/src/bin.ts +350 -0
- package/src/capability-routes.ts +275 -0
- package/src/capability-runtime.ts +313 -0
- package/src/capability-settings.ts +657 -0
- package/src/capability-tools.ts +666 -0
- package/src/catalog.ts +271 -0
- package/src/client/GrokBuildSettings.tsx +2221 -0
- package/src/client/index.tsx +37 -0
- package/src/client/locales.ts +421 -0
- package/src/codex-http.ts +447 -0
- package/src/codex-images.ts +485 -0
- package/src/codex-model-capabilities.ts +320 -0
- package/src/codex-search.ts +245 -0
- package/src/codex-usage.ts +263 -0
- package/src/gateway-anthropic-messages.ts +84 -0
- package/src/gateway-auth.ts +100 -0
- package/src/gateway-backend.ts +274 -0
- package/src/gateway-body.ts +49 -0
- package/src/gateway-config.ts +76 -0
- package/src/gateway-http.ts +104 -0
- package/src/gateway-openai-chat.ts +124 -0
- package/src/gateway-openai-responses.ts +53 -0
- package/src/gateway-parse.ts +224 -0
- package/src/gateway-protocol.ts +52 -0
- package/src/gateway-routes.ts +152 -0
- package/src/gateway.ts +242 -0
- package/src/grok-imagine.ts +1627 -0
- package/src/grok-import.ts +151 -0
- package/src/http-json.ts +82 -0
- package/src/ids.ts +45 -0
- package/src/imagine-routes.ts +461 -0
- package/src/index.ts +598 -0
- package/src/invariant.ts +17 -0
- package/src/kimi-errors.ts +26 -0
- package/src/media-store.ts +927 -0
- package/src/oauth-import-routes.ts +314 -0
- package/src/oauth-providers.ts +152 -0
- package/src/oauth-session.ts +183 -0
- package/src/oauth-sources.ts +1104 -0
- package/src/oauth.ts +620 -0
- package/src/provider.ts +128 -0
- package/src/proxy.ts +99 -0
- package/src/redact.ts +72 -0
- package/src/session.ts +218 -0
- package/src/store.ts +217 -0
- package/src/web-origin.ts +60 -0
- package/src/web-routes.ts +75 -0
|
@@ -0,0 +1,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
|
+
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
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native pi-ai OAuth providers and their stable Harness route aliases.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/oauth-providers
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Api, ApiKeyAuth, Provider } from "@earendil-works/pi-ai";
|
|
7
|
+
import { anthropicProvider } from "@earendil-works/pi-ai/providers/anthropic";
|
|
8
|
+
import { kimiCodingProvider } from "@earendil-works/pi-ai/providers/kimi-coding";
|
|
9
|
+
import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
|
|
10
|
+
import {
|
|
11
|
+
CLAUDE_CODE_OAUTH_AUTH_FILENAME,
|
|
12
|
+
CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
|
|
13
|
+
CLAUDE_CODE_OAUTH_ROUTE,
|
|
14
|
+
CLAUDE_PI_PROVIDER,
|
|
15
|
+
CODEX_OAUTH_AUTH_FILENAME,
|
|
16
|
+
CODEX_OAUTH_MODELS_CACHE_FILENAME,
|
|
17
|
+
CODEX_OAUTH_ROUTE,
|
|
18
|
+
CODEX_PI_PROVIDER,
|
|
19
|
+
type CodingOAuthProviderSlug,
|
|
20
|
+
KIMI_CODE_OAUTH_AUTH_FILENAME,
|
|
21
|
+
KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
|
|
22
|
+
KIMI_CODE_OAUTH_ROUTE,
|
|
23
|
+
KIMI_PI_PROVIDER,
|
|
24
|
+
} from "./ids.ts";
|
|
25
|
+
|
|
26
|
+
export type SubscriptionProviderSlug = Exclude<CodingOAuthProviderSlug, "grok">;
|
|
27
|
+
export type SubscriptionLoginMethod = "browser" | "device";
|
|
28
|
+
|
|
29
|
+
export interface OAuthProviderDefinition {
|
|
30
|
+
slug: SubscriptionProviderSlug;
|
|
31
|
+
route: string;
|
|
32
|
+
nativeProviderId: string;
|
|
33
|
+
displayName: string;
|
|
34
|
+
authFilename: string;
|
|
35
|
+
modelsCacheFilename: string;
|
|
36
|
+
loginMethods: readonly SubscriptionLoginMethod[];
|
|
37
|
+
recommendedLoginMethod: SubscriptionLoginMethod;
|
|
38
|
+
providerFactory(): Provider<Api>;
|
|
39
|
+
requestProvider(selectedIds?: readonly string[]): Provider<Api>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function requestTokenAuth(name: string, bearerHeader: boolean): ApiKeyAuth {
|
|
43
|
+
return {
|
|
44
|
+
name,
|
|
45
|
+
resolve: async ({ credential }) => {
|
|
46
|
+
const token = credential?.key?.trim();
|
|
47
|
+
if (token === undefined || token.length === 0) return undefined;
|
|
48
|
+
return bearerHeader
|
|
49
|
+
? { auth: { headers: { Authorization: `Bearer ${token}` } }, source: "OAuth bridge" }
|
|
50
|
+
: { auth: { apiKey: token }, source: "OAuth bridge" };
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function selectedProvider(
|
|
56
|
+
base: Provider<Api>,
|
|
57
|
+
selectedIds: readonly string[] | undefined,
|
|
58
|
+
apiKey: ApiKeyAuth | undefined,
|
|
59
|
+
): Provider<Api> {
|
|
60
|
+
const selected = selectedIds === undefined || selectedIds.length === 0 ? undefined : new Set(selectedIds);
|
|
61
|
+
return {
|
|
62
|
+
...base,
|
|
63
|
+
auth: apiKey === undefined ? base.auth : { ...base.auth, apiKey },
|
|
64
|
+
getModels: () => {
|
|
65
|
+
const models = base.getModels();
|
|
66
|
+
return selected === undefined ? models : models.filter((model) => selected.has(model.id));
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Remove the transport-only `apiKey` carrier without reintroducing it as an explicit undefined. */
|
|
72
|
+
function withoutApiKey<T extends { apiKey?: unknown }>(options: T): T {
|
|
73
|
+
const { apiKey: _dropped, ...rest } = options;
|
|
74
|
+
return rest as T;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* PiAiAdapter's api-key resolver seam necessarily populates `options.apiKey`.
|
|
79
|
+
* Kimi OAuth is header-owned Bearer auth, so remove that transport-only carrier
|
|
80
|
+
* after Models has derived Authorization and before the Anthropic client sees
|
|
81
|
+
* it (otherwise the SDK also emits an invalid x-api-key header).
|
|
82
|
+
*/
|
|
83
|
+
function stripApiKeyBeforeStream(provider: Provider<Api>): Provider<Api> {
|
|
84
|
+
return {
|
|
85
|
+
...provider,
|
|
86
|
+
stream: (model, context, options) =>
|
|
87
|
+
provider.stream(model, context, options === undefined ? undefined : withoutApiKey(options)),
|
|
88
|
+
streamSimple: (model, context, options) =>
|
|
89
|
+
provider.streamSimple(model, context, options === undefined ? undefined : withoutApiKey(options)),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function asProvider(factory: () => Provider): () => Provider<Api> {
|
|
94
|
+
return factory as () => Provider<Api>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const createCodexProvider = asProvider(openaiCodexProvider);
|
|
98
|
+
const createKimiProvider = asProvider(kimiCodingProvider);
|
|
99
|
+
const createClaudeProvider = asProvider(anthropicProvider);
|
|
100
|
+
|
|
101
|
+
export const CODEX_OAUTH_PROVIDER: OAuthProviderDefinition = {
|
|
102
|
+
slug: "codex",
|
|
103
|
+
route: CODEX_OAUTH_ROUTE,
|
|
104
|
+
nativeProviderId: CODEX_PI_PROVIDER,
|
|
105
|
+
displayName: "OpenAI Codex (ChatGPT Plus/Pro)",
|
|
106
|
+
authFilename: CODEX_OAUTH_AUTH_FILENAME,
|
|
107
|
+
modelsCacheFilename: CODEX_OAUTH_MODELS_CACHE_FILENAME,
|
|
108
|
+
loginMethods: ["device", "browser"],
|
|
109
|
+
recommendedLoginMethod: "device",
|
|
110
|
+
providerFactory: createCodexProvider,
|
|
111
|
+
requestProvider: (selectedIds) =>
|
|
112
|
+
selectedProvider(createCodexProvider(), selectedIds, requestTokenAuth("OpenAI Codex OAuth token", false)),
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export const KIMI_CODE_OAUTH_PROVIDER: OAuthProviderDefinition = {
|
|
116
|
+
slug: "kimi",
|
|
117
|
+
route: KIMI_CODE_OAUTH_ROUTE,
|
|
118
|
+
nativeProviderId: KIMI_PI_PROVIDER,
|
|
119
|
+
displayName: "Kimi Code (subscription)",
|
|
120
|
+
authFilename: KIMI_CODE_OAUTH_AUTH_FILENAME,
|
|
121
|
+
modelsCacheFilename: KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
|
|
122
|
+
loginMethods: ["device"],
|
|
123
|
+
recommendedLoginMethod: "device",
|
|
124
|
+
providerFactory: createKimiProvider,
|
|
125
|
+
requestProvider: (selectedIds) =>
|
|
126
|
+
stripApiKeyBeforeStream(
|
|
127
|
+
selectedProvider(createKimiProvider(), selectedIds, requestTokenAuth("Kimi Code OAuth token", true)),
|
|
128
|
+
),
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
export const CLAUDE_CODE_OAUTH_PROVIDER: OAuthProviderDefinition = {
|
|
132
|
+
slug: "claude",
|
|
133
|
+
route: CLAUDE_CODE_OAUTH_ROUTE,
|
|
134
|
+
nativeProviderId: CLAUDE_PI_PROVIDER,
|
|
135
|
+
displayName: "Claude Code (Pro/Max)",
|
|
136
|
+
authFilename: CLAUDE_CODE_OAUTH_AUTH_FILENAME,
|
|
137
|
+
modelsCacheFilename: CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
|
|
138
|
+
loginMethods: ["browser"],
|
|
139
|
+
recommendedLoginMethod: "browser",
|
|
140
|
+
providerFactory: createClaudeProvider,
|
|
141
|
+
requestProvider: (selectedIds) => selectedProvider(createClaudeProvider(), selectedIds, undefined),
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
export const OAUTH_PROVIDER_DEFINITIONS = [
|
|
145
|
+
CODEX_OAUTH_PROVIDER,
|
|
146
|
+
KIMI_CODE_OAUTH_PROVIDER,
|
|
147
|
+
CLAUDE_CODE_OAUTH_PROVIDER,
|
|
148
|
+
] as const;
|
|
149
|
+
|
|
150
|
+
export function oauthProviderDefinition(slug: string): OAuthProviderDefinition | undefined {
|
|
151
|
+
return OAUTH_PROVIDER_DEFINITIONS.find((provider) => provider.slug === slug);
|
|
152
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent OAuth session and static model selection for one subscription provider.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/oauth-session
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { mkdir, readFile, rm } from "node:fs/promises";
|
|
7
|
+
import { dirname, join, resolve } from "node:path";
|
|
8
|
+
import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
9
|
+
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
10
|
+
import type {
|
|
11
|
+
Api,
|
|
12
|
+
AuthInteraction,
|
|
13
|
+
Credential,
|
|
14
|
+
Model,
|
|
15
|
+
MutableModels,
|
|
16
|
+
OAuthCredential,
|
|
17
|
+
Provider,
|
|
18
|
+
} from "@earendil-works/pi-ai";
|
|
19
|
+
import { createModels } from "@earendil-works/pi-ai";
|
|
20
|
+
import type { OAuthProviderDefinition } from "./oauth-providers.ts";
|
|
21
|
+
import { OAuthCredentialFileStore, oauthCredentialPath } from "./store.ts";
|
|
22
|
+
|
|
23
|
+
const MODELS_CACHE_VERSION = 1;
|
|
24
|
+
|
|
25
|
+
interface ModelsCacheDocument {
|
|
26
|
+
version: typeof MODELS_CACHE_VERSION;
|
|
27
|
+
selected: string[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isENOENT(error: unknown): boolean {
|
|
31
|
+
return (error as NodeJS.ErrnoException | null)?.code === "ENOENT";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function parseIdList(value: unknown): string[] {
|
|
35
|
+
if (!Array.isArray(value)) return [];
|
|
36
|
+
return [...new Set(value.filter((id): id is string => typeof id === "string" && id.length > 0))];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function parseCache(text: string): string[] | undefined {
|
|
40
|
+
let value: unknown;
|
|
41
|
+
try {
|
|
42
|
+
value = JSON.parse(text);
|
|
43
|
+
} catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
|
47
|
+
const document = value as Record<string, unknown>;
|
|
48
|
+
if (document["version"] !== MODELS_CACHE_VERSION) return undefined;
|
|
49
|
+
const selected = parseIdList(document["selected"]);
|
|
50
|
+
return selected.length === 0 ? undefined : selected;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function oauthModelsCachePath(basename: string, dshHome?: string): string {
|
|
54
|
+
return resolve(join(resolveDshHome(dshHome), basename));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface OAuthProviderStatus {
|
|
58
|
+
authenticated: boolean;
|
|
59
|
+
expiresAt?: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class OAuthProviderSession {
|
|
63
|
+
readonly store: OAuthCredentialFileStore;
|
|
64
|
+
readonly models: MutableModels;
|
|
65
|
+
private readonly catalog: readonly Model<Api>[];
|
|
66
|
+
private readonly cacheFile: string;
|
|
67
|
+
private selectedIds: string[] | undefined;
|
|
68
|
+
|
|
69
|
+
constructor(
|
|
70
|
+
readonly definition: OAuthProviderDefinition,
|
|
71
|
+
onCatalogChange?: () => void,
|
|
72
|
+
store: OAuthCredentialFileStore = new OAuthCredentialFileStore(
|
|
73
|
+
definition.nativeProviderId,
|
|
74
|
+
oauthCredentialPath(definition.authFilename),
|
|
75
|
+
definition.route,
|
|
76
|
+
),
|
|
77
|
+
cacheFile: string = oauthModelsCachePath(definition.modelsCacheFilename),
|
|
78
|
+
) {
|
|
79
|
+
this.store = store;
|
|
80
|
+
this.cacheFile = resolve(cacheFile);
|
|
81
|
+
const provider = definition.providerFactory();
|
|
82
|
+
this.catalog = [...provider.getModels()];
|
|
83
|
+
this.models = createModels({ credentials: store });
|
|
84
|
+
this.models.setProvider(provider);
|
|
85
|
+
this.onCatalogChange = onCatalogChange;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private onCatalogChange: (() => void) | undefined;
|
|
89
|
+
|
|
90
|
+
availableModels(): Model<Api>[] {
|
|
91
|
+
return [...this.catalog];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
selectedModelIds(): string[] | undefined {
|
|
95
|
+
return this.selectedIds === undefined ? undefined : [...this.selectedIds];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
visibleModels(): Model<Api>[] {
|
|
99
|
+
if (this.selectedIds === undefined || this.selectedIds.length === 0) return this.availableModels();
|
|
100
|
+
const byId = new Map(this.catalog.map((model) => [model.id, model]));
|
|
101
|
+
return this.selectedIds.flatMap((id) => {
|
|
102
|
+
const model = byId.get(id);
|
|
103
|
+
return model === undefined ? [] : [model];
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
provider(): Provider {
|
|
108
|
+
return this.definition.requestProvider(this.visibleModels().map((model) => model.id));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async loadCachedModels(): Promise<void> {
|
|
112
|
+
try {
|
|
113
|
+
this.selectedIds = parseCache(await readFile(this.cacheFile, "utf8"));
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (!isENOENT(error)) throw error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async setSelectedModels(ids: readonly string[]): Promise<void> {
|
|
120
|
+
const available = new Set(this.catalog.map((model) => model.id));
|
|
121
|
+
const selected = [...new Set(ids.filter((id) => available.has(id)))];
|
|
122
|
+
this.selectedIds = selected.length === 0 ? undefined : selected;
|
|
123
|
+
await this.writeCache();
|
|
124
|
+
this.onCatalogChange?.();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async status(): Promise<OAuthProviderStatus> {
|
|
128
|
+
const credential = await this.store.read(this.definition.nativeProviderId);
|
|
129
|
+
if (credential?.type !== "oauth") return { authenticated: false };
|
|
130
|
+
return { authenticated: true, expiresAt: credential.expires };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async login(interaction: AuthInteraction): Promise<Credential> {
|
|
134
|
+
const credential = await this.models.login(this.definition.nativeProviderId, "oauth", interaction);
|
|
135
|
+
this.onCatalogChange?.();
|
|
136
|
+
return credential;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async resolveAccessToken(): Promise<string | undefined> {
|
|
140
|
+
const resolved = await this.models.getAuth(this.definition.nativeProviderId);
|
|
141
|
+
if (resolved === undefined) return undefined;
|
|
142
|
+
const credential = await this.store.read(this.definition.nativeProviderId);
|
|
143
|
+
return credential?.type === "oauth" ? credential.access : undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Backdate the stored token's expiry so the next `getAuth()` refreshes.
|
|
148
|
+
* Called after an upstream 401 rejected a locally-valid token.
|
|
149
|
+
*/
|
|
150
|
+
async invalidateAccessToken(): Promise<void> {
|
|
151
|
+
await this.store.invalidate(this.definition.nativeProviderId);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async storedCredential(): Promise<OAuthCredential | undefined> {
|
|
155
|
+
const credential = await this.store.read(this.definition.nativeProviderId);
|
|
156
|
+
return credential?.type === "oauth" ? credential : undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async logout(): Promise<void> {
|
|
160
|
+
try {
|
|
161
|
+
await this.models.logout(this.definition.nativeProviderId);
|
|
162
|
+
this.selectedIds = undefined;
|
|
163
|
+
await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
|
|
164
|
+
await rm(this.cacheFile, { force: true });
|
|
165
|
+
} finally {
|
|
166
|
+
// Credential deletion may succeed before cache cleanup fails. Always
|
|
167
|
+
// refresh discovery so an open selector cannot retain stale models.
|
|
168
|
+
this.onCatalogChange?.();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private async writeCache(): Promise<void> {
|
|
173
|
+
const document: ModelsCacheDocument = {
|
|
174
|
+
version: MODELS_CACHE_VERSION,
|
|
175
|
+
selected: this.selectedIds === undefined ? [] : [...this.selectedIds],
|
|
176
|
+
};
|
|
177
|
+
await mkdir(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
|
|
178
|
+
await writeFileAtomic(this.cacheFile, `${JSON.stringify(document)}\n`, {
|
|
179
|
+
mode: 0o600,
|
|
180
|
+
dirMode: 0o700,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|