mirror of
https://github.com/tester-army/e2e.git
synced 2026-12-03 04:45:58 +08:00
feat(oauth): sign in with a ChatGPT, GitHub Copilot, or SuperGrok subscription (#335)
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
---
|
||||
'@e2edev/oauth': minor
|
||||
'e2e': minor
|
||||
---
|
||||
|
||||
Sign in with a personal subscription instead of an API key. The new `@e2edev/oauth` package runs the OAuth flows for ChatGPT Plus/Pro (the Codex sign-in, browser or device code), GitHub Copilot (the GitHub CLI's login or a device flow for your OAuth App), and SuperGrok / X Premium+ (device code), stores the tokens in `~/.config/e2e/oauth.json`, refreshes them ahead of expiry, and exposes each plan as an AI SDK model: `chatgpt('gpt-5.5')`, `copilot('claude-sonnet-5')`, `grok('grok-4')`. The e2e CLI gains `e2e login <provider>` and `e2e logout`, and `e2e init` offers the three subscriptions next to the gateways.
|
||||
+2
-1
@@ -15,7 +15,8 @@
|
||||
"packages/mobile-benchmark/tests*/**/*.ts",
|
||||
"packages/mobile-benchmark/index.ts",
|
||||
"packages/e2e/tests/types/sdk-types.ts",
|
||||
"packages/playwright/tests/types/connection.ts"
|
||||
"packages/playwright/tests/types/connection.ts",
|
||||
"packages/oauth/tests/live/*.ts"
|
||||
],
|
||||
"ignorePatterns": [
|
||||
"docs/**",
|
||||
|
||||
@@ -36,7 +36,7 @@ descriptions and commit bodies; `git log` and `gh pr view` are the archive.
|
||||
`src/` (grep for them; zero hits is the invariant). The one exception is the
|
||||
`e2e init` scaffold presets in `src/cli/init/engines.ts`, which write the
|
||||
user's config and so name engine packages as text; the package build records
|
||||
the sibling engines' versions in `dist/cli/init/engine-versions.json` for the
|
||||
the sibling packages' versions in `dist/cli/init/sibling-versions.json` for the
|
||||
ranges they write. Each preset owns its prompt label, dependencies, config,
|
||||
example, and run command; interactive choices derive from this list. These
|
||||
presets never import engine implementations.
|
||||
|
||||
@@ -88,6 +88,7 @@
|
||||
"icon": "compass",
|
||||
"pages": [
|
||||
"models",
|
||||
"subscriptions",
|
||||
"authentication",
|
||||
"security",
|
||||
"agents",
|
||||
|
||||
@@ -101,6 +101,7 @@ Any AI SDK provider package works: `@ai-sdk/anthropic`, `@ai-sdk/google`,
|
||||
| One key for every vendor, billed by OpenRouter | `openrouter('vendor/model')` | `@openrouter/ai-sdk-provider` | `OPENROUTER_API_KEY` |
|
||||
| A local or self-hosted server | `createOpenAICompatible({ name, baseURL }).chatModel('model')` | `@ai-sdk/openai-compatible` | whatever you pass as `apiKey` |
|
||||
| One vendor, your own account | `openai('model')`, `anthropic('model')`, ... | `@ai-sdk/<vendor>` | the vendor's own |
|
||||
| Your ChatGPT, Copilot, or SuperGrok plan, no key | `chatgpt('model')` from `@e2edev/oauth/chatgpt`, `copilot('model')` from `/copilot`, `grok('model')` from `/grok` | `@e2edev/oauth` plus the matching `@ai-sdk/*` provider | none; `e2e login` stores the sign-in. See [Subscriptions](/subscriptions). |
|
||||
|
||||
The model id is whatever the package accepts. Gateways take `vendor/model`;
|
||||
a direct provider takes the vendor's bare id; a local server takes the name
|
||||
|
||||
+31
-4
@@ -47,9 +47,12 @@ The wizard asks three things when it creates a config:
|
||||
macOS and Android elsewhere, and opens Settings. **None** adds nothing.
|
||||
- The model gateway agent steps use. **Vercel AI Gateway** (the default),
|
||||
**OpenRouter**, an **OpenAI-compatible endpoint** (prompts for an HTTPS or
|
||||
loopback base URL), or **None**. A gateway adds `ai@^7.0.0`, the gateway's
|
||||
provider package when it has one, and an `agents` block that constructs
|
||||
the model.
|
||||
loopback base URL), a **ChatGPT Plus/Pro**, **GitHub Copilot**, or
|
||||
**SuperGrok subscription** (see [Subscriptions](/subscriptions)), or
|
||||
**None**. A gateway adds `ai@^7.0.0`, the gateway's provider package when
|
||||
it has one, and an `agents` block that constructs the model. A
|
||||
subscription adds `@e2edev/oauth` and names `e2e login <provider>` as the
|
||||
step before the first run.
|
||||
- Where to install the agent skill (see [e2e guide](#e2e-guide)):
|
||||
`.agents/skills/` for Codex, Cursor, Copilot, Gemini CLI, OpenCode, and
|
||||
Zed, and `.claude/skills/` for Claude Code. Both are preselected.
|
||||
@@ -65,7 +68,7 @@ lockfile, then the invoking package manager, then npm.
|
||||
|
||||
| Creates | Content |
|
||||
| --- | --- |
|
||||
| `package.json` | Created as a private ESM package when missing; otherwise only missing dependencies and scripts are added. Engine packages get the caret range of the version released with the CLI. A `test:e2e` script runs `e2e run` unless one exists |
|
||||
| `package.json` | Created as a private ESM package when missing; otherwise only missing dependencies and scripts are added. Sibling packages (`@e2edev/playwright`, `@e2edev/agent-device`, `@e2edev/oauth`) get the caret range of the version released with the CLI, or that exact version when the CLI is a prerelease. A `test:e2e` script runs `e2e run` unless one exists |
|
||||
| `e2e.config.ts` | One target for the selected engine. Playwright reads `APP_URL` (default `http://localhost:3000`) and shows the `command` option in a comment. With a gateway, `agents.default` is `createAgent({ model, system })` |
|
||||
| `tests/example.e2e.ts` | An app-open test that passes against any page, plus a commented agent test. Device setup gets a Settings check instead |
|
||||
| `.gitignore` | Appends `node_modules/`, `.e2e/artifacts/`, `.e2e/cache/`, `.e2e/sessions/`, `.e2e/report.json`, `.e2e/ai-trace.json`, `.e2e/junit.xml`, `.e2e/summary.md`, `.e2e/failures/`, and `.e2e/logs/`. Committing the cache is opt-in; see [commit your traces](/reference/config#commit-your-traces) |
|
||||
@@ -83,6 +86,30 @@ Cancellation leaves files untouched and exits 0. An invalid `package.json`
|
||||
exits 2 before any write. Without a terminal on stdin and stdout, `init`
|
||||
without `--yes` exits 2 and names the flag.
|
||||
|
||||
## e2e login
|
||||
|
||||
```bash
|
||||
npx e2e login openai # ChatGPT Plus/Pro, opens the browser
|
||||
npx e2e login openai --device # a code to enter on another device
|
||||
npx e2e login github-copilot --from-gh # reuse the GitHub CLI's login
|
||||
npx e2e login github-copilot --client-id <id> [--enterprise-url <host>]
|
||||
npx e2e login spacexai # SuperGrok / X Premium+, device code
|
||||
npx e2e login # pick one; signed-in ones are marked
|
||||
```
|
||||
|
||||
Signs in to a personal subscription and stores the login in
|
||||
`~/.config/e2e/oauth.json` for the models `@e2edev/oauth` constructs
|
||||
(`chatgpt()`, `copilot()`, `grok()`). An unknown provider is a usage error,
|
||||
exit 2. Needs `@e2edev/oauth` in the project; without it the command exits 1
|
||||
with the install line. See [Subscriptions](/subscriptions).
|
||||
|
||||
## e2e logout
|
||||
|
||||
```bash
|
||||
npx e2e logout # pick one of the stored logins
|
||||
npx e2e logout openai # forget one
|
||||
```
|
||||
|
||||
## e2e guide
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
---
|
||||
title: Subscriptions
|
||||
description: Use a personal ChatGPT, GitHub Copilot, or SuperGrok plan as the agent model, signed in once from the terminal.
|
||||
---
|
||||
|
||||
An agent model does not need a pay-per-token API key. `@e2edev/oauth` signs
|
||||
in to a subscription you already pay for and hands the runner an ordinary AI
|
||||
SDK model instance. The runner does not know the difference: it is still the
|
||||
line in `e2e.config.ts` that constructs the model.
|
||||
|
||||
| Plan | Sign in | Constructor | Provider package it needs |
|
||||
| --- | --- | --- | --- |
|
||||
| ChatGPT Plus/Pro | `e2e login openai` | `chatgpt('gpt-5.5')` | `@ai-sdk/openai` |
|
||||
| GitHub Copilot | `e2e login github-copilot` | `copilot('claude-sonnet-5')` | `@ai-sdk/openai-compatible` |
|
||||
| SuperGrok / X Premium+ | `e2e login spacexai` | `grok('grok-4')` | `@ai-sdk/xai` |
|
||||
|
||||
Claude Pro/Max is not offered. Anthropic's terms allow subscription sign-in
|
||||
only for Claude Code and its own applications, and the API rejects those
|
||||
tokens from other clients. Use an Anthropic API key, or reach Claude models
|
||||
through your Copilot plan.
|
||||
|
||||
## Set up
|
||||
|
||||
When it creates a config, `e2e init` lists the three plans next to the
|
||||
gateways and writes the config and dependencies; an existing config is left
|
||||
as it is. By hand:
|
||||
|
||||
```bash
|
||||
npm i -D @e2edev/oauth @ai-sdk/openai # or @ai-sdk/openai-compatible, @ai-sdk/xai
|
||||
npx e2e login openai
|
||||
```
|
||||
|
||||
```ts title="e2e.config.ts"
|
||||
import type { E2EConfig } from 'e2e';
|
||||
import { playwright } from '@e2edev/playwright';
|
||||
import { createAgent } from 'e2e/agent';
|
||||
import { chatgpt } from '@e2edev/oauth/chatgpt';
|
||||
|
||||
export default {
|
||||
targets: [{ engine: playwright({ url: 'http://localhost:3000' }) }],
|
||||
agents: { default: createAgent({ model: chatgpt('gpt-5.5') }) },
|
||||
} satisfies E2EConfig;
|
||||
```
|
||||
|
||||
Each constructor lives on its own subpath so a project installs only the
|
||||
provider package it uses. Constructing the model reads nothing; the stored
|
||||
login is read on the first model call, and a missing login fails that call
|
||||
with `MODEL_PROVIDER_FAILED` naming the `e2e login` command.
|
||||
|
||||
## How each sign-in works
|
||||
|
||||
**ChatGPT.** The same sign-in the Codex CLI uses: the browser opens
|
||||
`auth.openai.com`, and after you approve, it returns to a page served on
|
||||
`localhost:1455`. If that port is taken, or the browser has not come back
|
||||
after ten minutes, the terminal asks you to paste the URL it landed on.
|
||||
`--device` prints a code to enter on another device instead. Requests go to the Codex backend, which serves `gpt-5.5`,
|
||||
`gpt-5.4`, `gpt-5.4-mini`, and `gpt-5.3-codex-spark` to subscription
|
||||
sign-ins and draws on your plan's usage limits.
|
||||
|
||||
**GitHub Copilot.** The Copilot API accepts a GitHub sign-in as the bearer.
|
||||
When the GitHub CLI is signed in, `e2e login github-copilot` reuses its token
|
||||
and asks nothing. Otherwise pass `--client-id` with a
|
||||
[GitHub OAuth App](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app)
|
||||
of yours that has the device flow enabled, and enter the code GitHub shows.
|
||||
`--enterprise-url` points at a GitHub Enterprise host. Copilot serves OpenAI,
|
||||
Anthropic, Google, and SpaceXAI models; `curl -H "Authorization: Bearer $(gh auth token)" https://api.githubcopilot.com/models`
|
||||
lists what your plan has enabled.
|
||||
|
||||
**SuperGrok.** SpaceXAI's device flow: open `accounts.x.ai`, enter the code, done.
|
||||
Requests go to the ordinary SpaceXAI API with your plan's shared weekly usage pool.
|
||||
|
||||
## Where the login lives
|
||||
|
||||
`~/.config/e2e/oauth.json` (or under `$XDG_CONFIG_HOME`), mode 0600, one
|
||||
entry per provider. Tokens refresh themselves ahead of expiry, and one refresh
|
||||
serves every concurrent call of a run. `e2e login` without a provider shows
|
||||
a picker that marks the signed-in ones; `e2e logout` without a provider
|
||||
picks among the stored logins.
|
||||
|
||||
`E2E_OAUTH_CREDENTIALS` holding the same JSON replaces the file for a
|
||||
machine you cannot sign in on. It is read-only: `e2e login` and `e2e logout`
|
||||
refuse to change it. A ChatGPT or SuperGrok entry there is refreshed for the
|
||||
running process only, and since refresh tokens rotate, the value in the
|
||||
variable is spent after the first refresh. Subscriptions are for the machine you work on; CI
|
||||
keeps an API key.
|
||||
|
||||
## Your own product
|
||||
|
||||
The package is not tied to e2e. `createOAuthFetch(provider, { store, userAgent })`
|
||||
returns the `fetch` any AI SDK provider factory accepts, `login()` runs a
|
||||
flow with your own prompts, and `OAuthProvider` is the interface to add a
|
||||
vendor. The user agent and the `originator` name your product; the flows use
|
||||
the vendors' public CLI clients, never another client's identity.
|
||||
|
||||
```ts
|
||||
import { createOpenAI } from '@ai-sdk/openai';
|
||||
import { createOAuthFetch, createCodexProvider, FileCredentialStore } from '@e2edev/oauth';
|
||||
|
||||
const store = new FileCredentialStore('/path/of/your/choice.json');
|
||||
const fetch = createOAuthFetch(createCodexProvider({ originator: 'my-tool' }), { store, userAgent: 'my-tool/1.0' });
|
||||
const model = createOpenAI({ apiKey: 'oauth', fetch }).responses('gpt-5.5');
|
||||
```
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Choosing a model" icon="robot" href="/models">
|
||||
Gateways, providers, and where a key comes from.
|
||||
</Card>
|
||||
<Card title="CLI reference" icon="terminal" href="/reference/cli#e2e-login">
|
||||
Every flag of `e2e login` and `e2e logout`.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
+2
-2
@@ -9,7 +9,7 @@
|
||||
],
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm --filter e2e run build && pnpm --filter @e2edev/playwright run build && pnpm --filter @e2edev/agent-device run build && pnpm --filter @e2edev/github run build",
|
||||
"build": "pnpm --filter e2e run build && pnpm --filter @e2edev/playwright run build && pnpm --filter @e2edev/agent-device run build && pnpm --filter @e2edev/github run build && pnpm --filter @e2edev/oauth run build",
|
||||
"check": "pnpm run lint && pnpm run check:dead-code && pnpm run typecheck && pnpm run docs:check-errors && pnpm run docs:check",
|
||||
"check:dead-code": "fallow dead-code",
|
||||
"docs:check-errors": "node scripts/check-error-codes.ts",
|
||||
@@ -23,7 +23,7 @@
|
||||
"canary": "node scripts/canary-changeset.ts && changeset version --snapshot canary && pnpm run build",
|
||||
"canary:publish": "changeset publish --tag canary --no-git-tag",
|
||||
"typecheck": "pnpm run build && pnpm -r run typecheck",
|
||||
"test": "pnpm run build && pnpm --filter e2e run test && pnpm --filter @e2edev/playwright run test && pnpm --filter @e2edev/agent-device run test && pnpm --filter @e2edev/github run test",
|
||||
"test": "pnpm run build && pnpm --filter e2e run test && pnpm --filter @e2edev/playwright run test && pnpm --filter @e2edev/agent-device run test && pnpm --filter @e2edev/github run test && pnpm --filter @e2edev/oauth run test",
|
||||
"test:testbed": "pnpm run build && pnpm --filter @e2edev/testbed test",
|
||||
"test:web-benchmark": "pnpm run build && pnpm --filter @e2edev/web-benchmark test",
|
||||
"test:mobile-benchmark": "pnpm run build && pnpm --filter @e2edev/mobile-benchmark test",
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
"skills"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "node -e \"const fs=require('node:fs');for(const dir of ['dist','skills'])fs.rmSync(dir,{recursive:true,force:true});fs.cpSync('../../skills/e2e','skills/e2e',{recursive:true})\" && tsc --project tsconfig.build.json && node -e \"const fs=require('node:fs');const read=(dir)=>JSON.parse(fs.readFileSync('../'+dir+'/package.json','utf8'));const versions=Object.fromEntries(['playwright','agent-device'].map((dir)=>['@e2edev/'+dir,read(dir).version]));versions.playwright=read('playwright').devDependencies.playwright;fs.writeFileSync('dist/cli/init/engine-versions.json',JSON.stringify(versions)+'\\n')\" && node ../../scripts/stamp-dist.ts",
|
||||
"build": "node -e \"const fs=require('node:fs');for(const dir of ['dist','skills'])fs.rmSync(dir,{recursive:true,force:true});fs.cpSync('../../skills/e2e','skills/e2e',{recursive:true})\" && tsc --project tsconfig.build.json && node -e \"const fs=require('node:fs');const read=(dir)=>JSON.parse(fs.readFileSync('../'+dir+'/package.json','utf8'));const versions=Object.fromEntries(['playwright','agent-device','oauth'].map((dir)=>['@e2edev/'+dir,read(dir).version]));versions.playwright=read('playwright').devDependencies.playwright;fs.writeFileSync('dist/cli/init/sibling-versions.json',JSON.stringify(versions)+'\\n')\" && node ../../scripts/stamp-dist.ts",
|
||||
"prepublishOnly": "node ../../scripts/check-dist.ts",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
|
||||
@@ -20,6 +20,7 @@ import { DOCS_URL } from './docs-url.ts';
|
||||
import { guide } from './guide.ts';
|
||||
import { init } from './init.ts';
|
||||
import { mcp } from './mcp.ts';
|
||||
import { LOGIN_PROVIDERS, login, logout, type LoginOptions } from './login.ts';
|
||||
import { SignalLadder } from './signals.ts';
|
||||
import { skillTopics } from './skill.ts';
|
||||
import { telemetry as telemetryCommand, TELEMETRY_ACTIONS, type TelemetryAction } from './telemetry.ts';
|
||||
@@ -279,6 +280,35 @@ function createProgram(version: string, telemetry: Telemetry): Command {
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command('login')
|
||||
.summary('sign in to a ChatGPT, GitHub Copilot, or SuperGrok subscription for agent steps')
|
||||
.description(
|
||||
'Sign in once to a personal subscription and store the login for @e2edev/oauth models: openai (ChatGPT Plus/Pro, the Codex sign-in), github-copilot (GitHub Copilot; reuses the GitHub CLI login or runs a device flow for your OAuth App), spacexai (SuperGrok or X Premium+, device code). The config then constructs the model with chatgpt(), copilot(), or grok() from @e2edev/oauth. Requires @e2edev/oauth in the project.',
|
||||
)
|
||||
.addArgument(new Argument('[provider]', 'openai, github-copilot, or spacexai; omitted, a picker').choices(LOGIN_PROVIDERS))
|
||||
.option('--device', 'ChatGPT: show a code to enter on another device instead of opening a browser')
|
||||
.option('--client-id <id>', 'GitHub Copilot: the client id of your GitHub OAuth App with the device flow enabled')
|
||||
.option('--from-gh', 'GitHub Copilot: reuse the token of the signed-in GitHub CLI')
|
||||
.option('--enterprise-url <host>', 'GitHub Copilot: the GitHub Enterprise host')
|
||||
.addHelpText(
|
||||
'after',
|
||||
['', examples(['e2e login openai', 'e2e login github-copilot --from-gh', 'e2e login spacexai', 'e2e login']), '', docsLine('/subscriptions')].join('\n'),
|
||||
)
|
||||
.action(async (provider: string | undefined, options: LoginOptions) => {
|
||||
process.exitCode = await login(process.cwd(), provider, options);
|
||||
});
|
||||
|
||||
program
|
||||
.command('logout')
|
||||
.summary('forget a stored subscription login')
|
||||
.description('Remove the stored login of one provider (openai, github-copilot, spacexai). Without a provider, a picker over the stored logins.')
|
||||
.addArgument(new Argument('[provider]', 'openai, github-copilot, or spacexai; omitted, a picker').choices(LOGIN_PROVIDERS))
|
||||
.addHelpText('after', ['', examples(['e2e logout', 'e2e logout openai']), '', docsLine('/subscriptions')].join('\n'))
|
||||
.action(async (provider: string | undefined) => {
|
||||
process.exitCode = await logout(process.cwd(), provider);
|
||||
});
|
||||
|
||||
program
|
||||
.command('guide')
|
||||
.summary('print the e2e skill for coding agents')
|
||||
|
||||
@@ -10,7 +10,7 @@ import { DOCS_URL } from './docs-url.ts';
|
||||
import { findInstalledSkillDirs, planSkillInstall, SKILL_LOCATIONS } from './init/agent-skill.ts';
|
||||
import { isLoopbackHost } from '../internal/urls.ts';
|
||||
import { getEnginePresets, DEFAULT_ENGINE_ID, type EngineId } from './init/engines.ts';
|
||||
import { GATEWAYS, type GatewayId } from './init/gateways.ts';
|
||||
import { GATEWAYS, getGatewayPreset, type GatewayId } from './init/gateways.ts';
|
||||
import { findRegisteredMcpFiles, MCP_LOCATIONS, planMcpRegistration } from './init/mcp-config.ts';
|
||||
import { addDependencies, addScripts, describeManifestError, readPackage, serializePackage } from './init/package.ts';
|
||||
import { createScaffold, type ScaffoldModel } from './init/scaffold.ts';
|
||||
@@ -253,9 +253,12 @@ export async function init(cwd: string, options: InitOptions = {}): Promise<numb
|
||||
const runCommand = /^e2e run(?:\s|$)/u.test(manifest.scripts?.[RUN_SCRIPT] ?? '')
|
||||
? runScriptCommand(manager, RUN_SCRIPT)
|
||||
: execCommand(manager, 'e2e run');
|
||||
// A subscription gateway has no key to set; the sign-in is the step before the first run.
|
||||
const subscription = model === undefined ? undefined : getGatewayPreset(model.gateway).login;
|
||||
const next = [
|
||||
options.directory === undefined ? undefined : `cd ${shellArgument(options.directory)}`,
|
||||
install ? undefined : `${manager} install`,
|
||||
subscription === undefined ? undefined : execCommand(manager, `e2e login ${subscription}`),
|
||||
`${scaffold.needsAppUrl ? 'APP_URL=http://localhost:3000 ' : ''}${runCommand}`,
|
||||
].filter((step) => step !== undefined);
|
||||
clack.outro(`next: ${next.join(', then ')}`);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** CLI scaffold presets. Engine packages are referenced as generated source, never imported. */
|
||||
|
||||
import os from 'node:os';
|
||||
import { readJson } from '../../internal/package-version.ts';
|
||||
import { playwrightRange, siblingDependency, SIBLING_VERSIONS } from './versions.ts';
|
||||
|
||||
export interface EnginePreset {
|
||||
readonly id: string;
|
||||
@@ -16,45 +16,6 @@ export interface EnginePreset {
|
||||
readonly needsAppUrl: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Engine versions the build records next to this module, in
|
||||
* `engine-versions.json`, from the sibling packages' manifests. Absent when
|
||||
* running from source.
|
||||
*/
|
||||
const ENGINE_VERSIONS = readJson(import.meta.url, './engine-versions.json') as Readonly<Record<string, string>> | undefined;
|
||||
|
||||
/**
|
||||
* The range init writes for the runner and for an engine. Engines version
|
||||
* independently of the runner and pin it through their own peer range, so init
|
||||
* asks for the minor of the engine released alongside this runner. Package managers resolve a
|
||||
* range to the registry's `latest` tag whenever it satisfies, and `latest`
|
||||
* can trail the tag the runner came from by several minors, so a bare `0.x`
|
||||
* installed engines whose peer range rejected the runner.
|
||||
*
|
||||
* A canary runner pins itself and the exact engine build it shipped with.
|
||||
* Every canary engine names one runner build in its peer range, and a caret on
|
||||
* a prerelease resolves to the newest prerelease of that tuple, which names a
|
||||
* different one.
|
||||
*/
|
||||
export function dependencyRange(version: string | undefined): string {
|
||||
if (version === undefined) return '0.x';
|
||||
return version.includes('-') ? version : `^${version}`;
|
||||
}
|
||||
|
||||
function engineDependency(name: string): Readonly<Record<string, string>> {
|
||||
return { [name]: dependencyRange(ENGINE_VERSIONS?.[name]) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The range init writes for `playwright`, which `@e2edev/playwright` peers on
|
||||
* rather than installs, so an app that already ships Playwright keeps one copy
|
||||
* and one browser cache. The build records the version the engine was built
|
||||
* and tested against; from source, where nothing is recorded, any 1.x will do.
|
||||
*/
|
||||
export function playwrightRange(version: string | undefined): string {
|
||||
return version === undefined ? '^1' : `^${version}`;
|
||||
}
|
||||
|
||||
/** Builds prompt choices and scaffolds with defaults for the machine running init. */
|
||||
export function getEnginePresets() {
|
||||
const ios = os.platform() === 'darwin';
|
||||
@@ -63,7 +24,7 @@ export function getEnginePresets() {
|
||||
id: 'playwright',
|
||||
label: 'Web',
|
||||
hint: 'Playwright',
|
||||
dependencies: { ...engineDependency('@e2edev/playwright'), playwright: playwrightRange(ENGINE_VERSIONS?.['playwright']) },
|
||||
dependencies: { ...siblingDependency('@e2edev/playwright'), playwright: playwrightRange(SIBLING_VERSIONS?.['playwright']) },
|
||||
imports: ["import { playwright } from '@e2edev/playwright';"],
|
||||
config: ` targets: [{
|
||||
engine: playwright({
|
||||
@@ -94,7 +55,7 @@ test('app opens', async ({ app, web }) => {
|
||||
id: 'agent-device',
|
||||
label: 'Mobile (iOS/Android)',
|
||||
hint: 'agent-device',
|
||||
dependencies: engineDependency('@e2edev/agent-device'),
|
||||
dependencies: siblingDependency('@e2edev/agent-device'),
|
||||
imports: ["import { agentDevice } from '@e2edev/agent-device';"],
|
||||
config: ios
|
||||
? ` // Replace Settings with your app's bundle id.
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
* entry here.
|
||||
*/
|
||||
|
||||
export type GatewayId = 'vercel' | 'openrouter' | 'openai-compatible';
|
||||
import { siblingDependency } from './versions.ts';
|
||||
|
||||
export type GatewayId = 'vercel' | 'openrouter' | 'openai-compatible' | 'chatgpt' | 'copilot' | 'grok';
|
||||
|
||||
export interface GatewayPreset {
|
||||
readonly id: GatewayId;
|
||||
@@ -14,8 +16,10 @@ export interface GatewayPreset {
|
||||
/** Packages besides `ai` the generated config imports from. */
|
||||
readonly dependencies: Readonly<Record<string, string>>;
|
||||
readonly import: string;
|
||||
/** The comment line above the model, naming who serves it and which variable it reads. */
|
||||
/** The comment line above the model, naming who serves it and which variable it reads, or which sign-in it uses. */
|
||||
readonly comment: string;
|
||||
/** For a subscription: the `e2e login` provider that signs in, which init names as the next step. */
|
||||
readonly login?: string;
|
||||
/** The model expression, with the endpoint the user typed for an OpenAI-compatible one. */
|
||||
model(endpoint: string | undefined): string;
|
||||
}
|
||||
@@ -53,6 +57,36 @@ export const GATEWAYS: readonly GatewayPreset[] = [
|
||||
// apiKey: process.env.LLM_API_KEY,
|
||||
}).chatModel('gpt-5.6-luna')`,
|
||||
},
|
||||
{
|
||||
id: 'chatgpt',
|
||||
label: 'ChatGPT Plus/Pro subscription',
|
||||
hint: 'your ChatGPT plan through the Codex sign-in',
|
||||
dependencies: { ...siblingDependency('@e2edev/oauth'), '@ai-sdk/openai': '^4.0.0' },
|
||||
import: "import { chatgpt } from '@e2edev/oauth/chatgpt';",
|
||||
comment: 'Your ChatGPT subscription serves the model; sign in once with `e2e login openai`.',
|
||||
login: 'openai',
|
||||
model: () => "chatgpt('gpt-5.5')",
|
||||
},
|
||||
{
|
||||
id: 'copilot',
|
||||
label: 'GitHub Copilot subscription',
|
||||
hint: 'your Copilot plan: OpenAI, Anthropic, Google, and SpaceXAI models',
|
||||
dependencies: { ...siblingDependency('@e2edev/oauth'), '@ai-sdk/openai-compatible': '^3.0.0' },
|
||||
import: "import { copilot } from '@e2edev/oauth/copilot';",
|
||||
comment: 'Your GitHub Copilot subscription serves the model; sign in once with `e2e login github-copilot`.',
|
||||
login: 'github-copilot',
|
||||
model: () => "copilot('claude-sonnet-5')",
|
||||
},
|
||||
{
|
||||
id: 'grok',
|
||||
label: 'SuperGrok subscription',
|
||||
hint: 'your SuperGrok or X Premium+ plan',
|
||||
dependencies: { ...siblingDependency('@e2edev/oauth'), '@ai-sdk/xai': '^5.0.0' },
|
||||
import: "import { grok } from '@e2edev/oauth/grok';",
|
||||
comment: 'Your SuperGrok subscription serves the model; sign in once with `e2e login spacexai`.',
|
||||
login: 'spacexai',
|
||||
model: () => "grok('grok-4')",
|
||||
},
|
||||
];
|
||||
|
||||
export function getGatewayPreset(id: GatewayId): GatewayPreset {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { packageVersion } from '../../internal/package-version.ts';
|
||||
import { dependencyRange, getEnginePreset, type EngineId } from './engines.ts';
|
||||
import { getEnginePreset, type EngineId } from './engines.ts';
|
||||
import { dependencyRange } from './versions.ts';
|
||||
import { getGatewayPreset, type GatewayId } from './gateways.ts';
|
||||
|
||||
const AGENT_IMPORT = "import { createAgent } from 'e2e/agent';";
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Versions of the sibling packages released with this runner, recorded by the
|
||||
* build in `sibling-versions.json` next to this module from their manifests.
|
||||
* Absent when running from source. Both preset tables read from here.
|
||||
*/
|
||||
|
||||
import { readJson } from '../../internal/package-version.ts';
|
||||
|
||||
export const SIBLING_VERSIONS = readJson(import.meta.url, './sibling-versions.json') as Readonly<Record<string, string>> | undefined;
|
||||
|
||||
/**
|
||||
* The range init writes for the runner and for an engine. Engines version
|
||||
* independently of the runner and pin it through their own peer range, so init
|
||||
* asks for the minor of the engine released alongside this runner. Package managers resolve a
|
||||
* range to the registry's `latest` tag whenever it satisfies, and `latest`
|
||||
* can trail the tag the runner came from by several minors, so a bare `0.x`
|
||||
* installed engines whose peer range rejected the runner.
|
||||
*
|
||||
* A canary runner pins itself and the exact engine build it shipped with.
|
||||
* Every canary engine names one runner build in its peer range, and a caret on
|
||||
* a prerelease resolves to the newest prerelease of that tuple, which names a
|
||||
* different one.
|
||||
*/
|
||||
export function dependencyRange(version: string | undefined): string {
|
||||
if (version === undefined) return '0.x';
|
||||
return version.includes('-') ? version : `^${version}`;
|
||||
}
|
||||
|
||||
/** The range init writes for a sibling `@e2edev/*` package released alongside this runner. */
|
||||
export function siblingDependency(name: string): Readonly<Record<string, string>> {
|
||||
return { [name]: dependencyRange(SIBLING_VERSIONS?.[name]) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The range init writes for `playwright`, which `@e2edev/playwright` peers on
|
||||
* rather than installs, so an app that already ships Playwright keeps one copy
|
||||
* and one browser cache. The build records the version the engine was built
|
||||
* and tested against; from source, where nothing is recorded, any 1.x will do.
|
||||
*/
|
||||
export function playwrightRange(version: string | undefined): string {
|
||||
return version === undefined ? '^1' : `^${version}`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* `e2e login` and `e2e logout`: sign in to a personal subscription
|
||||
* (ChatGPT Plus/Pro, GitHub Copilot, SuperGrok) so a config can construct
|
||||
* its model from `@e2edev/oauth`. The flows live in that package; the CLI
|
||||
* calls its typed entry points, resolved from the project so the runner
|
||||
* itself never depends on any provider.
|
||||
*/
|
||||
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import pc from 'picocolors';
|
||||
|
||||
/** The providers `@e2edev/oauth` signs in to; commander rejects anything else as a usage error. */
|
||||
export const LOGIN_PROVIDERS = ['openai', 'github-copilot', 'spacexai'] as const;
|
||||
|
||||
export interface LoginOptions {
|
||||
readonly device?: boolean;
|
||||
readonly clientId?: string;
|
||||
readonly fromGh?: boolean;
|
||||
readonly enterpriseUrl?: string;
|
||||
}
|
||||
|
||||
/** What `@e2edev/oauth/cli` exports; typed here because the runner cannot import the package. */
|
||||
interface OAuthCli {
|
||||
runLogin(providerId: string | undefined, options: { method?: 'device'; clientId?: string; fromGitHubCli?: boolean; enterpriseUrl?: string }): Promise<number>;
|
||||
runLogout(providerId: string | undefined): Promise<number>;
|
||||
}
|
||||
|
||||
/** Loads `@e2edev/oauth/cli` from the project, or explains how to add it. */
|
||||
async function loadOAuthCli(cwd: string): Promise<OAuthCli | undefined> {
|
||||
const require = createRequire(path.join(cwd, 'package.json'));
|
||||
let resolved: string;
|
||||
try {
|
||||
resolved = require.resolve('@e2edev/oauth/cli');
|
||||
} catch {
|
||||
process.stderr.write(
|
||||
`${pc.red('error:')} @e2edev/oauth is not installed in this project. Add it with ${pc.cyan('npm i -D @e2edev/oauth')}, then import a model from it in e2e.config.ts, e.g. ${pc.cyan("import { chatgpt } from '@e2edev/oauth/chatgpt'")}.\n`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
return (await import(pathToFileURL(resolved).href)) as OAuthCli;
|
||||
}
|
||||
|
||||
/** Signs in to `provider`, or without one lets the user pick. */
|
||||
export async function login(cwd: string, provider: string | undefined, options: LoginOptions): Promise<number> {
|
||||
const cli = await loadOAuthCli(cwd);
|
||||
if (cli === undefined) return 1;
|
||||
return cli.runLogin(provider, {
|
||||
...(options.device === true ? { method: 'device' } : {}),
|
||||
...(options.clientId === undefined ? {} : { clientId: options.clientId }),
|
||||
...(options.fromGh === true ? { fromGitHubCli: true } : {}),
|
||||
...(options.enterpriseUrl === undefined ? {} : { enterpriseUrl: options.enterpriseUrl }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Forgets the login of `provider`, or without one lets the user pick among the stored ones. */
|
||||
export async function logout(cwd: string, provider: string | undefined): Promise<number> {
|
||||
const cli = await loadOAuthCli(cwd);
|
||||
if (cli === undefined) return 1;
|
||||
return cli.runLogout(provider);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { dependencyRange } from '../../src/cli/init/engines.ts';
|
||||
import { dependencyRange } from '../../src/cli/init/versions.ts';
|
||||
|
||||
// Use the built modules, just as config and test imports use the installed packages.
|
||||
const loaderModule = '../../dist/config/load.js';
|
||||
@@ -144,8 +144,8 @@ describe('initializing standalone projects', () => {
|
||||
const manifest = JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
||||
const playwrightVersion = (JSON.parse(readFileSync(path.resolve(PACKAGE_ROOT, '..', 'playwright', 'package.json'), 'utf8')) as { version: string }).version;
|
||||
expect(manifest.devDependencies['@e2edev/playwright']).toBe(dependencyRange(playwrightVersion));
|
||||
const recorded = JSON.parse(readFileSync(path.join(PACKAGE_ROOT, 'dist', 'cli', 'init', 'engine-versions.json'), 'utf8')) as Record<string, string>;
|
||||
expect(Object.keys(recorded).toSorted()).toEqual(['@e2edev/agent-device', '@e2edev/playwright', 'playwright']);
|
||||
const recorded = JSON.parse(readFileSync(path.join(PACKAGE_ROOT, 'dist', 'cli', 'init', 'sibling-versions.json'), 'utf8')) as Record<string, string>;
|
||||
expect(Object.keys(recorded).toSorted()).toEqual(['@e2edev/agent-device', '@e2edev/oauth', '@e2edev/playwright', 'playwright']);
|
||||
expect(manifest.devDependencies.playwright).toBe(`^${recorded.playwright}`);
|
||||
expect(manifest.devDependencies.ai).toBe('^7.0.0');
|
||||
expect(manifest.scripts).toEqual({ 'test:e2e': 'e2e run' });
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from 'node:path';
|
||||
import * as clack from '@clack/prompts';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { init } from '../../src/cli/init.ts';
|
||||
import { dependencyRange } from '../../src/cli/init/engines.ts';
|
||||
import { dependencyRange } from '../../src/cli/init/versions.ts';
|
||||
import { readSkillFiles } from '../../src/cli/skill.ts';
|
||||
|
||||
vi.mock('@clack/prompts', { spy: true });
|
||||
@@ -171,6 +171,9 @@ describe('e2e init', () => {
|
||||
expect.objectContaining({ value: 'vercel', label: 'Vercel AI Gateway' }),
|
||||
expect.objectContaining({ value: 'openrouter', label: 'OpenRouter' }),
|
||||
expect.objectContaining({ value: 'openai-compatible', label: 'OpenAI-compatible endpoint' }),
|
||||
expect.objectContaining({ value: 'chatgpt', label: 'ChatGPT Plus/Pro subscription' }),
|
||||
expect.objectContaining({ value: 'copilot', label: 'GitHub Copilot subscription' }),
|
||||
expect.objectContaining({ value: 'grok', label: 'SuperGrok subscription' }),
|
||||
expect.objectContaining({ value: 'none' }),
|
||||
],
|
||||
}));
|
||||
@@ -184,6 +187,26 @@ describe('e2e init', () => {
|
||||
expect(JSON.parse(read('package.json')).devDependencies).toHaveProperty('@ai-sdk/openai-compatible', '^3.0.0');
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ gateway: 'chatgpt', provider: 'openai', line: "import { chatgpt } from '@e2edev/oauth/chatgpt';", model: "model: chatgpt('gpt-5.5'),", sdk: '@ai-sdk/openai' },
|
||||
{ gateway: 'copilot', provider: 'github-copilot', line: "import { copilot } from '@e2edev/oauth/copilot';", model: "model: copilot('claude-sonnet-5'),", sdk: '@ai-sdk/openai-compatible' },
|
||||
{ gateway: 'grok', provider: 'spacexai', line: "import { grok } from '@e2edev/oauth/grok';", model: "model: grok('grok-4'),", sdk: '@ai-sdk/xai' },
|
||||
] as const)('writes a $gateway subscription model and names the sign-in as the next step', async ({ gateway, provider, line, model, sdk }) => {
|
||||
vi.mocked(clack.select).mockResolvedValueOnce('playwright').mockResolvedValueOnce(gateway);
|
||||
vi.mocked(clack.confirm).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
||||
|
||||
expect(await init(dir)).toBe(0);
|
||||
expect(clack.text).not.toHaveBeenCalled();
|
||||
expect(read('e2e.config.ts')).toContain(line);
|
||||
expect(read('e2e.config.ts')).toContain(model);
|
||||
expect(read('e2e.config.ts')).toContain(`sign in once with \`e2e login ${provider}\``);
|
||||
const devDependencies = JSON.parse(read('package.json')).devDependencies;
|
||||
expect(devDependencies).toHaveProperty('ai', '^7.0.0');
|
||||
expect(devDependencies).toHaveProperty('@e2edev/oauth');
|
||||
expect(devDependencies).toHaveProperty(sdk);
|
||||
expect(output()).toContain(`e2e login ${provider}, then`);
|
||||
});
|
||||
|
||||
it('validates the endpoint the way config resolution will', async () => {
|
||||
vi.mocked(clack.select).mockResolvedValueOnce('playwright').mockResolvedValueOnce('openai-compatible');
|
||||
vi.mocked(clack.confirm).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import Module from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { login, logout } from '../../src/cli/login.ts';
|
||||
|
||||
let dir: string;
|
||||
let stderr: string[];
|
||||
const nodePath = process.env['NODE_PATH'];
|
||||
|
||||
/** vitest puts the workspace's virtual store on NODE_PATH, which would let a bare temp project resolve @e2edev/oauth. */
|
||||
function setNodePath(value: string | undefined): void {
|
||||
if (value === undefined) delete process.env['NODE_PATH'];
|
||||
else process.env['NODE_PATH'] = value;
|
||||
(Module as unknown as Record<'_initPaths', () => void>)['_initPaths']();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setNodePath('');
|
||||
dir = mkdtempSync(path.join(os.tmpdir(), 'e2e-login-'));
|
||||
writeFileSync(path.join(dir, 'package.json'), '{"name":"proj","type":"module"}');
|
||||
stderr = [];
|
||||
vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => {
|
||||
stderr.push(String(chunk));
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setNodePath(nodePath);
|
||||
vi.restoreAllMocks();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** A stand-in `@e2edev/oauth` in the project's node_modules that records every call. */
|
||||
function installFakeOAuth(): string {
|
||||
const root = path.join(dir, 'node_modules', '@e2edev', 'oauth');
|
||||
mkdirSync(root, { recursive: true });
|
||||
const log = path.join(dir, 'calls.json');
|
||||
writeFileSync(path.join(root, 'package.json'), JSON.stringify({ name: '@e2edev/oauth', type: 'module', exports: { './cli': './cli.js' } }));
|
||||
writeFileSync(
|
||||
path.join(root, 'cli.js'),
|
||||
`import { writeFileSync } from 'node:fs';
|
||||
const record = (call) => { writeFileSync(${JSON.stringify(log)}, JSON.stringify(call)); return 0; };
|
||||
export const runLogin = async (provider, options) => record({ runLogin: [provider, options] });
|
||||
export const runLogout = async (provider) => record({ runLogout: [provider] });
|
||||
`,
|
||||
);
|
||||
return log;
|
||||
}
|
||||
|
||||
describe('e2e login / logout', () => {
|
||||
it('exits 1 with the install line when the project lacks @e2edev/oauth', async () => {
|
||||
expect(await login(dir, 'spacexai', {})).toBe(1);
|
||||
expect(stderr.join('')).toContain('npm i -D @e2edev/oauth');
|
||||
expect(await logout(dir, 'spacexai')).toBe(1);
|
||||
});
|
||||
|
||||
it('forwards the sign-in with typed options, leaves the pick to the package without a provider, and forgets one', async () => {
|
||||
const log = installFakeOAuth();
|
||||
const calls = () => JSON.parse(readFileSync(log, 'utf8'));
|
||||
expect(await login(dir, 'github-copilot', { device: true, clientId: 'Iv23', fromGh: true, enterpriseUrl: 'gh.acme.com' })).toBe(0);
|
||||
expect(calls()).toEqual({ runLogin: ['github-copilot', { method: 'device', clientId: 'Iv23', fromGitHubCli: true, enterpriseUrl: 'gh.acme.com' }] });
|
||||
expect(await login(dir, 'spacexai', {})).toBe(0);
|
||||
expect(calls()).toEqual({ runLogin: ['spacexai', {}] });
|
||||
expect(await login(dir, undefined, {})).toBe(0);
|
||||
expect(calls()).toEqual({ runLogin: [null, {}] });
|
||||
expect(await logout(dir, 'openai')).toBe(0);
|
||||
expect(calls()).toEqual({ runLogout: ['openai'] });
|
||||
expect(await logout(dir, undefined)).toBe(0);
|
||||
expect(calls()).toEqual({ runLogout: [null] });
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { dependencyRange, playwrightRange } from '../../src/cli/init/engines.ts';
|
||||
import { dependencyRange, playwrightRange } from '../../src/cli/init/versions.ts';
|
||||
|
||||
describe('dependencyRange', () => {
|
||||
it('asks for the minor of the engine version the build recorded', () => {
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 TesterArmy, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,26 @@
|
||||
# @e2edev/oauth
|
||||
|
||||
Sign in to a personal AI subscription once, then use it as a [Vercel AI SDK](https://ai-sdk.dev) model.
|
||||
|
||||
| Plan | Login | Model |
|
||||
| --- | --- | --- |
|
||||
| ChatGPT Plus/Pro (the Codex sign-in) | `npx e2e-oauth login openai` | `chatgpt('gpt-5.5')` from `@e2edev/oauth/chatgpt` |
|
||||
| GitHub Copilot | `npx e2e-oauth login github-copilot` | `copilot('claude-sonnet-5')` from `@e2edev/oauth/copilot` |
|
||||
| SuperGrok / X Premium+ | `npx e2e-oauth login spacexai` | `grok('grok-4')` from `@e2edev/oauth/grok` |
|
||||
|
||||
Each subpath needs its provider package: `@ai-sdk/openai`, `@ai-sdk/openai-compatible`, or `@ai-sdk/xai`.
|
||||
|
||||
```ts
|
||||
import { generateText } from 'ai';
|
||||
import { chatgpt } from '@e2edev/oauth/chatgpt';
|
||||
|
||||
const { text } = await generateText({ model: chatgpt('gpt-5.5'), prompt: 'Hello' });
|
||||
```
|
||||
|
||||
How it works: the login runs the vendor's OAuth flow (PKCE with a local callback, or an RFC 8628 device code) and stores the tokens in `~/.config/e2e/oauth.json` with mode 0600. The model is the vendor's own AI SDK provider constructed with a `fetch` that reads the stored login per request, refreshes it ahead of expiry (once, however many calls race), replaces the SDK's key header with the bearer token, and applies what the vendor needs beyond that: the Codex backend URL and body shape for ChatGPT, the initiator and vision headers for Copilot.
|
||||
|
||||
For your own product, `createOAuthFetch(provider, { store, userAgent })` is the `fetch` any provider factory accepts, `login(providerId, { callbacks })` runs a flow with your prompts, and `OAuthProvider` is the interface a new vendor implements. Set `userAgent` and `originator` to your product's name.
|
||||
|
||||
Claude Pro/Max is not included: Anthropic permits subscription sign-in only for its own applications.
|
||||
|
||||
Docs: https://docs.e2e.army/subscriptions
|
||||
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"name": "@e2edev/oauth",
|
||||
"version": "0.0.0",
|
||||
"description": "Sign in to a personal ChatGPT, GitHub Copilot, or SuperGrok subscription and use it as an AI SDK model",
|
||||
"keywords": [
|
||||
"e2e",
|
||||
"ai-sdk",
|
||||
"oauth",
|
||||
"chatgpt",
|
||||
"codex",
|
||||
"github-copilot",
|
||||
"grok",
|
||||
"subscription"
|
||||
],
|
||||
"license": "MIT",
|
||||
"contributors": [
|
||||
"Oskar Kwa\u015bniewski <oskar@tester.army>",
|
||||
"Szymon Rybczak <szymon@tester.army>"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tester-army/e2e.git",
|
||||
"directory": "packages/oauth"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/tester-army/e2e/issues"
|
||||
},
|
||||
"homepage": "https://github.com/tester-army/e2e/tree/main/packages/oauth#readme",
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "public",
|
||||
"provenance": false,
|
||||
"tag": "beta"
|
||||
},
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"e2e-oauth": "./dist/bin.js"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./chatgpt": {
|
||||
"types": "./dist/chatgpt.d.ts",
|
||||
"default": "./dist/chatgpt.js"
|
||||
},
|
||||
"./copilot": {
|
||||
"types": "./dist/copilot.d.ts",
|
||||
"default": "./dist/copilot.js"
|
||||
},
|
||||
"./grok": {
|
||||
"types": "./dist/grok.d.ts",
|
||||
"default": "./dist/grok.js"
|
||||
},
|
||||
"./cli": {
|
||||
"types": "./dist/cli.d.ts",
|
||||
"default": "./dist/cli.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc --project tsconfig.build.json && node ../../scripts/stamp-dist.ts",
|
||||
"prepublishOnly": "node ../../scripts/check-dist.ts",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:unit": "vitest run tests/unit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/provider": "4.0.17",
|
||||
"@clack/prompts": "1.8.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@ai-sdk/openai": "^4.0.0",
|
||||
"@ai-sdk/openai-compatible": "^3.0.0",
|
||||
"@ai-sdk/xai": "^5.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@ai-sdk/openai": {
|
||||
"optional": true
|
||||
},
|
||||
"@ai-sdk/openai-compatible": {
|
||||
"optional": true
|
||||
},
|
||||
"@ai-sdk/xai": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ai-sdk/openai": "4.0.69",
|
||||
"@ai-sdk/openai-compatible": "3.0.51",
|
||||
"@ai-sdk/xai": "5.0.2",
|
||||
"@types/node": "26.4.1",
|
||||
"ai": "7.0.105",
|
||||
"typescript": "7.0.2",
|
||||
"vitest": "5.0.0",
|
||||
"zod": "4.6.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env node
|
||||
import { runOAuthCli } from './cli.ts';
|
||||
|
||||
process.exitCode = await runOAuthCli(process.argv.slice(2));
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* The one-shot local HTTP server a browser login redirects back to. It
|
||||
* accepts exactly one answer for the expected state, a code or the vendor's
|
||||
* refusal, replies to the browser with a page, and hands the answer to the
|
||||
* flow. When the port is taken the flow falls back to the user pasting the
|
||||
* code, so a failure to listen is reported, not thrown.
|
||||
*/
|
||||
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { OAuthError } from './errors.ts';
|
||||
|
||||
export interface CallbackServerOptions {
|
||||
readonly port: number;
|
||||
readonly path: string;
|
||||
readonly state: string;
|
||||
readonly productName: string;
|
||||
}
|
||||
|
||||
export type CallbackAnswer = { readonly code: string } | { readonly error: string };
|
||||
|
||||
export interface CallbackServer {
|
||||
readonly redirectUri: string;
|
||||
/** The browser's answer; rejects with CANCELLED on the signal and TIMEOUT after `timeoutMs`. */
|
||||
waitForAnswer(signal: AbortSignal | undefined, timeoutMs: number): Promise<CallbackAnswer>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export async function startCallbackServer(options: CallbackServerOptions): Promise<CallbackServer | undefined> {
|
||||
const host = '127.0.0.1';
|
||||
let settle: ((answer: CallbackAnswer) => void) | undefined;
|
||||
const answered = new Promise<CallbackAnswer>((resolve) => {
|
||||
settle = (answer) => {
|
||||
resolve(answer);
|
||||
settle = undefined;
|
||||
};
|
||||
});
|
||||
|
||||
const server: Server = createServer((request, response) => {
|
||||
const url = new URL(request.url ?? '/', `http://${host}:${options.port}`);
|
||||
const reply = (status: number, heading: string, message: string): void => {
|
||||
response.writeHead(status, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
|
||||
response.end(renderPage(options.productName, heading, message));
|
||||
};
|
||||
if (url.pathname !== options.path) return reply(404, 'Not found', 'This address is not part of the login.');
|
||||
// The state binds the answer to this attempt; anything else on the port is ignored.
|
||||
if (url.searchParams.get('state') !== options.state) return reply(400, 'Login failed', 'The state does not match this login attempt.');
|
||||
const error = url.searchParams.get('error');
|
||||
if (error !== null) {
|
||||
reply(400, 'Login failed', url.searchParams.get('error_description') ?? error);
|
||||
settle?.({ error });
|
||||
return;
|
||||
}
|
||||
const code = url.searchParams.get('code');
|
||||
if (code === null || code === '') {
|
||||
reply(400, 'Login failed', 'The redirect carried no authorization code.');
|
||||
settle?.({ error: 'invalid_callback' });
|
||||
return;
|
||||
}
|
||||
reply(200, 'Signed in', 'You can close this window and return to the terminal.');
|
||||
settle?.({ code });
|
||||
});
|
||||
|
||||
const listening = await new Promise<boolean>((resolve) => {
|
||||
server.once('error', () => resolve(false));
|
||||
server.listen(options.port, host, () => resolve(true));
|
||||
});
|
||||
if (!listening) return undefined;
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
return {
|
||||
// Vendors register `localhost`, not the loopback address, as the redirect host.
|
||||
redirectUri: `http://localhost:${port}${options.path}`,
|
||||
waitForAnswer: (signal, timeoutMs) =>
|
||||
new Promise<CallbackAnswer>((resolve, reject) => {
|
||||
const cancelled = () => new OAuthError('CANCELLED', 'the login was cancelled');
|
||||
if (signal?.aborted) return reject(cancelled());
|
||||
const timer = setTimeout(() => reject(new OAuthError('TIMEOUT', 'the browser did not return in time')), timeoutMs);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(cancelled());
|
||||
};
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
void answered.finally(() => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
});
|
||||
answered.then(resolve, reject);
|
||||
}),
|
||||
close: () => {
|
||||
server.close();
|
||||
server.closeAllConnections();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
function renderPage(productName: string, heading: string, message: string): string {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>${escapeHtml(productName)}: ${escapeHtml(heading)}</title>
|
||||
<style>
|
||||
html { color-scheme: light dark; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: ui-sans-serif, system-ui, sans-serif; }
|
||||
main { max-width: 32rem; padding: 2rem; text-align: center; }
|
||||
h1 { font-size: 1.5rem; margin: 0 0 0.5rem; }
|
||||
p { margin: 0; opacity: 0.75; }
|
||||
</style>
|
||||
</head>
|
||||
<body><main><h1>${escapeHtml(heading)}</h1><p>${escapeHtml(message)}</p></main></body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* `chatgpt('gpt-5.5')`: a ChatGPT Plus/Pro subscription as an AI SDK model.
|
||||
* The instance is `@ai-sdk/openai`'s Responses model with a fetch that
|
||||
* carries the stored login; nothing is read until the first call.
|
||||
*/
|
||||
|
||||
import { createOpenAI } from '@ai-sdk/openai';
|
||||
import type { LanguageModelV4 } from '@ai-sdk/provider';
|
||||
import { createOAuthFetch } from './fetch.ts';
|
||||
import { USER_AGENT, loginHint } from './providers.ts';
|
||||
import { createCodexProvider, type CodexProviderOptions } from './providers/openai.ts';
|
||||
import { defaultCredentialStore } from './store.ts';
|
||||
import type { CredentialStore } from './types.ts';
|
||||
|
||||
export interface ChatGptOptions extends Pick<CodexProviderOptions, 'originator' | 'apiUrl'> {
|
||||
readonly store?: CredentialStore;
|
||||
readonly userAgent?: string;
|
||||
}
|
||||
|
||||
/** Models the Codex backend serves to subscription logins, as of September 2026. */
|
||||
export const CHATGPT_MODELS = ['gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.3-codex-spark'] as const;
|
||||
|
||||
export function chatgpt(modelId: string, options: ChatGptOptions = {}): LanguageModelV4 {
|
||||
const fetch = createOAuthFetch(createCodexProvider(options), {
|
||||
store: options.store ?? defaultCredentialStore(),
|
||||
userAgent: options.userAgent ?? USER_AGENT,
|
||||
loginHint: loginHint('openai'),
|
||||
});
|
||||
// The key header is removed per request; the value only satisfies the constructor.
|
||||
return createOpenAI({ apiKey: 'oauth', fetch, name: 'chatgpt' }).responses(modelId);
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* The terminal side of a login. `runLogin`, `runLogout`, and `runStatus` are
|
||||
* what the e2e CLI calls; `runOAuthCli` parses argv for the package's own
|
||||
* `e2e-oauth` bin and dispatches to them.
|
||||
*/
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { parseArgs } from 'node:util';
|
||||
import * as clack from '@clack/prompts';
|
||||
import { OAuthError } from './errors.ts';
|
||||
import { login, logout } from './login.ts';
|
||||
import { PROVIDER_IDS, getProvider, isProviderId, type LoginOptionsById, type ProviderId } from './providers.ts';
|
||||
import { defaultCredentialStore } from './store.ts';
|
||||
import type { OAuthLoginCallbacks } from './types.ts';
|
||||
|
||||
export interface CliIo {
|
||||
readonly stdout: NodeJS.WritableStream;
|
||||
readonly stderr: NodeJS.WritableStream;
|
||||
readonly isTTY: boolean;
|
||||
/** Opens a URL in the user's browser; the default spawns the platform opener. */
|
||||
readonly openUrl?: (url: string) => void;
|
||||
}
|
||||
|
||||
/** The flags every login takes, as the e2e CLI and the bin hand them over. */
|
||||
export interface LoginFlags {
|
||||
readonly method?: 'device';
|
||||
readonly clientId?: string;
|
||||
readonly fromGitHubCli?: boolean;
|
||||
readonly enterpriseUrl?: string;
|
||||
}
|
||||
|
||||
const USAGE = `Usage:
|
||||
e2e-oauth login [provider] [--device] [--client-id <id>] [--from-gh] [--enterprise-url <host>]
|
||||
e2e-oauth logout [provider]
|
||||
e2e-oauth status
|
||||
|
||||
Without a provider, login and logout show a picker.
|
||||
|
||||
Providers: ${PROVIDER_IDS.join(', ')}
|
||||
openai ChatGPT Plus/Pro (the Codex sign-in); --device for a machine without a browser
|
||||
github-copilot GitHub Copilot: the GitHub CLI's token when gh is signed in, or a device flow with --client-id
|
||||
spacexai SuperGrok / X Premium+ (device code)
|
||||
`;
|
||||
|
||||
/** Signs in to `providerId`; without one, a picker over the providers, marking those already signed in. */
|
||||
export async function runLogin(providerId: string | undefined, flags: LoginFlags, io: CliIo = defaultIo()): Promise<number> {
|
||||
return report(io, async () => {
|
||||
const id = providerId === undefined || providerId === '' ? await pickProvider(io, 'Which subscription do you want to sign in to?', await signedIn()) : requireProvider(providerId);
|
||||
const provider = getProvider(id);
|
||||
const controller = new AbortController();
|
||||
const onSigint = () => controller.abort();
|
||||
process.once('SIGINT', onSigint);
|
||||
const ui = terminalCallbacks(provider.name, io, controller.signal);
|
||||
try {
|
||||
const credentials = await login(id, { callbacks: ui.callbacks, options: toLoginOptions(id, flags) });
|
||||
ui.done(`${provider.name} login stored${credentials.expires === 0 ? '' : '; the token refreshes itself'}.`);
|
||||
} catch (cause) {
|
||||
ui.failed();
|
||||
throw cause;
|
||||
} finally {
|
||||
process.removeListener('SIGINT', onSigint);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Forgets the login of `providerId`; without one, a picker over the stored logins. */
|
||||
export async function runLogout(providerId: string | undefined, io: CliIo = defaultIo()): Promise<number> {
|
||||
return report(io, async () => {
|
||||
let id: ProviderId;
|
||||
if (providerId === undefined || providerId === '') {
|
||||
const stored = await signedIn();
|
||||
if (stored.size === 0) {
|
||||
io.stdout.write('No logins stored.\n');
|
||||
return;
|
||||
}
|
||||
id = await pickProvider(io, 'Which login do you want to forget?', stored, [...stored.keys()]);
|
||||
} else {
|
||||
id = requireProvider(providerId);
|
||||
}
|
||||
const had = await logout(id);
|
||||
say(io, had ? 'success' : 'info', had ? `Signed out of ${getProvider(id).name}.` : `No ${getProvider(id).name} login was stored.`);
|
||||
});
|
||||
}
|
||||
|
||||
/** The providers with a stored login, and how each one stands. */
|
||||
async function signedIn(): Promise<Map<ProviderId, string>> {
|
||||
const store = defaultCredentialStore();
|
||||
const out = new Map<ProviderId, string>();
|
||||
for (const id of await store.list()) {
|
||||
if (!isProviderId(id)) continue;
|
||||
out.set(id, describeExpiry((await store.get(id))?.expires));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const PROVIDER_HINTS: Record<ProviderId, string> = {
|
||||
openai: 'ChatGPT Plus/Pro, the Codex sign-in',
|
||||
'github-copilot': 'GitHub Copilot: OpenAI, Anthropic, Google, and SpaceXAI models',
|
||||
spacexai: 'SuperGrok or X Premium+',
|
||||
};
|
||||
|
||||
/** A terminal picker over providers; without a terminal the provider has to be named. */
|
||||
async function pickProvider(io: CliIo, message: string, stored: Map<ProviderId, string>, ids: readonly ProviderId[] = PROVIDER_IDS): Promise<ProviderId> {
|
||||
if (!io.isTTY) throw new OAuthError('MISCONFIGURED', `name a provider: ${ids.join(', ')}`);
|
||||
const choice = await clack.select<ProviderId>({
|
||||
message,
|
||||
options: ids.map((id) => ({ value: id, label: getProvider(id).name, hint: stored.has(id) ? `${stored.get(id)}; ${PROVIDER_HINTS[id]}` : PROVIDER_HINTS[id] })),
|
||||
});
|
||||
if (clack.isCancel(choice)) throw new OAuthError('CANCELLED', 'the login was cancelled');
|
||||
return choice as ProviderId;
|
||||
}
|
||||
|
||||
/** Every provider and how it stands: signed in with its token state, or how to sign in. */
|
||||
export async function runStatus(io: CliIo = defaultIo()): Promise<number> {
|
||||
return report(io, async () => {
|
||||
const stored = await signedIn();
|
||||
if (!io.isTTY) {
|
||||
for (const id of PROVIDER_IDS) io.stdout.write(`${id.padEnd(16)} ${getProvider(id).name.padEnd(16)} ${stored.get(id) ?? `not signed in; e2e login ${id}`}\n`);
|
||||
return;
|
||||
}
|
||||
clack.intro('Subscriptions');
|
||||
for (const id of PROVIDER_IDS) {
|
||||
const state = stored.get(id);
|
||||
const line = `${getProvider(id).name} (${id}): ${state ?? 'not signed in'}`;
|
||||
if (state === undefined) clack.log.info(line);
|
||||
else clack.log.success(line);
|
||||
}
|
||||
const missing = PROVIDER_IDS.filter((id) => !stored.has(id));
|
||||
clack.outro(missing.length === 0 ? 'Every subscription is signed in.' : `Sign in with ${missing.map((id) => `e2e login ${id}`).join(' or ')}.`);
|
||||
});
|
||||
}
|
||||
|
||||
/** One line to the user, styled when there is a terminal. */
|
||||
function say(io: CliIo, kind: 'success' | 'info' | 'error', message: string): void {
|
||||
if (!io.isTTY) {
|
||||
(kind === 'error' ? io.stderr : io.stdout).write(`${message}\n`);
|
||||
return;
|
||||
}
|
||||
clack.log[kind](message);
|
||||
}
|
||||
|
||||
/** The `e2e-oauth` bin: argv in, exit code out. */
|
||||
export async function runOAuthCli(argv: readonly string[], io: CliIo = defaultIo()): Promise<number> {
|
||||
return report(io, async () => {
|
||||
const { values, positionals } = parseArgs({
|
||||
args: [...argv],
|
||||
allowPositionals: true,
|
||||
options: {
|
||||
device: { type: 'boolean' },
|
||||
'client-id': { type: 'string' },
|
||||
'from-gh': { type: 'boolean' },
|
||||
'enterprise-url': { type: 'string' },
|
||||
help: { type: 'boolean', short: 'h' },
|
||||
},
|
||||
});
|
||||
const [command, providerId, ...extra] = positionals;
|
||||
if (values.help === true || command === undefined) {
|
||||
io.stdout.write(USAGE);
|
||||
return command === undefined ? 1 : 0;
|
||||
}
|
||||
if (extra.length > 0) throw new OAuthError('MISCONFIGURED', `unexpected argument ${extra[0]}.\n${USAGE}`);
|
||||
switch (command) {
|
||||
case 'login':
|
||||
return runLogin(
|
||||
providerId,
|
||||
{
|
||||
...(values.device === true ? { method: 'device' as const } : {}),
|
||||
...(values['client-id'] === undefined ? {} : { clientId: values['client-id'] }),
|
||||
...(values['from-gh'] === true ? { fromGitHubCli: true } : {}),
|
||||
...(values['enterprise-url'] === undefined ? {} : { enterpriseUrl: values['enterprise-url'] }),
|
||||
},
|
||||
io,
|
||||
);
|
||||
case 'logout':
|
||||
return runLogout(providerId, io);
|
||||
case 'status':
|
||||
return runStatus(io);
|
||||
default:
|
||||
throw new OAuthError('MISCONFIGURED', `Unknown command ${command}.\n${USAGE}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs a command, printing a failure as one line; cancellation exits like an interrupt. */
|
||||
async function report(io: CliIo, run: () => Promise<number | undefined>): Promise<number> {
|
||||
try {
|
||||
return (await run()) ?? 0;
|
||||
} catch (cause) {
|
||||
const message = cause instanceof Error ? cause.message : String(cause);
|
||||
if (cause instanceof OAuthError && cause.code === 'CANCELLED') {
|
||||
if (io.isTTY) clack.cancel(message);
|
||||
else io.stderr.write(`${message}\n`);
|
||||
return 130;
|
||||
}
|
||||
say(io, 'error', message);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
function requireProvider(id: string): ProviderId {
|
||||
if (!isProviderId(id)) throw new OAuthError('MISCONFIGURED', `name a provider: ${PROVIDER_IDS.join(', ')}`);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The provider's own login options from the shared flags; flags meant for another provider are ignored. */
|
||||
function toLoginOptions<Id extends ProviderId>(id: Id, flags: LoginFlags): LoginOptionsById[Id] {
|
||||
switch (id) {
|
||||
case 'openai':
|
||||
return (flags.method === undefined ? {} : { method: flags.method }) as LoginOptionsById[Id];
|
||||
case 'github-copilot':
|
||||
return {
|
||||
...(flags.clientId === undefined ? {} : { clientId: flags.clientId }),
|
||||
...(flags.fromGitHubCli === true ? { fromGitHubCli: true } : {}),
|
||||
...(flags.enterpriseUrl === undefined ? {} : { enterpriseUrl: flags.enterpriseUrl }),
|
||||
} as LoginOptionsById[Id];
|
||||
default:
|
||||
return {} as LoginOptionsById[Id];
|
||||
}
|
||||
}
|
||||
|
||||
function describeExpiry(expires: number | undefined): string {
|
||||
if (expires === undefined) return 'not signed in';
|
||||
if (expires === 0) return 'signed in';
|
||||
return expires <= Date.now() ? 'signed in, token expired (refreshes on the next call)' : `signed in, token valid until ${new Date(expires).toLocaleString()}`;
|
||||
}
|
||||
|
||||
/** Clack prompts around a login flow; plain lines when there is no terminal. */
|
||||
function terminalCallbacks(providerName: string, io: CliIo, signal: AbortSignal) {
|
||||
const spinner = io.isTTY ? clack.spinner() : undefined;
|
||||
if (io.isTTY) clack.intro(`Sign in to ${providerName}`);
|
||||
else io.stdout.write(`Sign in to ${providerName}\n`);
|
||||
const callbacks: OAuthLoginCallbacks = {
|
||||
signal,
|
||||
onAuth(info) {
|
||||
if (io.isTTY) {
|
||||
clack.note(info.userCode === undefined ? info.url : `${info.url}\n\nCode: ${info.userCode}`, info.userCode === undefined ? 'Open this page' : 'Open this page and enter the code');
|
||||
} else {
|
||||
io.stdout.write(`${info.url}\n${info.userCode === undefined ? '' : `Code: ${info.userCode}\n`}`);
|
||||
}
|
||||
io.stdout.write(`${info.instructions}\n`);
|
||||
(io.openUrl ?? openInBrowser)(info.url);
|
||||
spinner?.start('Waiting for the sign-in to finish');
|
||||
},
|
||||
onProgress(message) {
|
||||
if (spinner === undefined) io.stdout.write(`${message}\n`);
|
||||
else spinner.message(message);
|
||||
},
|
||||
async onPrompt(prompt) {
|
||||
spinner?.stop('Waiting for your input');
|
||||
if (!io.isTTY) throw new OAuthError('FLOW_FAILED', `${prompt.message}: this terminal is not interactive, so nothing can be pasted; use --device or run from a terminal`);
|
||||
const answer = await clack.text({ message: prompt.message, ...(prompt.placeholder === undefined ? {} : { placeholder: prompt.placeholder }) });
|
||||
if (clack.isCancel(answer)) throw new OAuthError('CANCELLED', 'the login was cancelled');
|
||||
spinner?.start('Finishing the sign-in');
|
||||
return answer as string;
|
||||
},
|
||||
};
|
||||
return {
|
||||
callbacks,
|
||||
done(message: string) {
|
||||
spinner?.stop('Signed in');
|
||||
if (io.isTTY) clack.outro(message);
|
||||
else io.stdout.write(`${message}\n`);
|
||||
},
|
||||
failed() {
|
||||
spinner?.stop('Sign-in failed');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function defaultIo(): CliIo {
|
||||
return { stdout: process.stdout, stderr: process.stderr, isTTY: process.stdout.isTTY === true && process.stdin.isTTY === true };
|
||||
}
|
||||
|
||||
/** Best effort: the URL is printed regardless, so a failure to open a browser is not an error. */
|
||||
function openInBrowser(url: string): void {
|
||||
const [command, args] =
|
||||
process.platform === 'darwin'
|
||||
? ['open', [url]]
|
||||
: process.platform === 'win32'
|
||||
? ['cmd', ['/c', 'start', '', url.replaceAll('&', '^&')]]
|
||||
: ['xdg-open', [url]];
|
||||
try {
|
||||
const child = spawn(command, args, { stdio: 'ignore', detached: true });
|
||||
child.on('error', () => {});
|
||||
child.unref();
|
||||
} catch {
|
||||
// The printed URL is the fallback.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* `copilot('claude-sonnet-5')`: a GitHub Copilot subscription as an AI SDK
|
||||
* model. Copilot serves OpenAI, Anthropic, Google, and SpaceXAI models over the
|
||||
* OpenAI chat protocol; the instance is `@ai-sdk/openai-compatible`'s chat
|
||||
* model at the Copilot API with a fetch that carries the stored login. An
|
||||
* enterprise login stored by `e2e login` routes to its own host.
|
||||
*/
|
||||
|
||||
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
||||
import type { LanguageModelV4 } from '@ai-sdk/provider';
|
||||
import { createOAuthFetch } from './fetch.ts';
|
||||
import { USER_AGENT, loginHint } from './providers.ts';
|
||||
import { COPILOT_API_URL, createCopilotProvider } from './providers/github-copilot.ts';
|
||||
import { defaultCredentialStore } from './store.ts';
|
||||
import type { CredentialStore } from './types.ts';
|
||||
|
||||
export interface CopilotOptions {
|
||||
readonly store?: CredentialStore;
|
||||
readonly userAgent?: string;
|
||||
/** Where the Copilot API is reached, for a proxy in front of it. */
|
||||
readonly baseURL?: string;
|
||||
}
|
||||
|
||||
export function copilot(modelId: string, options: CopilotOptions = {}): LanguageModelV4 {
|
||||
const fetch = createOAuthFetch(createCopilotProvider(), {
|
||||
store: options.store ?? defaultCredentialStore(),
|
||||
userAgent: options.userAgent ?? USER_AGENT,
|
||||
loginHint: loginHint('github-copilot'),
|
||||
});
|
||||
return createOpenAICompatible({
|
||||
name: 'github-copilot',
|
||||
baseURL: options.baseURL ?? COPILOT_API_URL,
|
||||
apiKey: 'oauth',
|
||||
fetch,
|
||||
includeUsage: true,
|
||||
}).chatModel(modelId);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* RFC 8628 device authorization: the server hands out a user code, the user
|
||||
* enters it on any device, and the client polls the token endpoint until the
|
||||
* grant lands. `runDeviceFlow` owns the timing for any vendor's shape;
|
||||
* `rfc8628Flow` is the standard shape itself, which GitHub and SpaceXAI both
|
||||
* speak apart from the status code they answer "pending" with.
|
||||
*/
|
||||
|
||||
import { OAuthError, describeResponse } from './errors.ts';
|
||||
import { positiveSeconds, postForm, type TokenResponse } from './token-endpoint.ts';
|
||||
import type { OAuthLoginCallbacks } from './types.ts';
|
||||
|
||||
export interface DeviceAuthorization {
|
||||
readonly deviceCode: string;
|
||||
readonly userCode: string;
|
||||
readonly verificationUri: string;
|
||||
readonly verificationUriComplete?: string;
|
||||
/** Seconds until the code expires. */
|
||||
readonly expiresIn: number;
|
||||
/** Seconds between polls. */
|
||||
readonly interval: number;
|
||||
}
|
||||
|
||||
export type DevicePoll<T> =
|
||||
| { readonly status: 'granted'; readonly value: T }
|
||||
| { readonly status: 'pending' }
|
||||
/** RFC 8628 §3.5: add five seconds to the interval, or take the interval the server named. */
|
||||
| { readonly status: 'slow_down'; readonly intervalSeconds?: number }
|
||||
| { readonly status: 'denied' }
|
||||
| { readonly status: 'expired' };
|
||||
|
||||
export interface DeviceFlowOptions<T> {
|
||||
start(): Promise<DeviceAuthorization>;
|
||||
poll(authorization: DeviceAuthorization, signal: AbortSignal | undefined): Promise<DevicePoll<T>>;
|
||||
instructions?(authorization: DeviceAuthorization): string;
|
||||
readonly callbacks: OAuthLoginCallbacks;
|
||||
/** Test seam. */
|
||||
readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
||||
readonly now?: () => number;
|
||||
}
|
||||
|
||||
const DEFAULT_INTERVAL_S = 5;
|
||||
const MIN_INTERVAL_MS = 1_000;
|
||||
const SLOW_DOWN_INCREMENT_MS = 5_000;
|
||||
const DEFAULT_EXPIRES_S = 15 * 60;
|
||||
|
||||
export async function runDeviceFlow<T>(options: DeviceFlowOptions<T>): Promise<T> {
|
||||
const sleep = options.sleep ?? abortableSleep;
|
||||
const now = options.now ?? Date.now;
|
||||
const { callbacks } = options;
|
||||
const authorization = await options.start();
|
||||
callbacks.onAuth({
|
||||
url: authorization.verificationUriComplete ?? authorization.verificationUri,
|
||||
userCode: authorization.userCode,
|
||||
instructions:
|
||||
options.instructions?.(authorization) ??
|
||||
`Open ${authorization.verificationUri} on any device and enter the code ${authorization.userCode}.`,
|
||||
});
|
||||
|
||||
const deadline = now() + positiveSeconds(authorization.expiresIn, DEFAULT_EXPIRES_S) * 1000;
|
||||
let intervalMs = Math.max(positiveSeconds(authorization.interval, DEFAULT_INTERVAL_S) * 1000, MIN_INTERVAL_MS);
|
||||
while (now() < deadline) {
|
||||
await sleep(Math.min(intervalMs, Math.max(0, deadline - now())), callbacks.signal);
|
||||
const result = await options.poll(authorization, callbacks.signal);
|
||||
// A grant that lands after the user cancelled is not a login.
|
||||
if (callbacks.signal?.aborted) throw new OAuthError('CANCELLED', 'the login was cancelled');
|
||||
switch (result.status) {
|
||||
case 'granted':
|
||||
return result.value;
|
||||
case 'pending':
|
||||
continue;
|
||||
case 'slow_down':
|
||||
intervalMs =
|
||||
result.intervalSeconds !== undefined && result.intervalSeconds > 0
|
||||
? result.intervalSeconds * 1000
|
||||
: intervalMs + SLOW_DOWN_INCREMENT_MS;
|
||||
continue;
|
||||
case 'denied':
|
||||
throw new OAuthError('CANCELLED', 'the authorization was denied');
|
||||
case 'expired':
|
||||
throw new OAuthError('TIMEOUT', 'the device code expired before the login finished; run the login again');
|
||||
}
|
||||
}
|
||||
throw new OAuthError('TIMEOUT', 'the device code expired before the login finished; run the login again');
|
||||
}
|
||||
|
||||
export interface Rfc8628Options {
|
||||
readonly vendor: string;
|
||||
readonly deviceCodeUrl: string;
|
||||
readonly tokenUrl: string;
|
||||
readonly clientId: string;
|
||||
/** The device request's body besides `client_id`: scope, and whatever the vendor adds. */
|
||||
readonly request: Record<string, string>;
|
||||
readonly callbacks: OAuthLoginCallbacks;
|
||||
}
|
||||
|
||||
/** The standard device flow; the poll reads the body before the status, since vendors disagree on the status for "pending". */
|
||||
export function rfc8628Flow(options: Rfc8628Options): Promise<TokenResponse> {
|
||||
const { vendor, clientId, callbacks } = options;
|
||||
return runDeviceFlow<TokenResponse>({
|
||||
callbacks,
|
||||
async start() {
|
||||
const response = await postForm(options.deviceCodeUrl, { client_id: clientId, ...options.request });
|
||||
if (!response.ok) throw new OAuthError('FLOW_FAILED', `${vendor} device login could not start: ${await describeResponse(response)}`);
|
||||
const json = (await response.json()) as Record<string, unknown>;
|
||||
const { device_code, user_code, verification_uri, verification_uri_complete } = json;
|
||||
if (typeof device_code !== 'string' || typeof user_code !== 'string' || typeof verification_uri !== 'string') {
|
||||
throw new OAuthError('FLOW_FAILED', `the ${vendor} device code response is missing fields`);
|
||||
}
|
||||
return {
|
||||
deviceCode: device_code,
|
||||
userCode: user_code,
|
||||
verificationUri: verification_uri,
|
||||
...(typeof verification_uri_complete === 'string' ? { verificationUriComplete: verification_uri_complete } : {}),
|
||||
expiresIn: Number(json['expires_in']),
|
||||
interval: Number(json['interval']),
|
||||
};
|
||||
},
|
||||
async poll(authorization, signal) {
|
||||
const response = await postForm(
|
||||
options.tokenUrl,
|
||||
{ grant_type: 'urn:ietf:params:oauth:grant-type:device_code', client_id: clientId, device_code: authorization.deviceCode },
|
||||
signal,
|
||||
);
|
||||
const json = (await response.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
if (typeof json['access_token'] === 'string' && json['access_token'] !== '') return { status: 'granted', value: json as unknown as TokenResponse };
|
||||
switch (json['error']) {
|
||||
case 'authorization_pending':
|
||||
return { status: 'pending' };
|
||||
case 'slow_down':
|
||||
return typeof json['interval'] === 'number' ? { status: 'slow_down', intervalSeconds: json['interval'] } : { status: 'slow_down' };
|
||||
case 'access_denied':
|
||||
case 'authorization_denied':
|
||||
return { status: 'denied' };
|
||||
case 'expired_token':
|
||||
return { status: 'expired' };
|
||||
default:
|
||||
throw new OAuthError('FLOW_FAILED', `${vendor} device login failed: ${String(json['error_description'] ?? json['error'] ?? response.status)}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) {
|
||||
reject(new OAuthError('CANCELLED', 'the login was cancelled'));
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
function onAbort(): void {
|
||||
clearTimeout(timer);
|
||||
reject(new OAuthError('CANCELLED', 'the login was cancelled'));
|
||||
}
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
export type OAuthErrorCode =
|
||||
/** No stored credentials for the provider. */
|
||||
| 'NOT_LOGGED_IN'
|
||||
/** The refresh token was rejected; the user signs in again. */
|
||||
| 'LOGIN_REQUIRED'
|
||||
/** The authorization server or the vendor API answered with an error during a flow. */
|
||||
| 'FLOW_FAILED'
|
||||
/** The user or the caller cancelled the flow. */
|
||||
| 'CANCELLED'
|
||||
/** The flow ran out of time waiting for the user. */
|
||||
| 'TIMEOUT'
|
||||
/** The flow needs an option the caller did not give (a client id, a CLI). */
|
||||
| 'MISCONFIGURED';
|
||||
|
||||
export class OAuthError extends Error {
|
||||
override readonly name = 'OAuthError';
|
||||
constructor(
|
||||
readonly code: OAuthErrorCode,
|
||||
message: string,
|
||||
options?: { cause?: unknown },
|
||||
) {
|
||||
super(message, options);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads an error body for a message without assuming JSON. */
|
||||
export async function describeResponse(response: Response): Promise<string> {
|
||||
const text = await response.text().catch(() => '');
|
||||
if (text === '') return `${response.status} ${response.statusText}`.trim();
|
||||
try {
|
||||
const json = JSON.parse(text) as { error?: unknown; error_description?: unknown; message?: unknown };
|
||||
const error = json.error;
|
||||
const detail =
|
||||
typeof json.error_description === 'string'
|
||||
? json.error_description
|
||||
: typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string'
|
||||
? error.message
|
||||
: typeof json.message === 'string'
|
||||
? json.message
|
||||
: typeof error === 'string'
|
||||
? error
|
||||
: undefined;
|
||||
return detail === undefined ? `${response.status}: ${text.slice(0, 200)}` : `${response.status}: ${detail}`;
|
||||
} catch {
|
||||
return `${response.status}: ${text.slice(0, 200)}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* The fetch an AI SDK provider is constructed with. Per request it reads the
|
||||
* stored credentials, refreshes them ahead of expiry, replaces the SDK's key
|
||||
* header with the bearer token, and hands the request to the provider; on a
|
||||
* 401 it refreshes once and retries. One refresh serves every model instance
|
||||
* and every concurrent call over the same credentials, because vendors that
|
||||
* rotate refresh tokens reject the second concurrent refresh.
|
||||
*/
|
||||
|
||||
import { OAuthError } from './errors.ts';
|
||||
import type { CredentialStore, FetchFunction, OAuthCredentials, OAuthProvider } from './types.ts';
|
||||
|
||||
export interface OAuthFetchOptions {
|
||||
readonly store: CredentialStore;
|
||||
/** The `User-Agent` sent to the vendor; name your product, never another client. */
|
||||
readonly userAgent: string;
|
||||
readonly fetch?: FetchFunction;
|
||||
/** How a missing login is described; the CLI names its own command. */
|
||||
readonly loginHint?: string;
|
||||
}
|
||||
|
||||
/** Refresh this long before `expires`, so a call never starts on a token about to lapse. */
|
||||
const REFRESH_SKEW_MS = 120_000;
|
||||
/** After a rejected refresh token, how long to wait for another process to store the rotated one. */
|
||||
const ROTATION_WAIT_MS = 500;
|
||||
const ROTATION_ATTEMPTS = 4;
|
||||
|
||||
/**
|
||||
* Per credentials source: the refresh in flight, and credentials renewed for
|
||||
* this process when the source could not keep them (the environment store).
|
||||
* Stores over the same file share one entry, so separate model instances
|
||||
* never race each other's refresh.
|
||||
*/
|
||||
interface SharedState {
|
||||
readonly refreshing: Map<string, Promise<OAuthCredentials>>;
|
||||
readonly renewed: Map<string, OAuthCredentials>;
|
||||
}
|
||||
const byObject = new WeakMap<CredentialStore, SharedState>();
|
||||
const byPath = new Map<string, SharedState>();
|
||||
|
||||
function sharedState(store: CredentialStore): SharedState {
|
||||
const path = (store as { readonly path?: unknown }).path;
|
||||
const map: { get(key: never): SharedState | undefined; set(key: never, value: SharedState): unknown } = typeof path === 'string' ? byPath : byObject;
|
||||
const key = (typeof path === 'string' ? path : store) as never;
|
||||
let state = map.get(key);
|
||||
if (state === undefined) map.set(key, (state = { refreshing: new Map(), renewed: new Map() }));
|
||||
return state;
|
||||
}
|
||||
|
||||
export function createOAuthFetch<Credentials extends OAuthCredentials>(
|
||||
provider: OAuthProvider<Credentials, never>,
|
||||
options: OAuthFetchOptions,
|
||||
): FetchFunction {
|
||||
const upstream = options.fetch ?? globalThis.fetch;
|
||||
const { store } = options;
|
||||
const shared = sharedState(store);
|
||||
|
||||
async function current(): Promise<Credentials> {
|
||||
const stored = await store.get(provider.id);
|
||||
if (stored === undefined) {
|
||||
throw new OAuthError(
|
||||
'NOT_LOGGED_IN',
|
||||
`no ${provider.name} login is stored${options.loginHint === undefined ? '' : `; ${options.loginHint}`}`,
|
||||
);
|
||||
}
|
||||
// What this process renewed wins over a source that could not keep it; the store holds this provider's own shape.
|
||||
return (shared.renewed.get(provider.id) ?? stored) as Credentials;
|
||||
}
|
||||
|
||||
async function persist(renewed: Credentials): Promise<void> {
|
||||
try {
|
||||
await store.set(provider.id, renewed);
|
||||
shared.renewed.delete(provider.id);
|
||||
} catch (cause) {
|
||||
if (!(cause instanceof OAuthError && cause.code === 'MISCONFIGURED')) throw cause;
|
||||
shared.renewed.set(provider.id, renewed);
|
||||
}
|
||||
}
|
||||
|
||||
/** After a rejected refresh token: the credentials another process stored meanwhile, if any. */
|
||||
async function rotatedElsewhere(rejected: Credentials): Promise<Credentials | undefined> {
|
||||
for (let attempt = 0; attempt < ROTATION_ATTEMPTS; attempt += 1) {
|
||||
const latest = await current();
|
||||
if (latest.refresh !== rejected.refresh) return latest;
|
||||
await new Promise((resolve) => setTimeout(resolve, ROTATION_WAIT_MS));
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function refresh(stale: Credentials): Promise<Credentials> {
|
||||
let pending = shared.refreshing.get(provider.id) as Promise<Credentials> | undefined;
|
||||
if (pending === undefined) {
|
||||
pending = (async () => {
|
||||
// Another process may have refreshed already: prefer what the store holds now.
|
||||
const latest = await current();
|
||||
if (latest.access !== stale.access && !expiring(latest)) return latest;
|
||||
try {
|
||||
const renewed = await provider.refresh(latest);
|
||||
await persist(renewed);
|
||||
return renewed;
|
||||
} catch (cause) {
|
||||
if (cause instanceof OAuthError && cause.code === 'LOGIN_REQUIRED') {
|
||||
const rotated = await rotatedElsewhere(latest);
|
||||
if (rotated !== undefined) return rotated;
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
})().finally(() => shared.refreshing.delete(provider.id));
|
||||
shared.refreshing.set(provider.id, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
return async (input, init) => {
|
||||
// Captured once so the request can be sent again after a refresh; a body stream is read here.
|
||||
const base = new Request(input, init);
|
||||
const body = base.method === 'GET' || base.method === 'HEAD' ? undefined : await base.arrayBuffer();
|
||||
const attempt = (credentials: Credentials) => {
|
||||
const headers = new Headers(base.headers);
|
||||
headers.delete('x-api-key');
|
||||
headers.set('authorization', `Bearer ${credentials.access}`);
|
||||
headers.set('user-agent', options.userAgent);
|
||||
const request = new Request(base.url, { method: base.method, headers, signal: base.signal, ...(body === undefined ? {} : { body }) });
|
||||
return provider.send === undefined ? upstream(request) : provider.send(request, credentials, upstream);
|
||||
};
|
||||
|
||||
let credentials = await current();
|
||||
if (expiring(credentials)) credentials = await refresh(credentials);
|
||||
const response = await attempt(credentials);
|
||||
if (response.status !== 401 || credentials.refresh === '') return response;
|
||||
await response.body?.cancel();
|
||||
return attempt(await refresh(credentials));
|
||||
};
|
||||
}
|
||||
|
||||
/** True when the token lapses within the skew; a token with no expiry never does. */
|
||||
function expiring(credentials: OAuthCredentials): boolean {
|
||||
return credentials.expires !== 0 && credentials.expires - REFRESH_SKEW_MS <= Date.now();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* `grok('grok-4')`: a SuperGrok or X Premium+ subscription as an AI SDK
|
||||
* model. The instance is `@ai-sdk/xai`'s model with a fetch that carries the
|
||||
* stored login; the API is the ordinary SpaceXAI API.
|
||||
*/
|
||||
|
||||
import type { LanguageModelV4 } from '@ai-sdk/provider';
|
||||
import { createXai } from '@ai-sdk/xai';
|
||||
import { createOAuthFetch } from './fetch.ts';
|
||||
import { USER_AGENT, loginHint } from './providers.ts';
|
||||
import { createXaiProvider } from './providers/xai.ts';
|
||||
import { defaultCredentialStore } from './store.ts';
|
||||
import type { CredentialStore } from './types.ts';
|
||||
|
||||
export interface GrokOptions {
|
||||
readonly store?: CredentialStore;
|
||||
readonly userAgent?: string;
|
||||
/** Where the SpaceXAI API is reached, for a proxy in front of it. */
|
||||
readonly baseURL?: string;
|
||||
}
|
||||
|
||||
export function grok(modelId: string, options: GrokOptions = {}): LanguageModelV4 {
|
||||
const fetch = createOAuthFetch(createXaiProvider(), {
|
||||
store: options.store ?? defaultCredentialStore(),
|
||||
userAgent: options.userAgent ?? USER_AGENT,
|
||||
loginHint: loginHint('spacexai'),
|
||||
});
|
||||
return createXai({ apiKey: 'oauth', fetch, ...(options.baseURL === undefined ? {} : { baseURL: options.baseURL }) })(modelId);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Sign in to a personal AI subscription once, then use it as an AI SDK model.
|
||||
*
|
||||
* Model constructors live on subpaths so a config installs only the provider
|
||||
* package it uses: `@e2edev/oauth/chatgpt`, `@e2edev/oauth/copilot`,
|
||||
* `@e2edev/oauth/grok`. This entry holds the flows, the stores, and the fetch
|
||||
* for anyone wiring a provider of their own.
|
||||
*/
|
||||
|
||||
export type { CredentialStore, FetchFunction, OAuthAuthInfo, OAuthCredentials, OAuthLoginCallbacks, OAuthPrompt, OAuthProvider } from './types.ts';
|
||||
export { OAuthError, type OAuthErrorCode } from './errors.ts';
|
||||
export { createOAuthFetch, type OAuthFetchOptions } from './fetch.ts';
|
||||
export { CREDENTIALS_ENV, EnvCredentialStore, FileCredentialStore, MemoryCredentialStore, defaultCredentialStore, defaultCredentialsPath } from './store.ts';
|
||||
export { rfc8628Flow, runDeviceFlow, type DeviceAuthorization, type DeviceFlowOptions, type DevicePoll, type Rfc8628Options } from './device-code.ts';
|
||||
export { requestTokens, type TokenResponse } from './token-endpoint.ts';
|
||||
export { foldResponsesStream } from './sse.ts';
|
||||
export { createCodexProvider, type CodexCredentials, type CodexLoginOptions, type CodexProviderOptions } from './providers/openai.ts';
|
||||
export { copilotBaseUrl, createCopilotProvider, enterpriseHost, type CopilotCredentials, type CopilotLoginOptions, type CopilotProviderOptions } from './providers/github-copilot.ts';
|
||||
export { createXaiProvider, type XaiProviderOptions } from './providers/xai.ts';
|
||||
export { PROVIDER_IDS, getProvider, isProviderId, type LoginOptionsById, type ProviderId } from './providers.ts';
|
||||
export { login, logout, type LoginInput } from './login.ts';
|
||||
@@ -0,0 +1,11 @@
|
||||
/** The payload of a JWT, or undefined when the token is not one. Signatures are not checked: the values only steer requests. */
|
||||
export function decodeJwtPayload(token: string): Record<string, unknown> | undefined {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return undefined;
|
||||
try {
|
||||
const payload: unknown = JSON.parse(Buffer.from(parts[1] as string, 'base64url').toString('utf8'));
|
||||
return typeof payload === 'object' && payload !== null ? (payload as Record<string, unknown>) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/** Runs a provider's login and keeps the result; the CLI and embedders share it. */
|
||||
|
||||
import { getProvider, type LoginOptionsById, type ProviderId } from './providers.ts';
|
||||
import { defaultCredentialStore } from './store.ts';
|
||||
import type { CredentialStore, OAuthCredentials, OAuthLoginCallbacks } from './types.ts';
|
||||
|
||||
export interface LoginInput<Id extends ProviderId> {
|
||||
readonly callbacks: OAuthLoginCallbacks;
|
||||
readonly options?: LoginOptionsById[Id];
|
||||
readonly store?: CredentialStore;
|
||||
}
|
||||
|
||||
export async function login<Id extends ProviderId>(providerId: Id, input: LoginInput<Id>): Promise<OAuthCredentials> {
|
||||
const store = input.store ?? defaultCredentialStore();
|
||||
const credentials = await getProvider(providerId).login(input.callbacks, input.options);
|
||||
await store.set(providerId, credentials);
|
||||
return credentials;
|
||||
}
|
||||
|
||||
/** Forgets a stored login; true when there was one. */
|
||||
export async function logout(providerId: ProviderId, store: CredentialStore = defaultCredentialStore()): Promise<boolean> {
|
||||
if ((await store.get(providerId)) === undefined) return false;
|
||||
await store.remove(providerId);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** PKCE (RFC 7636) verifier and S256 challenge, plus an opaque state, over Web Crypto. */
|
||||
|
||||
export interface Pkce {
|
||||
readonly verifier: string;
|
||||
readonly challenge: string;
|
||||
}
|
||||
|
||||
function base64url(bytes: Uint8Array | ArrayBuffer): string {
|
||||
return Buffer.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)).toString('base64url');
|
||||
}
|
||||
|
||||
export async function generatePkce(): Promise<Pkce> {
|
||||
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
|
||||
const challenge = base64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
|
||||
return { verifier, challenge };
|
||||
}
|
||||
|
||||
export function randomState(): string {
|
||||
return base64url(crypto.getRandomValues(new Uint8Array(24)));
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/** The built-in providers by id, and the login options each one takes. */
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createCodexProvider, type CodexLoginOptions } from './providers/openai.ts';
|
||||
import { createCopilotProvider, type CopilotLoginOptions } from './providers/github-copilot.ts';
|
||||
import { createXaiProvider } from './providers/xai.ts';
|
||||
import type { OAuthProvider } from './types.ts';
|
||||
|
||||
export interface LoginOptionsById {
|
||||
readonly openai: CodexLoginOptions;
|
||||
readonly 'github-copilot': CopilotLoginOptions;
|
||||
readonly spacexai: Record<string, never>;
|
||||
}
|
||||
|
||||
export type ProviderId = keyof LoginOptionsById;
|
||||
|
||||
export const PROVIDER_IDS = ['openai', 'github-copilot', 'spacexai'] as const satisfies readonly ProviderId[];
|
||||
|
||||
// Method shorthand is bivariant, so each specialised provider fits the base interface without a cast.
|
||||
const PROVIDERS: Record<ProviderId, OAuthProvider> = {
|
||||
openai: createCodexProvider(),
|
||||
'github-copilot': createCopilotProvider(),
|
||||
spacexai: createXaiProvider(),
|
||||
};
|
||||
|
||||
export function isProviderId(id: string): id is ProviderId {
|
||||
return (PROVIDER_IDS as readonly string[]).includes(id);
|
||||
}
|
||||
|
||||
export function getProvider(id: ProviderId): OAuthProvider {
|
||||
return PROVIDERS[id];
|
||||
}
|
||||
|
||||
/**
|
||||
* How requests identify this harness to a vendor: `e2e-oauth/<version> (<platform>; <arch>)`,
|
||||
* alongside the `originator` (ChatGPT) and `referrer` (SpaceXAI) the flows send. Never another client's name.
|
||||
*/
|
||||
export const USER_AGENT = `e2e-oauth/${packageVersion()} (${process.platform}; ${process.arch})`;
|
||||
|
||||
function packageVersion(): string {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version?: string };
|
||||
return manifest.version ?? '0.0.0';
|
||||
} catch {
|
||||
return '0.0.0';
|
||||
}
|
||||
}
|
||||
|
||||
/** How a missing login is described to the user: the CLI command that fixes it. */
|
||||
export function loginHint(id: ProviderId): string {
|
||||
return `run \`e2e login ${id}\` (or \`npx e2e-oauth login ${id}\`)`;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* GitHub Copilot. The Copilot API accepts a GitHub sign-in as the bearer, so
|
||||
* the login is either the token the GitHub CLI already holds or GitHub's
|
||||
* device flow (RFC 8628) for an OAuth App you register. GitHub user tokens do
|
||||
* not expire; a 401 means signing in again.
|
||||
*/
|
||||
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { rfc8628Flow } from '../device-code.ts';
|
||||
import { OAuthError } from '../errors.ts';
|
||||
import type { FetchFunction, OAuthCredentials, OAuthProvider } from '../types.ts';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export interface CopilotLoginOptions {
|
||||
/**
|
||||
* The client id of your GitHub OAuth App with the device flow enabled.
|
||||
* Without one, the login reuses the GitHub CLI's token when `gh` is signed in.
|
||||
*/
|
||||
readonly clientId?: string;
|
||||
/** Reuse `gh auth token` even when a client id is given. */
|
||||
readonly fromGitHubCli?: boolean;
|
||||
/** `github.example.com` for GitHub Enterprise; Copilot then lives at `copilot-api.github.example.com`. */
|
||||
readonly enterpriseUrl?: string;
|
||||
}
|
||||
|
||||
export interface CopilotCredentials extends OAuthCredentials {
|
||||
readonly enterpriseUrl?: string;
|
||||
}
|
||||
|
||||
export interface CopilotProviderOptions {
|
||||
/** Test seams: the GitHub host the device flow talks to, and how the GitHub CLI's token is read. */
|
||||
readonly githubUrl?: string;
|
||||
readonly githubCliToken?: (hostname: string | undefined) => Promise<string | undefined>;
|
||||
}
|
||||
|
||||
export const COPILOT_API_URL = 'https://api.githubcopilot.com';
|
||||
|
||||
/**
|
||||
* The bare host of a GitHub Enterprise URL. The bearer token goes to a host
|
||||
* derived from it, so anything besides a plain hostname (credentials, a path,
|
||||
* a query, a fragment, a port) is refused rather than guessed at.
|
||||
*/
|
||||
export function enterpriseHost(value: string): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value.includes('://') ? value : `https://${value}`);
|
||||
} catch {
|
||||
throw new OAuthError('MISCONFIGURED', `${value} is not a GitHub Enterprise host; pass the hostname, e.g. github.example.com`);
|
||||
}
|
||||
const plain =
|
||||
url.protocol === 'https:' &&
|
||||
url.username === '' &&
|
||||
url.password === '' &&
|
||||
url.port === '' &&
|
||||
(url.pathname === '/' || url.pathname === '') &&
|
||||
url.search === '' &&
|
||||
url.hash === '' &&
|
||||
/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i.test(url.hostname);
|
||||
if (!plain) throw new OAuthError('MISCONFIGURED', `${value} is not a GitHub Enterprise host; pass the hostname, e.g. github.example.com`);
|
||||
return url.hostname.toLowerCase();
|
||||
}
|
||||
|
||||
/** The Copilot API base for github.com or an enterprise host. */
|
||||
export function copilotBaseUrl(enterpriseUrl?: string): string {
|
||||
return enterpriseUrl === undefined || enterpriseUrl === '' ? COPILOT_API_URL : `https://copilot-api.${enterpriseHost(enterpriseUrl)}`;
|
||||
}
|
||||
|
||||
export function createCopilotProvider(options: CopilotProviderOptions = {}): OAuthProvider<CopilotCredentials, CopilotLoginOptions> {
|
||||
const cliToken = options.githubCliToken ?? githubCliToken;
|
||||
return {
|
||||
id: 'github-copilot',
|
||||
name: 'GitHub Copilot',
|
||||
async login(callbacks, loginOptions = {}) {
|
||||
const enterprise = loginOptions.enterpriseUrl === undefined ? undefined : enterpriseHost(loginOptions.enterpriseUrl);
|
||||
const stored = enterprise === undefined ? {} : { enterpriseUrl: enterprise };
|
||||
if (loginOptions.clientId !== undefined && loginOptions.fromGitHubCli !== true) {
|
||||
const tokens = await rfc8628Flow({
|
||||
vendor: 'GitHub',
|
||||
deviceCodeUrl: `${options.githubUrl ?? `https://${enterprise ?? 'github.com'}`}/login/device/code`,
|
||||
tokenUrl: `${options.githubUrl ?? `https://${enterprise ?? 'github.com'}`}/login/oauth/access_token`,
|
||||
clientId: loginOptions.clientId,
|
||||
request: { scope: 'read:user' },
|
||||
callbacks,
|
||||
});
|
||||
return { access: tokens.access_token, refresh: '', expires: 0, ...stored };
|
||||
}
|
||||
const token = await cliToken(enterprise);
|
||||
if (token === undefined) {
|
||||
throw new OAuthError(
|
||||
'MISCONFIGURED',
|
||||
'GitHub Copilot login needs either the GitHub CLI signed in (gh auth login) or the client id of a GitHub OAuth App with the device flow enabled',
|
||||
);
|
||||
}
|
||||
callbacks.onProgress?.('Using the GitHub CLI token');
|
||||
return { access: token, refresh: '', expires: 0, ...stored };
|
||||
},
|
||||
async refresh() {
|
||||
throw new OAuthError('LOGIN_REQUIRED', 'GitHub rejected the Copilot token; sign in again');
|
||||
},
|
||||
send(request, credentials, upstream) {
|
||||
return sendCopilotRequest(request, credentials, upstream);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function githubCliToken(hostname: string | undefined): Promise<string | undefined> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('gh', ['auth', 'token', ...(hostname === undefined ? [] : ['--hostname', hostname])], { timeout: 10_000 });
|
||||
return stdout.trim() === '' ? undefined : stdout.trim();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Routes an enterprise login at its host and adds Copilot's headers: who initiated the turn, and that images are present. */
|
||||
export async function sendCopilotRequest(request: Request, credentials: CopilotCredentials, upstream: FetchFunction): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
if (credentials.enterpriseUrl !== undefined && url.origin === COPILOT_API_URL) url.host = new URL(copilotBaseUrl(credentials.enterpriseUrl)).host;
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('openai-intent', 'conversation-edits');
|
||||
let initiator = 'user';
|
||||
let vision = false;
|
||||
const text = request.method === 'POST' ? await request.text() : undefined;
|
||||
if (text !== undefined) {
|
||||
try {
|
||||
const body = JSON.parse(text) as { messages?: Array<{ role?: string; content?: unknown }> };
|
||||
const messages = Array.isArray(body.messages) ? body.messages : [];
|
||||
if (messages.at(-1)?.role !== 'user') initiator = 'agent';
|
||||
vision = messages.some(
|
||||
(message) => Array.isArray(message.content) && message.content.some((part: { type?: string }) => part?.type === 'image_url'),
|
||||
);
|
||||
} catch {
|
||||
// Not JSON; the headers stay at their defaults.
|
||||
}
|
||||
}
|
||||
headers.set('x-initiator', initiator);
|
||||
if (vision) headers.set('copilot-vision-request', 'true');
|
||||
return upstream(new Request(url, { method: request.method, headers, signal: request.signal, ...(text === undefined ? {} : { body: text }) }));
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* ChatGPT Plus/Pro through the Codex OAuth client. The login is the one the
|
||||
* Codex CLI runs: PKCE authorization code against auth.openai.com with a
|
||||
* local callback on port 1455, or OpenAI's own user-code flow for a machine
|
||||
* without a browser. Requests then go to the Codex backend, which speaks the
|
||||
* Responses API, requires `store: false`, and answers only as a stream; the
|
||||
* stream is folded back into JSON when the SDK asked for a single response.
|
||||
*/
|
||||
|
||||
import { startCallbackServer, type CallbackAnswer, type CallbackServer } from '../callback-server.ts';
|
||||
import { runDeviceFlow } from '../device-code.ts';
|
||||
import { OAuthError, describeResponse } from '../errors.ts';
|
||||
import { decodeJwtPayload } from '../jwt.ts';
|
||||
import { generatePkce, randomState } from '../pkce.ts';
|
||||
import { foldResponsesStream } from '../sse.ts';
|
||||
import { expiryFrom, requestTokens, type TokenResponse } from '../token-endpoint.ts';
|
||||
import type { FetchFunction, OAuthCredentials, OAuthLoginCallbacks, OAuthProvider } from '../types.ts';
|
||||
|
||||
/** The public OAuth client of the Codex CLI, which every third-party harness signs in through. */
|
||||
const CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
|
||||
const ISSUER = 'https://auth.openai.com';
|
||||
const API_URL = 'https://chatgpt.com/backend-api/codex/responses';
|
||||
const CALLBACK_PORT = 1455;
|
||||
const CALLBACK_PATH = '/auth/callback';
|
||||
const SCOPE = 'openid profile email offline_access';
|
||||
const DEVICE_POLL_MARGIN_S = 3;
|
||||
const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
/** The backend rejects a request without instructions; this is the least it accepts when the SDK sent no system prompt. */
|
||||
const REQUIRED_INSTRUCTIONS = 'Follow the user request.';
|
||||
|
||||
export interface CodexCredentials extends OAuthCredentials {
|
||||
/** The ChatGPT account the requests bill to. */
|
||||
readonly accountId?: string;
|
||||
/** The compute residency the token pins, sent back so the backend routes accordingly. */
|
||||
readonly residency?: string;
|
||||
}
|
||||
|
||||
export interface CodexLoginOptions {
|
||||
/** `browser` (default) opens the authorization page; `device` prints a code for another device. */
|
||||
readonly method?: 'browser' | 'device';
|
||||
}
|
||||
|
||||
export interface CodexProviderOptions {
|
||||
/** The `originator` the authorization page and requests carry: your product's name. */
|
||||
readonly originator?: string;
|
||||
/** Test seams. */
|
||||
readonly issuer?: string;
|
||||
readonly apiUrl?: string;
|
||||
readonly callbackPort?: number;
|
||||
readonly loginTimeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createCodexProvider(options: CodexProviderOptions = {}): OAuthProvider<CodexCredentials, CodexLoginOptions> {
|
||||
const originator = options.originator ?? 'e2e';
|
||||
const issuer = options.issuer ?? ISSUER;
|
||||
const apiUrl = options.apiUrl ?? API_URL;
|
||||
const callbackPort = options.callbackPort ?? CALLBACK_PORT;
|
||||
const timeoutMs = options.loginTimeoutMs ?? LOGIN_TIMEOUT_MS;
|
||||
return {
|
||||
id: 'openai',
|
||||
name: 'ChatGPT',
|
||||
async login(callbacks, loginOptions = {}) {
|
||||
const tokens =
|
||||
loginOptions.method === 'device'
|
||||
? await deviceLogin(callbacks, issuer, timeoutMs)
|
||||
: await browserLogin(callbacks, { issuer, originator, callbackPort, timeoutMs });
|
||||
return toCredentials(tokens);
|
||||
},
|
||||
async refresh(credentials) {
|
||||
const tokens = await requestTokens(
|
||||
'ChatGPT',
|
||||
`${issuer}/oauth/token`,
|
||||
{ grant_type: 'refresh_token', refresh_token: credentials.refresh, client_id: CLIENT_ID },
|
||||
'LOGIN_REQUIRED',
|
||||
);
|
||||
return toCredentials(tokens, credentials);
|
||||
},
|
||||
async send(request, credentials, upstream) {
|
||||
return sendCodexRequest(request, credentials, upstream, { originator, apiUrl });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Credentials from a token response; a refresh that returns no new refresh token or account keeps the previous ones. */
|
||||
function toCredentials(tokens: TokenResponse, previous?: CodexCredentials): CodexCredentials {
|
||||
const accountId = extractAccountId(tokens) ?? previous?.accountId;
|
||||
const residency = extractResidency(tokens.access_token) ?? previous?.residency;
|
||||
const refresh = tokens.refresh_token ?? previous?.refresh;
|
||||
if (refresh === undefined) throw new OAuthError('FLOW_FAILED', 'the ChatGPT token response is missing refresh_token');
|
||||
return {
|
||||
access: tokens.access_token,
|
||||
refresh,
|
||||
expires: expiryFrom(tokens.expires_in),
|
||||
...(accountId === undefined ? {} : { accountId }),
|
||||
...(residency === undefined ? {} : { residency }),
|
||||
};
|
||||
}
|
||||
|
||||
const AUTH_CLAIM = 'https://api.openai.com/auth';
|
||||
|
||||
function claimsOf(token: string | undefined): Record<string, unknown> | undefined {
|
||||
return token === undefined ? undefined : decodeJwtPayload(token);
|
||||
}
|
||||
|
||||
export function extractAccountId(tokens: { id_token?: string; access_token?: string }): string | undefined {
|
||||
for (const claims of [claimsOf(tokens.id_token), claimsOf(tokens.access_token)]) {
|
||||
if (claims === undefined) continue;
|
||||
const nested = claims[AUTH_CLAIM] as Record<string, unknown> | undefined;
|
||||
const organizations = claims['organizations'] as Array<{ id?: unknown }> | undefined;
|
||||
const candidate = claims['chatgpt_account_id'] ?? nested?.['chatgpt_account_id'] ?? organizations?.[0]?.id;
|
||||
if (typeof candidate === 'string' && candidate !== '') return candidate;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function extractResidency(accessToken: string): string | undefined {
|
||||
const claims = decodeJwtPayload(accessToken);
|
||||
const nested = claims?.[AUTH_CLAIM] as Record<string, unknown> | undefined;
|
||||
const residency = nested?.['chatgpt_compute_residency'] ?? claims?.['chatgpt_compute_residency'];
|
||||
return typeof residency === 'string' && residency !== '' && residency !== 'no_constraint' ? residency : undefined;
|
||||
}
|
||||
|
||||
/** The code from what the user pasted: a full redirect URL, `code#state`, a query string, or the bare code. */
|
||||
export function parseAuthorizationInput(input: string): { code: string | undefined; state: string | undefined } {
|
||||
const value = input.trim();
|
||||
if (value === '') return { code: undefined, state: undefined };
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return { code: url.searchParams.get('code') ?? undefined, state: url.searchParams.get('state') ?? undefined };
|
||||
} catch {
|
||||
// Not a URL.
|
||||
}
|
||||
if (value.includes('#')) {
|
||||
const [code, state] = value.split('#', 2);
|
||||
return { code, state };
|
||||
}
|
||||
if (value.includes('code=')) {
|
||||
const params = new URLSearchParams(value);
|
||||
return { code: params.get('code') ?? undefined, state: params.get('state') ?? undefined };
|
||||
}
|
||||
return { code: value, state: undefined };
|
||||
}
|
||||
|
||||
function exchangeCode(issuer: string, code: string, redirectUri: string, verifier: string): Promise<TokenResponse> {
|
||||
return requestTokens('ChatGPT', `${issuer}/oauth/token`, {
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: redirectUri,
|
||||
client_id: CLIENT_ID,
|
||||
code_verifier: verifier,
|
||||
});
|
||||
}
|
||||
|
||||
interface BrowserLogin {
|
||||
readonly issuer: string;
|
||||
readonly originator: string;
|
||||
readonly callbackPort: number;
|
||||
readonly timeoutMs: number;
|
||||
}
|
||||
|
||||
async function browserLogin(callbacks: OAuthLoginCallbacks, flow: BrowserLogin): Promise<TokenResponse> {
|
||||
const { verifier, challenge } = await generatePkce();
|
||||
const state = randomState();
|
||||
const server = await startCallbackServer({ port: flow.callbackPort, path: CALLBACK_PATH, state, productName: 'ChatGPT login' });
|
||||
const redirectUri = server?.redirectUri ?? `http://localhost:${flow.callbackPort}${CALLBACK_PATH}`;
|
||||
const url = new URL(`${flow.issuer}/oauth/authorize`);
|
||||
url.search = new URLSearchParams({
|
||||
response_type: 'code',
|
||||
client_id: CLIENT_ID,
|
||||
redirect_uri: redirectUri,
|
||||
scope: SCOPE,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: 'S256',
|
||||
id_token_add_organizations: 'true',
|
||||
codex_cli_simplified_flow: 'true',
|
||||
state,
|
||||
originator: flow.originator,
|
||||
}).toString();
|
||||
callbacks.onAuth({
|
||||
url: url.toString(),
|
||||
instructions:
|
||||
server === undefined
|
||||
? `Port ${flow.callbackPort} is in use, so the browser cannot return here: sign in, then paste the URL the browser lands on.`
|
||||
: 'Sign in in the browser; this terminal continues when the browser returns, or asks for the URL it landed on.',
|
||||
});
|
||||
try {
|
||||
const code = server === undefined ? await pasteCode(callbacks, state) : await answerOrPaste(server, callbacks, state, flow.timeoutMs);
|
||||
if (code === undefined) throw new OAuthError('FLOW_FAILED', 'no authorization code was received');
|
||||
callbacks.onProgress?.('Exchanging the code for tokens');
|
||||
return await exchangeCode(flow.issuer, code, redirectUri, verifier);
|
||||
} finally {
|
||||
server?.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** The browser's answer; when it never comes back in time, the user pastes what it shows instead. */
|
||||
async function answerOrPaste(server: CallbackServer, callbacks: OAuthLoginCallbacks, state: string, timeoutMs: number): Promise<string | undefined> {
|
||||
let answer: CallbackAnswer;
|
||||
try {
|
||||
answer = await server.waitForAnswer(callbacks.signal, timeoutMs);
|
||||
} catch (cause) {
|
||||
if (cause instanceof OAuthError && cause.code === 'TIMEOUT') return pasteCode(callbacks, state);
|
||||
throw cause;
|
||||
}
|
||||
if ('error' in answer) {
|
||||
throw answer.error === 'access_denied'
|
||||
? new OAuthError('CANCELLED', 'the sign-in was declined in the browser')
|
||||
: new OAuthError('FLOW_FAILED', `ChatGPT refused the sign-in: ${answer.error}`);
|
||||
}
|
||||
return answer.code;
|
||||
}
|
||||
|
||||
async function pasteCode(callbacks: OAuthLoginCallbacks, state: string): Promise<string | undefined> {
|
||||
const pasted = parseAuthorizationInput(await callbacks.onPrompt({ message: 'Paste the URL the browser landed on (or the code it shows)' }));
|
||||
if (pasted.state !== undefined && pasted.state !== state) {
|
||||
throw new OAuthError('FLOW_FAILED', 'the pasted code belongs to a different login attempt; start over');
|
||||
}
|
||||
return pasted.code;
|
||||
}
|
||||
|
||||
/** The Codex CLI's device login: OpenAI's own user-code endpoints, pending until the user enters the code. */
|
||||
function deviceLogin(callbacks: OAuthLoginCallbacks, issuer: string, timeoutMs: number): Promise<TokenResponse> {
|
||||
const json = (url: string, body: unknown, signal?: AbortSignal) =>
|
||||
fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), ...(signal === undefined ? {} : { signal }) });
|
||||
return runDeviceFlow<TokenResponse>({
|
||||
callbacks,
|
||||
async start() {
|
||||
const response = await json(`${issuer}/api/accounts/deviceauth/usercode`, { client_id: CLIENT_ID });
|
||||
if (!response.ok) throw new OAuthError('FLOW_FAILED', `ChatGPT device login could not start: ${await describeResponse(response)}`);
|
||||
const device = (await response.json()) as { device_auth_id: string; user_code: string; interval?: string | number };
|
||||
return {
|
||||
deviceCode: device.device_auth_id,
|
||||
userCode: device.user_code,
|
||||
verificationUri: `${issuer}/codex/device`,
|
||||
expiresIn: timeoutMs / 1000,
|
||||
interval: Number(device.interval) + DEVICE_POLL_MARGIN_S,
|
||||
};
|
||||
},
|
||||
async poll(authorization, signal) {
|
||||
const response = await json(`${issuer}/api/accounts/deviceauth/token`, { device_auth_id: authorization.deviceCode, user_code: authorization.userCode }, signal);
|
||||
if (response.ok) {
|
||||
const grant = (await response.json()) as { authorization_code: string; code_verifier: string };
|
||||
return { status: 'granted', value: await exchangeCode(issuer, grant.authorization_code, `${issuer}/deviceauth/callback`, grant.code_verifier) };
|
||||
}
|
||||
// Pending shows as 403 or 404 until the user enters the code.
|
||||
if (response.status === 403 || response.status === 404) {
|
||||
await response.body?.cancel();
|
||||
return { status: 'pending' };
|
||||
}
|
||||
throw new OAuthError('FLOW_FAILED', `ChatGPT device login failed: ${await describeResponse(response)}`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** The Responses API body as the Codex backend wants it. */
|
||||
interface CodexBody {
|
||||
stream?: boolean;
|
||||
store?: boolean;
|
||||
instructions?: string;
|
||||
include?: string[];
|
||||
max_output_tokens?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes a Responses API request at the Codex backend with the body the
|
||||
* Codex CLI sends: no server-side storage, encrypted reasoning carried
|
||||
* between turns, always streamed. A caller that did not ask for a stream gets
|
||||
* the completed response folded back into one JSON body.
|
||||
*/
|
||||
export async function sendCodexRequest(
|
||||
request: Request,
|
||||
credentials: CodexCredentials,
|
||||
upstream: FetchFunction,
|
||||
options: { originator: string; apiUrl: string },
|
||||
): Promise<Response> {
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('originator', options.originator);
|
||||
if (credentials.accountId !== undefined) headers.set('chatgpt-account-id', credentials.accountId);
|
||||
if (!new URL(request.url).pathname.endsWith('/responses')) return upstream(new Request(request, { headers }));
|
||||
|
||||
if (credentials.residency !== undefined) headers.set('x-openai-internal-codex-residency', credentials.residency);
|
||||
let body: CodexBody;
|
||||
try {
|
||||
body = (await request.json()) as CodexBody;
|
||||
} catch (cause) {
|
||||
throw new OAuthError('FLOW_FAILED', 'the Responses request body is not JSON', { cause });
|
||||
}
|
||||
const wantedStream = body.stream === true;
|
||||
body.stream = true;
|
||||
body.store = false;
|
||||
if (body.instructions === undefined || body.instructions === '') body.instructions = REQUIRED_INSTRUCTIONS;
|
||||
const include = body.include ?? [];
|
||||
if (!include.includes('reasoning.encrypted_content')) body.include = [...include, 'reasoning.encrypted_content'];
|
||||
// The Codex backend sizes output itself; the Codex CLI sends no cap and the backend rejects some.
|
||||
delete body.max_output_tokens;
|
||||
const response = await upstream(new Request(options.apiUrl, { method: request.method, headers, body: JSON.stringify(body), signal: request.signal }));
|
||||
return wantedStream ? response : foldResponsesStream(response);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* SuperGrok and X Premium+ through SpaceXAI's OAuth server. SpaceXAI publishes RFC 8628
|
||||
* device authorization for the Grok CLI's public client; the token is a plain
|
||||
* bearer against the ordinary SpaceXAI API. Refresh tokens rotate, so a renewed
|
||||
* refresh token replaces the stored one at once.
|
||||
*/
|
||||
|
||||
import { rfc8628Flow } from '../device-code.ts';
|
||||
import { decodeJwtPayload } from '../jwt.ts';
|
||||
import { expiryFrom, requestTokens, type TokenResponse } from '../token-endpoint.ts';
|
||||
import type { OAuthCredentials, OAuthProvider } from '../types.ts';
|
||||
|
||||
/** The public OAuth client of the Grok CLI, which third-party harnesses sign in through. */
|
||||
const CLIENT_ID = 'b1a00492-073a-47ea-816f-4c329264a828';
|
||||
const ISSUER = 'https://auth.x.ai';
|
||||
const SCOPE = 'openid profile email offline_access grok-cli:access api:access';
|
||||
|
||||
export interface XaiProviderOptions {
|
||||
/** The `referrer` the device request names: your product. */
|
||||
readonly referrer?: string;
|
||||
/** Test seam. */
|
||||
readonly issuer?: string;
|
||||
}
|
||||
|
||||
export function createXaiProvider(options: XaiProviderOptions = {}): OAuthProvider<OAuthCredentials, Record<string, never>> {
|
||||
const issuer = options.issuer ?? ISSUER;
|
||||
const referrer = options.referrer ?? 'e2e';
|
||||
return {
|
||||
id: 'spacexai',
|
||||
name: 'SpaceXAI',
|
||||
async login(callbacks) {
|
||||
const tokens = await rfc8628Flow({
|
||||
vendor: 'SpaceXAI',
|
||||
deviceCodeUrl: `${issuer}/oauth2/device/code`,
|
||||
tokenUrl: `${issuer}/oauth2/token`,
|
||||
clientId: CLIENT_ID,
|
||||
request: { scope: SCOPE, referrer },
|
||||
callbacks,
|
||||
});
|
||||
return toCredentials(tokens, '');
|
||||
},
|
||||
async refresh(credentials) {
|
||||
const tokens = await requestTokens(
|
||||
'SpaceXAI',
|
||||
`${issuer}/oauth2/token`,
|
||||
{ grant_type: 'refresh_token', refresh_token: credentials.refresh, client_id: CLIENT_ID },
|
||||
'LOGIN_REQUIRED',
|
||||
);
|
||||
return toCredentials(tokens, credentials.refresh);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Expiry from the JWT when it carries one, else from `expires_in`; a refresh without a new refresh token keeps the old one. */
|
||||
function toCredentials(tokens: TokenResponse, previousRefresh: string): OAuthCredentials {
|
||||
const exp = decodeJwtPayload(tokens.access_token)?.['exp'];
|
||||
const expires = typeof exp === 'number' && exp > 0 ? exp * 1000 : expiryFrom(tokens.expires_in);
|
||||
return { access: tokens.access_token, refresh: tokens.refresh_token ?? previousRefresh, expires };
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Folds a server-sent-event response into the single JSON body a
|
||||
* non-streaming client expects. The OpenAI Responses stream ends in a
|
||||
* `response.completed` (or `response.incomplete`, when the output was cut
|
||||
* short) event whose `response` is exactly the object the non-streaming
|
||||
* endpoint returns, so that event becomes the body; a `response.failed` or
|
||||
* `error` event becomes an error body.
|
||||
*/
|
||||
|
||||
export interface SseEvent {
|
||||
readonly event?: string;
|
||||
readonly data: string;
|
||||
}
|
||||
|
||||
/** Splits a text/event-stream body into events, tolerating either newline convention. */
|
||||
export function parseSse(text: string): SseEvent[] {
|
||||
const events: SseEvent[] = [];
|
||||
for (const block of text.split(/\r?\n\r?\n/)) {
|
||||
let event: string | undefined;
|
||||
const data: string[] = [];
|
||||
for (const line of block.split(/\r?\n/)) {
|
||||
if (line.startsWith('event:')) event = line.slice(6).trim();
|
||||
else if (line.startsWith('data:')) data.push(line.slice(5).trimStart());
|
||||
}
|
||||
if (data.length === 0) continue;
|
||||
events.push(event === undefined ? { data: data.join('\n') } : { event, data: data.join('\n') });
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
export async function foldResponsesStream(response: Response): Promise<Response> {
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (!response.ok || !contentType.includes('text/event-stream')) return response;
|
||||
const text = await response.text();
|
||||
let failure: unknown;
|
||||
for (const { data } of parseSse(text)) {
|
||||
if (data === '[DONE]') continue;
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(data);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (typeof payload !== 'object' || payload === null) continue;
|
||||
const record = payload as Record<string, unknown>;
|
||||
if (record['type'] === 'response.completed' || record['type'] === 'response.incomplete') {
|
||||
return json(200, record['response']);
|
||||
}
|
||||
if (record['type'] === 'response.failed') {
|
||||
const inner = record['response'] as Record<string, unknown> | undefined;
|
||||
failure = inner?.['error'] ?? { message: 'the response failed' };
|
||||
} else if (record['type'] === 'error') {
|
||||
failure = { message: record['message'] ?? 'the response failed', code: record['code'] };
|
||||
}
|
||||
}
|
||||
if (failure !== undefined) return json(400, { error: failure });
|
||||
return json(502, { error: { message: 'the stream ended without a completed response' } });
|
||||
}
|
||||
|
||||
function json(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* Credentials between runs: one JSON file keyed by provider id, mode 0600.
|
||||
* Writes hold an advisory lock and replace the file atomically, so two runs
|
||||
* refreshing at once neither tear the file nor lose each other's entries.
|
||||
* `E2E_OAUTH_CREDENTIALS` holding the same JSON stands in for the file on a
|
||||
* machine the user cannot sign in on; that store refuses to write.
|
||||
*/
|
||||
|
||||
import { chmodSync, closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { OAuthError } from './errors.ts';
|
||||
import type { CredentialStore, OAuthCredentials } from './types.ts';
|
||||
|
||||
export const CREDENTIALS_ENV = 'E2E_OAUTH_CREDENTIALS';
|
||||
|
||||
type CredentialsFile = Record<string, OAuthCredentials>;
|
||||
|
||||
/** `$XDG_CONFIG_HOME/e2e/oauth.json`, or `~/.config/e2e/oauth.json`. */
|
||||
export function defaultCredentialsPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
const configHome = env['XDG_CONFIG_HOME'];
|
||||
const base = configHome !== undefined && configHome !== '' ? configHome : path.join(homedir(), '.config');
|
||||
return path.join(base, 'e2e', 'oauth.json');
|
||||
}
|
||||
|
||||
/** The store the model constructors and the CLI use: the environment variable when set, else the file. */
|
||||
export function defaultCredentialStore(env: NodeJS.ProcessEnv = process.env): CredentialStore {
|
||||
const fromEnv = env[CREDENTIALS_ENV];
|
||||
return fromEnv !== undefined && fromEnv !== '' ? new EnvCredentialStore(fromEnv) : new FileCredentialStore(defaultCredentialsPath(env));
|
||||
}
|
||||
|
||||
const LOCK_RETRY_MS = 25;
|
||||
const LOCK_STALE_MS = 10_000;
|
||||
const LOCK_WAIT_MS = 5_000;
|
||||
|
||||
export class FileCredentialStore implements CredentialStore {
|
||||
readonly path: string;
|
||||
|
||||
constructor(file: string = defaultCredentialsPath()) {
|
||||
this.path = file;
|
||||
}
|
||||
|
||||
async get(providerId: string): Promise<OAuthCredentials | undefined> {
|
||||
return this.read()[providerId];
|
||||
}
|
||||
|
||||
async set(providerId: string, credentials: OAuthCredentials): Promise<void> {
|
||||
await this.update((all) => ({ ...all, [providerId]: credentials }));
|
||||
}
|
||||
|
||||
async remove(providerId: string): Promise<void> {
|
||||
await this.update((all) => {
|
||||
const { [providerId]: _removed, ...rest } = all;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
|
||||
async list(): Promise<string[]> {
|
||||
return Object.keys(this.read());
|
||||
}
|
||||
|
||||
private read(): CredentialsFile {
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(this.path, 'utf8');
|
||||
} catch (cause) {
|
||||
if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return {};
|
||||
throw cause;
|
||||
}
|
||||
return parseCredentials(text, this.path);
|
||||
}
|
||||
|
||||
/** Read-modify-write under the lock, then an atomic replace. */
|
||||
private async update(change: (all: CredentialsFile) => CredentialsFile): Promise<void> {
|
||||
const dir = path.dirname(this.path);
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
// Creation modes only apply to new paths; a directory or file that already existed keeps what it had unless told otherwise.
|
||||
chmodSync(dir, 0o700);
|
||||
const release = await this.lock();
|
||||
try {
|
||||
const temp = `${this.path}.${process.pid}.${Date.now()}.tmp`;
|
||||
writeFileSync(temp, `${JSON.stringify(change(this.read()), null, 2)}\n`, { mode: 0o600 });
|
||||
chmodSync(temp, 0o600);
|
||||
try {
|
||||
renameSync(temp, this.path);
|
||||
} catch (cause) {
|
||||
rmSync(temp, { force: true });
|
||||
throw cause;
|
||||
}
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An advisory lock file created exclusively. A lock older than the stale
|
||||
* bound was left by a dead process: it is claimed by renaming it, which
|
||||
* only one waiter can win, so a lock a live process just created is never
|
||||
* removed from under it.
|
||||
*/
|
||||
private async lock(): Promise<() => void> {
|
||||
const lockPath = `${this.path}.lock`;
|
||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||
for (;;) {
|
||||
try {
|
||||
closeSync(openSync(lockPath, 'wx', 0o600));
|
||||
return () => rmSync(lockPath, { force: true });
|
||||
} catch (cause) {
|
||||
if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause;
|
||||
if (Date.now() - lockAge(lockPath) > LOCK_STALE_MS) {
|
||||
const claimed = `${lockPath}.${process.pid}.${Date.now()}.stale`;
|
||||
try {
|
||||
renameSync(lockPath, claimed);
|
||||
rmSync(claimed, { force: true });
|
||||
} catch {
|
||||
// Another waiter claimed it first; try the lock again.
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (Date.now() > deadline) throw new Error(`${lockPath} is held by another process; remove it if that process is gone`, { cause });
|
||||
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function lockAge(lockPath: string): number {
|
||||
try {
|
||||
return statSync(lockPath).mtimeMs;
|
||||
} catch {
|
||||
return Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
/** Credentials from the environment variable: readable everywhere, changed nowhere. */
|
||||
export class EnvCredentialStore implements CredentialStore {
|
||||
private readonly entries: CredentialsFile;
|
||||
constructor(json: string, source: string = CREDENTIALS_ENV) {
|
||||
this.entries = parseCredentials(json, source);
|
||||
}
|
||||
async get(providerId: string): Promise<OAuthCredentials | undefined> {
|
||||
return this.entries[providerId];
|
||||
}
|
||||
async set(): Promise<void> {
|
||||
throw new OAuthError('MISCONFIGURED', `${CREDENTIALS_ENV} is set, so logins come from the environment and cannot be changed here; unset it to sign in on this machine`);
|
||||
}
|
||||
async remove(): Promise<void> {
|
||||
return this.set();
|
||||
}
|
||||
async list(): Promise<string[]> {
|
||||
return Object.keys(this.entries);
|
||||
}
|
||||
}
|
||||
|
||||
/** A store for tests and embedders that keep credentials elsewhere. */
|
||||
export class MemoryCredentialStore implements CredentialStore {
|
||||
private readonly entries = new Map<string, OAuthCredentials>();
|
||||
constructor(initial: Record<string, OAuthCredentials> = {}) {
|
||||
for (const [id, credentials] of Object.entries(initial)) this.entries.set(id, credentials);
|
||||
}
|
||||
async get(providerId: string): Promise<OAuthCredentials | undefined> {
|
||||
return this.entries.get(providerId);
|
||||
}
|
||||
async set(providerId: string, credentials: OAuthCredentials): Promise<void> {
|
||||
this.entries.set(providerId, credentials);
|
||||
}
|
||||
async remove(providerId: string): Promise<void> {
|
||||
this.entries.delete(providerId);
|
||||
}
|
||||
async list(): Promise<string[]> {
|
||||
return [...this.entries.keys()];
|
||||
}
|
||||
}
|
||||
|
||||
/** The file's entries; one damaged entry is dropped rather than taking every login down with it. */
|
||||
function parseCredentials(text: string, source: string): CredentialsFile {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch (cause) {
|
||||
throw new Error(`${source} is not valid JSON`, { cause });
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
throw new Error(`${source} must hold an object keyed by provider id`);
|
||||
}
|
||||
const out: CredentialsFile = {};
|
||||
for (const [id, value] of Object.entries(parsed as Record<string, unknown>)) {
|
||||
if (isCredentials(value)) out[id] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isCredentials(value: unknown): value is OAuthCredentials {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return typeof record['access'] === 'string' && typeof record['refresh'] === 'string' && typeof record['expires'] === 'number';
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* The HTTP an OAuth flow is made of: form-encoded POSTs to a token endpoint
|
||||
* and the token response every vendor answers with. Timing values from the
|
||||
* wire are coerced defensively: a `NaN` expiry written to disk would poison
|
||||
* the credentials file.
|
||||
*/
|
||||
|
||||
import { OAuthError, describeResponse, type OAuthErrorCode } from './errors.ts';
|
||||
|
||||
export interface TokenResponse {
|
||||
readonly access_token: string;
|
||||
readonly refresh_token?: string;
|
||||
readonly id_token?: string;
|
||||
readonly expires_in?: number;
|
||||
}
|
||||
|
||||
export async function postForm(url: string, params: Record<string, string>, signal?: AbortSignal): Promise<Response> {
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
||||
body: new URLSearchParams(params),
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts a grant and returns the tokens. A 400 or 401 means the grant itself
|
||||
* was rejected and maps to `rejected` (LOGIN_REQUIRED for a refresh, FLOW_FAILED
|
||||
* for a code exchange); anything else not OK is FLOW_FAILED.
|
||||
*/
|
||||
export async function requestTokens(
|
||||
vendor: string,
|
||||
url: string,
|
||||
params: Record<string, string>,
|
||||
rejected: OAuthErrorCode = 'FLOW_FAILED',
|
||||
): Promise<TokenResponse> {
|
||||
const response = await postForm(url, params);
|
||||
if (!response.ok) {
|
||||
const code = response.status === 400 || response.status === 401 ? rejected : 'FLOW_FAILED';
|
||||
const suffix = code === 'LOGIN_REQUIRED' ? '; sign in again' : '';
|
||||
throw new OAuthError(code, `${vendor} token request failed (${await describeResponse(response)})${suffix}`);
|
||||
}
|
||||
const tokens = (await response.json()) as Partial<TokenResponse>;
|
||||
if (typeof tokens.access_token !== 'string' || tokens.access_token === '') {
|
||||
throw new OAuthError('FLOW_FAILED', `the ${vendor} token response is missing access_token`);
|
||||
}
|
||||
return tokens as TokenResponse;
|
||||
}
|
||||
|
||||
/** A seconds value from the server, or the default when it is missing or not a positive finite number. */
|
||||
export function positiveSeconds(value: unknown, fallback: number): number {
|
||||
const seconds = Number(value);
|
||||
return Number.isFinite(seconds) && seconds > 0 ? seconds : fallback;
|
||||
}
|
||||
|
||||
/** When a token expires, from `expires_in`; one hour when the server names nothing usable. */
|
||||
export function expiryFrom(expiresIn: unknown, now: number = Date.now()): number {
|
||||
const expiry = now + positiveSeconds(expiresIn, 3600) * 1000;
|
||||
return Number.isFinite(expiry) ? expiry : now + 3600 * 1000;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The contract between a subscription login and the AI SDK: a provider knows
|
||||
* how to sign the user in, refresh what the login returned, and send one API
|
||||
* request the vendor's way with a subscription token. Everything else (the
|
||||
* credential file, the fetch that swaps the token in, the model
|
||||
* constructors) is shared.
|
||||
*/
|
||||
|
||||
/** What a login returns and a refresh renews; providers extend it with what their requests need. */
|
||||
export interface OAuthCredentials {
|
||||
readonly access: string;
|
||||
/** Empty when the vendor issues non-expiring tokens. */
|
||||
readonly refresh: string;
|
||||
/** Epoch milliseconds; `0` when the token does not expire. */
|
||||
readonly expires: number;
|
||||
}
|
||||
|
||||
/** Where the user is sent and, for device flows, the code to enter there. */
|
||||
export interface OAuthAuthInfo {
|
||||
readonly url: string;
|
||||
readonly instructions: string;
|
||||
readonly userCode?: string;
|
||||
}
|
||||
|
||||
export interface OAuthPrompt {
|
||||
readonly message: string;
|
||||
readonly placeholder?: string;
|
||||
}
|
||||
|
||||
/** How a login flow talks to the terminal (or whatever hosts it). */
|
||||
export interface OAuthLoginCallbacks {
|
||||
/** The URL to open and how to finish there. Called once per flow. */
|
||||
onAuth(info: OAuthAuthInfo): void;
|
||||
/** Asks the user for text: the pasted code when the local callback never arrives. */
|
||||
onPrompt(prompt: OAuthPrompt): Promise<string>;
|
||||
onProgress?(message: string): void;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** The fetch signature AI SDK providers accept. */
|
||||
export type FetchFunction = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
export interface OAuthProvider<Credentials extends OAuthCredentials = OAuthCredentials, LoginOptions = unknown> {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
login(callbacks: OAuthLoginCallbacks, options?: LoginOptions): Promise<Credentials>;
|
||||
/** Renews the credentials, or throws an OAuthError when the user has to sign in again. */
|
||||
refresh(credentials: Credentials): Promise<Credentials>;
|
||||
/**
|
||||
* Sends one API request. It arrives with the bearer token and the user
|
||||
* agent set and the SDK's own key header removed; the provider rewrites the
|
||||
* URL, adds vendor headers, adjusts the body, and reads the answer as the
|
||||
* vendor gives it. Absent, the request goes out as is.
|
||||
*/
|
||||
send?(request: Request, credentials: Credentials, upstream: FetchFunction): Promise<Response>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where credentials live between runs, keyed by provider id. A store holds
|
||||
* whatever each provider's login returned, so a provider reads back its own
|
||||
* shape.
|
||||
*/
|
||||
export interface CredentialStore {
|
||||
get(providerId: string): Promise<OAuthCredentials | undefined>;
|
||||
set(providerId: string, credentials: OAuthCredentials): Promise<void>;
|
||||
remove(providerId: string): Promise<void>;
|
||||
/** Every provider id with stored credentials. */
|
||||
list(): Promise<string[]>;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Live check of a stored login: one forced tool call over a small red image,
|
||||
* the shape the e2e act loop sends. Run by hand after `e2e login <provider>`:
|
||||
* npx tsx tests/live/check.ts copilot claude-sonnet-5
|
||||
* npx tsx tests/live/check.ts chatgpt gpt-5.5
|
||||
* npx tsx tests/live/check.ts grok grok-4
|
||||
*/
|
||||
import { generateText, tool } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import type { LanguageModelV4 } from '@ai-sdk/provider';
|
||||
|
||||
const [kind = 'copilot', modelId] = process.argv.slice(2);
|
||||
const constructors: Record<string, (id: string) => Promise<LanguageModelV4>> = {
|
||||
copilot: async (id) => (await import('../../src/copilot.ts')).copilot(id),
|
||||
chatgpt: async (id) => (await import('../../src/chatgpt.ts')).chatgpt(id),
|
||||
grok: async (id) => (await import('../../src/grok.ts')).grok(id),
|
||||
};
|
||||
const defaults: Record<string, string> = { copilot: 'claude-sonnet-5', chatgpt: 'gpt-5.5', grok: 'grok-4' };
|
||||
const construct = constructors[kind];
|
||||
if (construct === undefined) throw new Error(`unknown kind ${kind}; one of ${Object.keys(constructors).join(', ')}`);
|
||||
const model = await construct(modelId ?? defaults[kind]!);
|
||||
|
||||
// An 8x8 red PNG.
|
||||
const png = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEUlEQVR4nGM4ISeHFTEMLQkAkL9BAbKfPiIAAAAASUVORK5CYII=',
|
||||
'base64',
|
||||
);
|
||||
const started = Date.now();
|
||||
const result = await generateText({
|
||||
model,
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: 'What color is this square? Report it with the tool.' }, { type: 'file', data: png, mediaType: 'image/png' }] }],
|
||||
tools: { report: tool({ inputSchema: z.object({ color: z.string() }) }) },
|
||||
toolChoice: { type: 'tool', toolName: 'report' },
|
||||
});
|
||||
console.log(JSON.stringify({ provider: model.provider, model: model.modelId, ms: Date.now() - started, toolCalls: result.toolCalls.map((c) => ({ name: c.toolName, input: c.input })), usage: result.usage }, null, 2));
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import * as cli from '../../src/cli.ts';
|
||||
|
||||
/** The e2e CLI types this module by hand; the names it calls must exist here. */
|
||||
describe('@e2edev/oauth/cli', () => {
|
||||
it('exports the entry points the e2e CLI calls', () => {
|
||||
expect(typeof cli.runLogin).toBe('function');
|
||||
expect(typeof cli.runLogout).toBe('function');
|
||||
expect(typeof cli.runStatus).toBe('function');
|
||||
});
|
||||
|
||||
it('needs a named provider when there is no terminal to pick in', async () => {
|
||||
const out: string[] = [];
|
||||
const io = { stdout: { write: (chunk: string) => (out.push(chunk), true) } as unknown as NodeJS.WritableStream, stderr: { write: (chunk: string) => (out.push(chunk), true) } as unknown as NodeJS.WritableStream, isTTY: false };
|
||||
expect(await cli.runLogin(undefined, {}, io)).toBe(1);
|
||||
expect(out.join('')).toContain('name a provider: openai, github-copilot, spacexai');
|
||||
});
|
||||
|
||||
it('turns an unknown provider or flag into one error line, not a stack trace', async () => {
|
||||
const out: string[] = [];
|
||||
const io = { stdout: { write: (chunk: string) => (out.push(chunk), true) } as unknown as NodeJS.WritableStream, stderr: { write: (chunk: string) => (out.push(chunk), true) } as unknown as NodeJS.WritableStream, isTTY: false };
|
||||
expect(await cli.runLogout('nope', io)).toBe(1);
|
||||
expect(out.join('')).toContain('name a provider: openai, github-copilot, spacexai');
|
||||
expect(out.join('').split('\n').filter(Boolean)).toHaveLength(1);
|
||||
out.length = 0;
|
||||
expect(await cli.runOAuthCli(['login', 'spacexai', '--bogus'], io)).toBe(1);
|
||||
expect(out.join('')).toMatch(/bogus/);
|
||||
out.length = 0;
|
||||
expect(await cli.runOAuthCli(['logout', 'spacexai', 'extra'], io)).toBe(1);
|
||||
expect(out.join('')).toContain('unexpected argument extra');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { generateText, tool } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { MemoryCredentialStore, copilotBaseUrl, createCopilotProvider, enterpriseHost } from '../../src/index.ts';
|
||||
import { copilot } from '../../src/copilot.ts';
|
||||
import { sendCopilotRequest } from '../../src/providers/github-copilot.ts';
|
||||
import { echoUpstream, json, useServers, type Echo, type Received } from './helpers/server.ts';
|
||||
|
||||
const serve = useServers(afterEach);
|
||||
const noCli = async () => undefined;
|
||||
|
||||
describe('Copilot login', () => {
|
||||
it('runs GitHub\'s device flow with the caller\'s OAuth App and stores a non-expiring token', async () => {
|
||||
let polls = 0;
|
||||
const github = await serve((request, response) => {
|
||||
if (request.url === '/login/device/code') {
|
||||
expect(new URLSearchParams(request.body).get('client_id')).toBe('Iv23_my_app');
|
||||
return json(response, 200, { device_code: 'dc', user_code: 'WXYZ-1234', verification_uri: 'https://github.com/login/device', expires_in: 900, interval: 0.001 });
|
||||
}
|
||||
expect(request.url).toBe('/login/oauth/access_token');
|
||||
const form = new URLSearchParams(request.body);
|
||||
expect(form.get('grant_type')).toBe('urn:ietf:params:oauth:grant-type:device_code');
|
||||
expect(form.get('client_id')).toBe('Iv23_my_app');
|
||||
expect(form.get('device_code')).toBe('dc');
|
||||
polls += 1;
|
||||
// GitHub answers pending with 200 and an error field.
|
||||
json(response, 200, polls < 3 ? { error: 'authorization_pending' } : { access_token: 'gho_token', token_type: 'bearer', scope: 'read:user' });
|
||||
});
|
||||
const provider = createCopilotProvider({ githubUrl: github.url, githubCliToken: noCli });
|
||||
let shown: unknown;
|
||||
const credentials = await provider.login({ onAuth: (info) => (shown = info), onPrompt: async () => '' }, { clientId: 'Iv23_my_app', enterpriseUrl: 'https://gh.acme.com/' });
|
||||
expect(shown).toMatchObject({ url: 'https://github.com/login/device', userCode: 'WXYZ-1234' });
|
||||
expect(credentials).toEqual({ access: 'gho_token', refresh: '', expires: 0, enterpriseUrl: 'gh.acme.com' });
|
||||
});
|
||||
|
||||
it('reuses the GitHub CLI token by default, and explains what it needs when there is none', async () => {
|
||||
const withCli = createCopilotProvider({ githubCliToken: async (hostname) => (hostname === undefined ? 'gho_cli' : undefined) });
|
||||
expect(await withCli.login({ onAuth() {}, onPrompt: async () => '' }, {})).toEqual({ access: 'gho_cli', refresh: '', expires: 0 });
|
||||
await expect(withCli.login({ onAuth() {}, onPrompt: async () => '' }, { enterpriseUrl: 'gh.acme.com' })).rejects.toMatchObject({ code: 'MISCONFIGURED' });
|
||||
await expect(withCli.login({ onAuth() {}, onPrompt: async () => '' }, { clientId: 'Iv23', fromGitHubCli: true })).resolves.toMatchObject({ access: 'gho_cli' });
|
||||
await expect(createCopilotProvider({ githubCliToken: noCli }).login({ onAuth() {}, onPrompt: async () => '' }, {})).rejects.toMatchObject({ code: 'MISCONFIGURED' });
|
||||
});
|
||||
|
||||
it('cannot refresh: a rejected token means signing in again', async () => {
|
||||
await expect(createCopilotProvider().refresh({ access: 'x', refresh: '', expires: 0 })).rejects.toMatchObject({ code: 'LOGIN_REQUIRED' });
|
||||
});
|
||||
|
||||
it('derives the enterprise API host and refuses anything but a plain hostname', async () => {
|
||||
expect(copilotBaseUrl()).toBe('https://api.githubcopilot.com');
|
||||
expect(copilotBaseUrl('https://github.acme.com/')).toBe('https://copilot-api.github.acme.com');
|
||||
expect(enterpriseHost('GitHub.Acme.com')).toBe('github.acme.com');
|
||||
for (const bad of ['evil.com@github.acme.com', 'github.acme.com/path', 'github.acme.com?x=1', 'github.acme.com:8443', 'http://github.acme.com', 'not a host', 'localhost']) {
|
||||
expect(() => enterpriseHost(bad), bad).toThrow(/not a GitHub Enterprise host/);
|
||||
}
|
||||
const provider = createCopilotProvider({ githubCliToken: async () => 'gho' });
|
||||
await expect(provider.login({ onAuth() {}, onPrompt: async () => '' }, { enterpriseUrl: 'evil.com@github.acme.com' })).rejects.toMatchObject({ code: 'MISCONFIGURED' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Copilot requests', () => {
|
||||
it('marks agent turns and image requests, and routes an enterprise login at its host', async () => {
|
||||
const withImage = new Request('https://api.githubcopilot.com/chat/completions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ messages: [{ role: 'user', content: [{ type: 'text', text: 'x' }, { type: 'image_url', image_url: { url: 'data:image/png;base64,AA==' } }] }, { role: 'assistant', content: 'ok' }] }),
|
||||
});
|
||||
const sent = (await (await sendCopilotRequest(withImage, { access: 'a', refresh: '', expires: 0, enterpriseUrl: 'gh.acme.com' }, echoUpstream)).json()) as Echo;
|
||||
expect(sent.url).toBe('https://copilot-api.gh.acme.com/chat/completions');
|
||||
expect(sent.headers).toMatchObject({ 'x-initiator': 'agent', 'copilot-vision-request': 'true', 'openai-intent': 'conversation-edits' });
|
||||
const plain = new Request('https://api.githubcopilot.com/chat/completions', { method: 'POST', body: JSON.stringify({ messages: [{ role: 'user', content: 'hi' }] }) });
|
||||
const sentPlain = (await (await sendCopilotRequest(plain, { access: 'a', refresh: '', expires: 0 }, echoUpstream)).json()) as Echo;
|
||||
expect(sentPlain.url).toBe('https://api.githubcopilot.com/chat/completions');
|
||||
expect(sentPlain.headers['x-initiator']).toBe('user');
|
||||
expect(sentPlain.headers['copilot-vision-request']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('serves generateText over the chat protocol with the stored GitHub token', async () => {
|
||||
let seen: Received | undefined;
|
||||
const api = await serve((request, response) => {
|
||||
seen = request;
|
||||
json(response, 200, {
|
||||
id: 'chatcmpl-1',
|
||||
object: 'chat.completion',
|
||||
created: 1,
|
||||
model: 'gpt-4.1',
|
||||
choices: [{ index: 0, finish_reason: 'tool_calls', message: { role: 'assistant', content: null, tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'report', arguments: '{"color":"red"}' } }] } }],
|
||||
usage: { prompt_tokens: 7, completion_tokens: 3, total_tokens: 10 },
|
||||
});
|
||||
});
|
||||
const store = new MemoryCredentialStore({ 'github-copilot': { access: 'gho_x', refresh: '', expires: 0 } });
|
||||
const model = copilot('gpt-4.1', { store, baseURL: api.url });
|
||||
expect(model).toMatchObject({ provider: 'github-copilot.chat', modelId: 'gpt-4.1' });
|
||||
const result = await generateText({
|
||||
model,
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: 'color?' }, { type: 'file', data: new Uint8Array([137, 80, 78, 71]), mediaType: 'image/png' }] }],
|
||||
tools: { report: tool({ inputSchema: z.object({ color: z.string() }) }) },
|
||||
toolChoice: { type: 'tool', toolName: 'report' },
|
||||
});
|
||||
expect(result.toolCalls[0]).toMatchObject({ toolName: 'report', input: { color: 'red' } });
|
||||
expect(seen!.url).toBe('/chat/completions');
|
||||
expect(seen!.headers['authorization']).toBe('Bearer gho_x');
|
||||
expect(seen!.headers['copilot-vision-request']).toBe('true');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { OAuthError, runDeviceFlow, type DevicePoll } from '../../src/index.ts';
|
||||
|
||||
const authorization = { deviceCode: 'dev', userCode: 'ABCD-1234', verificationUri: 'https://x/device', expiresIn: 60, interval: 5 };
|
||||
|
||||
function flow(polls: DevicePoll<string>[], sleeps: number[]) {
|
||||
const queue = [...polls];
|
||||
let onAuth: unknown;
|
||||
return {
|
||||
run: () =>
|
||||
runDeviceFlow<string>({
|
||||
start: async () => authorization,
|
||||
poll: async () => queue.shift() ?? { status: 'pending' },
|
||||
callbacks: { onAuth: (info) => (onAuth = info), onPrompt: async () => '' },
|
||||
sleep: async (ms) => void sleeps.push(ms),
|
||||
}),
|
||||
info: () => onAuth,
|
||||
};
|
||||
}
|
||||
|
||||
describe('runDeviceFlow', () => {
|
||||
it('polls through pending and slow_down, then returns the grant', async () => {
|
||||
const sleeps: number[] = [];
|
||||
const { run, info } = flow([{ status: 'pending' }, { status: 'slow_down' }, { status: 'pending' }, { status: 'granted', value: 'tok' }], sleeps);
|
||||
await expect(run()).resolves.toBe('tok');
|
||||
expect(info()).toMatchObject({ url: 'https://x/device', userCode: 'ABCD-1234' });
|
||||
// 5 s interval, then +5 s after slow_down.
|
||||
expect(sleeps).toEqual([5000, 5000, 10000, 10000]);
|
||||
});
|
||||
|
||||
it('honours the interval a slow_down names', async () => {
|
||||
const sleeps: number[] = [];
|
||||
const { run } = flow([{ status: 'slow_down', intervalSeconds: 2 }, { status: 'granted', value: 'ok' }], sleeps);
|
||||
await run();
|
||||
expect(sleeps).toEqual([5000, 2000]);
|
||||
});
|
||||
|
||||
it('turns denial and expiry into OAuthErrors', async () => {
|
||||
await expect(flow([{ status: 'denied' }], []).run()).rejects.toMatchObject({ code: 'CANCELLED' });
|
||||
await expect(flow([{ status: 'expired' }], []).run()).rejects.toMatchObject({ code: 'TIMEOUT' });
|
||||
});
|
||||
|
||||
it('stops when the device code lifetime runs out', async () => {
|
||||
let now = 0;
|
||||
const promise = runDeviceFlow<string>({
|
||||
start: async () => ({ ...authorization, expiresIn: 12 }),
|
||||
poll: async () => ({ status: 'pending' }),
|
||||
callbacks: { onAuth() {}, onPrompt: async () => '' },
|
||||
sleep: async (ms) => void (now += ms),
|
||||
now: () => now,
|
||||
});
|
||||
await expect(promise).rejects.toBeInstanceOf(OAuthError);
|
||||
});
|
||||
|
||||
it('stops at an abort signal', async () => {
|
||||
const controller = new AbortController();
|
||||
const promise = runDeviceFlow<string>({
|
||||
start: async () => authorization,
|
||||
poll: async () => ({ status: 'pending' }),
|
||||
callbacks: { onAuth: () => controller.abort(), onPrompt: async () => '', signal: controller.signal },
|
||||
});
|
||||
await expect(promise).rejects.toMatchObject({ code: 'CANCELLED' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { EnvCredentialStore, FileCredentialStore, MemoryCredentialStore, OAuthError, createOAuthFetch, type OAuthCredentials, type OAuthProvider } from '../../src/index.ts';
|
||||
import { json, useServers } from './helpers/server.ts';
|
||||
|
||||
const serve = useServers(afterEach);
|
||||
|
||||
type CountingProvider = OAuthProvider<OAuthCredentials, never> & { refreshes: string[] };
|
||||
|
||||
/** Refreshes rotate the refresh token and reject a token that was already rotated, like SpaceXAI and ChatGPT do. */
|
||||
function provider(overrides: Partial<OAuthProvider<OAuthCredentials, never>> = {}): CountingProvider {
|
||||
const self: CountingProvider = {
|
||||
id: 'test',
|
||||
name: 'Test',
|
||||
refreshes: [],
|
||||
async login() {
|
||||
return { access: 'x', refresh: 'y', expires: 0 };
|
||||
},
|
||||
async refresh(credentials: OAuthCredentials): Promise<OAuthCredentials> {
|
||||
if (self.refreshes.includes(credentials.refresh)) throw new OAuthError('LOGIN_REQUIRED', `refresh token ${credentials.refresh} was already used`);
|
||||
self.refreshes.push(credentials.refresh);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const n = self.refreshes.length;
|
||||
return { access: `fresh-${n}`, refresh: `rt-${n}`, expires: Date.now() + 3_600_000 };
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
return self;
|
||||
}
|
||||
|
||||
describe('createOAuthFetch', () => {
|
||||
it('swaps the SDK key header for the bearer token and names the product', async () => {
|
||||
const api = await serve((_request, response) => json(response, 200, { ok: true }));
|
||||
const store = new MemoryCredentialStore({ test: { access: 'tok', refresh: 'r', expires: 0 } });
|
||||
const fetch = createOAuthFetch(provider(), { store, userAgent: 'my-product/1.0' });
|
||||
const response = await fetch(`${api.url}/v1/thing`, { method: 'POST', headers: { 'x-api-key': 'oauth', authorization: 'Bearer oauth' }, body: '{}' });
|
||||
expect(await response.json()).toEqual({ ok: true });
|
||||
const [request] = api.requests;
|
||||
expect(request?.headers['authorization']).toBe('Bearer tok');
|
||||
expect(request?.headers['x-api-key']).toBeUndefined();
|
||||
expect(request?.headers['user-agent']).toBe('my-product/1.0');
|
||||
expect(request?.body).toBe('{}');
|
||||
});
|
||||
|
||||
it('fails with NOT_LOGGED_IN and the hint when nothing is stored', async () => {
|
||||
const fetch = createOAuthFetch(provider(), { store: new MemoryCredentialStore(), userAgent: 'p', loginHint: 'run e2e login test' });
|
||||
await expect(fetch('http://127.0.0.1:1/')).rejects.toMatchObject({ code: 'NOT_LOGGED_IN', message: expect.stringContaining('run e2e login test') });
|
||||
});
|
||||
|
||||
it('refreshes an expiring token once across model instances that share a store', async () => {
|
||||
const api = await serve((_request, response) => json(response, 200, {}));
|
||||
const store = new MemoryCredentialStore({ test: { access: 'stale', refresh: 'rt-0', expires: Date.now() + 1_000 } });
|
||||
const testProvider = provider();
|
||||
const first = createOAuthFetch(testProvider, { store, userAgent: 'p' });
|
||||
const second = createOAuthFetch(testProvider, { store, userAgent: 'p' });
|
||||
await Promise.all([first(api.url), second(api.url), first(api.url)]);
|
||||
expect(testProvider.refreshes).toEqual(['rt-0']);
|
||||
expect(api.requests.map((request) => request.headers['authorization'])).toEqual(['Bearer fresh-1', 'Bearer fresh-1', 'Bearer fresh-1']);
|
||||
expect(await store.get('test')).toMatchObject({ access: 'fresh-1', refresh: 'rt-1' });
|
||||
});
|
||||
|
||||
it('shares one refresh between separate file stores over the same file', async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'e2e-oauth-fetch-'));
|
||||
try {
|
||||
const file = path.join(dir, 'oauth.json');
|
||||
await new FileCredentialStore(file).set('test', { access: 'stale', refresh: 'rt-0', expires: Date.now() + 1_000 });
|
||||
const api = await serve((_request, response) => json(response, 200, {}));
|
||||
const testProvider = provider();
|
||||
const first = createOAuthFetch(testProvider, { store: new FileCredentialStore(file), userAgent: 'p' });
|
||||
const second = createOAuthFetch(testProvider, { store: new FileCredentialStore(file), userAgent: 'p' });
|
||||
await Promise.all([first(api.url), second(api.url)]);
|
||||
expect(testProvider.refreshes).toEqual(['rt-0']);
|
||||
expect(api.requests.map((request) => request.headers['authorization'])).toEqual(['Bearer fresh-1', 'Bearer fresh-1']);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps credentials it renewed for a source that cannot store them', async () => {
|
||||
const api = await serve((_request, response) => json(response, 200, {}));
|
||||
const store = new EnvCredentialStore(JSON.stringify({ test: { access: 'stale', refresh: 'rt-0', expires: Date.now() + 1_000 } }));
|
||||
const testProvider = provider();
|
||||
const fetch = createOAuthFetch(testProvider, { store, userAgent: 'p' });
|
||||
await fetch(api.url);
|
||||
await fetch(api.url);
|
||||
expect(testProvider.refreshes).toEqual(['rt-0']);
|
||||
expect(api.requests.map((request) => request.headers['authorization'])).toEqual(['Bearer fresh-1', 'Bearer fresh-1']);
|
||||
});
|
||||
|
||||
it('uses the credentials another process stored when its own refresh token was already rotated', async () => {
|
||||
const api = await serve((_request, response) => json(response, 200, {}));
|
||||
const store = new MemoryCredentialStore({ test: { access: 'stale', refresh: 'rt-0', expires: Date.now() + 1_000 } });
|
||||
const testProvider = provider();
|
||||
testProvider.refreshes.push('rt-0');
|
||||
const fetch = createOAuthFetch(testProvider, { store, userAgent: 'p' });
|
||||
// The other process rotated the token and stores it a moment after this one was rejected.
|
||||
setTimeout(() => void store.set('test', { access: 'theirs', refresh: 'rt-1', expires: Date.now() + 3_600_000 }), 300);
|
||||
await fetch(api.url);
|
||||
expect(api.requests[0]?.headers['authorization']).toBe('Bearer theirs');
|
||||
});
|
||||
|
||||
it('retries once with a refreshed token after a 401, also for a Request input', async () => {
|
||||
const api = await serve((request, response) => {
|
||||
if (request.headers['authorization'] === 'Bearer stale') json(response, 401, { error: 'expired' });
|
||||
else json(response, 200, { echo: request.body });
|
||||
});
|
||||
const store = new MemoryCredentialStore({ test: { access: 'stale', refresh: 'rt-0', expires: 0 } });
|
||||
const fetch = createOAuthFetch(provider(), { store, userAgent: 'p' });
|
||||
const response = await fetch(new Request(api.url, { method: 'POST', body: 'payload' }));
|
||||
expect(await response.json()).toEqual({ echo: 'payload' });
|
||||
expect(api.requests).toHaveLength(2);
|
||||
expect(api.requests[1]?.body).toBe('payload');
|
||||
});
|
||||
|
||||
it('does not retry a 401 for a token that cannot be refreshed', async () => {
|
||||
const api = await serve((_request, response) => json(response, 401, {}));
|
||||
const store = new MemoryCredentialStore({ test: { access: 'gh', refresh: '', expires: 0 } });
|
||||
const fetch = createOAuthFetch(provider(), { store, userAgent: 'p' });
|
||||
expect((await fetch(api.url)).status).toBe(401);
|
||||
expect(api.requests).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('lets the provider send the request its own way', async () => {
|
||||
const api = await serve((request, response) => json(response, 200, { path: request.url, marker: request.headers['x-marker'] }));
|
||||
const store = new MemoryCredentialStore({ test: { access: 'tok', refresh: '', expires: 0 } });
|
||||
const fetch = createOAuthFetch(
|
||||
provider({
|
||||
async send(request, credentials, upstream) {
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('x-marker', credentials.access);
|
||||
const response = await upstream(new Request(new URL('/rewritten', request.url), { headers }));
|
||||
return new Response(JSON.stringify({ wrapped: await response.json() }), { status: response.status });
|
||||
},
|
||||
}),
|
||||
{ store, userAgent: 'p' },
|
||||
);
|
||||
expect(await (await fetch(`${api.url}/original`)).json()).toEqual({ wrapped: { path: '/rewritten', marker: 'tok' } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
export interface Received {
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
readonly headers: Record<string, string>;
|
||||
readonly body: string;
|
||||
}
|
||||
|
||||
export type Handler = (request: Received, response: ServerResponse) => void | Promise<void>;
|
||||
|
||||
/** A local HTTP server that records every request and answers through `handler`. */
|
||||
export async function startServer(handler: Handler): Promise<{ url: string; requests: Received[]; close(): Promise<void> }> {
|
||||
const requests: Received[] = [];
|
||||
const server = createServer(async (request: IncomingMessage, response: ServerResponse) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of request) chunks.push(chunk as Buffer);
|
||||
const received: Received = {
|
||||
method: request.method ?? 'GET',
|
||||
url: request.url ?? '/',
|
||||
headers: Object.fromEntries(Object.entries(request.headers).map(([key, value]) => [key, Array.isArray(value) ? value.join(',') : String(value)])),
|
||||
body: Buffer.concat(chunks).toString('utf8'),
|
||||
};
|
||||
requests.push(received);
|
||||
try {
|
||||
await handler(received, response);
|
||||
} catch (error) {
|
||||
// An assertion inside a handler must not hang the client; the rejection still fails the run.
|
||||
if (!response.headersSent) response.writeHead(500, { 'content-type': 'application/json' });
|
||||
response.end();
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
return {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
requests,
|
||||
close: () =>
|
||||
new Promise((resolve) => {
|
||||
server.closeAllConnections();
|
||||
server.close(() => resolve());
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function json(response: ServerResponse, status: number, body: unknown): void {
|
||||
response.writeHead(status, { 'content-type': 'application/json' });
|
||||
response.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
/** A fake JWT with the given payload; signatures are never checked by the package. */
|
||||
export function fakeJwt(payload: Record<string, unknown>): string {
|
||||
const part = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');
|
||||
return `${part({ alg: 'none' })}.${part(payload)}.sig`;
|
||||
}
|
||||
|
||||
/** Closes every server a test started, so a failing assertion never leaks a listener into the next test. */
|
||||
export function useServers(afterEach: (fn: () => Promise<void>) => void) {
|
||||
const servers: Array<{ close(): Promise<void> }> = [];
|
||||
afterEach(async () => {
|
||||
for (const server of servers.splice(0)) await server.close();
|
||||
});
|
||||
return async (handler: Handler) => {
|
||||
const server = await startServer(handler);
|
||||
servers.push(server);
|
||||
return server;
|
||||
};
|
||||
}
|
||||
|
||||
/** A fake vendor that echoes what it was sent. */
|
||||
export async function echoUpstream(input: string | URL | Request): Promise<Response> {
|
||||
const request = input instanceof Request ? input : new Request(input);
|
||||
return new Response(JSON.stringify({ url: request.url, headers: Object.fromEntries(request.headers), body: await request.text() }));
|
||||
}
|
||||
|
||||
export interface Echo {
|
||||
readonly url: string;
|
||||
readonly headers: Record<string, string>;
|
||||
readonly body: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { EnvCredentialStore, MemoryCredentialStore, logout } from '../../src/index.ts';
|
||||
|
||||
describe('logout', () => {
|
||||
it('reports whether a login was stored and writes nothing when there was none', async () => {
|
||||
const store = new MemoryCredentialStore({ spacexai: { access: 'a', refresh: 'r', expires: 0 } });
|
||||
expect(await logout('openai', store)).toBe(false);
|
||||
expect(await logout('spacexai', store)).toBe(true);
|
||||
expect(await store.list()).toEqual([]);
|
||||
// A read-only source is not asked to remove what it does not hold.
|
||||
expect(await logout('openai', new EnvCredentialStore('{}'))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
import { generateText, tool } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { MemoryCredentialStore, createCodexProvider, type CodexCredentials } from '../../src/index.ts';
|
||||
import { chatgpt } from '../../src/chatgpt.ts';
|
||||
import { extractAccountId, parseAuthorizationInput, sendCodexRequest } from '../../src/providers/openai.ts';
|
||||
import { echoUpstream, fakeJwt, json, startServer, useServers, type Echo, type Received } from './helpers/server.ts';
|
||||
|
||||
const serve = useServers(afterEach);
|
||||
|
||||
const idToken = fakeJwt({ 'https://api.openai.com/auth': { chatgpt_account_id: 'acct_123' } });
|
||||
const accessToken = fakeJwt({ 'https://api.openai.com/auth': { chatgpt_compute_residency: 'eu' } });
|
||||
const tokenReply = { access_token: accessToken, refresh_token: 'ref', id_token: idToken, expires_in: 600 };
|
||||
|
||||
/** A free port for the callback server, so the tests never contend with a real Codex login on 1455. */
|
||||
async function freePort(): Promise<number> {
|
||||
const probe = await startServer(() => {});
|
||||
const port = Number(new URL(probe.url).port);
|
||||
await probe.close();
|
||||
return port;
|
||||
}
|
||||
|
||||
/** Simulates the browser returning to the callback server with the given query. */
|
||||
async function browserReturns(authorizeUrl: string, query: Record<string, string>): Promise<Response> {
|
||||
const url = new URL(authorizeUrl);
|
||||
const redirect = new URL(url.searchParams.get('redirect_uri')!);
|
||||
for (const [key, value] of Object.entries(query)) redirect.searchParams.set(key, value === '$state' ? url.searchParams.get('state')! : value);
|
||||
return fetch(redirect);
|
||||
}
|
||||
|
||||
describe('Codex login', () => {
|
||||
it('runs the browser flow: PKCE authorize URL, local callback, code exchange, account id and residency', async () => {
|
||||
const issuer = await serve((request, response) => json(response, request.url === '/oauth/token' ? 200 : 404, tokenReply));
|
||||
const provider = createCodexProvider({ issuer: issuer.url, originator: 'my-tool', callbackPort: await freePort() });
|
||||
let authorize: URL | undefined;
|
||||
let browser: Promise<Response> | undefined;
|
||||
const credentials = await provider.login({
|
||||
onAuth(info) {
|
||||
authorize = new URL(info.url);
|
||||
browser = browserReturns(info.url, { code: 'the-code', state: '$state' });
|
||||
},
|
||||
onPrompt: async () => {
|
||||
throw new Error('should not prompt');
|
||||
},
|
||||
});
|
||||
expect((await browser!).status).toBe(200);
|
||||
expect(authorize!.origin + authorize!.pathname).toBe(`${issuer.url}/oauth/authorize`);
|
||||
expect(authorize!.searchParams.get('originator')).toBe('my-tool');
|
||||
expect(authorize!.searchParams.get('code_challenge_method')).toBe('S256');
|
||||
expect(authorize!.searchParams.get('client_id')).toBe('app_EMoamEEZ73f0CkXaXp7hrann');
|
||||
const exchange = new URLSearchParams(issuer.requests.find((request) => request.url === '/oauth/token')?.body);
|
||||
expect(exchange.get('grant_type')).toBe('authorization_code');
|
||||
expect(exchange.get('code')).toBe('the-code');
|
||||
expect(exchange.get('code_verifier')).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
||||
expect(exchange.get('redirect_uri')).toBe(authorize!.searchParams.get('redirect_uri'));
|
||||
expect(credentials).toMatchObject({ access: accessToken, refresh: 'ref', accountId: 'acct_123', residency: 'eu' });
|
||||
expect(credentials.expires).toBeGreaterThan(Date.now());
|
||||
});
|
||||
|
||||
it('ignores a callback with the wrong state and treats a declined sign-in as cancelled', async () => {
|
||||
const issuer = await serve((_request, response) => json(response, 200, tokenReply));
|
||||
const provider = createCodexProvider({ issuer: issuer.url, callbackPort: await freePort() });
|
||||
const statuses: number[] = [];
|
||||
let browser: Promise<void> | undefined;
|
||||
await expect(
|
||||
provider.login({
|
||||
onAuth(info) {
|
||||
// The bogus callbacks are answered before the decline, which closes the server behind them.
|
||||
browser = (async () => {
|
||||
statuses.push((await browserReturns(info.url, { code: 'stolen', state: 'not-ours' })).status);
|
||||
statuses.push((await browserReturns(info.url, { error: 'x', state: 'not-ours' })).status);
|
||||
statuses.push((await browserReturns(info.url, { error: 'access_denied', state: '$state' })).status);
|
||||
})();
|
||||
},
|
||||
onPrompt: async () => '',
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'CANCELLED' });
|
||||
await browser;
|
||||
expect(statuses).toEqual([400, 400, 400]);
|
||||
expect(issuer.requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('asks for the pasted code when the callback port is taken or the browser never returns', async () => {
|
||||
const issuer = await serve((_request, response) => json(response, 200, tokenReply));
|
||||
const port = await freePort();
|
||||
const squatter = await startServer(() => {});
|
||||
const taken = createCodexProvider({ issuer: issuer.url, callbackPort: Number(new URL(squatter.url).port) });
|
||||
try {
|
||||
const credentials = await taken.login({ onAuth() {}, onPrompt: async () => `http://localhost/auth/callback?code=pasted-code` });
|
||||
expect(credentials.access).toBe(accessToken);
|
||||
expect(new URLSearchParams(issuer.requests.at(-1)?.body).get('code')).toBe('pasted-code');
|
||||
} finally {
|
||||
await squatter.close();
|
||||
}
|
||||
// After the browser fails to return in time, the terminal asks for the URL instead of failing.
|
||||
const slow = createCodexProvider({ issuer: issuer.url, callbackPort: port, loginTimeoutMs: 50 });
|
||||
const pasted = await slow.login({ onAuth() {}, onPrompt: async () => 'late-code' });
|
||||
expect(pasted.access).toBe(accessToken);
|
||||
expect(new URLSearchParams(issuer.requests.at(-1)?.body).get('code')).toBe('late-code');
|
||||
});
|
||||
|
||||
it('is cancelled at once by an already aborted signal and by a malformed callback', async () => {
|
||||
const issuer = await serve((_request, response) => json(response, 200, tokenReply));
|
||||
const provider = createCodexProvider({ issuer: issuer.url, callbackPort: await freePort(), loginTimeoutMs: 60_000 });
|
||||
const aborted = AbortSignal.abort();
|
||||
await expect(provider.login({ onAuth() {}, onPrompt: async () => '', signal: aborted })).rejects.toMatchObject({ code: 'CANCELLED' });
|
||||
await expect(
|
||||
provider.login({
|
||||
onAuth: (info) => void browserReturns(info.url, { state: '$state' }),
|
||||
onPrompt: async () => '',
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'FLOW_FAILED', message: expect.stringContaining('invalid_callback') });
|
||||
});
|
||||
|
||||
it('runs the device flow through OpenAI\'s user-code endpoints', async () => {
|
||||
let polls = 0;
|
||||
const issuer = await serve((request, response) => {
|
||||
if (request.url === '/api/accounts/deviceauth/usercode') return json(response, 200, { device_auth_id: 'dev-1', user_code: 'ABCD-EFGH', interval: '0.001' });
|
||||
if (request.url === '/api/accounts/deviceauth/token') {
|
||||
polls += 1;
|
||||
return polls < 3 ? json(response, 403, {}) : json(response, 200, { authorization_code: 'granted-code', code_verifier: 'verifier' });
|
||||
}
|
||||
if (request.url === '/oauth/token') {
|
||||
const form = new URLSearchParams(request.body);
|
||||
expect(form.get('code')).toBe('granted-code');
|
||||
expect(form.get('code_verifier')).toBe('verifier');
|
||||
expect(form.get('redirect_uri')).toBe(`${issuer.url}/deviceauth/callback`);
|
||||
return json(response, 200, tokenReply);
|
||||
}
|
||||
json(response, 404, {});
|
||||
});
|
||||
const provider = createCodexProvider({ issuer: issuer.url });
|
||||
let shown: unknown;
|
||||
const credentials = await provider.login({ onAuth: (info) => (shown = info), onPrompt: async () => '' }, { method: 'device' });
|
||||
expect(shown).toMatchObject({ url: `${issuer.url}/codex/device`, userCode: 'ABCD-EFGH' });
|
||||
expect(credentials.accountId).toBe('acct_123');
|
||||
});
|
||||
|
||||
it('parses every form the user may paste', () => {
|
||||
expect(parseAuthorizationInput('http://localhost:1455/auth/callback?code=abc&state=st')).toEqual({ code: 'abc', state: 'st' });
|
||||
expect(parseAuthorizationInput('abc#st')).toEqual({ code: 'abc', state: 'st' });
|
||||
expect(parseAuthorizationInput('code=abc&state=st')).toEqual({ code: 'abc', state: 'st' });
|
||||
expect(parseAuthorizationInput(' abc ')).toEqual({ code: 'abc', state: undefined });
|
||||
expect(parseAuthorizationInput('')).toEqual({ code: undefined, state: undefined });
|
||||
});
|
||||
|
||||
it('reads the account id from either token', () => {
|
||||
expect(extractAccountId({ id_token: idToken })).toBe('acct_123');
|
||||
expect(extractAccountId({ access_token: fakeJwt({ organizations: [{ id: 'org_1' }] }) })).toBe('org_1');
|
||||
expect(extractAccountId({ access_token: 'opaque' })).toBeUndefined();
|
||||
});
|
||||
|
||||
it('refreshes keeping the account id and the old refresh token when none comes back, and asks for a new login on a rejected one', async () => {
|
||||
let reply: { status: number; body: unknown } = { status: 200, body: { access_token: 'new', expires_in: 'garbage' } };
|
||||
const issuer = await serve((request, response) => {
|
||||
expect(new URLSearchParams(request.body).get('grant_type')).toBe('refresh_token');
|
||||
json(response, reply.status, reply.body);
|
||||
});
|
||||
const provider = createCodexProvider({ issuer: issuer.url });
|
||||
const renewed = await provider.refresh({ access: 'old', refresh: 'old-r', expires: 0, accountId: 'acct_123', residency: 'eu' });
|
||||
expect(renewed).toMatchObject({ access: 'new', refresh: 'old-r', accountId: 'acct_123', residency: 'eu' });
|
||||
expect(renewed.expires).toBeGreaterThan(Date.now());
|
||||
reply = { status: 400, body: { error: 'invalid_grant' } };
|
||||
await expect(provider.refresh(renewed)).rejects.toMatchObject({ code: 'LOGIN_REQUIRED' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Codex requests', () => {
|
||||
it('routes a Responses request at the Codex backend with the body the backend requires', async () => {
|
||||
const original = new Request('https://api.openai.com/v1/responses', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ model: 'gpt-5.5', input: [], max_output_tokens: 100, include: ['x'] }),
|
||||
});
|
||||
const credentials = { access: 'a', refresh: 'r', expires: 0, accountId: 'acct', residency: 'eu' };
|
||||
const sent = (await (await sendCodexRequest(original, credentials, echoUpstream, { originator: 'e2e', apiUrl: 'https://chatgpt.com/backend-api/codex/responses' })).json()) as Echo;
|
||||
expect(sent.url).toBe('https://chatgpt.com/backend-api/codex/responses');
|
||||
expect(sent.headers).toMatchObject({ 'chatgpt-account-id': 'acct', originator: 'e2e', 'x-openai-internal-codex-residency': 'eu' });
|
||||
expect(JSON.parse(sent.body)).toEqual({ model: 'gpt-5.5', input: [], stream: true, store: false, instructions: 'Follow the user request.', include: ['x', 'reasoning.encrypted_content'] });
|
||||
});
|
||||
|
||||
it('leaves other paths untouched apart from the headers', async () => {
|
||||
const other = new Request('https://api.openai.com/v1/models');
|
||||
const sent = (await (await sendCodexRequest(other, { access: 'a', refresh: 'r', expires: 0 }, echoUpstream, { originator: 'e2e', apiUrl: 'https://c/x' })).json()) as Echo;
|
||||
expect(sent.url).toBe('https://api.openai.com/v1/models');
|
||||
expect(sent.headers).toMatchObject({ originator: 'e2e' });
|
||||
});
|
||||
|
||||
it('serves generateText with a forced tool call from a backend that only streams', async () => {
|
||||
let seen: Received | undefined;
|
||||
const backend = await serve((request, response) => {
|
||||
seen = request;
|
||||
const completed = {
|
||||
id: 'resp_1',
|
||||
object: 'response',
|
||||
created_at: 1,
|
||||
status: 'completed',
|
||||
model: 'gpt-5.5',
|
||||
output: [{ type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'report', arguments: '{"color":"red"}', status: 'completed' }],
|
||||
usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } },
|
||||
};
|
||||
response.writeHead(200, { 'content-type': 'text/event-stream' });
|
||||
response.write(`event: response.created\ndata: ${JSON.stringify({ type: 'response.created', response: { id: 'resp_1' } })}\n\n`);
|
||||
response.write(`event: response.completed\ndata: ${JSON.stringify({ type: 'response.completed', response: completed })}\n\n`);
|
||||
response.end();
|
||||
});
|
||||
const login: CodexCredentials = { access: 'tok', refresh: 'r', expires: 0, accountId: 'acct_9' };
|
||||
const store = new MemoryCredentialStore({ 'openai': login });
|
||||
const model = chatgpt('gpt-5.5', { store, apiUrl: `${backend.url}/codex/responses` });
|
||||
expect(model).toMatchObject({ provider: 'chatgpt.responses', modelId: 'gpt-5.5' });
|
||||
const result = await generateText({
|
||||
model,
|
||||
prompt: 'What color?',
|
||||
tools: { report: tool({ inputSchema: z.object({ color: z.string() }) }) },
|
||||
toolChoice: { type: 'tool', toolName: 'report' },
|
||||
});
|
||||
expect(result.toolCalls[0]).toMatchObject({ toolName: 'report', input: { color: 'red' } });
|
||||
expect(result.usage.inputTokens).toBe(10);
|
||||
const body = JSON.parse(seen!.body) as Record<string, unknown>;
|
||||
expect(body['stream']).toBe(true);
|
||||
expect(body['store']).toBe(false);
|
||||
expect(seen!.headers['authorization']).toBe('Bearer tok');
|
||||
expect(seen!.headers['chatgpt-account-id']).toBe('acct_9');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { foldResponsesStream } from '../../src/index.ts';
|
||||
import { parseSse } from '../../src/sse.ts';
|
||||
|
||||
function sse(events: Array<{ event?: string; data: unknown }>): Response {
|
||||
const text = events.map(({ event, data }) => `${event === undefined ? '' : `event: ${event}\n`}data: ${typeof data === 'string' ? data : JSON.stringify(data)}\n\n`).join('');
|
||||
return new Response(text, { status: 200, headers: { 'content-type': 'text/event-stream' } });
|
||||
}
|
||||
|
||||
describe('foldResponsesStream', () => {
|
||||
it('returns the completed response object as JSON', async () => {
|
||||
const completed = { id: 'resp_1', object: 'response', output: [{ type: 'message', content: [{ type: 'output_text', text: 'hi' }] }], usage: { input_tokens: 1, output_tokens: 2 } };
|
||||
const folded = await foldResponsesStream(
|
||||
sse([
|
||||
{ event: 'response.created', data: { type: 'response.created', response: { id: 'resp_1' } } },
|
||||
{ event: 'response.output_text.delta', data: { type: 'response.output_text.delta', delta: 'hi' } },
|
||||
{ event: 'response.completed', data: { type: 'response.completed', response: completed } },
|
||||
]),
|
||||
);
|
||||
expect(folded.status).toBe(200);
|
||||
expect(folded.headers.get('content-type')).toBe('application/json');
|
||||
expect(await folded.json()).toEqual(completed);
|
||||
});
|
||||
|
||||
it('turns a failed response into an error body', async () => {
|
||||
const folded = await foldResponsesStream(sse([{ data: { type: 'response.failed', response: { error: { code: 'rate_limit_exceeded', message: 'slow down' } } } }]));
|
||||
expect(folded.status).toBe(400);
|
||||
expect(await folded.json()).toEqual({ error: { code: 'rate_limit_exceeded', message: 'slow down' } });
|
||||
});
|
||||
|
||||
it('reports a stream that never completes', async () => {
|
||||
const folded = await foldResponsesStream(sse([{ data: { type: 'response.created' } }, { data: '[DONE]' }]));
|
||||
expect(folded.status).toBe(502);
|
||||
});
|
||||
|
||||
it('passes through non-stream and error responses untouched', async () => {
|
||||
const plain = new Response('{"a":1}', { status: 200, headers: { 'content-type': 'application/json' } });
|
||||
expect(await foldResponsesStream(plain)).toBe(plain);
|
||||
const error = new Response('nope', { status: 429, headers: { 'content-type': 'text/event-stream' } });
|
||||
expect(await foldResponsesStream(error)).toBe(error);
|
||||
});
|
||||
|
||||
it('parses CRLF streams and multi-line data', () => {
|
||||
expect(parseSse('event: a\r\ndata: 1\r\ndata: 2\r\n\r\ndata: {"b":1}\r\n\r\n')).toEqual([{ event: 'a', data: '1\n2' }, { data: '{"b":1}' }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { CREDENTIALS_ENV, EnvCredentialStore, FileCredentialStore, defaultCredentialStore, defaultCredentialsPath } from '../../src/index.ts';
|
||||
|
||||
const dirs: string[] = [];
|
||||
function tempFile(): string {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'e2e-oauth-'));
|
||||
dirs.push(dir);
|
||||
return path.join(dir, 'nested', 'oauth.json');
|
||||
}
|
||||
afterEach(() => {
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const creds = { access: 'a', refresh: 'r', expires: 123, accountId: 'acct' };
|
||||
|
||||
describe('FileCredentialStore', () => {
|
||||
it('creates the file with owner-only permissions and round-trips entries', async () => {
|
||||
const file = tempFile();
|
||||
const store = new FileCredentialStore(file);
|
||||
expect(await store.get('spacexai')).toBeUndefined();
|
||||
await store.set('spacexai', creds);
|
||||
expect(statSync(file).mode & 0o777).toBe(0o600);
|
||||
expect(statSync(path.dirname(file)).mode & 0o777).toBe(0o700);
|
||||
expect(await store.get('spacexai')).toEqual(creds);
|
||||
expect(await store.list()).toEqual(['spacexai']);
|
||||
await store.remove('spacexai');
|
||||
expect(await store.list()).toEqual([]);
|
||||
expect(readFileSync(file, 'utf8')).toBe('{}\n');
|
||||
expect(() => statSync(`${file}.lock`)).toThrow();
|
||||
});
|
||||
|
||||
it('keeps other providers when one is written, even from concurrent writers', async () => {
|
||||
const file = tempFile();
|
||||
const a = new FileCredentialStore(file);
|
||||
const b = new FileCredentialStore(file);
|
||||
await Promise.all([a.set('a', creds), b.set('b', { ...creds, access: 'b' }), a.set('c', { ...creds, access: 'c' })]);
|
||||
expect((await a.list()).toSorted()).toEqual(['a', 'b', 'c']);
|
||||
expect((await b.get('b'))?.access).toBe('b');
|
||||
});
|
||||
|
||||
it('defers a writer while another process holds the lock', async () => {
|
||||
const file = tempFile();
|
||||
const store = new FileCredentialStore(file);
|
||||
await store.set('x', creds);
|
||||
writeFileSync(`${file}.lock`, '');
|
||||
let settled = false;
|
||||
const pending = store.set('y', creds).then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
expect(settled).toBe(false);
|
||||
rmSync(`${file}.lock`, { force: true });
|
||||
await pending;
|
||||
expect((await store.list()).toSorted()).toEqual(['x', 'y']);
|
||||
});
|
||||
|
||||
it('tightens the permissions of a directory and file that already existed', async () => {
|
||||
const file = tempFile();
|
||||
const { mkdirSync, chmodSync } = await import('node:fs');
|
||||
mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
|
||||
writeFileSync(file, '{}', { mode: 0o644 });
|
||||
chmodSync(file, 0o644);
|
||||
await new FileCredentialStore(file).set('x', creds);
|
||||
expect(statSync(path.dirname(file)).mode & 0o777).toBe(0o700);
|
||||
expect(statSync(file).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it('takes over a stale lock left by a dead process', async () => {
|
||||
const file = tempFile();
|
||||
const store = new FileCredentialStore(file);
|
||||
await store.set('x', creds);
|
||||
writeFileSync(`${file}.lock`, '');
|
||||
const old = Date.now() / 1000 - 60;
|
||||
const { utimesSync } = await import('node:fs');
|
||||
utimesSync(`${file}.lock`, old, old);
|
||||
await store.set('y', creds);
|
||||
expect((await store.list()).toSorted()).toEqual(['x', 'y']);
|
||||
});
|
||||
|
||||
it('drops a damaged entry instead of losing every login', async () => {
|
||||
const file = tempFile();
|
||||
const store = new FileCredentialStore(file);
|
||||
await store.set('x', creds);
|
||||
writeFileSync(file, JSON.stringify({ x: creds, broken: { access: 1 }, nan: { access: 'a', refresh: 'r', expires: null } }));
|
||||
expect(await store.list()).toEqual(['x']);
|
||||
expect(await store.get('broken')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('defaults to the XDG config directory', () => {
|
||||
expect(defaultCredentialsPath({ XDG_CONFIG_HOME: '/tmp/xdg' })).toBe('/tmp/xdg/e2e/oauth.json');
|
||||
expect(defaultCredentialsPath({})).toMatch(/\.config\/e2e\/oauth\.json$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EnvCredentialStore', () => {
|
||||
it('is chosen when the variable is set, reads it, and refuses to change it', async () => {
|
||||
const store = defaultCredentialStore({ [CREDENTIALS_ENV]: JSON.stringify({ 'github-copilot': creds }) });
|
||||
expect(store).toBeInstanceOf(EnvCredentialStore);
|
||||
expect(await store.get('github-copilot')).toEqual(creds);
|
||||
expect(await store.list()).toEqual(['github-copilot']);
|
||||
await expect(store.set('spacexai', creds)).rejects.toMatchObject({ code: 'MISCONFIGURED', message: expect.stringContaining(CREDENTIALS_ENV) });
|
||||
await expect(store.remove('github-copilot')).rejects.toMatchObject({ code: 'MISCONFIGURED' });
|
||||
expect(defaultCredentialStore({ [CREDENTIALS_ENV]: '' })).toBeInstanceOf(FileCredentialStore);
|
||||
});
|
||||
|
||||
it('rejects malformed JSON naming the variable', () => {
|
||||
expect(() => new EnvCredentialStore('nope')).toThrow(new RegExp(`${CREDENTIALS_ENV} is not valid JSON`));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { generateText } from 'ai';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { MemoryCredentialStore, createXaiProvider } from '../../src/index.ts';
|
||||
import { grok } from '../../src/grok.ts';
|
||||
import { fakeJwt, json, useServers, type Received } from './helpers/server.ts';
|
||||
|
||||
const serve = useServers(afterEach);
|
||||
|
||||
describe('SpaceXAI login', () => {
|
||||
it('runs the RFC 8628 device flow against auth.x.ai and reads expiry from the JWT', async () => {
|
||||
const exp = Math.floor(Date.now() / 1000) + 900;
|
||||
let polls = 0;
|
||||
const issuer = await serve((request, response) => {
|
||||
const form = new URLSearchParams(request.body);
|
||||
if (request.url === '/oauth2/device/code') {
|
||||
expect(form.get('client_id')).toBe('b1a00492-073a-47ea-816f-4c329264a828');
|
||||
expect(form.get('scope')).toContain('grok-cli:access');
|
||||
expect(form.get('referrer')).toBe('my-tool');
|
||||
return json(response, 200, { device_code: 'dc', user_code: 'ABCD-EFGH', verification_uri: 'https://accounts.x.ai/oauth2/device', verification_uri_complete: 'https://accounts.x.ai/oauth2/device?user_code=ABCD-EFGH', expires_in: 1800, interval: 0.001 });
|
||||
}
|
||||
expect(form.get('grant_type')).toBe('urn:ietf:params:oauth:grant-type:device_code');
|
||||
polls += 1;
|
||||
// SpaceXAI answers pending with 400 and an error field.
|
||||
if (polls === 1) json(response, 400, { error: 'authorization_pending', error_description: 'User has not yet authorized' });
|
||||
else if (polls === 2) json(response, 400, { error: 'slow_down' });
|
||||
else json(response, 200, { access_token: fakeJwt({ exp }), refresh_token: 'rt-1', expires_in: 900 });
|
||||
});
|
||||
const provider = createXaiProvider({ issuer: issuer.url, referrer: 'my-tool' });
|
||||
let shown: unknown;
|
||||
const credentials = await provider.login({ onAuth: (info) => (shown = info), onPrompt: async () => '' });
|
||||
expect(shown).toMatchObject({ url: 'https://accounts.x.ai/oauth2/device?user_code=ABCD-EFGH', userCode: 'ABCD-EFGH' });
|
||||
expect(credentials).toEqual({ access: fakeJwt({ exp }), refresh: 'rt-1', expires: exp * 1000 });
|
||||
});
|
||||
|
||||
it('refreshes with rotation and keeps the old refresh token when none is returned', async () => {
|
||||
let rotate = true;
|
||||
const issuer = await serve((request, response) => {
|
||||
const form = new URLSearchParams(request.body);
|
||||
expect(form.get('grant_type')).toBe('refresh_token');
|
||||
expect(form.get('refresh_token')).toBe(rotate ? 'rt-1' : 'rt-2');
|
||||
json(response, 200, rotate ? { access_token: 'a2', refresh_token: 'rt-2', expires_in: 60 } : { access_token: 'a3', expires_in: 60 });
|
||||
});
|
||||
const provider = createXaiProvider({ issuer: issuer.url });
|
||||
const second = await provider.refresh({ access: 'a1', refresh: 'rt-1', expires: 0 });
|
||||
expect(second).toMatchObject({ access: 'a2', refresh: 'rt-2' });
|
||||
rotate = false;
|
||||
expect(await provider.refresh(second)).toMatchObject({ access: 'a3', refresh: 'rt-2' });
|
||||
});
|
||||
|
||||
it('serves generateText with the bearer token against the SpaceXAI API', async () => {
|
||||
let seen: Received | undefined;
|
||||
const api = await serve((request, response) => {
|
||||
seen = request;
|
||||
if (request.url.endsWith('/responses')) {
|
||||
return json(response, 200, {
|
||||
id: 'resp_1',
|
||||
object: 'response',
|
||||
created_at: 1,
|
||||
status: 'completed',
|
||||
model: 'grok-4',
|
||||
output: [{ type: 'message', id: 'msg_1', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'hello', annotations: [] }] }],
|
||||
usage: { input_tokens: 3, output_tokens: 1, total_tokens: 4 },
|
||||
});
|
||||
}
|
||||
json(response, 200, {
|
||||
id: 'c1',
|
||||
object: 'chat.completion',
|
||||
created: 1,
|
||||
model: 'grok-4',
|
||||
choices: [{ index: 0, finish_reason: 'stop', message: { role: 'assistant', content: 'hello' } }],
|
||||
usage: { prompt_tokens: 3, completion_tokens: 1, total_tokens: 4 },
|
||||
});
|
||||
});
|
||||
const store = new MemoryCredentialStore({ spacexai: { access: 'xai-tok', refresh: 'rt', expires: 0 } });
|
||||
const model = grok('grok-4', { store, baseURL: api.url });
|
||||
expect(model).toMatchObject({ modelId: 'grok-4' });
|
||||
expect(model.provider).toMatch(/^xai/);
|
||||
const result = await generateText({ model, prompt: 'hi' });
|
||||
expect(result.text).toBe('hello');
|
||||
expect(seen!.headers['authorization']).toBe('Bearer xai-tok');
|
||||
expect(seen!.headers['user-agent']).toMatch(/^e2e-oauth\/\d+\.\d+\.\d+\S* \(\w+; \w+\)$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"noEmit": false,
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"declarationMap": true
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "tests/**/*.ts"],
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
/** Unit tests: local HTTP servers stand in for the issuers and APIs, no network. */
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/unit/**/*.test.ts'],
|
||||
testTimeout: 30_000,
|
||||
pool: 'forks',
|
||||
},
|
||||
});
|
||||
Generated
+119
@@ -355,6 +355,40 @@ importers:
|
||||
specifier: 7.0.2
|
||||
version: 7.0.2
|
||||
|
||||
packages/oauth:
|
||||
dependencies:
|
||||
'@ai-sdk/provider':
|
||||
specifier: 4.0.17
|
||||
version: 4.0.17
|
||||
'@clack/prompts':
|
||||
specifier: 1.8.0
|
||||
version: 1.8.0
|
||||
devDependencies:
|
||||
'@ai-sdk/openai':
|
||||
specifier: 4.0.69
|
||||
version: 4.0.69(zod@4.6.1)
|
||||
'@ai-sdk/openai-compatible':
|
||||
specifier: 3.0.51
|
||||
version: 3.0.51(zod@4.6.1)
|
||||
'@ai-sdk/xai':
|
||||
specifier: 5.0.2
|
||||
version: 5.0.2(zod@4.6.1)
|
||||
'@types/node':
|
||||
specifier: 26.4.1
|
||||
version: 26.4.1
|
||||
ai:
|
||||
specifier: 7.0.105
|
||||
version: 7.0.105(zod@4.6.1)
|
||||
typescript:
|
||||
specifier: 7.0.2
|
||||
version: 7.0.2
|
||||
vitest:
|
||||
specifier: 5.0.0
|
||||
version: 5.0.0(@types/node@26.4.1)(vite@8.1.5(@types/node@26.4.1)(esbuild@0.28.2)(jiti@1.21.7)(tsx@4.23.13)(yaml@2.9.0))
|
||||
zod:
|
||||
specifier: 4.6.1
|
||||
version: 4.6.1
|
||||
|
||||
packages/playwright:
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
@@ -457,22 +491,56 @@ packages:
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@ai-sdk/gateway@4.0.85':
|
||||
resolution: {integrity: sha512-c8ztST/CslupqO3p7izsAuG3TlKg9mhE6mGJ42iUADsSMJIV5IOKd9AsLG33QCAY7SWs6NDO2giM/rq7bUTNlQ==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@ai-sdk/openai-compatible@3.0.47':
|
||||
resolution: {integrity: sha512-6w3ymyP2KV4qzKlMH/Fm6Tmk+2ksiqktZFBbKCGIaoPSBWX+M4HmMW0BFUh9Ar0CtjOia3E8GlYAoEERONuhyg==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@ai-sdk/openai-compatible@3.0.51':
|
||||
resolution: {integrity: sha512-zgVSj3dsvH8hNgorFA1Be/uk2+4W0cYTeSrOfqkc95g4SeomsuGepJQoi3Uefdfs8WyWxMjypJgUIAum0f8dCQ==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@ai-sdk/openai@4.0.69':
|
||||
resolution: {integrity: sha512-HAKua/QVNjwsBpJE3SUGLEPCSRThOLiiOy92gsUOkX4ZnEJHubkR6REHvi4RGGIn97lYBma+mq3BjBqgyNuhwQ==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@ai-sdk/provider-utils@5.0.39':
|
||||
resolution: {integrity: sha512-VIFp4Qv3j+V941crFB1y2VG5yeGbeLOFRxiPaZJETkkpo1H5WviLx6H5yRkFkrXIGxnTGygKsPgCAJG0X61Auw==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@ai-sdk/provider-utils@5.0.43':
|
||||
resolution: {integrity: sha512-gw/bcNseOGSs59TMtV4H1KwqXXe24NHgx+uBYr98pa4Fg6Uvp8hPPxjuckVnfFFyIxHCDew8so0ujpvcSuyMZA==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@ai-sdk/provider@4.0.13':
|
||||
resolution: {integrity: sha512-sJvnbFIFLzmKFXIjfwS8XCOAj6puHCawItwvA9PBZgk2f/l/TiC4OSfK3ueDbUVXfRCOn5eJN97EIF10toIOmQ==}
|
||||
engines: {node: '>=22'}
|
||||
|
||||
'@ai-sdk/provider@4.0.17':
|
||||
resolution: {integrity: sha512-VYMBxIQdcHqbIf1j+YZlI9Ati6LZ4wJe0GGd4z4a5H/KxTggjeOiyaVYTnfF7LHZK5jMQ+rofmzz4QPqf++NUw==}
|
||||
engines: {node: '>=22'}
|
||||
|
||||
'@ai-sdk/xai@5.0.2':
|
||||
resolution: {integrity: sha512-KVQscOx90KrIQauNua0Dh9jKNEPktqR7SSb2NKKkr1FkTUcKkVGKNDh2dOXtaD+AR5V9+ULe4UhplLvzwY+EKQ==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
'@alcalzone/ansi-tokenize@0.2.5':
|
||||
resolution: {integrity: sha512-3NX/MpTdroi0aKz134A6RC2Gb2iXVECN4QaAXnvCIxxIm3C3AVB1mkUe8NaaiyvOpDfsrqWhYtj+Q6a62RrTsw==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -2900,6 +2968,12 @@ packages:
|
||||
resolution: {integrity: sha512-0poP0T7el6Vq3rstR8Mn4V/IQrpBLO6POkUSrN7RhyY+GF/InCFShQzsQ39T25gkHhLgSLByyAz+Kjb+c2L98w==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
ai@7.0.105:
|
||||
resolution: {integrity: sha512-gkV3W+tTtWwQ41KNV/KjV8wabBrk+bnbnZ3f0AWp/T9LLyljose8uhFViKleVy7tIdEiR2PiS4BpbNdcExf7rQ==}
|
||||
engines: {node: '>=22'}
|
||||
peerDependencies:
|
||||
zod: ^3.25.76 || ^4.1.8
|
||||
|
||||
ai@7.0.97:
|
||||
resolution: {integrity: sha512-tQGZ234p/bk5X/LNQdB43a5/z1Bve7wK0EOR1AwN6xrosZih4MIC/3pXhcnytcpBJHMbhLISW6J1dFTd/tnwPA==}
|
||||
engines: {node: '>=22'}
|
||||
@@ -7152,12 +7226,31 @@ snapshots:
|
||||
'@vercel/oidc': 3.2.0
|
||||
zod: 4.6.1
|
||||
|
||||
'@ai-sdk/gateway@4.0.85(zod@4.6.1)':
|
||||
dependencies:
|
||||
'@ai-sdk/provider': 4.0.17
|
||||
'@ai-sdk/provider-utils': 5.0.43(zod@4.6.1)
|
||||
'@vercel/oidc': 3.2.0
|
||||
zod: 4.6.1
|
||||
|
||||
'@ai-sdk/openai-compatible@3.0.47(zod@4.6.1)':
|
||||
dependencies:
|
||||
'@ai-sdk/provider': 4.0.13
|
||||
'@ai-sdk/provider-utils': 5.0.39(zod@4.6.1)
|
||||
zod: 4.6.1
|
||||
|
||||
'@ai-sdk/openai-compatible@3.0.51(zod@4.6.1)':
|
||||
dependencies:
|
||||
'@ai-sdk/provider': 4.0.17
|
||||
'@ai-sdk/provider-utils': 5.0.43(zod@4.6.1)
|
||||
zod: 4.6.1
|
||||
|
||||
'@ai-sdk/openai@4.0.69(zod@4.6.1)':
|
||||
dependencies:
|
||||
'@ai-sdk/provider': 4.0.17
|
||||
'@ai-sdk/provider-utils': 5.0.43(zod@4.6.1)
|
||||
zod: 4.6.1
|
||||
|
||||
'@ai-sdk/provider-utils@5.0.39(zod@4.6.1)':
|
||||
dependencies:
|
||||
'@ai-sdk/provider': 4.0.13
|
||||
@@ -7167,10 +7260,29 @@ snapshots:
|
||||
undici: 7.29.1
|
||||
zod: 4.6.1
|
||||
|
||||
'@ai-sdk/provider-utils@5.0.43(zod@4.6.1)':
|
||||
dependencies:
|
||||
'@ai-sdk/provider': 4.0.17
|
||||
'@standard-schema/spec': 1.1.0
|
||||
'@workflow/serde': 4.1.0
|
||||
eventsource-parser: 3.1.1
|
||||
undici: 7.29.1
|
||||
zod: 4.6.1
|
||||
|
||||
'@ai-sdk/provider@4.0.13':
|
||||
dependencies:
|
||||
json-schema: 0.4.0
|
||||
|
||||
'@ai-sdk/provider@4.0.17':
|
||||
dependencies:
|
||||
json-schema: 0.4.0
|
||||
|
||||
'@ai-sdk/xai@5.0.2(zod@4.6.1)':
|
||||
dependencies:
|
||||
'@ai-sdk/provider': 4.0.17
|
||||
'@ai-sdk/provider-utils': 5.0.43(zod@4.6.1)
|
||||
zod: 4.6.1
|
||||
|
||||
'@alcalzone/ansi-tokenize@0.2.5':
|
||||
dependencies:
|
||||
ansi-styles: 6.2.3
|
||||
@@ -10032,6 +10144,13 @@ snapshots:
|
||||
clean-stack: 4.2.0
|
||||
indent-string: 5.0.0
|
||||
|
||||
ai@7.0.105(zod@4.6.1):
|
||||
dependencies:
|
||||
'@ai-sdk/gateway': 4.0.85(zod@4.6.1)
|
||||
'@ai-sdk/provider': 4.0.17
|
||||
'@ai-sdk/provider-utils': 5.0.43(zod@4.6.1)
|
||||
zod: 4.6.1
|
||||
|
||||
ai@7.0.97(zod@4.6.1):
|
||||
dependencies:
|
||||
'@ai-sdk/gateway': 4.0.78(zod@4.6.1)
|
||||
|
||||
Reference in New Issue
Block a user