opencode-devin 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,43 +0,0 @@
1
- /**
2
- * Token exchange: `POST {authApi}/auth/cli/token {code, code_verifier}`.
3
- *
4
- * Returns the token in the `devin-session-token$<jwt>` form opencode stores
5
- * and sends as the bearer credential. Never echoes the code or token.
6
- */
7
- import { AUTH_API_URL, TOKEN_PREFIX } from "../constants.js";
8
- export class DevinAuthError extends Error {
9
- status;
10
- constructor(message, status) {
11
- super(message);
12
- this.name = "DevinAuthError";
13
- this.status = status;
14
- }
15
- }
16
- /** Exchange a PKCE authorization code for the long-lived session token. */
17
- export async function exchangeCode(input) {
18
- const response = await fetch(`${AUTH_API_URL}/auth/cli/token`, {
19
- method: "POST",
20
- headers: { "Content-Type": "application/json", Accept: "application/json" },
21
- body: JSON.stringify({ code: input.code, code_verifier: input.verifier }),
22
- signal: AbortSignal.timeout(30_000),
23
- }).catch((cause) => {
24
- throw new DevinAuthError(`Token exchange request to ${AUTH_API_URL} failed: ${String(cause)}`, 0);
25
- });
26
- const text = await response.text();
27
- if (!response.ok) {
28
- let message = text || `Token exchange failed with HTTP ${response.status}`;
29
- try {
30
- const err = JSON.parse(text);
31
- if (err.message)
32
- message = err.message;
33
- }
34
- catch {
35
- // non-JSON body — keep the raw text
36
- }
37
- throw new DevinAuthError(message, response.status);
38
- }
39
- const token = JSON.parse(text).token;
40
- if (!token)
41
- throw new DevinAuthError("Token exchange succeeded but the response had no token", response.status);
42
- return `${TOKEN_PREFIX}${token}`;
43
- }
@@ -1,15 +0,0 @@
1
- import { type CallbackServer } from "./loopback.ts";
2
- export interface LoginFlow {
3
- /** URL to open in the browser. */
4
- url: string;
5
- /** Resolve with the authorization code (auto: wait for redirect; code: pass the pasted code). */
6
- finish: (code?: string) => Promise<string>;
7
- /** Abort the flow and release resources. */
8
- close: () => void;
9
- }
10
- /** Start an automatic login: binds the loopback server and returns the URL to open. */
11
- export declare function loginAuto(): Promise<LoginFlow & {
12
- server: CallbackServer;
13
- }>;
14
- /** Start a manual login: no loopback; the webapp displays the code for pasting. */
15
- export declare function loginManual(): Promise<LoginFlow>;
@@ -1,51 +0,0 @@
1
- /**
2
- * Devin CLI login flow (PKCE), shared by the plugin's `/connect` methods and
3
- * the standalone `scripts/devin.ts login` command.
4
- *
5
- * Two modes, matching what the webapp supports:
6
- * - "auto": loopback callback — browser redirects to 127.0.0.1, we capture
7
- * the code. Hands-free once the user finishes the web login.
8
- * - "code": no redirect_uri — the webapp shows a code the user pastes back.
9
- * Fallback for headless machines and environments where loopback
10
- * redirects can't reach the browser.
11
- */
12
- import { authorizeUrl } from "./url.js";
13
- import { exchangeCode } from "./exchange.js";
14
- import { startCallbackServer } from "./loopback.js";
15
- import { challengeFor, generateState, generateVerifier } from "./pkce.js";
16
- /** Start an automatic login: binds the loopback server and returns the URL to open. */
17
- export async function loginAuto() {
18
- const verifier = generateVerifier();
19
- const state = generateState();
20
- const server = await startCallbackServer(state);
21
- const url = authorizeUrl({ state, challenge: await challengeFor(verifier), redirectUri: server.redirectUri });
22
- return {
23
- url,
24
- server,
25
- finish: async () => {
26
- try {
27
- const code = await server.code;
28
- return await exchangeCode({ code, verifier });
29
- }
30
- finally {
31
- server.close();
32
- }
33
- },
34
- close: () => server.close(),
35
- };
36
- }
37
- /** Start a manual login: no loopback; the webapp displays the code for pasting. */
38
- export async function loginManual() {
39
- const verifier = generateVerifier();
40
- const state = generateState();
41
- const url = authorizeUrl({ state, challenge: await challengeFor(verifier) });
42
- return {
43
- url,
44
- finish: async (code) => {
45
- if (!code?.trim())
46
- throw new Error("Manual login requires the pasted authorization code");
47
- return exchangeCode({ code: code.trim(), verifier });
48
- },
49
- close: () => { },
50
- };
51
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * Loopback callback server for the Devin CLI login flow.
3
- *
4
- * Binds first so the redirect port is known before the sign-in URL is
5
- * returned, and pre-registers the waiter before the browser opens — a cached
6
- * app.devin.ai session can round-trip fast enough to hit `/callback` before
7
- * the caller awaits the promise.
8
- */
9
- export interface CallbackServer {
10
- redirectUri: string;
11
- code: Promise<string>;
12
- close: () => void;
13
- }
14
- /** Bind a one-shot HTTP server and wait for the authorization code. */
15
- export declare function startCallbackServer(state: string, timeoutMs?: number): Promise<CallbackServer>;
@@ -1,93 +0,0 @@
1
- /**
2
- * Loopback callback server for the Devin CLI login flow.
3
- *
4
- * Binds first so the redirect port is known before the sign-in URL is
5
- * returned, and pre-registers the waiter before the browser opens — a cached
6
- * app.devin.ai session can round-trip fast enough to hit `/callback` before
7
- * the caller awaits the promise.
8
- */
9
- import { CALLBACK_PATH } from "../constants.js";
10
- /**
11
- * How long the loopback listener stays armed waiting for the browser redirect.
12
- *
13
- * The integration method registration has no cancellation hook, so an
14
- * abandoned sign-in (tab closed, user picked the paste-code method instead)
15
- * would otherwise leave the port bound and the HTTP server running for the
16
- * life of the process. This timer is the only place that can be cleaned up
17
- * from, so it is the backstop. Long enough for a real interactive login
18
- * including any second factor.
19
- */
20
- const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
21
- /** Bind a one-shot HTTP server and wait for the authorization code. */
22
- export function startCallbackServer(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
23
- return new Promise((resolve, reject) => {
24
- let settle;
25
- let fail;
26
- const code = new Promise((res, rej) => {
27
- settle = res;
28
- fail = rej;
29
- });
30
- let timer;
31
- let stopped = false;
32
- const clearTimer = () => {
33
- if (timer)
34
- clearTimeout(timer);
35
- timer = undefined;
36
- };
37
- const stop = () => {
38
- if (stopped)
39
- return;
40
- stopped = true;
41
- clearTimer();
42
- server.stop(true);
43
- };
44
- let server;
45
- try {
46
- server = Bun.serve({
47
- hostname: "127.0.0.1",
48
- port: 0,
49
- async fetch(req) {
50
- const url = new URL(req.url);
51
- const page = (title, body, status = 200) => new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head>` +
52
- `<body style="font-family:system-ui;margin:3rem"><h1>${title}</h1><p>${body}</p></body></html>`, { status, headers: { "Content-Type": "text/html; charset=utf-8" } });
53
- if (url.pathname !== CALLBACK_PATH) {
54
- return page("Not found", "", 404);
55
- }
56
- if (url.searchParams.get("state") !== state) {
57
- return page("Invalid state parameter", "This may indicate a security issue. Please try again.", 400);
58
- }
59
- const received = url.searchParams.get("code");
60
- if (!received) {
61
- return page("No authorization code received", "Please return to the terminal and try again.", 400);
62
- }
63
- settle?.(received);
64
- // Stopping here would kill the listener before this response is
65
- // delivered, so the success page would never reach the browser.
66
- // The caller closes the server once the code is exchanged.
67
- clearTimer();
68
- return page("Signed in to Devin", "You can close this tab and return to opencode.");
69
- },
70
- });
71
- }
72
- catch (cause) {
73
- reject(cause instanceof Error ? cause : new Error("Failed to bind loopback callback server"));
74
- return;
75
- }
76
- // Armed before the caller can learn the redirect URI, so there is no
77
- // window in which a completed redirect would leave the timer running.
78
- timer = setTimeout(() => {
79
- const label = timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)}s` : `${timeoutMs}ms`;
80
- fail?.(new Error(`Login timed out after ${label}`));
81
- stop();
82
- }, timeoutMs);
83
- resolve({
84
- // The server is listening at this point, so the port is always set.
85
- redirectUri: `http://127.0.0.1:${server.port}${CALLBACK_PATH}`,
86
- code,
87
- close: () => {
88
- fail?.(new Error("Login cancelled"));
89
- stop();
90
- },
91
- });
92
- });
93
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * PKCE (S256) helpers, matching the Devin CLI (chisel): 32 random bytes,
3
- * base64url-encoded, and a base64url SHA-256 challenge derived from the
4
- * verifier.
5
- */
6
- /** PKCE code verifier: 32 random bytes, base64url without padding. */
7
- export declare function generateVerifier(): string;
8
- /** S256 challenge: base64url(sha256(verifier)). */
9
- export declare function challengeFor(verifier: string): Promise<string>;
10
- /** CSRF state token. */
11
- export declare function generateState(): string;
package/dist/auth/pkce.js DELETED
@@ -1,27 +0,0 @@
1
- /**
2
- * PKCE (S256) helpers, matching the Devin CLI (chisel): 32 random bytes,
3
- * base64url-encoded, and a base64url SHA-256 challenge derived from the
4
- * verifier.
5
- */
6
- const encoder = new TextEncoder();
7
- function base64url(bytes) {
8
- return Buffer.from(bytes).toString("base64url");
9
- }
10
- function randomToken() {
11
- const bytes = new Uint8Array(32);
12
- crypto.getRandomValues(bytes);
13
- return base64url(bytes);
14
- }
15
- /** PKCE code verifier: 32 random bytes, base64url without padding. */
16
- export function generateVerifier() {
17
- return randomToken();
18
- }
19
- /** S256 challenge: base64url(sha256(verifier)). */
20
- export async function challengeFor(verifier) {
21
- const digest = await crypto.subtle.digest("SHA-256", encoder.encode(verifier));
22
- return base64url(new Uint8Array(digest));
23
- }
24
- /** CSRF state token. */
25
- export function generateState() {
26
- return randomToken();
27
- }
@@ -1,12 +0,0 @@
1
- /**
2
- * Devin CLI login URL (`{webapp}/auth/cli/continue`).
3
- *
4
- * With `redirect_uri` the webapp redirects the browser back to our loopback
5
- * server; without it, the webapp shows the user a code to paste instead.
6
- */
7
- export interface AuthorizeInput {
8
- state: string;
9
- challenge: string;
10
- redirectUri?: string;
11
- }
12
- export declare function authorizeUrl(input: AuthorizeInput): string;
package/dist/auth/url.js DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * Devin CLI login URL (`{webapp}/auth/cli/continue`).
3
- *
4
- * With `redirect_uri` the webapp redirects the browser back to our loopback
5
- * server; without it, the webapp shows the user a code to paste instead.
6
- */
7
- import { WEBAPP_URL } from "../constants.js";
8
- export function authorizeUrl(input) {
9
- const url = new URL("/auth/cli/continue", WEBAPP_URL);
10
- if (input.redirectUri)
11
- url.searchParams.set("redirect_uri", input.redirectUri);
12
- url.searchParams.set("state", input.state);
13
- url.searchParams.set("prompt", "select_account");
14
- url.searchParams.set("code_challenge", input.challenge);
15
- url.searchParams.set("code_challenge_method", "S256");
16
- return url.toString();
17
- }
@@ -1,26 +0,0 @@
1
- /**
2
- * `GetUserJwt` — mints the short-lived `user_jwt` required by catalog and chat
3
- * RPCs. The long-lived session token alone is not accepted.
4
- *
5
- * The real lifetime comes from the token's own `exp` claim; the cache only
6
- * trusts it, and falls back to {@link FALLBACK_JWT_TTL_SECONDS} when `exp` is
7
- * missing or unparseable. Observed tokens run roughly 24 minutes.
8
- *
9
- * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
10
- */
11
- export declare class CloudAuthError extends Error {
12
- readonly status: number;
13
- constructor(message: string, status: number);
14
- }
15
- export interface UserJwt {
16
- jwt: string;
17
- expiresAt: number;
18
- }
19
- /** Mint a fresh user_jwt for the given session token. */
20
- export declare function mintUserJwt(apiKey: string, host?: string, signal?: AbortSignal): Promise<UserJwt>;
21
- /** Cache key for one credential against one host. */
22
- export declare const credentialKey: (host: string, apiKey: string) => string;
23
- /** Mint a user_jwt, reusing a cached one until shortly before expiry. */
24
- export declare function getCachedUserJwt(apiKey: string, host?: string, signal?: AbortSignal): Promise<string>;
25
- /** Drop the cached user_jwt (e.g. after an auth failure). */
26
- export declare function clearCachedUserJwt(): void;
@@ -1,119 +0,0 @@
1
- /**
2
- * `GetUserJwt` — mints the short-lived `user_jwt` required by catalog and chat
3
- * RPCs. The long-lived session token alone is not accepted.
4
- *
5
- * The real lifetime comes from the token's own `exp` claim; the cache only
6
- * trusts it, and falls back to {@link FALLBACK_JWT_TTL_SECONDS} when `exp` is
7
- * missing or unparseable. Observed tokens run roughly 24 minutes.
8
- *
9
- * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
10
- */
11
- import { encodeMessage, iterFields } from "./wire.js";
12
- import { buildMetadata } from "./metadata.js";
13
- import { DEFAULT_API_SERVER } from "../constants.js";
14
- const MINT_TIMEOUT_MS = 30_000;
15
- /**
16
- * Assumed lifetime when the token carries no readable `exp`. Deliberately
17
- * shorter than the observed ~24 minutes: a too-short assumption costs one extra
18
- * mint, a too-long one keeps sending a token the server will reject.
19
- */
20
- const FALLBACK_JWT_TTL_SECONDS = 600;
21
- export class CloudAuthError extends Error {
22
- status;
23
- constructor(message, status) {
24
- super(message);
25
- this.name = "CloudAuthError";
26
- this.status = status;
27
- }
28
- }
29
- /** Mint a fresh user_jwt for the given session token. */
30
- export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
31
- const metadata = buildMetadata({
32
- apiKey,
33
- sessionId: crypto.randomUUID(),
34
- requestId: BigInt(Date.now()),
35
- triggerId: crypto.randomUUID(),
36
- });
37
- const request = encodeMessage(1, metadata);
38
- const timeout = AbortSignal.timeout(MINT_TIMEOUT_MS);
39
- const response = await fetch(`${host.replace(/\/$/, "")}/exa.auth_pb.AuthService/GetUserJwt`, {
40
- method: "POST",
41
- headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
42
- body: new Uint8Array(request),
43
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
44
- });
45
- const buf = Buffer.from(await response.arrayBuffer());
46
- if (!response.ok) {
47
- throw new CloudAuthError(`GetUserJwt HTTP ${response.status}: ${buf.toString("utf8").slice(0, 400)}`, response.status);
48
- }
49
- let jwt = null;
50
- for (const field of iterFields(buf)) {
51
- if (field.num === 1 && field.wire === 2 && Buffer.isBuffer(field.value)) {
52
- const candidate = field.value.toString("utf8");
53
- if (/^eyJ[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}$/.test(candidate)) {
54
- jwt = candidate;
55
- break;
56
- }
57
- }
58
- }
59
- if (!jwt) {
60
- throw new CloudAuthError(`GetUserJwt 200 but no field-1 JWT found (${buf.length} bytes)`, response.status);
61
- }
62
- let expiresAt = Math.floor(Date.now() / 1000) + FALLBACK_JWT_TTL_SECONDS;
63
- try {
64
- const parts = jwt.split(".");
65
- const pad = (s) => s + "=".repeat((4 - (s.length % 4)) % 4);
66
- const payload = JSON.parse(Buffer.from(pad(parts[1]).replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
67
- if (typeof payload.exp === "number")
68
- expiresAt = payload.exp;
69
- }
70
- catch {
71
- // non-JWT payload — keep the conservative fallback
72
- }
73
- return { jwt, expiresAt };
74
- }
75
- /**
76
- * Separator for composite cache keys.
77
- *
78
- * 0x1F (unit separator) cannot appear in a host or a token, so keys built from
79
- * them are unambiguous. It is spelled as an escape rather than a literal control
80
- * byte so it stays visible in diffs and review: silently dropped by a re-encode,
81
- * `host="a" key="bc"` would collide with `host="ab" key="c"` and two different
82
- * credentials would share a cached session.
83
- */
84
- const KEY_SEPARATOR = "\x1f";
85
- /** Cache key for one credential against one host. */
86
- export const credentialKey = (host, apiKey) => `${host}${KEY_SEPARATOR}${apiKey}`;
87
- let cache = null;
88
- const inFlight = new Map();
89
- let cacheEpoch = 0;
90
- /** Mint a user_jwt, reusing a cached one until shortly before expiry. */
91
- export async function getCachedUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
92
- const now = Math.floor(Date.now() / 1000);
93
- if (cache && cache.apiKey === apiKey && cache.host === host && cache.expiresAt > now + 60) {
94
- return cache.jwt;
95
- }
96
- const key = credentialKey(host, apiKey);
97
- const pending = inFlight.get(key);
98
- if (pending)
99
- return (await pending).jwt;
100
- const promise = mintUserJwt(apiKey, host, signal);
101
- inFlight.set(key, promise);
102
- const epochAtStart = cacheEpoch;
103
- try {
104
- const minted = await promise;
105
- if (cacheEpoch === epochAtStart) {
106
- cache = { ...minted, apiKey, host };
107
- }
108
- return minted.jwt;
109
- }
110
- finally {
111
- inFlight.delete(key);
112
- }
113
- }
114
- /** Drop the cached user_jwt (e.g. after an auth failure). */
115
- export function clearCachedUserJwt() {
116
- cache = null;
117
- inFlight.clear();
118
- cacheEpoch++;
119
- }
@@ -1,62 +0,0 @@
1
- /**
2
- * `GetCascadeModelConfigs` — per-account model catalog from Cognition.
3
- *
4
- * Returns every model UID the subscription can use, with pricing and context
5
- * windows. This is the same source the Devin CLI uses (`GetCliModelConfigs`).
6
- * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
7
- */
8
- export interface ModelPricing {
9
- /** Price per 1M input tokens (USD), or 0 if free. */
10
- input: number;
11
- /** Price per 1M cached input tokens (USD), or 0 if N/A. */
12
- cachedInput: number;
13
- /** Price per 1M output tokens (USD), or 0 if free. */
14
- output: number;
15
- }
16
- export interface ModelCapability {
17
- /** Feature name, e.g. "Effort", "Thinking", "Fast Mode", "1M Context". */
18
- name: string;
19
- enabled: boolean;
20
- /** Optional value, e.g. "Medium" for Effort. */
21
- value?: string;
22
- }
23
- export interface ModelCatalogEntry {
24
- modelUid: string;
25
- label: string;
26
- disabled: boolean;
27
- contextWindow: number;
28
- pricing?: ModelPricing;
29
- capabilities?: ModelCapability[];
30
- /** Base model UID without the effort suffix (e.g. "claude-opus-4-8" for "claude-opus-4-8-medium"). */
31
- baseModelUid?: string;
32
- /** Reasoning effort level if encoded in the UID (none/low/medium/high/xhigh/max). */
33
- effortLevel?: string;
34
- }
35
- export interface Catalog {
36
- byUid: Map<string, ModelCatalogEntry>;
37
- fetchedAt: number;
38
- apiKey: string;
39
- host: string;
40
- }
41
- /**
42
- * Raised when the account's catalog lists the model but marks it disabled.
43
- *
44
- * Only this case is safe to fail on: the catalog states it explicitly, so the
45
- * upstream request would be rejected regardless. A model that is simply absent
46
- * is *not* asserted on, because the catalog is not guaranteed to enumerate every
47
- * uid Cascade accepts and a false rejection would break a working model.
48
- */
49
- export declare class ModelNotAvailableError extends Error {
50
- readonly modelUid: string;
51
- readonly label: string;
52
- constructor(modelUid: string, label: string);
53
- }
54
- /** The catalog as the request path needs it: everything, and the usable subset. */
55
- export interface CatalogSnapshot {
56
- /** Every model the account can see, including ones disabled for its tier. */
57
- readonly entries: readonly ModelCatalogEntry[];
58
- /** The subset currently usable; what the effort-variant lookup resolves against. */
59
- readonly enabled: readonly ModelCatalogEntry[];
60
- }
61
- /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
62
- export declare function getCachedCatalog(apiKey: string, host?: string, signal?: AbortSignal): Promise<Catalog | null>;