@mupt-ai/dari-gateway 1.0.354 → 1.0.355
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.md +5 -5
- package/dist/link/assets.js +0 -3
- package/dist/link/client.d.ts +2 -2
- package/dist/link/client.js +2 -2
- package/dist/link/endpoints.js +31 -8
- package/dist/link/errors.js +0 -1
- package/dist/link/self_hosted.js +11 -3
- package/dist/link/service.d.ts +3 -1
- package/dist/link/service.js +1 -0
- package/dist/models/catalog.js +0 -1
- package/dist/models/provider_defaults.js +0 -5
- package/dist/models/provider_models.json +0 -182
- package/dist/models/subscriptions.js +0 -1
- package/dist/platform/platform.d.ts +11 -0
- package/dist/providers/codex_usage.d.ts +6 -0
- package/dist/providers/codex_usage.js +2 -1
- package/dist/providers/execution.js +0 -3
- package/dist/providers/provider_call.js +1 -5
- package/dist/providers/subscription_limits.d.ts +1 -1
- package/dist/providers/subscription_limits.js +1 -4
- package/dist/providers/subscription_resets.d.ts +53 -0
- package/dist/providers/subscription_resets.js +184 -0
- package/dist/self_host/connected.d.ts +51 -0
- package/dist/self_host/connected.js +197 -0
- package/dist/self_host/hosted_sync.d.ts +53 -0
- package/dist/self_host/hosted_sync.js +261 -0
- package/dist/self_host/main.d.ts +5 -0
- package/dist/self_host/main.js +58 -10
- package/dist/self_host/platform.js +15 -2
- package/dist/self_host/resolve.js +0 -1
- package/dist/self_host/subscriptions/http.d.ts +4 -1
- package/dist/self_host/subscriptions/http.js +83 -11
- package/dist/self_host/subscriptions/index.d.ts +3 -3
- package/dist/self_host/subscriptions/index.js +3 -3
- package/dist/self_host/subscriptions/oauth.d.ts +3 -4
- package/dist/self_host/subscriptions/oauth.js +9 -76
- package/dist/self_host/subscriptions/resets.d.ts +41 -0
- package/dist/self_host/subscriptions/resets.js +235 -0
- package/dist/self_host/subscriptions/store.d.ts +61 -8
- package/dist/self_host/subscriptions/store.js +151 -26
- package/dist/self_host/subscriptions/usage.d.ts +3 -1
- package/dist/self_host/subscriptions/usage.js +12 -7
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
- package/src/link/assets.ts +0 -3
- package/src/link/client.ts +5 -3
- package/src/link/endpoints.ts +35 -7
- package/src/link/errors.ts +0 -1
- package/src/link/self_hosted.ts +9 -3
- package/src/link/service.ts +4 -0
- package/src/models/catalog.ts +0 -1
- package/src/models/provider_defaults.ts +0 -5
- package/src/models/provider_models.json +0 -182
- package/src/models/subscriptions.ts +0 -1
- package/src/platform/platform.ts +9 -0
- package/src/providers/codex_usage.ts +2 -1
- package/src/providers/execution.ts +0 -3
- package/src/providers/provider_call.ts +1 -5
- package/src/providers/subscription_limits.ts +1 -3
- package/src/providers/subscription_resets.ts +256 -0
- package/src/self_host/connected.ts +239 -0
- package/src/self_host/hosted_sync.ts +285 -0
- package/src/self_host/main.ts +55 -9
- package/src/self_host/platform.ts +13 -1
- package/src/self_host/resolve.ts +0 -1
- package/src/self_host/subscriptions/http.ts +85 -10
- package/src/self_host/subscriptions/index.ts +5 -2
- package/src/self_host/subscriptions/oauth.ts +8 -91
- package/src/self_host/subscriptions/resets.ts +254 -0
- package/src/self_host/subscriptions/store.ts +185 -27
- package/src/self_host/subscriptions/usage.ts +13 -7
- package/src/types.ts +0 -3
- package/dist/providers/github_copilot.d.ts +0 -8
- package/dist/providers/github_copilot.js +0 -21
- package/src/providers/github_copilot.ts +0 -24
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
} from "./resolve.js";
|
|
17
17
|
import { type SubscriptionStore } from "./subscriptions/index.js";
|
|
18
18
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
19
|
+
import { hasBankedResets, providerBaseUrls, recoverHeldPlans } from "./subscriptions/resets.js";
|
|
19
20
|
|
|
20
21
|
/**
|
|
21
22
|
* The self-hosted platform: routers from the config file and router specs,
|
|
@@ -68,7 +69,18 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
|
|
|
68
69
|
return deps.subscriptions.holdModel(credentialId, limit.model, limit.resetsAt, limit.reason);
|
|
69
70
|
}
|
|
70
71
|
const another = deps.subscriptions.markUnavailable(credentialId, limit.resetsAt, limit.reason);
|
|
71
|
-
if (linkGrantId === undefined)
|
|
72
|
+
if (linkGrantId === undefined) {
|
|
73
|
+
// The owner's plans may come back early: from the provider's own
|
|
74
|
+
// report, or by spending a banked reset (resets.ts).
|
|
75
|
+
const held = deps.subscriptions.get(credentialId);
|
|
76
|
+
if (held === null || held.owner !== null || !hasBankedResets(held)) return another;
|
|
77
|
+
if (held.provider === "anthropic_claude_code" && another) return another;
|
|
78
|
+
return await recoverHeldPlans({
|
|
79
|
+
store: deps.subscriptions,
|
|
80
|
+
fetch: deps.fetch,
|
|
81
|
+
baseUrls: providerBaseUrls(deps.config.providers),
|
|
82
|
+
}, held);
|
|
83
|
+
}
|
|
72
84
|
// A grant's retry may use only its own subscriptions.
|
|
73
85
|
const provider = deps.subscriptions.get(credentialId)?.provider;
|
|
74
86
|
return provider !== undefined && deps.subscriptions.activeCredential(
|
package/src/self_host/resolve.ts
CHANGED
|
@@ -442,7 +442,6 @@ const SUBSCRIPTION_PLAN_NAMES: Record<SubscriptionProvider, string> = {
|
|
|
442
442
|
openai_codex: "ChatGPT",
|
|
443
443
|
meta_muse: "Muse Code",
|
|
444
444
|
opencode_go: "OpenCode Go",
|
|
445
|
-
github_copilot: "GitHub Copilot",
|
|
446
445
|
xai_grok: "Grok",
|
|
447
446
|
vercel_token_pass: "Vercel Token Pass",
|
|
448
447
|
};
|
|
@@ -19,21 +19,31 @@ import {
|
|
|
19
19
|
activeModelHolds,
|
|
20
20
|
currentUsage,
|
|
21
21
|
isHeld,
|
|
22
|
+
sameConnectedAccount,
|
|
23
|
+
SubscriptionAccountConnectedError,
|
|
24
|
+
type ConnectedAccount,
|
|
22
25
|
type SubscriptionCredential,
|
|
23
26
|
type SubscriptionStore,
|
|
24
27
|
} from "./store.js";
|
|
28
|
+
import { hasBankedResets, listResets, useReset, type ProviderBaseUrls } from "./resets.js";
|
|
25
29
|
import { refreshStaleUsage } from "./usage.js";
|
|
26
30
|
|
|
27
31
|
export type SubscriptionHttpDeps = {
|
|
28
32
|
store: SubscriptionStore;
|
|
29
33
|
fetch: OAuthFetch;
|
|
34
|
+
// Where Claude and ChatGPT are reached for usage and banked resets.
|
|
35
|
+
baseUrls?: ProviderBaseUrls;
|
|
30
36
|
now?: () => Date;
|
|
37
|
+
// The user's plans hosted Dari holds (on Dari and on other computers), read
|
|
38
|
+
// before a sign-in connects a new account. Set when this gateway is
|
|
39
|
+
// connected to hosted Dari.
|
|
40
|
+
hostedAccounts?: () => Promise<ConnectedAccount[]>;
|
|
31
41
|
};
|
|
32
42
|
|
|
33
43
|
const BASE = "/v1/organizations/current/credentials";
|
|
34
44
|
// Subscription names are env-var-style, which keeps other credential routes
|
|
35
45
|
// such as `provider-credentials/...` out of these matches.
|
|
36
|
-
const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/auto-reset)?$/;
|
|
46
|
+
const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/auto-reset|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
|
|
37
47
|
|
|
38
48
|
class HttpError extends Error {
|
|
39
49
|
constructor(readonly status: number, message: string) {
|
|
@@ -52,9 +62,9 @@ export async function handleSubscriptionRequest(
|
|
|
52
62
|
const now = deps.now?.() ?? new Date();
|
|
53
63
|
try {
|
|
54
64
|
if (path === "" && request.method === "GET") {
|
|
55
|
-
//
|
|
65
|
+
// Plans whose usage is read only when asked, or idle since their last response.
|
|
56
66
|
if (url.searchParams.get("refresh_usage") === "true") {
|
|
57
|
-
await refreshStaleUsage(deps.store, { fetch: deps.fetch, now });
|
|
67
|
+
await refreshStaleUsage(deps.store, { fetch: deps.fetch, now, ...(deps.baseUrls ? { baseUrls: deps.baseUrls } : {}) });
|
|
58
68
|
}
|
|
59
69
|
return json(200, listBody(deps.store, now));
|
|
60
70
|
}
|
|
@@ -88,15 +98,45 @@ export async function handleSubscriptionRequest(
|
|
|
88
98
|
}
|
|
89
99
|
return json(200, summary(deps.store, found(renamed, name), now));
|
|
90
100
|
}
|
|
101
|
+
if (action === "/private" && request.method === "PUT") {
|
|
102
|
+
// Private plans stay off hosted Dari: a connected gateway neither
|
|
103
|
+
// serves nor reports them.
|
|
104
|
+
const body = await readBody(request);
|
|
105
|
+
if (typeof body.private !== "boolean") throw new HttpError(400, "private must be true or false.");
|
|
106
|
+
return json(200, summary(deps.store, found(deps.store.setPrivate(name, body.private, now), name), now));
|
|
107
|
+
}
|
|
91
108
|
if (action === "/mark-available" && request.method === "POST") {
|
|
92
109
|
return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
|
|
93
110
|
}
|
|
94
|
-
if (action === "/auto-reset" && request.method === "
|
|
95
|
-
|
|
111
|
+
if (action === "/auto-reset" && request.method === "PUT") {
|
|
112
|
+
const body = await readBody(request);
|
|
113
|
+
if (typeof body.enabled !== "boolean") throw new HttpError(400, "enabled must be true or false.");
|
|
114
|
+
const credential = resettable(found(deps.store.getByName(name), name));
|
|
115
|
+
return json(200, summary(deps.store, found(deps.store.setAutoRedeemResets(credential.name, body.enabled, now), name), now));
|
|
116
|
+
}
|
|
117
|
+
if (action === "/resets" && request.method === "GET") {
|
|
118
|
+
const credential = resettable(found(deps.store.getByName(name), name));
|
|
119
|
+
const resets = await fromProvider(() => listResets({ ...deps, now }, credential));
|
|
120
|
+
return json(200, {
|
|
121
|
+
resets: resets.map((reset) => ({
|
|
122
|
+
id: reset.id,
|
|
123
|
+
label: reset.label,
|
|
124
|
+
expires_at: reset.expiresAt?.toISOString() ?? null,
|
|
125
|
+
usable: reset.usable,
|
|
126
|
+
})),
|
|
127
|
+
// Always read live here; hosted Dari may show an earlier list.
|
|
128
|
+
read_at: null,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
if (action?.startsWith("/resets/") && request.method === "POST") {
|
|
132
|
+
const credential = resettable(found(deps.store.getByName(name), name));
|
|
133
|
+
const resetId = decodeURIComponent(action.slice("/resets/".length, -"/use".length));
|
|
134
|
+
return json(200, { result: await fromProvider(() => useReset({ ...deps, now }, credential, resetId)) });
|
|
96
135
|
}
|
|
97
136
|
return null;
|
|
98
137
|
} catch (error) {
|
|
99
138
|
if (error instanceof HttpError) return json(error.status, { detail: error.message });
|
|
139
|
+
if (error instanceof SubscriptionAccountConnectedError) return json(409, { detail: error.message });
|
|
100
140
|
if (error instanceof SubscriptionOAuthInputError) return json(400, { detail: error.message });
|
|
101
141
|
if (error instanceof SubscriptionOAuthProviderError) return json(502, { detail: error.message });
|
|
102
142
|
throw error;
|
|
@@ -108,7 +148,7 @@ function listBody(store: SubscriptionStore, now: Date) {
|
|
|
108
148
|
SUBSCRIPTION_PROVIDERS.map((provider) => store.activeCredential(provider, now)?.id),
|
|
109
149
|
);
|
|
110
150
|
return {
|
|
111
|
-
credentials: store.list().map((credential) => credentialBody(credential, active.has(credential.id), now)),
|
|
151
|
+
credentials: store.list(undefined, true).map((credential) => credentialBody(credential, active.has(credential.id), now)),
|
|
112
152
|
// Plan gating is hosted-only; a self-hosted gateway always allows routing.
|
|
113
153
|
autorouting_allowed: true,
|
|
114
154
|
};
|
|
@@ -123,9 +163,13 @@ async function startSession(deps: SubscriptionHttpDeps, body: Record<string, unk
|
|
|
123
163
|
if (credentialName !== null && (typeof credentialName !== "string" || !credentialName.trim())) {
|
|
124
164
|
throw new HttpError(400, "credential_name must be a non-empty string.");
|
|
125
165
|
}
|
|
126
|
-
|
|
166
|
+
const reconnecting = credentialName === null ? null : deps.store.getByName(credentialName);
|
|
167
|
+
if (credentialName !== null && reconnecting?.provider !== provider) {
|
|
127
168
|
throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(credentialName)}.`);
|
|
128
169
|
}
|
|
170
|
+
// A reconnected plan stays where it was unless the caller says otherwise.
|
|
171
|
+
const isPrivate = body.private ?? reconnecting?.private ?? false;
|
|
172
|
+
if (typeof isPrivate !== "boolean") throw new HttpError(400, "private must be true or false.");
|
|
129
173
|
const authorization = await startOAuth(provider as SubscriptionProvider, { fetch: deps.fetch, now });
|
|
130
174
|
const session = deps.store.createSession(
|
|
131
175
|
{
|
|
@@ -133,6 +177,7 @@ async function startSession(deps: SubscriptionHttpDeps, body: Record<string, unk
|
|
|
133
177
|
flow: authorization.flow,
|
|
134
178
|
credentialName,
|
|
135
179
|
owner: null,
|
|
180
|
+
private: isPrivate,
|
|
136
181
|
expiresAt: authorization.expiresAt,
|
|
137
182
|
},
|
|
138
183
|
now,
|
|
@@ -164,7 +209,21 @@ async function completeSession(deps: SubscriptionHttpDeps, body: Record<string,
|
|
|
164
209
|
now,
|
|
165
210
|
});
|
|
166
211
|
deps.store.deleteSession(token);
|
|
167
|
-
|
|
212
|
+
// Reconnecting a plan to the account it already holds needs no check, so it
|
|
213
|
+
// works even when hosted Dari cannot be read.
|
|
214
|
+
const target = session.credentialName === null ? null : deps.store.getByName(session.credentialName);
|
|
215
|
+
const reconnectsSameAccount = target !== null && sameConnectedAccount(target, tokens);
|
|
216
|
+
let elsewhere: ConnectedAccount[] = [];
|
|
217
|
+
if (deps.hostedAccounts !== undefined && !reconnectsSameAccount) {
|
|
218
|
+
try {
|
|
219
|
+
elsewhere = await deps.hostedAccounts();
|
|
220
|
+
} catch (error) {
|
|
221
|
+
// The provider code is spent: keep the sign-in, checked against this
|
|
222
|
+
// gateway's own plans only, rather than make the user start over.
|
|
223
|
+
console.error("hosted account check failed", error instanceof Error ? error.message : String(error));
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const stored = deps.store.connect(tokens, session.credentialName, now, null, session.private, elsewhere);
|
|
168
227
|
if (stored === null) {
|
|
169
228
|
throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(session.credentialName)}.`);
|
|
170
229
|
}
|
|
@@ -248,6 +307,8 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
|
|
|
248
307
|
// subscription here belongs to the gateway's one user.
|
|
249
308
|
credential_scope: "user",
|
|
250
309
|
oauth_provider: credential.provider,
|
|
310
|
+
// Kept off hosted Dari (`dari accounts subscription connect --on private`).
|
|
311
|
+
private: credential.private,
|
|
251
312
|
created_at: credential.createdAt.toISOString(),
|
|
252
313
|
last_used_at: credential.lastUsedAt?.toISOString() ?? null,
|
|
253
314
|
unavailable_until: held ? credential.unavailableUntil!.toISOString() : null,
|
|
@@ -263,11 +324,25 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
|
|
|
263
324
|
// The share of its tightest window the plan last reported used, and
|
|
264
325
|
// every window as shown; null when it reports none and is not held.
|
|
265
326
|
usage: usageBody(credential, now),
|
|
266
|
-
|
|
267
|
-
auto_redeem_resets: false,
|
|
327
|
+
auto_redeem_resets: credential.autoRedeemResets,
|
|
268
328
|
};
|
|
269
329
|
}
|
|
270
330
|
|
|
331
|
+
function resettable(credential: SubscriptionCredential): SubscriptionCredential {
|
|
332
|
+
if (!hasBankedResets(credential)) throw new HttpError(400, "Only ChatGPT and Claude Code plans have banked resets.");
|
|
333
|
+
return credential;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// A provider that fails to answer is a bad gateway, as on hosted Dari.
|
|
337
|
+
async function fromProvider<T>(call: () => Promise<T>): Promise<T> {
|
|
338
|
+
try {
|
|
339
|
+
return await call();
|
|
340
|
+
} catch (error) {
|
|
341
|
+
if (error instanceof HttpError) throw error;
|
|
342
|
+
throw new HttpError(502, error instanceof Error ? error.message : String(error));
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
271
346
|
function found(credential: SubscriptionCredential | null, name: string): SubscriptionCredential {
|
|
272
347
|
if (credential === null) throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(name)}.`);
|
|
273
348
|
return credential;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Personal subscriptions for a self-hosted, single-tenant gateway: Claude Code,
|
|
3
|
-
* ChatGPT, Muse Code, OpenCode Go,
|
|
3
|
+
* ChatGPT, Muse Code, OpenCode Go, and Grok plans
|
|
4
4
|
* connected over OAuth, and Vercel Token Pass keys, used in place of API keys.
|
|
5
5
|
*
|
|
6
6
|
* - `oauth.ts`: the providers' OAuth protocols (Claude Code PKCE with a
|
|
@@ -28,7 +28,6 @@ export { freshAccessToken } from "./access.js";
|
|
|
28
28
|
export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http.js";
|
|
29
29
|
export {
|
|
30
30
|
CODEX_APPROVAL_PENDING,
|
|
31
|
-
GITHUB_APPROVAL_PENDING,
|
|
32
31
|
META_APPROVAL_PENDING,
|
|
33
32
|
OPENCODE_APPROVAL_PENDING,
|
|
34
33
|
XAI_APPROVAL_PENDING,
|
|
@@ -46,10 +45,14 @@ export {
|
|
|
46
45
|
type SubscriptionProvider,
|
|
47
46
|
} from "./oauth.js";
|
|
48
47
|
export {
|
|
48
|
+
SubscriptionAccountConnectedError,
|
|
49
49
|
SubscriptionStore,
|
|
50
50
|
activeModelHolds,
|
|
51
51
|
currentUsage,
|
|
52
52
|
isHeld,
|
|
53
|
+
sameConnectedAccount,
|
|
54
|
+
type AccountRef,
|
|
55
|
+
type ConnectedAccount,
|
|
53
56
|
type PendingOAuthSession,
|
|
54
57
|
type SubscriptionCredential,
|
|
55
58
|
type SubscriptionModelHold,
|
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "node:crypto";
|
|
2
2
|
|
|
3
|
-
import { COPILOT_HEADERS } from "../../providers/github_copilot.js";
|
|
4
|
-
|
|
5
3
|
/**
|
|
6
4
|
* OAuth protocols for personal subscriptions: Claude Code (PKCE, the user
|
|
7
5
|
* pastes back the `code#state` Anthropic shows), ChatGPT/Codex (device code,
|
|
8
6
|
* the gateway polls for approval), Muse Code (Meta's device code, then the
|
|
9
7
|
* subscription's Model API key minted from the sign-in token), OpenCode Go
|
|
10
8
|
* (the OpenCode Console device sign-in `opencode auth login` runs, scoped to
|
|
11
|
-
* the workspace that holds the plan),
|
|
12
|
-
*
|
|
9
|
+
* the workspace that holds the plan), Grok (xAI's device sign-in, as its
|
|
10
|
+
* own coding agent runs it), and Vercel
|
|
13
11
|
* Token Pass (no protocol: the plan is a Token Pass key the user pastes).
|
|
14
12
|
* Every network call goes through the injected `fetch`.
|
|
15
13
|
*/
|
|
@@ -19,7 +17,6 @@ export type SubscriptionProvider =
|
|
|
19
17
|
| "openai_codex"
|
|
20
18
|
| "meta_muse"
|
|
21
19
|
| "opencode_go"
|
|
22
|
-
| "github_copilot"
|
|
23
20
|
| "xai_grok"
|
|
24
21
|
| "vercel_token_pass";
|
|
25
22
|
|
|
@@ -28,7 +25,6 @@ export const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[] = [
|
|
|
28
25
|
"openai_codex",
|
|
29
26
|
"meta_muse",
|
|
30
27
|
"opencode_go",
|
|
31
|
-
"github_copilot",
|
|
32
28
|
"xai_grok",
|
|
33
29
|
"vercel_token_pass",
|
|
34
30
|
];
|
|
@@ -131,30 +127,12 @@ type DeviceSignIn = {
|
|
|
131
127
|
deviceCodeUrl: string;
|
|
132
128
|
tokenUrl: string;
|
|
133
129
|
scope?: string;
|
|
134
|
-
headers?: Record<string, string>;
|
|
135
130
|
};
|
|
136
131
|
|
|
137
|
-
// GitHub Copilot's sign-in, as VS Code's Copilot Chat runs it, for github.com
|
|
138
|
-
// accounts. The GitHub token it grants is the refresh token: it mints the
|
|
139
|
-
// short-lived Copilot token that serves requests.
|
|
140
|
-
const GITHUB_COPILOT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
|
|
141
|
-
const COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token";
|
|
142
|
-
const GITHUB_USER_URL = "https://api.github.com/user";
|
|
143
|
-
// Copilot tokens live about half an hour; mint the next one before then.
|
|
144
|
-
const COPILOT_TOKEN_SKEW_MS = 5 * 60_000;
|
|
145
|
-
|
|
146
132
|
// SuperGrok and X Premium sign in as xAI's Grok CLI does.
|
|
147
133
|
const XAI_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
148
134
|
|
|
149
135
|
const DEVICE_SIGN_INS = {
|
|
150
|
-
github_copilot: {
|
|
151
|
-
vendor: "GitHub",
|
|
152
|
-
clientId: GITHUB_COPILOT_CLIENT_ID,
|
|
153
|
-
deviceCodeUrl: "https://github.com/login/device/code",
|
|
154
|
-
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
155
|
-
scope: "read:user",
|
|
156
|
-
headers: { "User-Agent": COPILOT_HEADERS["User-Agent"]! },
|
|
157
|
-
},
|
|
158
136
|
xai_grok: {
|
|
159
137
|
vendor: "xAI",
|
|
160
138
|
clientId: XAI_CLIENT_ID,
|
|
@@ -170,7 +148,6 @@ function isDeviceProvider(provider: SubscriptionProvider): provider is DevicePro
|
|
|
170
148
|
return provider in DEVICE_SIGN_INS;
|
|
171
149
|
}
|
|
172
150
|
|
|
173
|
-
export const GITHUB_APPROVAL_PENDING = approvalPending("GitHub");
|
|
174
151
|
export const XAI_APPROVAL_PENDING = approvalPending("xAI");
|
|
175
152
|
|
|
176
153
|
function approvalPending(vendor: string): string {
|
|
@@ -201,7 +178,6 @@ export async function startOAuth(
|
|
|
201
178
|
signIn.deviceCodeUrl,
|
|
202
179
|
{ client_id: signIn.clientId, ...(signIn.scope === undefined ? {} : { scope: signIn.scope }) },
|
|
203
180
|
`${signIn.vendor} device code request`,
|
|
204
|
-
signIn.headers,
|
|
205
181
|
);
|
|
206
182
|
const complete = device.verification_uri_complete;
|
|
207
183
|
return {
|
|
@@ -296,19 +272,6 @@ export async function completeOAuth(
|
|
|
296
272
|
if (provider === "vercel_token_pass") return vercelTokenPassTokens(authorizationResponse, now);
|
|
297
273
|
if (isDeviceProvider(provider)) {
|
|
298
274
|
const token = await deviceApproval(provider, requiredString(flow, "device_code"), options.fetch);
|
|
299
|
-
if (provider === "github_copilot") {
|
|
300
|
-
const githubToken = requiredString(token, "access_token");
|
|
301
|
-
const tokens = await copilotTokens(githubToken, options.fetch, now).catch((error: unknown) => {
|
|
302
|
-
// GitHub mints no Copilot token for an account without a plan.
|
|
303
|
-
if (error instanceof SubscriptionOAuthProviderError && [401, 403, 404].includes(error.status ?? 0)) {
|
|
304
|
-
throw new SubscriptionOAuthInputError(
|
|
305
|
-
"This GitHub account has no active Copilot plan. Subscribe at https://github.com/features/copilot/plans, then connect again.",
|
|
306
|
-
);
|
|
307
|
-
}
|
|
308
|
-
throw error;
|
|
309
|
-
});
|
|
310
|
-
return { ...tokens, accountEmail: await githubAccount(options.fetch, githubToken) };
|
|
311
|
-
}
|
|
312
275
|
return deviceTokens(provider, token, now, null);
|
|
313
276
|
}
|
|
314
277
|
if (provider === "opencode_go") {
|
|
@@ -434,7 +397,6 @@ export async function refreshOAuth(
|
|
|
434
397
|
): Promise<OAuthTokens> {
|
|
435
398
|
const now = options.now ?? new Date();
|
|
436
399
|
if (credential.provider === "vercel_token_pass") return vercelTokenPassTokens(credential.refreshToken, now);
|
|
437
|
-
if (credential.provider === "github_copilot") return await copilotTokens(credential.refreshToken, options.fetch, now);
|
|
438
400
|
if (isDeviceProvider(credential.provider)) {
|
|
439
401
|
const signIn: DeviceSignIn = DEVICE_SIGN_INS[credential.provider];
|
|
440
402
|
const token = await postForm(
|
|
@@ -442,7 +404,6 @@ export async function refreshOAuth(
|
|
|
442
404
|
signIn.tokenUrl,
|
|
443
405
|
{ grant_type: "refresh_token", client_id: signIn.clientId, refresh_token: credential.refreshToken },
|
|
444
406
|
`${signIn.vendor} sign-in refresh`,
|
|
445
|
-
signIn.headers,
|
|
446
407
|
);
|
|
447
408
|
return deviceTokens(credential.provider, token, now, credential.refreshToken);
|
|
448
409
|
}
|
|
@@ -664,16 +625,14 @@ function postForm(
|
|
|
664
625
|
url: string,
|
|
665
626
|
payload: Record<string, string>,
|
|
666
627
|
operation: string,
|
|
667
|
-
headers: Record<string, string> = {},
|
|
668
628
|
): Promise<Record<string, unknown>> {
|
|
669
|
-
return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation
|
|
629
|
+
return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation);
|
|
670
630
|
}
|
|
671
631
|
|
|
672
|
-
// A null body is a GET.
|
|
673
632
|
async function requestJson(
|
|
674
633
|
fetch: OAuthFetch,
|
|
675
634
|
url: string,
|
|
676
|
-
body: string
|
|
635
|
+
body: string,
|
|
677
636
|
contentType: string,
|
|
678
637
|
operation: string,
|
|
679
638
|
headers: Record<string, string> = {},
|
|
@@ -681,14 +640,14 @@ async function requestJson(
|
|
|
681
640
|
let response: Response;
|
|
682
641
|
try {
|
|
683
642
|
response = await fetch(url, {
|
|
684
|
-
method:
|
|
643
|
+
method: "POST",
|
|
685
644
|
headers: {
|
|
686
645
|
Accept: "application/json",
|
|
687
|
-
|
|
646
|
+
"Content-Type": contentType,
|
|
688
647
|
"User-Agent": "Dari/1.0",
|
|
689
648
|
...headers,
|
|
690
649
|
},
|
|
691
|
-
|
|
650
|
+
body,
|
|
692
651
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
693
652
|
});
|
|
694
653
|
} catch {
|
|
@@ -762,8 +721,7 @@ async function opencodeEmail(fetch: OAuthFetch, accessToken: string): Promise<st
|
|
|
762
721
|
}
|
|
763
722
|
}
|
|
764
723
|
|
|
765
|
-
// Ask a device sign-in whether the user approved its code.
|
|
766
|
-
// unfinished sign-in with HTTP 200 and an `error`; the others with HTTP 400.
|
|
724
|
+
// Ask a device sign-in whether the user approved its code.
|
|
767
725
|
async function deviceApproval(
|
|
768
726
|
provider: DeviceProvider,
|
|
769
727
|
deviceCode: string,
|
|
@@ -782,7 +740,6 @@ async function deviceApproval(
|
|
|
782
740
|
client_id: signIn.clientId,
|
|
783
741
|
},
|
|
784
742
|
`${signIn.vendor} device approval check`,
|
|
785
|
-
signIn.headers,
|
|
786
743
|
);
|
|
787
744
|
errorCode = typeof token.error === "string" ? token.error : undefined;
|
|
788
745
|
} catch (error) {
|
|
@@ -824,46 +781,6 @@ function deviceTokens(
|
|
|
824
781
|
};
|
|
825
782
|
}
|
|
826
783
|
|
|
827
|
-
// Mints the Copilot token that serves requests from the GitHub token.
|
|
828
|
-
async function copilotTokens(githubToken: string, fetch: OAuthFetch, now: Date): Promise<OAuthTokens> {
|
|
829
|
-
const minted = await requestJson(
|
|
830
|
-
fetch,
|
|
831
|
-
COPILOT_TOKEN_URL,
|
|
832
|
-
null,
|
|
833
|
-
"",
|
|
834
|
-
"GitHub Copilot token request",
|
|
835
|
-
{ ...COPILOT_HEADERS, Authorization: `Bearer ${githubToken}` },
|
|
836
|
-
);
|
|
837
|
-
const expiresAt = minted.expires_at;
|
|
838
|
-
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) {
|
|
839
|
-
throw new SubscriptionOAuthProviderError(INCOMPLETE);
|
|
840
|
-
}
|
|
841
|
-
return {
|
|
842
|
-
provider: "github_copilot",
|
|
843
|
-
accessToken: requiredString(minted, "token"),
|
|
844
|
-
refreshToken: githubToken,
|
|
845
|
-
expiresAt: new Date(Math.max(now.getTime(), expiresAt * 1000 - COPILOT_TOKEN_SKEW_MS)),
|
|
846
|
-
accountId: null,
|
|
847
|
-
accountEmail: null,
|
|
848
|
-
};
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
// The signed-in GitHub account's email, else its login; best effort.
|
|
852
|
-
async function githubAccount(fetch: OAuthFetch, githubToken: string): Promise<string | null> {
|
|
853
|
-
try {
|
|
854
|
-
const user = await requestJson(fetch, GITHUB_USER_URL, null, "", "GitHub account lookup", {
|
|
855
|
-
Authorization: `Bearer ${githubToken}`,
|
|
856
|
-
});
|
|
857
|
-
for (const field of ["email", "login"]) {
|
|
858
|
-
const value = user[field];
|
|
859
|
-
if (typeof value === "string" && value) return value;
|
|
860
|
-
}
|
|
861
|
-
return null;
|
|
862
|
-
} catch {
|
|
863
|
-
return null;
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
|
|
867
784
|
// The pasted key is both tokens; refreshing hands the same key back.
|
|
868
785
|
function vercelTokenPassTokens(key: string, now: Date): OAuthTokens {
|
|
869
786
|
const apiKey = key.trim();
|