@mupt-ai/dari-gateway 0.0.0-stage → 0.2.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.
Files changed (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +135 -2
  3. package/dari-gateway.example.yaml +28 -0
  4. package/package.json +42 -4
  5. package/src/bun.ts +4 -0
  6. package/src/context/eval_catalog.ts +11 -0
  7. package/src/context/interaction_fingerprint.ts +691 -0
  8. package/src/context/interaction_fingerprint_format.ts +189 -0
  9. package/src/context/interaction_lease_depth.ts +150 -0
  10. package/src/context/lease_history.ts +200 -0
  11. package/src/context/pricing.ts +30 -0
  12. package/src/context/provider_prompt_accounting.ts +241 -0
  13. package/src/context/routing_context.ts +337 -0
  14. package/src/http/auth.ts +43 -0
  15. package/src/http/errors.ts +114 -0
  16. package/src/http/handler.ts +110 -0
  17. package/src/http/http2_server.ts +122 -0
  18. package/src/http/serve.ts +119 -0
  19. package/src/index.ts +22 -0
  20. package/src/ingress/anthropic_messages.ts +162 -0
  21. package/src/ingress/anthropic_models.ts +28 -0
  22. package/src/ingress/chat_completions.ts +49 -0
  23. package/src/ingress/claude_code/request_context.ts +36 -0
  24. package/src/ingress/codex.ts +81 -0
  25. package/src/ingress/codex_models.ts +113 -0
  26. package/src/ingress/json.ts +113 -0
  27. package/src/ingress/models.ts +55 -0
  28. package/src/interaction/capabilities.ts +30 -0
  29. package/src/interaction/image.ts +12 -0
  30. package/src/interaction/portable_reasoning_state.ts +25 -0
  31. package/src/interaction/provider_continuation_state.ts +36 -0
  32. package/src/interaction/tool_identity.ts +65 -0
  33. package/src/interaction/types.ts +282 -0
  34. package/src/models/context_limits.ts +8 -0
  35. package/src/models/execution_provider.ts +22 -0
  36. package/src/models/gateways.ts +73 -0
  37. package/src/models/ids.ts +26 -0
  38. package/src/models/provider_defaults.ts +47 -0
  39. package/src/models/runtime_overrides.ts +221 -0
  40. package/src/observability/errors.ts +25 -0
  41. package/src/platform/platform.ts +204 -0
  42. package/src/platform/routing_contract.ts +6 -0
  43. package/src/protocol/input/anthropic_messages.ts +531 -0
  44. package/src/protocol/input/chat_completions.ts +255 -0
  45. package/src/protocol/input/chat_completions_validation.ts +293 -0
  46. package/src/protocol/input/openai_responses.ts +749 -0
  47. package/src/protocol/input/router_model.ts +53 -0
  48. package/src/protocol/output/anthropic_messages.ts +32 -0
  49. package/src/protocol/output/anthropic_messages_output.ts +129 -0
  50. package/src/protocol/output/anthropic_messages_stream.ts +281 -0
  51. package/src/protocol/output/chat_completions.ts +451 -0
  52. package/src/protocol/output/chat_reasoning_detail.ts +19 -0
  53. package/src/protocol/output/delivered_stream_snapshot.ts +31 -0
  54. package/src/protocol/output/openai_responses.ts +30 -0
  55. package/src/protocol/output/openai_responses_output.ts +159 -0
  56. package/src/protocol/output/openai_responses_stream.ts +631 -0
  57. package/src/protocol/output/sse_stream.ts +102 -0
  58. package/src/providers/anthropic_safeguards.ts +115 -0
  59. package/src/providers/aws_assume_role.ts +147 -0
  60. package/src/providers/cancel_estimate.ts +140 -0
  61. package/src/providers/execution.ts +800 -0
  62. package/src/providers/model_capabilities.ts +50 -0
  63. package/src/providers/pi.ts +499 -0
  64. package/src/providers/pi_context.ts +466 -0
  65. package/src/providers/pi_options.ts +416 -0
  66. package/src/providers/pi_output.ts +500 -0
  67. package/src/providers/provider_attempt_runner.ts +153 -0
  68. package/src/providers/provider_call.ts +433 -0
  69. package/src/providers/provider_reported_cost.ts +138 -0
  70. package/src/providers/reasoning.ts +59 -0
  71. package/src/providers/response_capture.ts +65 -0
  72. package/src/providers/stream_finalization.ts +264 -0
  73. package/src/providers/subscription_limits.ts +208 -0
  74. package/src/providers/subscription_usage.ts +99 -0
  75. package/src/runtime/claude_code/auxiliary_routing.ts +80 -0
  76. package/src/runtime/customer_disconnect.ts +66 -0
  77. package/src/runtime/explicit_model.ts +86 -0
  78. package/src/runtime/harness_identity/conversation.ts +87 -0
  79. package/src/runtime/harness_identity/extract.ts +323 -0
  80. package/src/runtime/harness_identity/index.ts +14 -0
  81. package/src/runtime/prepare_routed_completion.ts +224 -0
  82. package/src/runtime/provider_stream_lifecycle.ts +105 -0
  83. package/src/runtime/provider_stream_outcome.ts +83 -0
  84. package/src/runtime/request_tags.ts +34 -0
  85. package/src/runtime/routed_completion.ts +102 -0
  86. package/src/runtime/routed_protocol.ts +33 -0
  87. package/src/runtime/routed_runtime.ts +722 -0
  88. package/src/runtime/routing_lease.ts +273 -0
  89. package/src/runtime/runtime_reporter.ts +115 -0
  90. package/src/self_host/config.ts +173 -0
  91. package/src/self_host/main.ts +104 -0
  92. package/src/self_host/platform.ts +63 -0
  93. package/src/self_host/prefix_store.ts +315 -0
  94. package/src/self_host/resolve.ts +240 -0
  95. package/src/self_host/subscriptions/access.ts +43 -0
  96. package/src/self_host/subscriptions/http.ts +204 -0
  97. package/src/self_host/subscriptions/index.ts +43 -0
  98. package/src/self_host/subscriptions/oauth.ts +395 -0
  99. package/src/self_host/subscriptions/store.ts +339 -0
  100. package/src/strategies/auto_routing_selector.ts +72 -0
  101. package/src/strategies/eval_relevance.ts +57 -0
  102. package/src/strategies/fallback_decision.ts +30 -0
  103. package/src/strategies/priority_selector.ts +40 -0
  104. package/src/strategies/route_decision.ts +106 -0
  105. package/src/strategies/routing.ts +455 -0
  106. package/src/strategies/selector_projection.ts +207 -0
  107. package/src/telemetry/background.ts +40 -0
  108. package/src/telemetry/benchmark_replay.ts +160 -0
  109. package/src/telemetry/billing_finalization.ts +167 -0
  110. package/src/telemetry/ingest_values.ts +15 -0
  111. package/src/telemetry/model_cost.ts +14 -0
  112. package/src/telemetry/prefix_state.ts +183 -0
  113. package/src/telemetry/report.ts +832 -0
  114. package/src/telemetry/requests/interaction_observability.ts +258 -0
  115. package/src/telemetry/requests/retained_interaction_request.ts +20 -0
  116. package/src/telemetry/scrub.ts +38 -0
  117. package/src/telemetry/skills/claude/catalog.ts +119 -0
  118. package/src/telemetry/skills/claude/file_reads.ts +153 -0
  119. package/src/telemetry/skills/claude/observations.ts +450 -0
  120. package/src/telemetry/skills/codex/catalog.ts +171 -0
  121. package/src/telemetry/skills/codex/exec_file_reads.ts +55 -0
  122. package/src/telemetry/skills/codex/explicit.ts +116 -0
  123. package/src/telemetry/skills/codex/file_reads.ts +51 -0
  124. package/src/telemetry/skills/codex/identity.ts +21 -0
  125. package/src/telemetry/skills/observations.ts +94 -0
  126. package/src/telemetry/skills/paths.ts +82 -0
  127. package/src/telemetry/skills/pi.ts +276 -0
  128. package/src/telemetry/skills/shell_file_reads.ts +267 -0
  129. package/src/telemetry/skills/shell_words.ts +202 -0
  130. package/src/telemetry/tools/input.ts +16 -0
  131. package/src/telemetry/tools/observations.ts +349 -0
  132. package/src/telemetry/usage.ts +173 -0
  133. package/src/types.ts +150 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * The subscription endpoints the Dari CLI calls, with the same paths and JSON
3
+ * shapes as the hosted API. The gateway is single-tenant: `current` is the
4
+ * only organization, and every caller that passes the gateway's own auth owns
5
+ * every subscription. Errors are `{"detail": "..."}`, which the CLI prints.
6
+ */
7
+ import {
8
+ SUBSCRIPTION_PROVIDERS,
9
+ SubscriptionOAuthInputError,
10
+ SubscriptionOAuthProviderError,
11
+ completeOAuth,
12
+ startOAuth,
13
+ type OAuthFetch,
14
+ type SubscriptionProvider,
15
+ } from "./oauth";
16
+ import { isHeld, type SubscriptionCredential, type SubscriptionStore } from "./store";
17
+
18
+ export type SubscriptionHttpDeps = {
19
+ store: SubscriptionStore;
20
+ fetch: OAuthFetch;
21
+ now?: () => Date;
22
+ };
23
+
24
+ const BASE = "/v1/organizations/current/credentials";
25
+ // Subscription names are env-var-style, which keeps other credential routes
26
+ // such as `provider-credentials/...` out of these matches.
27
+ const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/auto-reset)?$/;
28
+
29
+ class HttpError extends Error {
30
+ constructor(readonly status: number, message: string) {
31
+ super(message);
32
+ }
33
+ }
34
+
35
+ /** Handle a subscription route, or return null when the request is not one. */
36
+ export async function handleSubscriptionRequest(
37
+ request: Request,
38
+ deps: SubscriptionHttpDeps,
39
+ ): Promise<Response | null> {
40
+ const url = new URL(request.url);
41
+ if (url.pathname !== BASE && !url.pathname.startsWith(`${BASE}/`)) return null;
42
+ const path = url.pathname.slice(BASE.length);
43
+ const now = deps.now?.() ?? new Date();
44
+ try {
45
+ if (path === "" && request.method === "GET") return json(200, listBody(deps.store, now));
46
+ if (path === "/oauth/sessions" && request.method === "POST") {
47
+ return json(201, await startSession(deps, await readBody(request), now));
48
+ }
49
+ if (path === "/oauth/sessions/complete" && request.method === "POST") {
50
+ return json(200, await completeSession(deps, await readBody(request), now));
51
+ }
52
+ const named = NAMED.exec(path);
53
+ if (named === null) return null;
54
+ const name = named[1]!;
55
+ const action = named[2];
56
+ if (action === undefined && request.method === "DELETE") {
57
+ // The hosted API requires `scope=user` so an old client deleting an
58
+ // organization secret by name never disconnects a subscription.
59
+ if (url.searchParams.get("scope") !== "user") throw new HttpError(400, "scope=user is required.");
60
+ const removed = deps.store.disconnect(name);
61
+ return json(200, credentialBody(found(removed, name), false, now));
62
+ }
63
+ if (action === "/label" && request.method === "PUT") {
64
+ const body = await readBody(request);
65
+ const label = body.label ?? null;
66
+ if (label !== null && typeof label !== "string") throw new HttpError(400, "label must be a string.");
67
+ let renamed: SubscriptionCredential | null;
68
+ try {
69
+ renamed = deps.store.rename(name, label, now);
70
+ } catch (error) {
71
+ if (error instanceof RangeError) throw new HttpError(400, error.message);
72
+ throw error;
73
+ }
74
+ return json(200, summary(deps.store, found(renamed, name), now));
75
+ }
76
+ if (action === "/mark-available" && request.method === "POST") {
77
+ return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
78
+ }
79
+ if (action === "/auto-reset" && request.method === "POST") {
80
+ throw new HttpError(400, "Spending banked Codex resets is not supported by this gateway.");
81
+ }
82
+ return null;
83
+ } catch (error) {
84
+ if (error instanceof HttpError) return json(error.status, { detail: error.message });
85
+ if (error instanceof SubscriptionOAuthInputError) return json(400, { detail: error.message });
86
+ if (error instanceof SubscriptionOAuthProviderError) return json(502, { detail: error.message });
87
+ throw error;
88
+ }
89
+ }
90
+
91
+ function listBody(store: SubscriptionStore, now: Date) {
92
+ const active = new Set(
93
+ SUBSCRIPTION_PROVIDERS.map((provider) => store.activeCredential(provider, now)?.id),
94
+ );
95
+ return {
96
+ credentials: store.list().map((credential) => credentialBody(credential, active.has(credential.id), now)),
97
+ // Plan gating is hosted-only; a self-hosted gateway always allows routing.
98
+ autorouting_allowed: true,
99
+ };
100
+ }
101
+
102
+ async function startSession(deps: SubscriptionHttpDeps, body: Record<string, unknown>, now: Date) {
103
+ const provider = body.provider;
104
+ if (typeof provider !== "string" || !SUBSCRIPTION_PROVIDERS.includes(provider as SubscriptionProvider)) {
105
+ throw new HttpError(400, `provider must be one of: ${SUBSCRIPTION_PROVIDERS.join(", ")}.`);
106
+ }
107
+ const credentialName = body.credential_name ?? null;
108
+ if (credentialName !== null && (typeof credentialName !== "string" || !credentialName.trim())) {
109
+ throw new HttpError(400, "credential_name must be a non-empty string.");
110
+ }
111
+ if (credentialName !== null && deps.store.getByName(credentialName)?.provider !== provider) {
112
+ throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(credentialName)}.`);
113
+ }
114
+ const authorization = await startOAuth(provider as SubscriptionProvider, { fetch: deps.fetch, now });
115
+ const session = deps.store.createSession(
116
+ {
117
+ provider: provider as SubscriptionProvider,
118
+ flow: authorization.flow,
119
+ credentialName,
120
+ expiresAt: authorization.expiresAt,
121
+ },
122
+ now,
123
+ );
124
+ return {
125
+ provider,
126
+ session_token: session.token,
127
+ authorization_url: authorization.authorizationUrl,
128
+ expires_at: authorization.expiresAt.toISOString(),
129
+ user_code: authorization.userCode,
130
+ };
131
+ }
132
+
133
+ async function completeSession(deps: SubscriptionHttpDeps, body: Record<string, unknown>, now: Date) {
134
+ const token = body.session_token;
135
+ const authorizationResponse = body.authorization_response ?? "";
136
+ if (typeof token !== "string" || !token || typeof authorizationResponse !== "string") {
137
+ throw new HttpError(400, "session_token and authorization_response must be strings.");
138
+ }
139
+ const session = deps.store.getSession(token);
140
+ if (session === null) throw new HttpError(400, "Invalid subscription authorization session.");
141
+ if (session.expiresAt <= now) {
142
+ deps.store.deleteSession(token);
143
+ throw new HttpError(400, "Subscription authorization session has expired. Start again.");
144
+ }
145
+ // A pending device approval keeps the session so the CLI can retry.
146
+ const tokens = await completeOAuth(session.provider, session.flow, authorizationResponse, {
147
+ fetch: deps.fetch,
148
+ now,
149
+ });
150
+ deps.store.deleteSession(token);
151
+ const stored = deps.store.connect(tokens, session.credentialName, now);
152
+ if (stored === null) {
153
+ throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(session.credentialName)}.`);
154
+ }
155
+ return summary(deps.store, stored, now);
156
+ }
157
+
158
+ function summary(store: SubscriptionStore, credential: SubscriptionCredential, now: Date) {
159
+ return credentialBody(credential, store.activeCredential(credential.provider, now)?.id === credential.id, now);
160
+ }
161
+
162
+ /** The fields the CLI reads from a credential, never its tokens. */
163
+ function credentialBody(credential: SubscriptionCredential, active: boolean, now: Date) {
164
+ const held = isHeld(credential, now);
165
+ return {
166
+ id: credential.id,
167
+ name: credential.name,
168
+ label: credential.label,
169
+ safe_metadata: credential.accountEmail === null ? {} : { account_email: credential.accountEmail },
170
+ // Hosted organizations also hold organization-scoped secrets; every
171
+ // subscription here belongs to the gateway's one user.
172
+ credential_scope: "user",
173
+ oauth_provider: credential.provider,
174
+ created_at: credential.createdAt.toISOString(),
175
+ last_used_at: credential.lastUsedAt?.toISOString() ?? null,
176
+ unavailable_until: held ? credential.unavailableUntil!.toISOString() : null,
177
+ unavailable_reason: held ? credential.unavailableReason : null,
178
+ subscription_active: active,
179
+ // Spending banked Codex resets is hosted-only.
180
+ auto_redeem_resets: false,
181
+ };
182
+ }
183
+
184
+ function found(credential: SubscriptionCredential | null, name: string): SubscriptionCredential {
185
+ if (credential === null) throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(name)}.`);
186
+ return credential;
187
+ }
188
+
189
+ async function readBody(request: Request): Promise<Record<string, unknown>> {
190
+ let body: unknown;
191
+ try {
192
+ body = await request.json();
193
+ } catch {
194
+ throw new HttpError(400, "Request body must be JSON.");
195
+ }
196
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
197
+ throw new HttpError(400, "Request body must be a JSON object.");
198
+ }
199
+ return body as Record<string, unknown>;
200
+ }
201
+
202
+ function json(status: number, body: unknown): Response {
203
+ return Response.json(body, { status });
204
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Personal subscriptions for a self-hosted, single-tenant gateway: Claude Code
3
+ * (Max/Pro) and ChatGPT (Codex) plans connected over OAuth and used in place
4
+ * of API keys.
5
+ *
6
+ * - `oauth.ts`: the providers' OAuth protocols (Claude Code PKCE with a
7
+ * pasted `code#state`, ChatGPT device code) and token refresh.
8
+ * - `store.ts`: SQLite storage. Tokens are plaintext in the gateway's own
9
+ * database file; protect that file like a secret.
10
+ * - `access.ts`: `freshAccessToken` refreshes a token expiring within five
11
+ * minutes before handing it out, one refresh per credential at a time.
12
+ * - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
13
+ * Dari CLI uses to connect, list, rename, release, and disconnect
14
+ * subscriptions. The caller authenticates the request first.
15
+ *
16
+ * Routing picks `store.activeCredential(provider)`: the subscription in use
17
+ * while it serves, then the next one in connection order that is not held. When a provider reports a usage limit,
18
+ * `store.markUnavailable` holds that subscription until its reset and says
19
+ * whether another one can serve the retry.
20
+ */
21
+ export { freshAccessToken } from "./access";
22
+ export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http";
23
+ export {
24
+ CODEX_APPROVAL_PENDING,
25
+ SUBSCRIPTION_PROVIDERS,
26
+ SubscriptionOAuthInputError,
27
+ SubscriptionOAuthProviderError,
28
+ completeOAuth,
29
+ parseAuthorizationResponse,
30
+ refreshOAuth,
31
+ startOAuth,
32
+ type OAuthAuthorization,
33
+ type OAuthFetch,
34
+ type OAuthOptions,
35
+ type OAuthTokens,
36
+ type SubscriptionProvider,
37
+ } from "./oauth";
38
+ export {
39
+ SubscriptionStore,
40
+ isHeld,
41
+ type PendingOAuthSession,
42
+ type SubscriptionCredential,
43
+ } from "./store";
@@ -0,0 +1,395 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+
3
+ /**
4
+ * OAuth protocols for personal subscriptions: Claude Code (PKCE, the user
5
+ * pastes back the `code#state` Anthropic shows) and ChatGPT/Codex (device
6
+ * code, the gateway polls for approval). Every network call goes through the
7
+ * injected `fetch`.
8
+ */
9
+
10
+ export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex";
11
+
12
+ export const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[] = [
13
+ "anthropic_claude_code",
14
+ "openai_codex",
15
+ ];
16
+
17
+ export type OAuthFetch = (url: string, init: RequestInit) => Promise<Response>;
18
+
19
+ export type OAuthOptions = { fetch: OAuthFetch; now?: Date };
20
+
21
+ /** The provider refused or could not be reached (HTTP 502 at the edge). */
22
+ export class SubscriptionOAuthProviderError extends Error {
23
+ constructor(message: string, readonly status?: number) {
24
+ super(message);
25
+ this.name = "SubscriptionOAuthProviderError";
26
+ }
27
+ }
28
+
29
+ /** The user's input or flow state is wrong (HTTP 400 at the edge). */
30
+ export class SubscriptionOAuthInputError extends Error {
31
+ constructor(message: string) {
32
+ super(message);
33
+ this.name = "SubscriptionOAuthInputError";
34
+ }
35
+ }
36
+
37
+ export type OAuthAuthorization = {
38
+ authorizationUrl: string;
39
+ expiresAt: Date;
40
+ // Shown to the user for the device-code flow only.
41
+ userCode: string | null;
42
+ // Secret per-flow state the completion step needs.
43
+ flow: Record<string, string>;
44
+ };
45
+
46
+ export type OAuthTokens = {
47
+ provider: SubscriptionProvider;
48
+ accessToken: string;
49
+ refreshToken: string;
50
+ expiresAt: Date;
51
+ // The ChatGPT account the token acts for; null for Claude Code.
52
+ accountId: string | null;
53
+ accountEmail: string | null;
54
+ };
55
+
56
+ const FLOW_TIMEOUT_MS = 15 * 60_000;
57
+ const REQUEST_TIMEOUT_MS = 30_000;
58
+ const INCOMPLETE = "Subscription OAuth provider returned an incomplete response.";
59
+
60
+ export const CLAUDE_CODE_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
61
+ const CLAUDE_AUTHORIZE_URL = "https://claude.com/cai/oauth/authorize";
62
+ const CLAUDE_TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
63
+ // Anthropic shows `code#state` on its own callback page for the user to paste back.
64
+ const CLAUDE_REDIRECT_URI = "https://platform.claude.com/oauth/code/callback";
65
+ const CLAUDE_CODE_SCOPES =
66
+ "user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
67
+
68
+ export const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
69
+ const OPENAI_AUTH_BASE_URL = "https://auth.openai.com";
70
+ const CODEX_AUTHORIZE_URL = `${OPENAI_AUTH_BASE_URL}/codex/device`;
71
+ const CODEX_DEVICE_AUTH_URL = `${OPENAI_AUTH_BASE_URL}/api/accounts/deviceauth`;
72
+ const CODEX_TOKEN_URL = `${OPENAI_AUTH_BASE_URL}/oauth/token`;
73
+ const CODEX_REDIRECT_URI = `${OPENAI_AUTH_BASE_URL}/deviceauth/callback`;
74
+ const CODEX_ACCOUNT_CLAIM = "https://api.openai.com/auth";
75
+
76
+ export const CODEX_APPROVAL_PENDING =
77
+ "OpenAI approval is still pending. Enter the code at OpenAI, finish approval, then try again.";
78
+
79
+ export async function startOAuth(
80
+ provider: SubscriptionProvider,
81
+ options: OAuthOptions,
82
+ ): Promise<OAuthAuthorization> {
83
+ const expiresAt = new Date((options.now ?? new Date()).getTime() + FLOW_TIMEOUT_MS);
84
+ if (provider === "anthropic_claude_code") {
85
+ const verifier = randomUrlSafe(32);
86
+ const challenge = base64Url(createHash("sha256").update(verifier).digest());
87
+ // The pasted `code#state` is shown to the user, so state must not be the verifier.
88
+ const state = randomUrlSafe(32);
89
+ const query = new URLSearchParams({
90
+ code: "true",
91
+ client_id: CLAUDE_CODE_CLIENT_ID,
92
+ response_type: "code",
93
+ redirect_uri: CLAUDE_REDIRECT_URI,
94
+ scope: CLAUDE_CODE_SCOPES,
95
+ code_challenge: challenge,
96
+ code_challenge_method: "S256",
97
+ state,
98
+ });
99
+ return {
100
+ authorizationUrl: `${CLAUDE_AUTHORIZE_URL}?${query}`,
101
+ expiresAt,
102
+ userCode: null,
103
+ flow: { code_verifier: verifier, state },
104
+ };
105
+ }
106
+ const payload = await postJson(
107
+ options.fetch,
108
+ `${CODEX_DEVICE_AUTH_URL}/usercode`,
109
+ { client_id: CODEX_CLIENT_ID },
110
+ "OpenAI device code request",
111
+ );
112
+ const userCode = requiredString({ user_code: payload.user_code || payload.usercode }, "user_code");
113
+ return {
114
+ authorizationUrl: CODEX_AUTHORIZE_URL,
115
+ expiresAt,
116
+ userCode,
117
+ flow: { device_auth_id: requiredString(payload, "device_auth_id"), user_code: userCode },
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Finish a flow. Claude Code needs the pasted authorization response; the
123
+ * device-code flow ignores it and asks OpenAI whether the user approved.
124
+ */
125
+ export async function completeOAuth(
126
+ provider: SubscriptionProvider,
127
+ flow: Record<string, string>,
128
+ authorizationResponse: string,
129
+ options: OAuthOptions,
130
+ ): Promise<OAuthTokens> {
131
+ const now = options.now ?? new Date();
132
+ if (provider === "anthropic_claude_code") {
133
+ const verifier = requiredString(flow, "code_verifier");
134
+ const expectedState = requiredString(flow, "state");
135
+ if (!authorizationResponse.trim()) {
136
+ throw new SubscriptionOAuthInputError("Anthropic authorization code is required.");
137
+ }
138
+ const { code, state } = parseAuthorizationResponse(authorizationResponse);
139
+ if (state !== null && state !== expectedState) {
140
+ throw new SubscriptionOAuthInputError("Anthropic authorization state does not match. Start again.");
141
+ }
142
+ const token = await postJson(
143
+ options.fetch,
144
+ CLAUDE_TOKEN_URL,
145
+ {
146
+ grant_type: "authorization_code",
147
+ client_id: CLAUDE_CODE_CLIENT_ID,
148
+ code,
149
+ state: state ?? expectedState,
150
+ redirect_uri: CLAUDE_REDIRECT_URI,
151
+ code_verifier: verifier,
152
+ },
153
+ "Anthropic subscription token exchange",
154
+ );
155
+ return claudeTokens(token, now, null);
156
+ }
157
+
158
+ // The provider, not user-supplied input, supplies the authorization code.
159
+ let approval: Record<string, unknown>;
160
+ try {
161
+ approval = await postJson(
162
+ options.fetch,
163
+ `${CODEX_DEVICE_AUTH_URL}/token`,
164
+ {
165
+ device_auth_id: requiredString(flow, "device_auth_id"),
166
+ user_code: requiredString(flow, "user_code"),
167
+ },
168
+ "OpenAI device approval check",
169
+ );
170
+ } catch (error) {
171
+ if (error instanceof SubscriptionOAuthProviderError && (error.status === 403 || error.status === 404)) {
172
+ throw new SubscriptionOAuthInputError(CODEX_APPROVAL_PENDING);
173
+ }
174
+ throw error;
175
+ }
176
+ const token = await postForm(
177
+ options.fetch,
178
+ CODEX_TOKEN_URL,
179
+ {
180
+ grant_type: "authorization_code",
181
+ client_id: CODEX_CLIENT_ID,
182
+ code: requiredString(approval, "authorization_code"),
183
+ code_verifier: requiredString(approval, "code_verifier"),
184
+ redirect_uri: CODEX_REDIRECT_URI,
185
+ },
186
+ "OpenAI subscription token exchange",
187
+ );
188
+ return codexTokens(token, now, null, null);
189
+ }
190
+
191
+ export async function refreshOAuth(
192
+ credential: { provider: SubscriptionProvider; refreshToken: string; accountId: string | null },
193
+ options: OAuthOptions,
194
+ ): Promise<OAuthTokens> {
195
+ const now = options.now ?? new Date();
196
+ if (credential.provider === "anthropic_claude_code") {
197
+ const token = await postJson(
198
+ options.fetch,
199
+ CLAUDE_TOKEN_URL,
200
+ {
201
+ grant_type: "refresh_token",
202
+ client_id: CLAUDE_CODE_CLIENT_ID,
203
+ refresh_token: credential.refreshToken,
204
+ scope: CLAUDE_CODE_SCOPES,
205
+ },
206
+ "Anthropic subscription token refresh",
207
+ );
208
+ return claudeTokens(token, now, credential.refreshToken);
209
+ }
210
+ const token = await postJson(
211
+ options.fetch,
212
+ CODEX_TOKEN_URL,
213
+ {
214
+ grant_type: "refresh_token",
215
+ refresh_token: credential.refreshToken,
216
+ client_id: CODEX_CLIENT_ID,
217
+ },
218
+ "OpenAI subscription token refresh",
219
+ );
220
+ return codexTokens(token, now, credential.refreshToken, credential.accountId);
221
+ }
222
+
223
+ /** Accepts the full callback URL, `code#state`, a `code=...&state=...` query, or a bare code. */
224
+ export function parseAuthorizationResponse(value: string): { code: string; state: string | null } {
225
+ const normalized = value.trim();
226
+ if (URL.canParse(normalized)) {
227
+ const parsed = new URL(normalized);
228
+ const code = parsed.searchParams.get("code");
229
+ if (parsed.host && code) return { code, state: parsed.searchParams.get("state") || null };
230
+ }
231
+ const hash = normalized.indexOf("#");
232
+ if (hash > 0) {
233
+ return { code: normalized.slice(0, hash), state: normalized.slice(hash + 1) || null };
234
+ }
235
+ if (normalized.includes("code=")) {
236
+ const query = new URLSearchParams(normalized);
237
+ const code = query.get("code");
238
+ if (code) return { code, state: query.get("state") || null };
239
+ }
240
+ if (normalized) return { code: normalized, state: null };
241
+ throw new SubscriptionOAuthInputError("Authorization code or redirect URL is required.");
242
+ }
243
+
244
+ function claudeTokens(
245
+ payload: Record<string, unknown>,
246
+ now: Date,
247
+ fallbackRefreshToken: string | null,
248
+ ): OAuthTokens {
249
+ const account = payload.account;
250
+ const email = isRecord(account) ? account.email_address : undefined;
251
+ return {
252
+ provider: "anthropic_claude_code",
253
+ accessToken: requiredString(payload, "access_token"),
254
+ refreshToken: refreshTokenFrom(payload, fallbackRefreshToken),
255
+ expiresAt: new Date(now.getTime() + positiveInt(payload.expires_in) * 1000),
256
+ accountId: null,
257
+ accountEmail: typeof email === "string" && email ? email : null,
258
+ };
259
+ }
260
+
261
+ function codexTokens(
262
+ payload: Record<string, unknown>,
263
+ now: Date,
264
+ fallbackRefreshToken: string | null,
265
+ fallbackAccountId: string | null,
266
+ ): OAuthTokens {
267
+ const accessToken = requiredString(payload, "access_token");
268
+ const refreshToken = refreshTokenFrom(payload, fallbackRefreshToken);
269
+ const idToken = typeof payload.id_token === "string" ? payload.id_token : null;
270
+ const accountId = (idToken === null ? null : codexAccountId(idToken))
271
+ ?? codexAccountId(accessToken)
272
+ ?? fallbackAccountId;
273
+ if (accountId === null) {
274
+ throw new SubscriptionOAuthProviderError("OpenAI subscription token is missing its account identifier.");
275
+ }
276
+ const email = idToken === null ? undefined : jwtPayload(idToken)?.email;
277
+ return {
278
+ provider: "openai_codex",
279
+ accessToken,
280
+ refreshToken,
281
+ expiresAt: codexExpiration(payload, accessToken, now),
282
+ accountId,
283
+ accountEmail: typeof email === "string" && email ? email : null,
284
+ };
285
+ }
286
+
287
+ function codexAccountId(token: string): string | null {
288
+ const auth = jwtPayload(token)?.[CODEX_ACCOUNT_CLAIM];
289
+ const accountId = isRecord(auth) ? auth.chatgpt_account_id : undefined;
290
+ return typeof accountId === "string" && accountId ? accountId : null;
291
+ }
292
+
293
+ function codexExpiration(payload: Record<string, unknown>, accessToken: string, now: Date): Date {
294
+ if (payload.expires_in !== undefined && payload.expires_in !== null) {
295
+ return new Date(now.getTime() + positiveInt(payload.expires_in) * 1000);
296
+ }
297
+ const exp = jwtPayload(accessToken)?.exp;
298
+ if (typeof exp === "number" && Number.isFinite(exp)) return new Date(exp * 1000);
299
+ throw new SubscriptionOAuthProviderError("OpenAI subscription token is missing its expiration.");
300
+ }
301
+
302
+ function refreshTokenFrom(payload: Record<string, unknown>, fallback: string | null): string {
303
+ const value = payload.refresh_token;
304
+ const refreshToken = typeof value === "string" && value ? value : fallback;
305
+ if (!refreshToken) throw new SubscriptionOAuthProviderError(INCOMPLETE);
306
+ return refreshToken;
307
+ }
308
+
309
+ function requiredString(payload: Record<string, unknown>, name: string): string {
310
+ const value = payload[name];
311
+ if (typeof value !== "string" || !value) throw new SubscriptionOAuthProviderError(INCOMPLETE);
312
+ return value;
313
+ }
314
+
315
+ function positiveInt(value: unknown): number {
316
+ const parsed = typeof value === "string" && /^\s*[+-]?\d+\s*$/.test(value) ? Number(value) : value;
317
+ if (typeof parsed === "number" && Number.isInteger(parsed) && parsed > 0) return parsed;
318
+ throw new SubscriptionOAuthProviderError(INCOMPLETE);
319
+ }
320
+
321
+ function jwtPayload(token: string): Record<string, unknown> | null {
322
+ const parts = token.split(".");
323
+ if (parts.length !== 3) return null;
324
+ try {
325
+ const decoded: unknown = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8"));
326
+ return isRecord(decoded) ? decoded : null;
327
+ } catch {
328
+ return null;
329
+ }
330
+ }
331
+
332
+ function postJson(
333
+ fetch: OAuthFetch,
334
+ url: string,
335
+ payload: Record<string, string>,
336
+ operation: string,
337
+ ): Promise<Record<string, unknown>> {
338
+ return requestJson(fetch, url, JSON.stringify(payload), "application/json", operation);
339
+ }
340
+
341
+ function postForm(
342
+ fetch: OAuthFetch,
343
+ url: string,
344
+ payload: Record<string, string>,
345
+ operation: string,
346
+ ): Promise<Record<string, unknown>> {
347
+ return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation);
348
+ }
349
+
350
+ async function requestJson(
351
+ fetch: OAuthFetch,
352
+ url: string,
353
+ body: string,
354
+ contentType: string,
355
+ operation: string,
356
+ ): Promise<Record<string, unknown>> {
357
+ let response: Response;
358
+ try {
359
+ response = await fetch(url, {
360
+ method: "POST",
361
+ headers: { Accept: "application/json", "Content-Type": contentType, "User-Agent": "Dari/1.0" },
362
+ body,
363
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
364
+ });
365
+ } catch {
366
+ throw new SubscriptionOAuthProviderError(`${operation} could not reach the provider.`);
367
+ }
368
+ if (!response.ok) {
369
+ await response.body?.cancel();
370
+ throw new SubscriptionOAuthProviderError(
371
+ `${operation} failed with provider status ${response.status}.`,
372
+ response.status,
373
+ );
374
+ }
375
+ let decoded: unknown;
376
+ try {
377
+ decoded = await response.json();
378
+ } catch {
379
+ throw new SubscriptionOAuthProviderError(`${operation} returned an invalid response.`);
380
+ }
381
+ if (!isRecord(decoded)) throw new SubscriptionOAuthProviderError(`${operation} returned an invalid response.`);
382
+ return decoded;
383
+ }
384
+
385
+ function randomUrlSafe(size: number): string {
386
+ return base64Url(randomBytes(size));
387
+ }
388
+
389
+ function base64Url(value: Buffer): string {
390
+ return value.toString("base64url");
391
+ }
392
+
393
+ function isRecord(value: unknown): value is Record<string, unknown> {
394
+ return typeof value === "object" && value !== null && !Array.isArray(value);
395
+ }