@lks347/dsh-oauth 0.0.0-stage → 1.0.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.
- package/README.en.md +155 -0
- package/README.md +101 -2
- package/app.js +1045 -0
- package/auth.html +80 -0
- package/client.js +31 -0
- package/cordis.patch.yml +4 -0
- package/docs/CONNECTIONS.md +77 -0
- package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
- package/docs/RELEASE-1.0.1.md +48 -0
- package/docs/RELEASE-1.0.2.md +8 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/docs/evidence/release-1.0.1.json +38 -0
- package/index.html +43 -0
- package/package.json +64 -4
- package/providers.js +73 -0
- package/scripts/check-upstreams.mjs +27 -0
- package/scripts/link-peers.js +38 -0
- package/scripts/verify-browser.mjs +297 -0
- package/scripts/verify-host.mjs +431 -0
- package/scripts/verify-live.mjs +268 -0
- package/scripts/verify-package.mjs +168 -0
- package/scripts/verify-persistence.mjs +307 -0
- package/scripts/verify-subscriptions-ui.mjs +321 -0
- package/src/account.js +85 -0
- package/src/account.test.js +52 -0
- package/src/authorization.js +199 -0
- package/src/authorization.test.js +332 -0
- package/src/catalog.js +180 -0
- package/src/catalog.test.js +146 -0
- package/src/chat-recovery.js +110 -0
- package/src/chat-recovery.test.js +261 -0
- package/src/connection-runtime.js +129 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +104 -0
- package/src/grants.test.js +340 -0
- package/src/index.js +676 -0
- package/src/local-imports.js +263 -0
- package/src/local-imports.test.js +201 -0
- package/src/media.js +152 -0
- package/src/models.js +610 -0
- package/src/models.test.js +503 -0
- package/src/profile-store.js +51 -0
- package/src/pulls.js +100 -0
- package/src/pulls.test.js +156 -0
- package/src/qwen.js +141 -0
- package/src/qwen.test.js +35 -0
- package/src/request-errors.js +50 -0
- package/src/request-errors.test.js +131 -0
- package/src/routes.js +47 -0
- package/src/routes.test.js +136 -0
- package/src/subscription-models.test.js +160 -0
- package/src/usage/aggregators.js +292 -0
- package/src/usage/aggregators.test.js +316 -0
- package/src/usage/core.js +68 -0
- package/src/usage/index.js +93 -0
- package/src/usage/official.js +339 -0
- package/src/usage/official.test.js +273 -0
- package/src/usage/service.test.js +89 -0
- package/src/xai-browser.js +272 -0
- package/src/xai-browser.test.js +256 -0
- package/src/xai-login.js +121 -0
- package/src/xai-login.test.js +259 -0
- package/styles.css +364 -0
- package/theme.js +118 -0
- package/upstreams.json +10 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half: serve the OAuth panel, and drive the harness authorization
|
|
3
|
+
* seam so "登录" opens the provider's own page.
|
|
4
|
+
*/
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
|
|
10
|
+
import AuthorizationService from "@deepseek-ai/dsh-authorization";
|
|
11
|
+
import { credentialKey, credentialKeyId, credentialKeyScope } from "@deepseek-ai/dsh-credentials";
|
|
12
|
+
import { accountClientFrom, loginCallbackOrigin, loginSource, signInFailed } from "./account.js";
|
|
13
|
+
import { registerMediaTools } from "./media.js";
|
|
14
|
+
import { fetchAccountModels } from "./models.js";
|
|
15
|
+
import { createPullStore } from "./pulls.js";
|
|
16
|
+
import { qwenEndpoint } from "./qwen.js";
|
|
17
|
+
import { createAuthorizationSessions } from "./authorization.js";
|
|
18
|
+
import { createGrantResolver, QWEN_KEY_NAME } from "./grants.js";
|
|
19
|
+
import { restoreRoute, writeRoute } from "./routes.js";
|
|
20
|
+
import { withGrantRecovery } from "./request-errors.js";
|
|
21
|
+
import { registerChatRecovery } from "./chat-recovery.js";
|
|
22
|
+
import { createXaiBrowserAuthorization } from "./xai-login.js";
|
|
23
|
+
import { createConnectionRuntime } from "./connection-runtime.js";
|
|
24
|
+
import { connectionRef, connectionMetadata, validSecret } from "./connections.js";
|
|
25
|
+
import { createUsageService, usageIds } from "./usage/index.js";
|
|
26
|
+
import { providerDefinitions, getProviderDefinition } from "./catalog.js";
|
|
27
|
+
import { discoverLocalSources, fetchAntigravityCliModels, readLocalSource } from "./local-imports.js";
|
|
28
|
+
|
|
29
|
+
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
30
|
+
const VERSION = JSON.parse(await readFile(join(ROOT, "package.json"), "utf8")).version;
|
|
31
|
+
const PI_AI = "llm-pi-ai";
|
|
32
|
+
const OAUTH_SCOPE = "dsh-oauth";
|
|
33
|
+
const QWEN_ID = "qwen";
|
|
34
|
+
const DEEPSEEK_ACCOUNT = "deepseek-account";
|
|
35
|
+
const DEEPSEEK_KEY = credentialKey("deepseek-account-platform", "default");
|
|
36
|
+
|
|
37
|
+
const FILES = {
|
|
38
|
+
"/oauth": "index.html",
|
|
39
|
+
"/oauth/": "index.html",
|
|
40
|
+
"/oauth/index.html": "index.html",
|
|
41
|
+
"/oauth/app.js": "app.js",
|
|
42
|
+
"/oauth/auth.html": "auth.html",
|
|
43
|
+
"/oauth/providers.js": "providers.js",
|
|
44
|
+
"/oauth/styles.css": "styles.css",
|
|
45
|
+
"/oauth/theme.js": "theme.js",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const TYPES = {
|
|
49
|
+
".html": "text/html; charset=utf-8",
|
|
50
|
+
".js": "text/javascript; charset=utf-8",
|
|
51
|
+
".css": "text/css; charset=utf-8",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export const name = "dsh-oauth";
|
|
55
|
+
export const inject = ["credentials", "settings"];
|
|
56
|
+
|
|
57
|
+
const runtimes = new WeakMap();
|
|
58
|
+
|
|
59
|
+
export async function apply(ctx) {
|
|
60
|
+
const sessions = new Map();
|
|
61
|
+
const authorizationSessions = createAuthorizationSessions({ sessions });
|
|
62
|
+
const connectionRuntime = createConnectionRuntime(ctx.credentials, createGrantResolver(ctx.credentials));
|
|
63
|
+
const resolveGrant = connectionRuntime.resolve;
|
|
64
|
+
const pulls = createPullStore(ctx.profileContext?.dir);
|
|
65
|
+
const usage = createUsageService({ directory: ctx.profileContext?.dir, contextFor: connectionRuntime.contextFor });
|
|
66
|
+
runtimes.set(ctx, { sessions, authorizationSessions, resolveGrant, pulls, connectionRuntime, usage, mutations: new Map() });
|
|
67
|
+
ctx.on('llm/stream', (options, next) => (async function* () {
|
|
68
|
+
if (typeof options.provider === 'string') {
|
|
69
|
+
await mutateProvider(ctx, options.provider, async () => {
|
|
70
|
+
const connection = await connectionRuntime.connections.read(options.provider);
|
|
71
|
+
const pull = await currentPull(ctx, options.provider);
|
|
72
|
+
if (options.provider === 'anthropic' && pull && (!connection || connection.mode === 'oauth')) {
|
|
73
|
+
throw new Error('Connect a Claude Console API key and refresh this plugin’s Claude model configuration.');
|
|
74
|
+
}
|
|
75
|
+
if (connection?.mode === 'local' || connection?.mode === 'key') {
|
|
76
|
+
if (!pull) throw new Error('Import the selected connection’s models before using this provider.');
|
|
77
|
+
await resolveGrant(options.provider);
|
|
78
|
+
}
|
|
79
|
+
const model = pull?.models?.find(row => row.id === options.model);
|
|
80
|
+
if (model?.tools === false && Array.isArray(options.tools) && options.tools.length) throw new Error('This imported model explicitly does not support tool calls. Choose a model with tool support.');
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
yield* next();
|
|
84
|
+
})());
|
|
85
|
+
ctx.on("dispose", () => runtimes.get(ctx)?.xaiBrowser?.dispose());
|
|
86
|
+
registerChatRecovery(ctx, resolveGrant);
|
|
87
|
+
ctx.on("dispose", () => authorizationSessions.dispose());
|
|
88
|
+
if (ctx.get("authorization") === undefined) {
|
|
89
|
+
try {
|
|
90
|
+
await ctx.plugin(AuthorizationService);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
93
|
+
if (!message.includes("has been registered")) throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const serve = (req, res) => handle(ctx, req, res).catch((error) => {
|
|
97
|
+
if (!res.headersSent) json(res, error instanceof SyntaxError ? 400 : 500, {
|
|
98
|
+
error: error instanceof Error ? error.message : String(error),
|
|
99
|
+
});
|
|
100
|
+
else res.end();
|
|
101
|
+
});
|
|
102
|
+
ctx.inject(["tools", "systemPrompt"], (scoped) => {
|
|
103
|
+
registerMediaTools(scoped, resolveGrant, pulls);
|
|
104
|
+
});
|
|
105
|
+
ctx.inject(["webServer"], (web) => {
|
|
106
|
+
web.effect(() => web.webServer.register({
|
|
107
|
+
kind: "prefix",
|
|
108
|
+
path: "/oauth",
|
|
109
|
+
handler: serve,
|
|
110
|
+
}), "dsh-oauth: panel");
|
|
111
|
+
});
|
|
112
|
+
let maintaining = false;
|
|
113
|
+
const maintain = async () => {
|
|
114
|
+
if (maintaining) return;
|
|
115
|
+
maintaining = true;
|
|
116
|
+
try {
|
|
117
|
+
for (const pull of await pulls.list({ includeExpired: true })) {
|
|
118
|
+
try {
|
|
119
|
+
if (pull.expiresAt !== null && pull.expiresAt <= Date.now()) await currentPull(ctx, pull.id);
|
|
120
|
+
else if (pull.id === QWEN_ID || (await connectionRuntime.connections.read(pull.id))?.mode === 'local') await resolveGrant(pull.id);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
ctx.logger.warn(error instanceof Error ? error : new Error(String(error)));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} catch (error) {
|
|
126
|
+
ctx.logger.warn(error instanceof Error ? error : new Error(String(error)));
|
|
127
|
+
} finally { maintaining = false; }
|
|
128
|
+
};
|
|
129
|
+
const timer = setInterval(() => void maintain(), 60000);
|
|
130
|
+
timer.unref?.();
|
|
131
|
+
ctx.on("dispose", () => clearInterval(timer));
|
|
132
|
+
void maintain();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function handle(ctx, req, res) {
|
|
136
|
+
const { sessions, authorizationSessions } = runtimes.get(ctx);
|
|
137
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
138
|
+
if (url.pathname === "/oauth/api/login/status" && req.method === "GET") {
|
|
139
|
+
const id = providerId(url.searchParams.get("provider"));
|
|
140
|
+
if (!id) return json(res, 400, { error: "需要 provider id" });
|
|
141
|
+
if (id === DEEPSEEK_ACCOUNT) await updateDeepSeekSession(ctx);
|
|
142
|
+
return json(res, 200, authorizationSessions.get(id) ?? { status: "idle", pending: false });
|
|
143
|
+
}
|
|
144
|
+
if ((url.pathname === "/oauth/api/login/answer" || url.pathname === "/oauth/api/login/cancel") && req.method === "POST") {
|
|
145
|
+
const body = await readJson(req);
|
|
146
|
+
const id = providerId(body.provider);
|
|
147
|
+
if (!id) return json(res, 400, { error: "需要 provider id" });
|
|
148
|
+
try {
|
|
149
|
+
if (url.pathname.endsWith("/answer")) authorizationSessions.answer(id, body);
|
|
150
|
+
else {
|
|
151
|
+
if (id === DEEPSEEK_ACCOUNT) {
|
|
152
|
+
const session = sessions.get(id);
|
|
153
|
+
if (!session || typeof body.attemptId !== "string" || session.attemptId !== body.attemptId) {
|
|
154
|
+
throw new Error("登录尝试已更新,请刷新后重试");
|
|
155
|
+
}
|
|
156
|
+
if (session.status === "pending") {
|
|
157
|
+
const account = deepseekAccount(ctx);
|
|
158
|
+
if (session.upstreamAttemptId) await account.cancelSignIn(session.upstreamAttemptId);
|
|
159
|
+
await updateDeepSeekSession(ctx);
|
|
160
|
+
if (session.status === "pending") session.status = "cancelled";
|
|
161
|
+
}
|
|
162
|
+
} else authorizationSessions.cancel(id, body);
|
|
163
|
+
}
|
|
164
|
+
return json(res, 200, authorizationSessions.get(id));
|
|
165
|
+
} catch (error) {
|
|
166
|
+
return json(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (url.pathname === "/oauth/api/providers" && req.method === "GET") {
|
|
170
|
+
return json(res, 200, { version: VERSION, providers: await listProviders(ctx) });
|
|
171
|
+
}
|
|
172
|
+
if (url.pathname === '/oauth/api/import/sources' && req.method === 'GET') {
|
|
173
|
+
const sources = await discoverLocalSources();
|
|
174
|
+
for (const source of sources) {
|
|
175
|
+
source.providers = source.providers.map(row => {
|
|
176
|
+
const definition = getProviderDefinition(row.provider);
|
|
177
|
+
const supported = !!definition && (row.authType === 'oauth' ? definition.oauthConnect !== false : definition.keyConnect);
|
|
178
|
+
return supported ? row : { ...row, available: false, reasonCode: 'unsupported-provider' };
|
|
179
|
+
});
|
|
180
|
+
source.available = source.providers.some(row => row.available);
|
|
181
|
+
}
|
|
182
|
+
return json(res, 200, { sources });
|
|
183
|
+
}
|
|
184
|
+
if (['/oauth/api/connect', '/oauth/api/connection', '/oauth/api/usage', '/oauth/api/import'].includes(url.pathname) && req.method === 'POST') {
|
|
185
|
+
const body = await readJson(req);
|
|
186
|
+
const id = providerId(body.provider);
|
|
187
|
+
if (!id) return json(res, 400, { error: '需要 provider id' });
|
|
188
|
+
const runtime = runtimes.get(ctx);
|
|
189
|
+
try {
|
|
190
|
+
if (url.pathname.endsWith('/usage') && id === 'anthropic') return json(res, 200, { status: 'unsupported' });
|
|
191
|
+
if (url.pathname.endsWith('/usage')) return json(res, 200, await runtime.usage.get(id, { force: body.force === true }));
|
|
192
|
+
await mutateProvider(ctx, id, async () => {
|
|
193
|
+
if (runtime.sessions.get(id)?.status === 'pending') throw new Error('Cancel the pending login before replacing this connection.');
|
|
194
|
+
const definition = getProviderDefinition(id, body);
|
|
195
|
+
if (url.pathname.endsWith('/connect')) {
|
|
196
|
+
if (!definition?.keyConnect) throw new Error('This provider does not support this key connection.');
|
|
197
|
+
validSecret(body.access); connectionMetadata(body);
|
|
198
|
+
if (body.billingAccess) validSecret(body.billingAccess);
|
|
199
|
+
if (id === 'zai' && !!body.organizationId !== !!body.projectId) throw new Error('Z.AI organization and project IDs must be configured together.');
|
|
200
|
+
await dropRoute(ctx, id);
|
|
201
|
+
await runtime.connectionRuntime.connections.connect(id, body);
|
|
202
|
+
} else if (url.pathname.endsWith('/import')) {
|
|
203
|
+
const imported = await readLocalSource(body.source, id);
|
|
204
|
+
if (!definition || (imported.grant.type === 'api_key' ? !definition.keyConnect : definition.oauthConnect === false)) throw new Error('This local credential has no supported model route.');
|
|
205
|
+
await dropRoute(ctx, id);
|
|
206
|
+
await runtime.connectionRuntime.connections.saveLocal(id, body.source, imported.label);
|
|
207
|
+
await runtime.resolveGrant(id);
|
|
208
|
+
} else {
|
|
209
|
+
if (!definition) throw new Error('Unknown provider.');
|
|
210
|
+
const current = await runtime.connectionRuntime.connections.read(id);
|
|
211
|
+
const metadata = { ...current?.metadata, ...connectionMetadata(body) };
|
|
212
|
+
if (id === 'new-api' && !getProviderDefinition(id, metadata)?.keyConnect) throw new Error('Configure a valid HTTPS gateway API root.');
|
|
213
|
+
if (id === 'zai' && !!metadata.organizationId !== !!metadata.projectId) throw new Error('Z.AI organization and project IDs must be configured together.');
|
|
214
|
+
if (body.billingAccess) validSecret(body.billingAccess);
|
|
215
|
+
// Endpoint/scope changes require re-import, so an old route cannot use a new region's key.
|
|
216
|
+
if (['region', 'baseURL', 'organizationId', 'workspaceId', 'projectId'].some(key => body[key] !== undefined)) await dropRoute(ctx, id);
|
|
217
|
+
await runtime.connectionRuntime.connections.configure(id, body);
|
|
218
|
+
}
|
|
219
|
+
await runtime.usage.invalidate(id);
|
|
220
|
+
});
|
|
221
|
+
return json(res, 200, { ok: true });
|
|
222
|
+
} catch (error) { return json(res, 400, { error: error instanceof Error ? error.message : 'Connection failed.' }); }
|
|
223
|
+
}
|
|
224
|
+
if (url.pathname === "/oauth/api/login" && req.method === "POST") {
|
|
225
|
+
const body = await readJson(req);
|
|
226
|
+
const id = typeof body.provider === "string" ? body.provider : "";
|
|
227
|
+
if (!/^[a-z][a-z0-9-]*$/.test(id)) return json(res, 400, { error: "需要 provider id" });
|
|
228
|
+
try {
|
|
229
|
+
const started = await startLogin(ctx, id, req, body.method);
|
|
230
|
+
return json(res, 200, started);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
return json(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (url.pathname === "/oauth/api/models" && req.method === "POST") {
|
|
236
|
+
const body = await readJson(req);
|
|
237
|
+
const id = providerId(body.provider);
|
|
238
|
+
if (id === undefined) return json(res, 400, { error: "需要 provider id" });
|
|
239
|
+
try {
|
|
240
|
+
if (id === 'google-antigravity' && body.source === 'agy') return json(res, 200, { models: await fetchAntigravityCliModels() });
|
|
241
|
+
const models = await accountModels(ctx, id);
|
|
242
|
+
return json(res, 200, { models });
|
|
243
|
+
} catch (error) {
|
|
244
|
+
return json(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (url.pathname === "/oauth/api/pull" && req.method === "POST") {
|
|
248
|
+
const body = await readJson(req);
|
|
249
|
+
const id = providerId(body.provider);
|
|
250
|
+
if (id === undefined) return json(res, 400, { error: "需要 provider id" });
|
|
251
|
+
try {
|
|
252
|
+
const saved = await mutateProvider(ctx, id, () => savePull(ctx, id, body));
|
|
253
|
+
return json(res, 200, saved);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
return json(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (url.pathname === "/oauth/api/logout" && req.method === "POST") {
|
|
259
|
+
const body = await readJson(req);
|
|
260
|
+
const id = providerId(body.provider);
|
|
261
|
+
if (id === undefined) return json(res, 400, { error: "需要 provider id" });
|
|
262
|
+
authorizationSessions.clear(id);
|
|
263
|
+
if (id === "xai") {
|
|
264
|
+
runtimes.get(ctx).xaiBrowser?.cancel(credentialKey(PI_AI, "xai"));
|
|
265
|
+
ctx.get("authorization")?.cancel(credentialKey(PI_AI, "xai"));
|
|
266
|
+
}
|
|
267
|
+
if (id === DEEPSEEK_ACCOUNT) {
|
|
268
|
+
const account = deepseekAccount(ctx);
|
|
269
|
+
if (account !== undefined && typeof account.signOut === "function") {
|
|
270
|
+
await account.signOut(accountClientFrom(req));
|
|
271
|
+
} else await ctx.credentials.deleteRecord(DEEPSEEK_KEY);
|
|
272
|
+
} else {
|
|
273
|
+
const disconnect = async () => {
|
|
274
|
+
await runtimes.get(ctx).usage.invalidate(id);
|
|
275
|
+
await runtimes.get(ctx).connectionRuntime.connections.disconnect(id);
|
|
276
|
+
await ctx.credentials.deleteRecord(credentialKey(id === QWEN_ID ? OAUTH_SCOPE : PI_AI, id));
|
|
277
|
+
if (id === QWEN_ID && typeof ctx.credentials.unset === "function") await ctx.credentials.unset(QWEN_KEY_NAME);
|
|
278
|
+
await dropRoute(ctx, id);
|
|
279
|
+
};
|
|
280
|
+
await mutateProvider(ctx, id, disconnect);
|
|
281
|
+
}
|
|
282
|
+
return json(res, 200, { ok: true });
|
|
283
|
+
}
|
|
284
|
+
const file = FILES[url.pathname];
|
|
285
|
+
if (file === undefined || req.method !== "GET" && req.method !== "HEAD") {
|
|
286
|
+
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
|
287
|
+
res.end("not found");
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const body = await readFile(join(ROOT, file));
|
|
291
|
+
const type = TYPES[file.slice(file.lastIndexOf("."))] ?? "application/octet-stream";
|
|
292
|
+
res.writeHead(200, { "content-type": type, "cache-control": "no-store" });
|
|
293
|
+
res.end(req.method === "HEAD" ? undefined : body);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function listProviders(ctx) {
|
|
297
|
+
const { sessions } = runtimes.get(ctx);
|
|
298
|
+
const authorization = ctx.get("authorization");
|
|
299
|
+
const flows = (authorization?.list() ?? []).filter((entry) =>
|
|
300
|
+
credentialKeyScope(entry.key) === PI_AI && entry.methods.some((method) => method.id === "oauth"));
|
|
301
|
+
const rows = [];
|
|
302
|
+
for (const flow of flows) {
|
|
303
|
+
const id = credentialKeyId(flow.key);
|
|
304
|
+
const info = await ctx.credentials.describeRecord(flow.key);
|
|
305
|
+
const loggedIn = info.configured && info.kind === "grant";
|
|
306
|
+
let tokenPreview = "";
|
|
307
|
+
let expiresAt = null;
|
|
308
|
+
if (loggedIn) {
|
|
309
|
+
const record = await ctx.credentials.readRecord(flow.key);
|
|
310
|
+
const payload = record?.kind === "grant" ? record.payload : undefined;
|
|
311
|
+
const access = payload && typeof payload === "object" ? payload.access : undefined;
|
|
312
|
+
if (typeof access === "string" && access.length > 8) {
|
|
313
|
+
tokenPreview = `${access.slice(0, 4)}…${access.slice(-4)}`;
|
|
314
|
+
}
|
|
315
|
+
const expires = payload && typeof payload === "object" ? payload.expires : undefined;
|
|
316
|
+
if (typeof expires === "number") expiresAt = expires;
|
|
317
|
+
}
|
|
318
|
+
const pull = await currentPull(ctx, id);
|
|
319
|
+
const session = sessions.get(id);
|
|
320
|
+
rows.push({
|
|
321
|
+
id,
|
|
322
|
+
name: flow.label,
|
|
323
|
+
flow: "pkce",
|
|
324
|
+
...(id === "xai" ? { loginMethods: ["browser", "device"], defaultLoginMethod: "browser" } : {}),
|
|
325
|
+
group: "订阅 OAuth",
|
|
326
|
+
pullable: ["openai-codex", "anthropic", "github-copilot", "kimi-coding", "openrouter", "xai"].includes(id),
|
|
327
|
+
cli: id === "xai" ? "" : `dsh oauth login ${id}`,
|
|
328
|
+
docs: "#",
|
|
329
|
+
loggedIn,
|
|
330
|
+
tokenPreview,
|
|
331
|
+
expiresAt,
|
|
332
|
+
sourceLabel: loggedIn ? "本机登录" : "",
|
|
333
|
+
pending: session?.status === "pending",
|
|
334
|
+
error: session?.error ?? "",
|
|
335
|
+
pulledModels: [...(pull?.models ?? []), ...(pull?.media ?? [])],
|
|
336
|
+
pullExpiresAt: pull?.expiresAt ?? null,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
rows.push(await qwenRow(ctx));
|
|
340
|
+
const deepseek = await deepseekRow(ctx);
|
|
341
|
+
if (deepseek !== undefined) rows.push(deepseek);
|
|
342
|
+
for (const definition of providerDefinitions) {
|
|
343
|
+
if (!rows.some(row => row.id === definition.id)) rows.push({ id: definition.id, name: definition.name, group: definition.group, flow: 'key', loggedIn: false, pending: false, pulledModels: [], cli: '', docs: definition.docs ?? '#' });
|
|
344
|
+
}
|
|
345
|
+
for (const row of rows) {
|
|
346
|
+
const runtime = runtimes.get(ctx);
|
|
347
|
+
const connection = await runtime.connectionRuntime.connections.read(row.id);
|
|
348
|
+
const definition = getProviderDefinition(row.id, connection?.metadata);
|
|
349
|
+
const pull = await currentPull(ctx, row.id);
|
|
350
|
+
const native = row.flow !== 'key';
|
|
351
|
+
row.keyConnect = definition?.keyConnect === true || row.id === 'new-api' || row.id === 'aliyun-token-plan';
|
|
352
|
+
const oauth = native && definition?.oauthConnect !== false && row.id !== QWEN_ID;
|
|
353
|
+
row.authMethods = [...(oauth ? ['oauth'] : []), ...(row.keyConnect ? ['key'] : []), ...(definition && row.id !== QWEN_ID ? ['local'] : [])];
|
|
354
|
+
row.usageSupported = usageIds.has(row.id) && row.id !== 'anthropic';
|
|
355
|
+
row.credentialConfigured = !!connection?.access || row.loggedIn && definition?.oauthConnect !== false || connection?.mode === 'local';
|
|
356
|
+
row.billingCredentialConfigured = !!connection?.billingAccess;
|
|
357
|
+
row.loggedIn = row.credentialConfigured;
|
|
358
|
+
if (connection?.mode === 'local') {
|
|
359
|
+
try {
|
|
360
|
+
const { grant } = await readLocalSource(connection.localSource, row.id);
|
|
361
|
+
if (grant.type === 'oauth' && definition?.oauthConnect === false) row.sourceStatus = 'unsupported-provider';
|
|
362
|
+
} catch (error) { row.sourceStatus = error.code ?? 'source-unavailable'; }
|
|
363
|
+
if (row.sourceStatus) row.loggedIn = false;
|
|
364
|
+
}
|
|
365
|
+
if (row.id === 'anthropic') {
|
|
366
|
+
row.name = definition.name;
|
|
367
|
+
row.cli = '';
|
|
368
|
+
}
|
|
369
|
+
if (definition?.docs) row.docs = definition.docs;
|
|
370
|
+
row.connection = connection?.metadata ?? {};
|
|
371
|
+
row.sourceLabel = connection?.mode === 'key' ? 'API Key' : connection?.mode === 'local' ? `${connection.sourceLabel} · external-managed` : row.sourceLabel;
|
|
372
|
+
row.pullable = row.pullable || !!definition?.modelsURL || !!definition?.catalogProvider;
|
|
373
|
+
row.pulledModels = [...(pull?.models ?? []), ...(pull?.media ?? [])];
|
|
374
|
+
row.pullExpiresAt = pull?.expiresAt ?? null;
|
|
375
|
+
row.pullPermanent = !!pull && pull.expiresAt === null;
|
|
376
|
+
row.modelSource = definition?.modelSource;
|
|
377
|
+
row.supportReason = definition?.reason;
|
|
378
|
+
if (row.id === 'google-antigravity') row.cliCatalog = true;
|
|
379
|
+
delete row.tokenPreview;
|
|
380
|
+
}
|
|
381
|
+
return rows;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function mutateProvider(ctx, id, operation) {
|
|
385
|
+
const mutations = runtimes.get(ctx).mutations;
|
|
386
|
+
const next = (mutations.get(id) ?? Promise.resolve()).then(operation);
|
|
387
|
+
mutations.set(id, next.catch(() => {}));
|
|
388
|
+
return next;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function qwenRow(ctx) {
|
|
392
|
+
const { sessions } = runtimes.get(ctx);
|
|
393
|
+
const key = credentialKey(OAUTH_SCOPE, QWEN_ID);
|
|
394
|
+
const info = await ctx.credentials.describeRecord(key);
|
|
395
|
+
const loggedIn = info.configured && info.kind === "grant";
|
|
396
|
+
const pull = await currentPull(ctx, QWEN_ID);
|
|
397
|
+
const session = sessions.get(QWEN_ID);
|
|
398
|
+
let tokenPreview = "";
|
|
399
|
+
let expiresAt = null;
|
|
400
|
+
if (loggedIn) {
|
|
401
|
+
const record = await ctx.credentials.readRecord(key);
|
|
402
|
+
const payload = record?.kind === "grant" ? record.payload : undefined;
|
|
403
|
+
tokenPreview = tokenPreviewOf(payload);
|
|
404
|
+
if (payload && typeof payload.expires === "number") expiresAt = payload.expires;
|
|
405
|
+
}
|
|
406
|
+
return {
|
|
407
|
+
id: QWEN_ID,
|
|
408
|
+
name: "通义千问",
|
|
409
|
+
flow: "pkce",
|
|
410
|
+
group: "Coding Plan",
|
|
411
|
+
pullable: true,
|
|
412
|
+
cli: "",
|
|
413
|
+
docs: "https://chat.qwen.ai",
|
|
414
|
+
loggedIn,
|
|
415
|
+
tokenPreview,
|
|
416
|
+
expiresAt,
|
|
417
|
+
sourceLabel: loggedIn ? "通义千问账号" : "",
|
|
418
|
+
pending: session?.status === "pending",
|
|
419
|
+
error: session?.error ?? "",
|
|
420
|
+
pulledModels: [...(pull?.models ?? []), ...(pull?.media ?? [])],
|
|
421
|
+
pullExpiresAt: pull?.expiresAt ?? null,
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function deepseekRow(ctx) {
|
|
426
|
+
const { sessions } = runtimes.get(ctx);
|
|
427
|
+
await updateDeepSeekSession(ctx);
|
|
428
|
+
const account = deepseekAccount(ctx);
|
|
429
|
+
let info;
|
|
430
|
+
try {
|
|
431
|
+
info = await ctx.credentials.describeRecord(DEEPSEEK_KEY);
|
|
432
|
+
} catch {
|
|
433
|
+
if (account === undefined) return undefined;
|
|
434
|
+
}
|
|
435
|
+
if (account === undefined && info?.configured !== true) return undefined;
|
|
436
|
+
const loggedIn = info?.configured === true && info.kind === "grant";
|
|
437
|
+
let tokenPreview = "";
|
|
438
|
+
if (loggedIn) {
|
|
439
|
+
const record = await ctx.credentials.readRecord(DEEPSEEK_KEY);
|
|
440
|
+
const payload = record?.kind === "grant" ? record.payload : undefined;
|
|
441
|
+
tokenPreview = tokenPreviewOf(payload);
|
|
442
|
+
}
|
|
443
|
+
const session = sessions.get(DEEPSEEK_ACCOUNT);
|
|
444
|
+
return {
|
|
445
|
+
id: DEEPSEEK_ACCOUNT,
|
|
446
|
+
name: "DeepSeek 官方账号",
|
|
447
|
+
flow: "browser",
|
|
448
|
+
group: "官方账号",
|
|
449
|
+
pullable: false,
|
|
450
|
+
cli: "",
|
|
451
|
+
docs: "https://platform.deepseek.com",
|
|
452
|
+
loggedIn,
|
|
453
|
+
tokenPreview,
|
|
454
|
+
expiresAt: null,
|
|
455
|
+
sourceLabel: loggedIn ? "官方账号" : "",
|
|
456
|
+
pending: session?.status === "pending",
|
|
457
|
+
error: session?.error ?? "",
|
|
458
|
+
pulledModels: [],
|
|
459
|
+
pullExpiresAt: null,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function tokenPreviewOf(payload) {
|
|
464
|
+
const token = payload && typeof payload === "object"
|
|
465
|
+
? (typeof payload.access === "string" ? payload.access : typeof payload.token === "string" ? payload.token : "")
|
|
466
|
+
: "";
|
|
467
|
+
return token.length > 8 ? `${token.slice(0, 4)}…${token.slice(-4)}` : "";
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function deepseekAccount(ctx) {
|
|
471
|
+
try {
|
|
472
|
+
const account = ctx.get("deepseekAccount");
|
|
473
|
+
return account && typeof account === "object" ? account : undefined;
|
|
474
|
+
} catch {
|
|
475
|
+
return undefined;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async function startLogin(ctx, id, req, method) {
|
|
480
|
+
if (id === QWEN_ID) throw new Error("旧版通义千问 OAuth 已停止接受新连接,请使用阿里云 Token Plan 密钥。");
|
|
481
|
+
if (getProviderDefinition(id)?.oauthConnect === false) throw new Error("请使用 Claude Console API Key 连接。Claude 订阅登录由 Claude Code 管理。");
|
|
482
|
+
const runtime = runtimes.get(ctx);
|
|
483
|
+
if (runtime.sessions.get(id)?.status !== 'pending' && id !== DEEPSEEK_ACCOUNT) {
|
|
484
|
+
await mutateProvider(ctx, id, async () => {
|
|
485
|
+
await runtime.usage.invalidate(id);
|
|
486
|
+
await runtime.connectionRuntime.connections.disconnect(id);
|
|
487
|
+
await dropRoute(ctx, id);
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
if (id === "xai") {
|
|
491
|
+
if (method !== undefined && method !== "browser" && method !== "device") throw new Error("xAI 登录方式无效");
|
|
492
|
+
const authorization = ctx.get("authorization");
|
|
493
|
+
if (!authorization) throw new Error("authorization 服务还没有挂上");
|
|
494
|
+
const runtime = runtimes.get(ctx);
|
|
495
|
+
const selected = method ?? "browser";
|
|
496
|
+
if (runtime.sessions.get(id)?.status === "pending") {
|
|
497
|
+
if (runtime.xaiLoginMethod !== selected) throw new Error("请先取消当前 xAI 登录,再切换登录方式");
|
|
498
|
+
return runtime.authorizationSessions.get(id);
|
|
499
|
+
}
|
|
500
|
+
runtime.xaiLoginMethod = selected;
|
|
501
|
+
if (!runtime.xaiBrowser || runtime.xaiBrowserHost !== authorization) {
|
|
502
|
+
runtime.xaiBrowser?.dispose();
|
|
503
|
+
runtime.xaiBrowser = createXaiBrowserAuthorization(ctx, authorization);
|
|
504
|
+
runtime.xaiBrowserHost = authorization;
|
|
505
|
+
}
|
|
506
|
+
if (method === "device") {
|
|
507
|
+
if (runtime.xaiBrowser.describe(credentialKey(PI_AI, "xai"))?.inFlight) {
|
|
508
|
+
throw new Error("xAI 正在登录,请先完成或取消当前尝试");
|
|
509
|
+
}
|
|
510
|
+
return startScopedLogin(ctx, id, PI_AI);
|
|
511
|
+
}
|
|
512
|
+
return runtime.authorizationSessions.begin(runtime.xaiBrowser, id, credentialKey(PI_AI, "xai"));
|
|
513
|
+
}
|
|
514
|
+
if (id === DEEPSEEK_ACCOUNT) return startDeepSeekLogin(ctx, req);
|
|
515
|
+
return startScopedLogin(ctx, id, PI_AI);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
async function startScopedLogin(ctx, id, scope) {
|
|
519
|
+
const authorization = ctx.get("authorization");
|
|
520
|
+
if (authorization === undefined) throw new Error("authorization 服务还没有挂上");
|
|
521
|
+
const key = credentialKey(scope, id);
|
|
522
|
+
const flow = authorization.describe(key);
|
|
523
|
+
if (flow === undefined || !flow.methods.some((method) => method.id === "oauth")) {
|
|
524
|
+
throw new Error(`没有 ${id} 的 OAuth 登录`);
|
|
525
|
+
}
|
|
526
|
+
return runtimes.get(ctx).authorizationSessions.begin(authorization, id, key);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
async function startDeepSeekLogin(ctx, req) {
|
|
530
|
+
const { sessions } = runtimes.get(ctx);
|
|
531
|
+
const account = deepseekAccount(ctx);
|
|
532
|
+
if (account === undefined || typeof account.startSignIn !== "function") {
|
|
533
|
+
throw new Error("当前桌面版没有挂上 DeepSeek 官方账号登录");
|
|
534
|
+
}
|
|
535
|
+
const origin = loginCallbackOrigin(req.headers?.host);
|
|
536
|
+
const source = loginSource(origin);
|
|
537
|
+
const attemptId = randomUUID();
|
|
538
|
+
sessions.set(DEEPSEEK_ACCOUNT, { status: "pending", attemptId });
|
|
539
|
+
let state;
|
|
540
|
+
try { state = await account.startSignIn(accountClientFrom(req), origin, source); }
|
|
541
|
+
catch (error) {
|
|
542
|
+
sessions.set(DEEPSEEK_ACCOUNT, { status: "error", attemptId, error: error instanceof Error ? error.message : String(error) });
|
|
543
|
+
throw error;
|
|
544
|
+
}
|
|
545
|
+
const session = sessions.get(DEEPSEEK_ACCOUNT);
|
|
546
|
+
session.upstreamAttemptId = state?.attempt?.id;
|
|
547
|
+
let url = state?.attempt?.authorizeUrl;
|
|
548
|
+
for (let attempt = 0; attempt < 40 && (typeof url !== "string" || url.length === 0); attempt += 1) {
|
|
549
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
550
|
+
const next = await account.getState();
|
|
551
|
+
session.upstreamAttemptId = next?.attempt?.id ?? session.upstreamAttemptId;
|
|
552
|
+
const phase = next?.attempt?.phase;
|
|
553
|
+
if (signInFailed(phase)) {
|
|
554
|
+
const message = "DeepSeek 官方账号登录没有完成";
|
|
555
|
+
sessions.set(DEEPSEEK_ACCOUNT, { status: "error", error: message, attemptId });
|
|
556
|
+
throw new Error(message);
|
|
557
|
+
}
|
|
558
|
+
url = next?.attempt?.authorizeUrl;
|
|
559
|
+
if (next?.status === "credential-stored" && (phase === "succeeded" || phase === undefined)) break;
|
|
560
|
+
}
|
|
561
|
+
if (typeof url === "string" && url.length > 0) session.url = url;
|
|
562
|
+
await updateDeepSeekSession(ctx);
|
|
563
|
+
return runtimes.get(ctx).authorizationSessions.get(DEEPSEEK_ACCOUNT);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
async function updateDeepSeekSession(ctx) {
|
|
567
|
+
const session = runtimes.get(ctx).sessions.get(DEEPSEEK_ACCOUNT);
|
|
568
|
+
if (session?.status !== "pending") return;
|
|
569
|
+
const state = await deepseekAccount(ctx)?.getState?.();
|
|
570
|
+
if (state?.attempt?.id) session.upstreamAttemptId = state.attempt.id;
|
|
571
|
+
if (signInFailed(state?.attempt?.phase)) {
|
|
572
|
+
session.status = state.attempt.phase === "cancelled" ? "cancelled" : "error";
|
|
573
|
+
if (session.status === "error") session.error = "DeepSeek 官方账号登录没有完成";
|
|
574
|
+
} else if (state?.status === "credential-stored" && (!state.attempt || state.attempt.phase === "succeeded")) {
|
|
575
|
+
session.status = "authorized";
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function providerId(value) {
|
|
580
|
+
return typeof value === "string" && /^[a-z][a-z0-9-]*$/.test(value) ? value : undefined;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
async function grantPayload(ctx, id) {
|
|
584
|
+
return runtimes.get(ctx).resolveGrant(id);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
async function accountModels(ctx, id) {
|
|
588
|
+
const connection = await runtimes.get(ctx).connectionRuntime.connections.read(id);
|
|
589
|
+
return withGrantRecovery(id, runtimes.get(ctx).resolveGrant,
|
|
590
|
+
(grant) => fetchAccountModels(id, { ...grant, ...connection?.metadata }));
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async function currentPull(ctx, id) {
|
|
594
|
+
const pull = await runtimes.get(ctx).pulls.read(id);
|
|
595
|
+
if (pull === undefined) return undefined;
|
|
596
|
+
if (pull.expiresAt === null || pull.expiresAt > Date.now()) return pull;
|
|
597
|
+
await dropRoute(ctx, id);
|
|
598
|
+
return undefined;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async function savePull(ctx, id, body) {
|
|
602
|
+
const available = await accountModels(ctx, id);
|
|
603
|
+
const known = new Map(available.map((model) => [model.id, model]));
|
|
604
|
+
const chosen = Array.isArray(body.models) ? body.models.filter((modelId) => typeof modelId === "string" && known.has(modelId)) : [];
|
|
605
|
+
if (chosen.length === 0) throw new Error("至少选择一个从该 OAuth 账号拉到的模型");
|
|
606
|
+
const expiresAt = body.expiresAt === null || body.expiresAt === undefined ? null : Number(body.expiresAt);
|
|
607
|
+
if (expiresAt !== null && (!Number.isFinite(expiresAt) || expiresAt <= Date.now())) throw new Error("过期时间要晚于现在");
|
|
608
|
+
if (expiresAt !== null && expiresAt > Date.now() + 366 * 24 * 60 * 60 * 1000) throw new Error("过期时间不能超过一年");
|
|
609
|
+
const chat = chosen.map((modelId) => known.get(modelId)).filter((model) => model.role === "chat");
|
|
610
|
+
if (chat.length === 0) throw new Error("至少选择一个对话模型。生图和生视频模型不会替换当前对话。");
|
|
611
|
+
const payload = await grantPayload(ctx, id);
|
|
612
|
+
if (id === QWEN_ID && typeof payload.access === "string" && typeof ctx.credentials.set === "function") {
|
|
613
|
+
await ctx.credentials.set(QWEN_KEY_NAME, payload.access);
|
|
614
|
+
}
|
|
615
|
+
const models = chat.map(modelProfile);
|
|
616
|
+
const custom = await runtimes.get(ctx).connectionRuntime.customRoute(id);
|
|
617
|
+
const connection = await runtimes.get(ctx).connectionRuntime.connections.read(id);
|
|
618
|
+
const definition = getProviderDefinition(id, connection?.metadata);
|
|
619
|
+
if (custom && !definition?.baseURL) throw new Error('This subscription has no verified inference endpoint for the selected region.');
|
|
620
|
+
const codingPlan = custom ? {
|
|
621
|
+
displayName: definition.name, api: definition.api ?? 'openai-completions', baseURL: definition.baseURL,
|
|
622
|
+
apiKeyEnv: connectionRef(id), defaultInput: ['text'], models,
|
|
623
|
+
...(definition.routeHeaders ? { headers: definition.routeHeaders } : {}),
|
|
624
|
+
} : id === QWEN_ID ? {
|
|
625
|
+
displayName: "通义千问",
|
|
626
|
+
api: "openai-completions",
|
|
627
|
+
baseURL: qwenEndpoint(payload.resourceUrl),
|
|
628
|
+
apiKeyEnv: QWEN_KEY_NAME,
|
|
629
|
+
defaultInput: ["text"],
|
|
630
|
+
models,
|
|
631
|
+
} : undefined;
|
|
632
|
+
const previous = await runtimes.get(ctx).pulls.read(id);
|
|
633
|
+
const route = await writeRoute(ctx.settings, id, models, codingPlan, previous?.route);
|
|
634
|
+
const pull = {
|
|
635
|
+
models: chat,
|
|
636
|
+
media: available.filter((model) => model.role === "image" || model.role === "video"),
|
|
637
|
+
expiresAt,
|
|
638
|
+
importedAt: new Date().toISOString(),
|
|
639
|
+
source: custom ? 'api-key' : connection?.mode === 'local' ? 'external-managed' : 'oauth',
|
|
640
|
+
route: { edits: route.edits },
|
|
641
|
+
};
|
|
642
|
+
try { await runtimes.get(ctx).pulls.write(id, pull); }
|
|
643
|
+
catch (error) { await restoreRoute(ctx.settings, route.rollback); throw error; }
|
|
644
|
+
return pull;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function modelProfile(model) {
|
|
648
|
+
const entry = { id: model.id, name: model.name };
|
|
649
|
+
if (Number.isInteger(model.contextWindow) && model.contextWindow > 0) entry.contextWindow = model.contextWindow;
|
|
650
|
+
if (Number.isInteger(model.maxTokens) && model.maxTokens > 0) entry.maxTokens = model.maxTokens;
|
|
651
|
+
if (Array.isArray(model.input) && model.input.length > 0) entry.input = model.input;
|
|
652
|
+
if (model.reasoningEfforts === false || model.reasoningEfforts && typeof model.reasoningEfforts === "object") entry.reasoningEfforts = model.reasoningEfforts;
|
|
653
|
+
if (model.compat && typeof model.compat === 'object') entry.compat = model.compat;
|
|
654
|
+
return entry;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
async function dropRoute(ctx, id) {
|
|
658
|
+
const pull = await runtimes.get(ctx).pulls.read(id);
|
|
659
|
+
await restoreRoute(ctx.settings, pull?.route);
|
|
660
|
+
await runtimes.get(ctx).pulls.delete(id);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function json(res, status, body) {
|
|
664
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
665
|
+
res.end(JSON.stringify(body));
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
async function readJson(req) {
|
|
669
|
+
const chunks = [];
|
|
670
|
+
let size = 0;
|
|
671
|
+
for await (const chunk of req) { size += chunk.length; if (size > 65536) throw new SyntaxError('Request is too large.'); chunks.push(chunk); }
|
|
672
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
673
|
+
if (text.length === 0) return {};
|
|
674
|
+
const parsed = JSON.parse(text);
|
|
675
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
676
|
+
}
|