diff --git a/README.md b/README.md index 89c16e7..4b614f8 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [minimax](packages/minimax) | MiniMax Code (China): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code` | | [minimax](packages/minimax) | MiniMax Code (international): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code-global` | | [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` | +| [nous](packages/nous) | Nous Portal models, with Nous Portal's device sign-in | `nous-portal` | | [opendesign](packages/opendesign) | Open Design Cloud (open-design.ai), with the Open Design CLI's device sign-in | `opendesign` | | [qoder](packages/qoder) | Qoder subscription (qoder.com), with Qoder's device sign-in | `qoder` | | [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` | diff --git a/packages/nous/README.md b/packages/nous/README.md new file mode 100644 index 0000000..d0c4422 --- /dev/null +++ b/packages/nous/README.md @@ -0,0 +1,147 @@ +# @magpie-community/opencode-nous-auth + +Signs in to [Nous Portal](https://portal.nousresearch.com) with its OAuth +Device Authorization flow and sends model requests in +[magpie](https://usemagpie.ai) and [OpenCode](https://opencode.ai). Provider id: +`nous-portal`. This is separate from magpie's `nous` API-key preset. + +## Signing in + +Once the package is available from magpie's plugin registry: + +```sh +magpie plugin add @magpie-community/opencode-nous-auth +magpie plugin login nous-portal +``` + +Magpie displays a verification URL and a code. Open the page, sign in and +approve the code there; finish any CAPTCHA in your browser. The plugin polls +for approval and completes sign-in without a local callback server. +Hermes Agent does not need to be installed or running. + +In OpenCode, add `"@magpie-community/opencode-nous-auth"` to the `plugin` +array in `opencode.json`, then run `opencode auth login`. + +The flow uses Nous Portal's `/api/oauth/device/code` and `/api/oauth/token` +with public client `hermes-cli`, scope `inference:invoke`, and no client +secret. Device polling follows [RFC 8628](https://www.rfc-editor.org/rfc/rfc8628.html#section-3.5), +including the server's interval and `slow_down` responses. Nous has not +confirmed whether independent clients may use the public `hermes-cli` +OAuth client ID. + +For ChatGPT plan sharing, see [Nous Portal's documentation](https://portal.nousresearch.com/help/chatgpt-plan-sharing). + +## Where the sign-in is kept + +Magpie keeps the account in its plugin credential store; OpenCode uses its own +sign-in store. The saved OAuth fields are `access` (inference JWT), `expires` +(epoch milliseconds) and `refresh` (versioned JSON containing the refresh +token, scope, token type and inference endpoint). **The entire `refresh` value +is secret**, even though it looks like JSON. + +Expiry uses the earlier of the token response's lifetime and the JWT's `exp`. +If both are absent, renewal is scheduled one hour after the exchange, with +the same two-minute lead. This is a local fallback, not a Nous lifetime +guarantee; a 401 can still trigger renewal sooner. Explicitly expired or +malformed lifetimes are not extended. + +Nothing is read from or written to `~/.hermes/auth.json`. A separate device +sign-in is intentional: Nous refresh tokens are single-use, and copying one +from Hermes could invalidate Hermes's session when either program renews it. + +Magpie uses `auth.refresh` with a two-minute lead and saves the rotated +tokens. OpenCode does not call that hook, so the plugin also checks before +each request and persists renewals through `client.auth.set`. Concurrent +refreshes within one plugin instance share one exchange. A rotated pair is +kept in memory before a save is attempted, so a failed save does not cause +that instance to reuse the old refresh token. + +**Do not run multiple hosts against the same saved account.** The per-request +save is not an atomic cross-process operation; a crash during an unsaved +rotation may require signing in again. Only explicit `invalid_grant`, +`invalid_token` or `refresh_token_reused` errors mark the grant expired. +Other refresh refusals, including HTML or empty 401/403 responses, keep the +credentials and allow a later retry. + +## Requests + +Models use OpenAI Chat Completions (`@ai-sdk/openai-compatible`) at +`https://inference-api.nousresearch.com/v1`. Magpie translates requests from +other agent protocols. Every request uses the current inference JWT as a +Bearer token; the refresh token is sent only to Portal's token endpoint in +`x-nous-refresh-token`, never to inference. + +The plugin accepts only known inference paths (`/models`, `/chat/completions`, +`/completions`, `/embeddings`) at the production Nous inference or welcome +host. A Portal response cannot redirect Bearer tokens to an arbitrary host; +HTTP redirects are refused. Caller-supplied credentials and magpie-internal +headers are removed before forwarding. + +A 401 triggers at most one refresh and retry. Other upstream errors keep +their status, and streaming responses pass through without buffering or +rewriting their content. The upstream `content-encoding` and `content-length` +headers are removed because fetch may already have decoded the body. + +## Models + +After sign-in, the account's live `/v1/models` list replaces the single +bootstrap entry (`Hermes-4-70B`). Model ids are preserved, including the +vendor prefix such as `openai/gpt-6-luna`. In magpie an exposed model is +addressed as `nous-portal/openai/gpt-6-luna`. + +Magpie may initially expose only part of the catalog. To choose a model +listed for your account and test it: + +```sh +magpie provider refresh nous-portal +magpie provider models nous-portal +openai/gpt-6-luna +magpie provider test nous-portal openai/gpt-6-luna +``` + +The `provider test` command takes the upstream id (`openai/gpt-6-luna`), not +the magpie-prefixed id. Model availability and billing depend on the account; +a model appearing in `/models` does not guarantee access. The plugin does +not guess model prices, context limits or vision/reasoning capabilities when +the catalog does not provide them. A failed catalog read does not become an +empty entitlement list. + +## Not included + +- Nous Portal API keys (`nous` remains magpie's separate built-in preset). +- Importing Hermes credentials or running Hermes's subscription proxy. +- Direct ChatGPT/Codex OAuth, billing or quota reporting, or daily check-in. +- An arbitrary inference URL override or cross-process token coordination. + +## Test + +Run the offline checks from the repository root with a temporary HOME: + +```sh +h=$(mktemp -d) +HOME="$h" node --test packages/nous/index.test.mjs +HOME="$h" bun test +rm -rf "$h" +bun scripts/check.mjs +``` + +Before publication, try the local package with magpie's isolated test script: + +```sh +export MAGPIE=/absolute/path/to/magpie +sh scripts/try.sh nous +sh scripts/try.sh nous login nous-portal +sh scripts/try.sh nous provider refresh nous-portal +sh scripts/try.sh nous provider test nous-portal openai/gpt-6-luna +``` + +`try.sh` uses `.sandbox/nous` rather than your real magpie sign-ins. It clears +ordinary environment variables, including proxy settings; configure a proxy +inside the sandbox if needed. Do not use a portable Windows magpie binary +that ignores HOME isolation. Sign-in and `provider test` contact Nous Portal; +the latter may consume account credits. Test a model your account can use, +and never share the sandbox's credential files. + +Protocol reference: Hermes Agent's +[device flow](https://github.com/NousResearch/hermes-agent/blob/8b9ac5773ea07189f23aa9dfcdba1e59fd759c21/hermes_cli/auth_device_flow.py), +[refresh handling](https://github.com/NousResearch/hermes-agent/blob/8b9ac5773ea07189f23aa9dfcdba1e59fd759c21/hermes_cli/auth_nous.py) +and [Nous Portal proxy adapter](https://github.com/NousResearch/hermes-agent/blob/8b9ac5773ea07189f23aa9dfcdba1e59fd759c21/hermes_cli/proxy/adapters/nous_portal.py). diff --git a/packages/nous/index.mjs b/packages/nous/index.mjs new file mode 100644 index 0000000..1c4e6f0 --- /dev/null +++ b/packages/nous/index.mjs @@ -0,0 +1,126 @@ +import { ID, INFERENCE, WELCOME, LEAD, AuthError, createAuth, metadata } from "./oauth.mjs" + +const NPM = "@ai-sdk/openai-compatible" +const PATHS = new Set(["/v1/chat/completions", "/v1/completions", "/v1/embeddings", "/v1/models"]) + +function target(input) { + const u = new URL(input) + if (![new URL(INFERENCE).origin, new URL(WELCOME).origin].includes(u.origin) || + u.username || u.password || u.hash || !PATHS.has(u.pathname)) throw new AuthError("refusing_inference_destination") + return u.pathname.slice(3) + u.search +} + +function abortable(work, signal) { + signal.throwIfAborted() + return new Promise((resolve, reject) => { + const stop = () => reject(signal.reason) + signal.addEventListener("abort", stop, { once: true }) + Promise.resolve().then(() => { signal.throwIfAborted(); return work() }).then(resolve, reject).finally(() => signal.removeEventListener("abort", stop)) + }) +} + +function model(provider, id, baseURL) { + const known = provider.models?.[id] + return { + id, providerID: provider.id, name: known?.name ?? id, + api: { id, url: baseURL, npm: NPM }, status: "active", headers: known?.headers ?? {}, options: known?.options ?? {}, + cost: known?.cost ?? { input: 0, output: 0, cache: { read: 0, write: 0 } }, + limit: known?.limit ?? { context: 0, output: 0 }, + capabilities: known?.capabilities ?? { + temperature: true, reasoning: false, attachment: false, toolcall: true, + input: { text: true, image: false, audio: false, video: false, pdf: false }, + output: { text: true, image: false, audio: false, video: false, pdf: false }, interleaved: false, + }, + release_date: known?.release_date ?? "", variants: known?.variants ?? {}, + } +} + +export async function NousPortalAuthPlugin({ client }) { + const auth = createAuth(client) + async function signedFetch(getAuth, input, init) { + const req = new Request(input, init) + const path = target(req.url) // refuse foreign destinations before even refreshing + req.signal.throwIfAborted() + // These endpoints take JSON, not uploads. Keep the exact request bytes for + // at most one 401 replay; the upstream RESPONSE is never buffered or parsed. + const body = req.body ? await req.arrayBuffer() : undefined + let a = await abortable(() => auth.fresh(getAuth), req.signal) + const send = (current) => { + req.signal.throwIfAborted() + const headers = new Headers(req.headers) + for (const name of [...headers.keys()]) { + if (["authorization", "x-api-key", "x-nous-refresh-token", "cookie", "proxy-authorization", "content-length", "host", "connection", "transfer-encoding", "upgrade", "te", "trailer", "proxy-connection", "keep-alive"].includes(name) || name.startsWith("x-magpie-")) headers.delete(name) + } + headers.set("Authorization", "Bearer " + current.access) + return fetch(metadata(current).baseURL + path, { + method: req.method, headers, body, signal: req.signal, redirect: "error", + }) + } + let renewed = a.signIn === "renewed" + let res = await send(a) + if (res.status === 401) { + await res.body?.cancel() + a = await abortable(() => auth.fresh(getAuth, a.access), req.signal) + renewed ||= a.signIn === "renewed" + res = await send(a) + } + const headers = new Headers(res.headers) + // fetch decodes the body; the upstream wire encoding and size no longer apply. + headers.delete("content-encoding") + headers.delete("content-length") + headers.set("X-Magpie-Sign-In", renewed && res.ok ? "renewed" : "kept") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) + } + return { + config: async (config) => { + config.provider ??= {} + const p = config.provider[ID] ??= {} + p.name ??= "Nous Portal (OAuth)" + p.npm ??= NPM + p.api ??= INFERENCE + // Bootstrap only, from Hermes's subscription-proxy documentation. A + // successful live catalog REPLACES it, even when the account has no models. + p.models = { "Hermes-4-70B": { name: "Hermes-4-70B", limit: { context: 0, output: 0 } }, ...(p.models ?? {}) } + }, + provider: { + id: ID, + async models(provider, { auth: saved }) { + if (saved?.type !== "oauth") return provider.models + // Magpie calls auth.refresh before this hook. Only an auth SNAPSHOT + // is supplied here, not getAuth: never redeem or persist through that + // snapshot, which cannot notice a concurrent logout or new login. + const a = auth.current(saved) + const baseURL = metadata(a).baseURL + let res + try { + res = await fetch(baseURL + "/models", { + headers: { Accept: "application/json", Authorization: "Bearer " + a.access }, + signal: AbortSignal.timeout(15000), redirect: "error", + }) + } catch { throw new AuthError("models_unavailable") } + if (!res.ok) throw new AuthError("models_unavailable", false, res.status) + let body + try { body = await res.json() } catch { throw new AuthError("invalid_models_response") } + if (!Array.isArray(body?.data)) throw new AuthError("invalid_models_response") + const out = [] + for (const m of body.data) { + if (typeof m?.id !== "string" || !m.id.trim()) throw new AuthError("invalid_models_response") + out.push([m.id, model(provider, m.id, baseURL)]) + } + return Object.fromEntries(out) + }, + }, + auth: { + provider: ID, icon: "nousresearch", refreshLead: LEAD, + refresh: auth.refresh, + async loader(getAuth) { + if ((await auth.read(getAuth))?.type !== "oauth") return {} + return { + baseURL: INFERENCE, apiKey: "nous-portal-oauth", + fetch: (input, init) => signedFetch(getAuth, input, init), + } + }, + methods: [{ type: "oauth", label: "Nous Portal (device code)", authorize: auth.authorize }], + }, + } +} diff --git a/packages/nous/index.test.mjs b/packages/nous/index.test.mjs new file mode 100644 index 0000000..3d503a1 --- /dev/null +++ b/packages/nous/index.test.mjs @@ -0,0 +1,817 @@ +import { test, beforeEach, afterEach } from "node:test" +import assert from "node:assert/strict" +import { tmpdir, homedir } from "node:os" +import { relative, isAbsolute } from "node:path" +import * as entry from "./index.mjs" +import { createAuth, metadata, inferenceURL, ID, PORTAL, INFERENCE, WELCOME, LEAD, SCOPE, CLIENT_ID } from "./oauth.mjs" + +// Protocol fixtures follow Hermes's auth_device_flow.py, auth_nous.py and +// auth_constants.py: synthetic tokens, NEVER captured user credentials. +const home = relative(tmpdir(), homedir()) +assert.ok(home && home !== ".." && !home.startsWith(".." + "/") && !home.startsWith(".." + "\\") && !isAbsolute(home), "Run with an isolated HOME under the temporary directory") +const NOW = 1800000000000 +const originalFetch = globalThis.fetch +const originalNow = Date.now +const noNetwork = async () => { throw new Error("unexpected request: tests must not reach the network") } +beforeEach(() => { globalThis.fetch = noNetwork }) +afterEach(() => { globalThis.fetch = originalFetch; Date.now = originalNow }) +const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } }) +const jwt = (c = {}) => ["eyJhbGciOiJSUzI1NiJ9", Buffer.from(JSON.stringify({ sub: "test-account", scope: SCOPE, exp: (NOW + 3600000) / 1000, ...c })).toString("base64url"), "test-signature"].join(".") +const payload = (extra = {}) => ({ access_token: jwt(), refresh_token: "rotated-test-refresh", expires_in: 3600, scope: SCOPE, token_type: "Bearer", inference_base_url: INFERENCE, ...extra }) +const saved = (extra = {}, meta = {}) => ({ + type: "oauth", access: jwt(), expires: NOW + 3600000, + refresh: JSON.stringify({ version: 1, token: "old-test-refresh", scope: SCOPE, tokenType: "Bearer", baseURL: INFERENCE, ...meta }), ...extra, +}) +const device = (extra = {}) => ({ device_code: "secret-device-code", user_code: "ABCD-EFGH", verification_uri: PORTAL + "/activate", verification_uri_complete: PORTAL + "/activate?user_code=ABCD-EFGH", expires_in: 600, interval: 5, ...extra }) +function deferred() { + let resolve, reject + const promise = new Promise((yes, no) => { resolve = yes; reject = no }) + return { promise, resolve, reject } +} +function store(initial) { + let value = structuredClone(initial) + const writes = [] + const client = { auth: { set: async ({ path, body }) => { assert.equal(path.id, ID); writes.push(structuredClone(body)); value = structuredClone(body); return {} } } } + return { client, writes, get: async () => structuredClone(value), replace: (v) => { value = structuredClone(v) } } +} +function clock() { + let time = NOW + const sleeps = [] + return { now: () => time, advance: (ms) => { time += ms }, sleeps, sleep: async (ms) => { sleeps.push(ms); time += ms } } +} +function options(c, request) { return { now: c.now, clock: c.now, sleep: c.sleep, request } } +const expiring = () => saved({ expires: NOW + LEAD - 1, access: jwt({ exp: (NOW + LEAD - 1) / 1000 }) }) + +// Sign-in: browser/device separation, pacing, terminal and edge errors. +test("device authorization uses only inference:invoke and the public client; callback is single-flight", async () => { + const c = clock(), calls = [] + const replies = [json(device()), json({ error: "authorization_pending" }, 400), json({ error: "slow_down" }, 400), json(payload())] + const flow = createAuth({}, options(c, async (url, init) => { calls.push({ url, init }); return replies.shift() })) + const a = await flow.authorize() + assert.equal(a.url, device().verification_uri_complete) + assert.equal(a.method, "auto") + assert.match(a.instructions, /ABCD-EFGH/) + assert.ok(!a.instructions.includes("secret-device-code")) + const p = a.callback() + assert.equal(p, a.callback()) + const result = await p + assert.equal(result.type, "success") + assert.equal(result.expires, NOW + 3600000) + assert.equal(metadata(result).token, "rotated-test-refresh") + assert.deepEqual(c.sleeps, [5000, 5000, 10000]) + assert.equal(calls[0].url, PORTAL + "/api/oauth/device/code") + assert.deepEqual(Object.fromEntries(new URLSearchParams(calls[0].init.body)), { client_id: CLIENT_ID, scope: SCOPE }) + for (const { url, init } of calls) { + assert.equal(init.redirect, "error") + assert.equal(init.headers["Content-Type"], "application/x-www-form-urlencoded") + assert.ok(!url.includes("secret-device-code")) + assert.ok(!init.body.includes("billing:manage")) + } + assert.deepEqual(Object.fromEntries(new URLSearchParams(calls[1].init.body)), { + grant_type: "urn:ietf:params:oauth:grant-type:device_code", client_id: CLIENT_ID, device_code: "secret-device-code", + }) +}) + +test("omitted interval defaults to five seconds; verification_uri_complete is optional", async () => { + const c = clock() + let call = 0 + const flow = createAuth({}, options(c, async () => ++call === 1 ? json(device({ interval: undefined, verification_uri_complete: undefined })) : json(payload()))) + const a = await flow.authorize() + assert.equal(a.url, device().verification_uri) + assert.equal((await a.callback()).type, "success") + assert.deepEqual(c.sleeps, [5000]) +}) + +test("a late callback cannot restart the device code lifetime", async () => { + const c = clock() + let calls = 0 + const a = await createAuth({}, options(c, async () => { calls++; return json(device()) })).authorize() + c.advance(600000) + const r = await a.callback() + assert.equal(r.type, "failed") + assert.match(r.error, /expired_token/) + assert.equal(calls, 1) +}) + +test("429 Retry-After and a non-JSON WAF response back off within the original deadline", async () => { + const c = clock() + const replies = [json(device()), json({ error: "invalid_grant" }, 429, { "retry-after": "20" }), new Response("challenge", { status: 403, headers: { "x-vercel-mitigated": "challenge" } }), json(payload())] + const a = await createAuth({}, options(c, async () => replies.shift())).authorize() + assert.equal((await a.callback()).type, "success") + assert.deepEqual(c.sleeps, [5000, 20000, 40000]) +}) + +test("a transport timeout backs off without polling past expiry", async () => { + const c = clock() + let calls = 0 + const a = await createAuth({}, options(c, async () => { + if (++calls === 1) return json(device({ expires_in: 12 })) + throw new Error("transport with secret-device-code") + })).authorize() + const r = await a.callback() + assert.equal(r.type, "failed") + assert.match(r.error, /expired_token/) + assert.equal(calls, 2) + assert.deepEqual(c.sleeps, [5000, 7000]) + assert.ok(!r.error.includes("secret-device-code")) +}) + +test("access_denied stops immediately and does not echo vendor descriptions", async () => { + const c = clock(), replies = [json(device()), json({ error: "access_denied", error_description: "secret-device-code rotated-test-refresh" }, 400)] + const a = await createAuth({}, options(c, async () => replies.shift())).authorize() + const r = await a.callback() + assert.equal(r.type, "failed") + assert.match(r.error, /access_denied/) + assert.ok(!r.error.includes("secret-device-code")) + assert.equal(c.sleeps.length, 1) +}) + +test("verification URLs are pinned before the host can open a browser", async () => { + for (const bad of ["https://attacker.invalid/activate", "http://portal.nousresearch.com/activate", "https://portal.nousresearch.com:8443/activate", "https://user@portal.nousresearch.com/activate", "javascript:alert(1)"]) { + const c = clock() + await assert.rejects(createAuth({}, options(c, async () => json(device({ verification_uri_complete: bad })))).authorize(), /invalid_verification_uri/) + } +}) + +test("malformed device replies are not silently assigned arbitrary defaults", async () => { + for (const bad of [{ expires_in: 0 }, { expires_in: "600" }, { interval: -1 }, { device_code: "" }, { user_code: "" }]) { + const c = clock() + await assert.rejects(createAuth({}, options(c, async () => json(device(bad)))).authorize(), /invalid_device_code_response/) + } +}) + +test("initial login rejects non-inference, expired and non-JWT access tokens", async () => { + for (const access of ["opaque-token", jwt({ scope: "billing:manage" }), jwt({ exp: -1 })]) { + const c = clock(), replies = [json(device()), json(payload({ access_token: access, scope: "billing:manage" }))] + const a = await createAuth({}, options(c, async () => replies.shift())).authorize() + assert.equal((await a.callback()).type, "failed") + } +}) + +// Refresh: standard store fields, rotations, ownership and failure semantics. +test("host refresh uses x-nous-refresh-token, never a refresh_token form field", async () => { + const s = store(expiring()), c = clock() + const flow = createAuth(s.client, options(c, async (url, init) => { + assert.equal(url, PORTAL + "/api/oauth/token") + assert.equal(init.redirect, "error") + assert.equal(init.headers["x-nous-refresh-token"], "old-test-refresh") + assert.deepEqual(Object.fromEntries(new URLSearchParams(init.body)), { grant_type: "refresh_token", client_id: CLIENT_ID }) + return json(payload({ access_token: jwt({ exp: (NOW + 600000) / 1000 }), inference_base_url: WELCOME })) + })) + const fields = await flow.refresh(await s.get()) + assert.deepEqual(Object.keys(fields).sort(), ["access", "expires", "refresh"]) + assert.equal(fields.expires, NOW + 600000) + assert.equal(metadata(fields).baseURL, WELCOME) + assert.equal(s.writes.length, 0, "the host must own its guarded save") +}) + +test("requests and the host refresh share one rotation, including different loaders", async () => { + const s = store(expiring()), c = clock(), entered = deferred(), reply = deferred() + let calls = 0 + const flow = createAuth(s.client, options(c, async () => { calls++; entered.resolve(); await reply.promise; return json(payload()) })) + const a = await s.get() + const work = Promise.all([flow.fresh(s.get), flow.fresh(s.get), flow.refresh(a), flow.refresh(a)]) + await entered.promise + reply.resolve() + const got = await work + assert.equal(calls, 1) + assert.equal(s.writes.length, 1) + assert.ok(got.every((r) => metadata(r).token === "rotated-test-refresh")) +}) + +test("failed persistence retains the successor and retries saving, not the spent refresh token", async () => { + const s = store(expiring()), c = clock() + const save = s.client.auth.set + let fails = true, calls = 0 + s.client.auth.set = async (args) => { if (fails) throw new Error("disk full"); return save(args) } + const flow = createAuth(s.client, options(c, async () => { calls++; return json(payload()) })) + await assert.rejects(flow.fresh(s.get), (e) => e.code === "could_not_save_rotated_token" && e.signIn === "kept") + fails = false + const a = await flow.fresh(s.get) + assert.equal(calls, 1) + assert.equal(metadata(a).token, "rotated-test-refresh") + assert.equal(metadata(await s.get()).token, "rotated-test-refresh") +}) + +test("an SDK error result is also a failed save", async () => { + const s = store(expiring()), c = clock() + s.client.auth.set = async () => ({ error: { message: "write failed" } }) + const flow = createAuth(s.client, options(c, async () => json(payload()))) + await assert.rejects(flow.fresh(s.get), /could_not_save_rotated_token/) +}) + +test("a rotated refresh token is persisted before rejecting an unusable JWT", async () => { + const s = store(expiring()), c = clock() + const spent = [] + const flow = createAuth(s.client, options(c, async (_url, init) => { + spent.push(init.headers["x-nous-refresh-token"]) + return json(spent.length === 1 ? payload({ access_token: "not-a-jwt" }) : payload({ refresh_token: "third-refresh" })) + })) + await assert.rejects(flow.fresh(s.get), /unusable_inference_jwt/) + assert.equal(metadata(await s.get()).token, "rotated-test-refresh") + await assert.rejects(flow.fresh(s.get), /unusable_inference_jwt/) + assert.equal(spent.length, 1, "malformed success must not cause a tight refresh loop") + c.advance(31000) + await flow.fresh(s.get) + assert.deepEqual(spent, ["old-test-refresh", "rotated-test-refresh"]) +}) + +test("host refresh returns an unusable rotated successor for the host to persist", async () => { + const s = store(expiring()), c = clock() + const flow = createAuth(s.client, options(c, async () => json(payload({ access_token: "" })))) + const fields = await flow.refresh(await s.get()) + assert.equal(fields.access, "") + assert.equal(metadata(fields).token, "rotated-test-refresh") + assert.equal(s.writes.length, 0) +}) + +test("a transient early-refresh failure keeps a still-valid JWT and observes a cooldown", async () => { + for (const status of [408, 429, 500, 503]) { + const s = store(expiring()), c = clock() + let calls = 0 + const flow = createAuth(s.client, options(c, async () => { calls++; return json({ error: "invalid_grant" }, status) })) + assert.equal((await flow.fresh(s.get)).access, (await s.get()).access) + await flow.fresh(s.get) + assert.equal(calls, 1) + assert.equal(s.writes.length, 0) + } +}) + +test("a temporary failure after actual expiry is kept, not signed out", async () => { + const s = store(saved({ expires: NOW - 1, access: jwt({ exp: (NOW - 1) / 1000 }) })), c = clock() + const flow = createAuth(s.client, options(c, async () => json({}, 503))) + await assert.rejects(flow.fresh(s.get), (e) => e.signIn === "kept") + assert.equal(s.writes.length, 0) +}) + +test("grant-dead errors require sign-in; WAF 403 and 429 do not", async () => { + for (const code of ["invalid_grant", "invalid_token", "refresh_token_reused"]) { + const s = store(expiring()), c = clock() + let calls = 0 + const flow = createAuth(s.client, options(c, async () => { calls++; return json({ error: code, error_description: "old-test-refresh" }, 400) })) + await assert.rejects(flow.fresh(s.get), (e) => e.signIn === "expired" && !e.message.includes("old-test-refresh")) + await assert.rejects(flow.fresh(s.get), (e) => e.signIn === "expired") + assert.equal(calls, 1) + assert.equal(s.writes.length, 0) + } + const s = store(expiring()), c = clock() + const flow = createAuth(s.client, options(c, async () => new Response("checkpoint", { status: 403, headers: { "x-vercel-mitigated": "deny" } }))) + assert.equal((await flow.fresh(s.get)).access, (await s.get()).access) +}) + +test("a newer login wins over an in-flight old refresh", async () => { + const s = store(expiring()), c = clock(), entered = deferred(), reply = deferred() + const flow = createAuth(s.client, options(c, async () => { entered.resolve(); await reply.promise; return json(payload()) })) + const p = flow.fresh(s.get) + await entered.promise + const next = saved({ access: jwt({ sub: "other-account" }) }, { token: "new-login-refresh" }) + s.replace(next) + reply.resolve() + assert.equal((await p).access, next.access) + assert.deepEqual(await s.get(), next) + assert.equal(s.writes.length, 0) +}) + +test("refresh preserves metadata changed while the exchange is in flight", async () => { + const s = store({ ...expiring(), label: "before" }), c = clock(), entered = deferred(), reply = deferred() + const flow = createAuth(s.client, options(c, async () => { entered.resolve(); await reply.promise; return json(payload()) })) + const p = flow.fresh(s.get) + await entered.promise + s.replace({ ...await s.get(), label: "after" }) + reply.resolve() + await p + assert.equal((await s.get()).label, "after") +}) + +test("accounts with the same display identity have independent refresh state", async () => { + const a = store(expiring()), b = store({ ...expiring(), refresh: saved({}, { token: "other-refresh" }).refresh }) + const c = clock(), tokens = [] + const flow = createAuth({}, options(c, async (_url, init) => { const t = init.headers["x-nous-refresh-token"]; tokens.push(t); return json(payload({ refresh_token: t + "-next" })) })) + const [x, y] = await Promise.all([flow.refresh(await a.get()), flow.refresh(await b.get())]) + assert.deepEqual(tokens.sort(), ["old-test-refresh", "other-refresh"]) + assert.notEqual(metadata(x).token, metadata(y).token) +}) + +test("a stale snapshot follows multiple rotations without redeeming an old token", async () => { + const c = clock(), initial = expiring(), spent = [] + const flow = createAuth({}, options(c, async (_url, init) => { + spent.push(init.headers["x-nous-refresh-token"]) + return json(payload({ access_token: jwt({ exp: (c.now() + 3600000) / 1000 }), refresh_token: `next-${spent.length}` })) + })) + await flow.refresh(initial) + c.advance(3600000) + await flow.refresh(initial) + c.advance(3600000) + await flow.refresh(initial) + assert.deepEqual(spent, ["old-test-refresh", "next-1", "next-2"]) +}) + +test("inference URL metadata cannot grant authority to an arbitrary recipient", () => { + assert.equal(inferenceURL(WELCOME + "/"), WELCOME) + for (const url of ["http://inference-api.nousresearch.com/v1", "https://evil.invalid/v1", INFERENCE + "?token=x", INFERENCE + "/other", "https://user@inference-api.nousresearch.com/v1", "https://inference-api.nousresearch.com:8443/v1"]) assert.equal(inferenceURL(url), INFERENCE) +}) + +test("saved-state corruption is not an empty account or a successful parse", async () => { + const s = store(saved({ refresh: "not-json" })), c = clock() + await assert.rejects(createAuth(s.client, options(c, noNetwork)).fresh(s.get), (e) => e.code === "unreadable_saved_sign_in" && e.signIn === "kept") + assert.equal(s.writes.length, 0) +}) + +// End-to-end through the exported plugin hooks, with every fetch intercepted. +test("one entrypoint, distinct provider id, non-destructive config and standard loader contract", async () => { + assert.deepEqual(Object.entries(entry).filter(([, v]) => typeof v === "function").map(([k]) => k), ["NousPortalAuthPlugin"]) + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }) + const config = { provider: { nous: { name: "API key preset" }, [ID]: { name: "Custom label", models: { custom: { name: "Mine" } } } } } + await hooks.config(config) + assert.equal(config.provider.nous.name, "API key preset") + assert.equal(config.provider[ID].name, "Custom label") + assert.equal(config.provider[ID].models.custom.name, "Mine") + assert.equal(hooks.auth.refreshLead, LEAD) + assert.deepEqual(await hooks.auth.loader(async () => ({ type: "api", key: "unrelated" })), {}) + assert.equal((await hooks.auth.loader(s.get)).apiKey, "nous-portal-oauth") +}) + +test("Request bytes, tool calls, caller headers and SSE are preserved; unrelated credentials are stripped", async () => { + Date.now = () => NOW + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + const body = '{ "model": "nous/hermes-test", "messages": [], "tools": [{"type":"function","function":{"name":"run"}}], "stream": true }' + const ac = new AbortController() + const req = new Request(INFERENCE + "/chat/completions", { method: "POST", body, signal: ac.signal, headers: { authorization: "placeholder", "x-api-key": "do-not-forward", "x-nous-refresh-token": "also-private", cookie: "private", "x-magpie-work-dir": "/private", "x-test": "keep", "content-type": "application/json" } }) + const sse = 'data: {"choices":[{"delta":{"tool_calls":[]}}]}\n\ndata: [DONE]\n\n' + const response = new Response(sse, { headers: { "content-type": "text/event-stream", "x-upstream": "kept" } }) + globalThis.fetch = async (url, init) => { + assert.equal(url, INFERENCE + "/chat/completions") + assert.equal(Buffer.from(init.body).toString(), body) + assert.equal(init.headers.get("authorization"), "Bearer " + (await s.get()).access) + for (const name of ["x-api-key", "x-nous-refresh-token", "cookie", "x-magpie-work-dir", "content-length"]) assert.equal(init.headers.has(name), false) + assert.equal(init.headers.get("x-test"), "keep") + assert.equal(init.redirect, "error") + assert.equal(init.signal.aborted, false) + return response + } + const result = await loader.fetch(req) + // Response may wrap the stream (Bun does); identity is not its contract. + assert.equal(result.status, response.status) + assert.equal(result.headers.get("content-type"), "text/event-stream") + assert.equal(result.headers.get("x-upstream"), "kept") + assert.equal(result.headers.get("x-magpie-sign-in"), "kept") + assert.equal(await result.text(), sse) + assert.equal(req.headers.get("authorization"), "placeholder") +}) + +test("SSE bytes arrive before upstream closes and consumer cancellation reaches upstream", { timeout: 15000 }, async () => { + Date.now = () => NOW + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + let controller, cancelled, closed = false, reader, timer + const source = new ReadableStream({ + start(c) { controller = c }, + cancel(reason) { cancelled = reason; closed = true }, + }) + globalThis.fetch = async () => new Response(source, { headers: { "content-type": "text/event-stream" } }) + // Hold the source open until its bytes have reached the consumer. The timer + // only detects a deadlock; no timing threshold decides whether streaming works. + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("SSE did not reach the consumer while upstream was still open")), 5000) + }) + const pending = loader.fetch(INFERENCE + "/chat/completions", { method: "POST", body: '{"stream":true}' }) + try { + const result = await Promise.race([pending, deadline]) + assert.equal(result.headers.get("content-type"), "text/event-stream") + reader = result.body.getReader() + const bytes = Buffer.from('data: {"choices":[{"delta":{"content":"你好"}}]}\n\ndata: [DONE]\n\n') + const split = bytes.indexOf(Buffer.from("你")) + 1 // split a UTF-8 character, not just an SSE event + for (const chunk of [bytes.subarray(0, split), bytes.subarray(split)]) { + controller.enqueue(chunk) + const received = [] + let length = 0 + // A runtime may rechunk a stream; compare bytes, not read boundaries. + while (length < chunk.length) { + const part = await Promise.race([reader.read(), deadline]) + assert.equal(part.done, false, "the source has not ended") + received.push(Buffer.from(part.value)) + length += part.value.byteLength + } + assert.deepEqual(Buffer.concat(received), chunk) + assert.equal(closed, false) + } + await Promise.race([reader.cancel("consumer stopped"), deadline]) + assert.equal(cancelled, "consumer stopped") + } finally { + clearTimeout(timer) + // Also releases a buffering regression, so a failing test leaves no reader + // or pending fetch running into the next test. + if (!closed) { controller.close(); closed = true } + if (reader) { await reader.cancel(); reader.releaseLock() } + await pending.catch(() => {}) + } +}) + +test("401 cancels the old response, refreshes once and replays the exact body only once", async () => { + Date.now = () => NOW + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + let calls = 0, refreshes = 0, cancelled = false + const bodies = [], bearers = [] + globalThis.fetch = async (url, init) => { + if (url === PORTAL + "/api/oauth/token") { refreshes++; return json(payload({ access_token: jwt({ sub: "renewed" }) })) } + calls++; bodies.push(Buffer.from(init.body).toString()); bearers.push(init.headers.get("authorization")) + return calls === 1 ? new Response(new ReadableStream({ cancel() { cancelled = true } }), { status: 401 }) : json({ error: "still unauthorized" }, 401) + } + const response = await loader.fetch(INFERENCE + "/chat/completions", { method: "POST", body: '{"stream":true}' }) + assert.equal(response.status, 401) + assert.equal(calls, 2) + assert.equal(refreshes, 1) + assert.equal(cancelled, true) + assert.deepEqual(bodies, ['{"stream":true}', '{"stream":true}']) + assert.notEqual(bearers[0], bearers[1]) +}) + +test("403, 429 and server failures are returned without a forced refresh or replay", async () => { + Date.now = () => NOW + for (const status of [403, 429, 500]) { + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + let calls = 0 + globalThis.fetch = async (url) => { calls++; assert.ok(url.startsWith(INFERENCE)); return json({ error: "test" }, status, { "retry-after": "60" }) } + const response = await loader.fetch(INFERENCE + "/chat/completions", { method: "POST", body: "{}" }) + assert.equal(response.status, status) + assert.equal(response.headers.get("x-magpie-sign-in"), "kept") + assert.equal(response.headers.get("retry-after"), "60") + assert.equal(calls, 1) + } +}) + +test("foreign origins, alternate ports and unsupported paths are refused before refresh", async () => { + Date.now = () => NOW + const s = store(expiring()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + let calls = 0 + globalThis.fetch = async () => { calls++; throw new Error("must not send") } + for (const url of ["https://evil.invalid/v1/models", "http://inference-api.nousresearch.com/v1/models", "https://inference-api.nousresearch.com:8443/v1/models", INFERENCE + "/messages", INFERENCE + "/images/generations", INFERENCE + "/models#secret"]) await assert.rejects(loader.fetch(url), /refusing_inference_destination/) + assert.equal(calls, 0) +}) + +test("RequestInit overrides the Request, including method, body and headers", async () => { + Date.now = () => NOW + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + globalThis.fetch = async (_url, init) => { + assert.equal(init.method, "POST") + assert.equal(Buffer.from(init.body).toString(), "override") + assert.equal(init.headers.get("x-test"), "new") + return json({}) + } + await loader.fetch(new Request(INFERENCE + "/chat/completions", { method: "POST", body: "old", headers: { "x-test": "old" } }), { method: "POST", body: "override", headers: { "x-test": "new" } }) +}) + +test("an already-aborted request neither refreshes nor sends inference", async () => { + Date.now = () => NOW + const s = store(expiring()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + let calls = 0 + globalThis.fetch = async () => { calls++; return json(payload()) } + const ac = new AbortController(); ac.abort() + await assert.rejects(loader.fetch(INFERENCE + "/models", { signal: ac.signal }), (e) => e.name === "AbortError") + assert.equal(calls, 0) +}) + +test("aborting one waiter does not abandon a rotating token needed by another request", async () => { + Date.now = () => NOW + const s = store(expiring()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + const entered = deferred(), reply = deferred() + let refreshes = 0, inferences = 0 + globalThis.fetch = async (url) => { + if (url === PORTAL + "/api/oauth/token") { refreshes++; entered.resolve(); await reply.promise; return json(payload()) } + inferences++; return json({ data: [] }) + } + const ac = new AbortController() + const first = loader.fetch(INFERENCE + "/models", { signal: ac.signal }) + const firstRejected = assert.rejects(first, (e) => e.name === "AbortError") + await entered.promise + const second = loader.fetch(INFERENCE + "/models") + ac.abort() + await firstRejected + reply.resolve() + await second + assert.equal(refreshes, 1) + assert.equal(inferences, 1) + assert.equal(metadata(await s.get()).token, "rotated-test-refresh") +}) + +test("the live model catalog preserves slash IDs and replaces the bootstrap, including an empty list", async () => { + Date.now = () => NOW + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }) + const provider = { id: ID, models: { "Hermes-4-70B": {}, "vendor/model": { name: "Known", limit: { context: 123, output: 45 } } } } + globalThis.fetch = async (url) => { assert.equal(url, INFERENCE + "/models"); return json({ data: [{ id: "vendor/model" }, { id: "nous/hermes-test" }] }) } + const models = await hooks.provider.models(provider, { auth: await s.get() }) + assert.deepEqual(Object.keys(models), ["vendor/model", "nous/hermes-test"]) + assert.equal(models["vendor/model"].api.id, "vendor/model") + assert.equal(models["vendor/model"].limit.context, 123) + globalThis.fetch = async () => json({ data: [] }) + assert.deepEqual(await hooks.provider.models(provider, { auth: await s.get() }), {}) +}) + +test("bad catalog reads throw instead of pretending the account has no models", async () => { + Date.now = () => NOW + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }) + for (const body of [{}, { data: {} }, { data: [{ id: "" }] }]) { + globalThis.fetch = async () => json(body) + await assert.rejects(hooks.provider.models({ id: ID, models: {} }, { auth: await s.get() }), /invalid_models_response/) + } +}) + +test("cancellation while reading the request body never starts an orphaned refresh", async () => { + Date.now = () => NOW + const s = store(expiring()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + let controller, calls = 0 + const ac = new AbortController() + const body = new ReadableStream({ start(c) { controller = c } }) + globalThis.fetch = async () => { calls++; throw new Error("must not start") } + const pending = loader.fetch(new Request(INFERENCE + "/chat/completions", { method: "POST", body, duplex: "half", signal: ac.signal })) + const rejected = assert.rejects(pending, (e) => e.name === "AbortError") + ac.abort() + controller.close() + await rejected + await Promise.resolve() + assert.equal(calls, 0) +}) + +test("catalog snapshots never rotate or overwrite a concurrently changed account", async () => { + Date.now = () => NOW + const s = store(expiring()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }) + const snapshot = await s.get() + const next = saved({}, { token: "new-login-refresh" }) + let calls = 0 + globalThis.fetch = async (url, init) => { + calls++ + assert.equal(url, INFERENCE + "/models") + assert.equal(init.redirect, "error") + assert.equal(new Headers(init.headers).get("authorization"), "Bearer " + snapshot.access) + s.replace(next) + return json({ data: [] }) + } + await hooks.provider.models({ id: ID, models: {} }, { auth: snapshot }) + assert.equal(calls, 1) + assert.equal(s.writes.length, 0) + assert.deepEqual(await s.get(), next) +}) + +test("a failed credential read is unknown, not a logout, and cannot leak store contents", async () => { + const s = store(expiring()), c = clock() + const flow = createAuth(s.client, options(c, noNetwork)) + await assert.rejects(flow.fresh(async () => { throw new Error("parse error: old-test-refresh") }), (e) => e.code === "could_not_read_sign_in" && e.signIn === "kept" && !e.message.includes("old-test-refresh")) + assert.equal(s.writes.length, 0) +}) + +test("a successful proactive request refresh reports renewed without changing SSE bytes", async () => { + Date.now = () => NOW + const s = store(expiring()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + globalThis.fetch = async (url) => url === PORTAL + "/api/oauth/token" ? json(payload()) : new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + const result = await loader.fetch(INFERENCE + "/chat/completions", { method: "POST", body: "{}" }) + assert.equal(result.headers.get("x-magpie-sign-in"), "renewed") + assert.equal(await result.text(), "data: [DONE]\n\n") +}) + +test("device polling uses monotonic time even when the wall clock moves backwards", async () => { + let monotonic = 0, wall = NOW, calls = 0 + const flow = createAuth({}, { + now: () => wall, clock: () => monotonic, + sleep: async (ms) => { monotonic += ms }, + request: async () => { + if (++calls === 1) return json(device({ expires_in: 12 })) + wall -= 3600000 + return json({ error: "authorization_pending" }, 400) + }, + }) + assert.equal((await (await flow.authorize()).callback()).type, "failed") + assert.equal(monotonic, 12000) + assert.equal(calls, 3) +}) + +test("a broken server lifetime cannot leave a login poll running indefinitely", async () => { + const c = clock() + let calls = 0 + const a = await createAuth({}, options(c, async () => { + if (++calls === 1) return json(device({ expires_in: 1e100, interval: 1e100 })) + throw new Error("must not poll past the local deadline") + })).authorize() + assert.equal((await a.callback()).type, "failed") + assert.deepEqual(c.sleeps, [1800000]) + assert.equal(calls, 1) +}) + +test("JWT scp arrays work; missing subjects never become a shared synthetic account id", async () => { + const c = clock() + const replies = [json(device()), json(payload({ access_token: jwt({ scope: undefined, scp: [SCOPE], sub: undefined }), scope: undefined }))] + const a = await createAuth({}, options(c, async () => replies.shift())).authorize() + const result = await a.callback() + assert.equal(result.type, "success") + assert.equal(Object.hasOwn(result, "accountId"), false) +}) + +test("HTTP-date Retry-After is measured against the wall clock, independent of timezone", async () => { + const c = clock() + const replies = [json(device()), json({}, 503, { "retry-after": new Date(NOW + 25000).toUTCString() }), json(payload())] + const a = await createAuth({}, options(c, async () => replies.shift())).authorize() + assert.equal((await a.callback()).type, "success") + assert.deepEqual(c.sleeps, [5000, 20000]) +}) + +// PR #163: transport failures are not evidence that a refresh grant is dead. +const blockedReplies = [ + ["HTML 403", () => new Response("blocked old-test-refresh", { status: 403, headers: { "content-type": "text/html" } })], + ["empty 401", () => new Response(null, { status: 401 })], + ["JSON without an OAuth code", () => json({}, 403)], + ["unknown OAuth code", () => json({ error: "proxy_denied", error_description: "old-test-refresh" }, 401)], + ["nested error", () => json({ error: { code: "invalid_grant" } }, 403)], +] + +test("host refresh keeps unknown 401/403 refusals and retries after cooldown", async () => { + for (const [name, reply] of blockedReplies) { + const c = clock(), original = expiring(), s = store(original) + let calls = 0 + const flow = createAuth(s.client, options(c, async () => ++calls === 1 ? reply() : json(payload()))) + const kept = (e) => e.code === "oauth_request_failed" && e.signIn === "kept" && !e.message.includes("old-test-refresh") + await assert.rejects(flow.refresh(original), kept, name) + await assert.rejects(flow.refresh(original), kept, name) + assert.equal(calls, 1, "do not hammer a blocked endpoint") + assert.deepEqual(await s.get(), original) + c.advance(30001) + const got = await flow.refresh(original) + assert.equal(metadata(got).token, "rotated-test-refresh", name) + assert.equal(calls, 2, "an unknown refusal must not permanently disable refresh") + assert.equal(s.writes.length, 0, "the host owns persistence") + } +}) + +test("an expired account survives blocked refresh and saves a later successful rotation", async () => { + for (const [name, reply] of blockedReplies) { + const c = clock(), original = saved({ expires: NOW - 1, access: jwt({ exp: (NOW - 1) / 1000 }) }), s = store(original) + let calls = 0 + const flow = createAuth(s.client, options(c, async () => ++calls === 1 ? reply() : json(payload()))) + await assert.rejects(flow.fresh(s.get), (e) => e.signIn === "kept", name) + await assert.rejects(flow.fresh(s.get), (e) => e.signIn === "kept", name) + assert.equal(calls, 1) + assert.deepEqual(await s.get(), original) + assert.equal(s.writes.length, 0) + c.advance(30001) + assert.equal((await flow.fresh(s.get)).signIn, "renewed", name) + assert.equal(metadata(await s.get()).token, "rotated-test-refresh") + assert.equal(s.writes.length, 1) + } +}) + +test("an unknown refresh refusal keeps a valid JWT but never reuses a rejected bearer", async () => { + for (const [name, reply] of blockedReplies) { + const c = clock(), original = expiring(), s = store(original) + let calls = 0 + const flow = createAuth(s.client, options(c, async () => { calls++; return reply() })) + assert.equal((await flow.fresh(s.get)).access, original.access, name) + await assert.rejects(flow.fresh(s.get, original.access), (e) => e.signIn === "kept", name) + assert.equal(calls, 1) + assert.deepEqual(await s.get(), original) + assert.equal(s.writes.length, 0) + } +}) + +test("explicit dead grants still expire the account on 400, 401 and 403", async () => { + for (const status of [400, 401, 403]) for (const error of ["invalid_grant", "invalid_token", "refresh_token_reused"]) { + const c = clock(), s = store(expiring()) + let calls = 0 + const flow = createAuth(s.client, options(c, async () => { calls++; return json({ error }, status) })) + await assert.rejects(flow.refresh(await s.get()), (e) => e.signIn === "expired" && e.code === error) + c.advance(60000) + await assert.rejects(flow.fresh(s.get), (e) => e.signIn === "expired" && e.code === error) + assert.equal(calls, 1) + assert.equal(s.writes.length, 0) + } +}) + +test("device login without either expiry uses a one-hour scheduling fallback", async () => { + const c = clock(), replies = [json(device()), json(payload({ expires_in: undefined, access_token: jwt({ exp: undefined }) }))] + const flow = createAuth({}, options(c, async () => replies.shift())) + const login = await flow.authorize(), got = await login.callback() + assert.equal(got.type, "success") + assert.equal(got.expires, c.now() + 3600000) + assert.equal(flow.current({ ...got, type: "oauth" }).access, got.access) +}) + +test("host renewal without expiry returns a stable lifetime instead of renewing every 30s", async () => { + const c = clock(), original = expiring() + let calls = 0 + const flow = createAuth({}, options(c, async () => { + calls++ + return json(payload({ expires_in: undefined, access_token: jwt({ exp: undefined }) })) + })) + const got = await flow.refresh(original) + assert.equal(got.expires, NOW + 3600000) + c.advance(31000) + assert.deepEqual(await flow.refresh({ ...original, ...got }), got) + assert.equal(calls, 1) +}) + +test("request renewal persists fallback expiry across reloads and honors the refresh lead", async () => { + const c = clock(), s = store(expiring()), spent = [] + const request = async (_url, init) => { + spent.push(init.headers["x-nous-refresh-token"]) + return json(payload({ expires_in: undefined, access_token: jwt({ exp: undefined, iat: c.now() / 1000 }), refresh_token: `rotated-${spent.length}` })) + } + const flow = createAuth(s.client, options(c, request)) + const got = await flow.fresh(s.get) + assert.equal(got.expires, NOW + 3600000) + assert.equal(s.writes.length, 1) + const reloaded = createAuth(s.client, options(c, request)) + c.advance(31000) + assert.equal((await reloaded.fresh(s.get)).expires, got.expires) + c.advance(3600000 - LEAD - 31000 - 1) + assert.equal((await reloaded.fresh(s.get)).expires, got.expires) + assert.equal(spent.length, 1) + c.advance(1) + const next = await reloaded.fresh(s.get) + assert.equal(next.expires, c.now() + 3600000) + assert.deepEqual(spent, ["old-test-refresh", "rotated-1"]) + assert.equal(s.writes.length, 2) +}) + +test("known lifetimes take precedence over the fallback and use the earlier bound", async () => { + for (const [ttl, jwtTTL, expected] of [[900, 3600, 900], [undefined, 600, 600], [7200, 900, 900], [7200, undefined, 7200]]) { + const c = clock() + const flow = createAuth({}, options(c, async () => json(payload({ expires_in: ttl, access_token: jwt({ exp: jwtTTL === undefined ? undefined : NOW / 1000 + jwtTTL }) })))) + assert.equal((await flow.refresh(expiring())).expires, NOW + expected * 1000) + } +}) + +test("fallback expiry does not extend an explicitly expired or malformed lifetime", async () => { + const cases = [ + ...[0, -1, null, "3600", 1e308].map(expires_in => ({ expires_in })), + ...[0, -1, null, "1800003600", 1e308].map(exp => ({ expires_in: undefined, access_token: jwt({ exp }) })), + ] + for (const fields of cases) { + const c = clock() + const flow = createAuth({}, options(c, async () => json(payload(fields)))) + const got = await flow.refresh(expiring()) + assert.equal(got.expires, 1) + assert.equal(metadata(got).token, "rotated-test-refresh", "a bad lifetime cannot discard an already rotated refresh token") + assert.throws(() => flow.current({ type: "oauth", ...got }), /unusable_inference_jwt/) + } +}) + +test("fallback expiry cannot make malformed or non-inference JWTs usable", async () => { + for (const fields of [ + { access_token: "not-a-jwt" }, + { access_token: jwt({ exp: undefined, scope: "profile" }), scope: "profile" }, + { access_token: jwt({ exp: undefined }), token_type: "Basic" }, + ]) { + const c = clock() + const flow = createAuth({}, options(c, async () => json(payload({ expires_in: undefined, ...fields })))) + const got = await flow.refresh(expiring()) + assert.equal(got.expires, 1) + assert.equal(metadata(got).token, "rotated-test-refresh") + assert.throws(() => flow.current({ type: "oauth", ...got }), /unusable_inference_jwt/) + } +}) + +test("decoded response headers are stripped for success, errors and the final 401 replay", async () => { + Date.now = () => NOW + for (const status of [200, 401, 403, 429, 500]) { + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + let calls = 0 + const body = status === 200 ? 'data: {"text":"你好"}\n\ndata: [DONE]\n\n' : '{"error":"upstream refused"}' + globalThis.fetch = async (url) => { + if (String(url).includes("/api/oauth/token")) return json(payload({ access_token: jwt({ jti: "next" }) })) + calls++ + return new Response(body, { status, headers: { "content-type": status === 200 ? "text/event-stream" : "application/json", "content-encoding": "gzip", "content-length": "999", "retry-after": "7", "x-upstream": "kept" } }) + } + const res = await loader.fetch(INFERENCE + "/chat/completions", { method: "POST", body: "{}" }) + assert.equal(res.status, status) + assert.equal(res.headers.has("content-encoding"), false) + assert.equal(res.headers.has("content-length"), false) + assert.equal(res.headers.get("x-upstream"), "kept") + assert.equal(res.headers.get("retry-after"), "7") + assert.equal(await res.text(), body) + assert.equal(calls, status === 401 ? 2 : 1) + } +}) + +test("native fetch decompression through a loopback server preserves bytes without wire headers", { timeout: 15000 }, async () => { + const { createServer } = await import("node:http") + const { gzipSync } = await import("node:zlib") + const body = 'data: {"choices":[{"delta":{"content":"你好"}}]}\n\ndata: [DONE]\n\n' + const zipped = gzipSync(Buffer.from(body)) + const server = createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/event-stream", "content-encoding": "gzip", "content-length": String(zipped.length), "x-upstream": "native", connection: "close" }) + res.end(zipped) + }) + try { + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve) }) + Date.now = () => NOW + const s = store(saved()), hooks = await entry.NousPortalAuthPlugin({ client: s.client }), loader = await hooks.auth.loader(s.get) + globalThis.fetch = async (url, init) => { + assert.equal(url, INFERENCE + "/chat/completions") + return originalFetch(`http://127.0.0.1:${server.address().port}/`, init) + } + const res = await loader.fetch(INFERENCE + "/chat/completions", { method: "POST", body: "{}" }) + assert.equal(res.headers.get("content-type"), "text/event-stream") + assert.equal(res.headers.get("x-upstream"), "native") + assert.equal(res.headers.has("content-encoding"), false) + assert.equal(res.headers.has("content-length"), false) + assert.equal(await res.text(), body) + } finally { + await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())) + } +}) diff --git a/packages/nous/oauth.mjs b/packages/nous/oauth.mjs new file mode 100644 index 0000000..e3f5303 --- /dev/null +++ b/packages/nous/oauth.mjs @@ -0,0 +1,305 @@ +// Nous Portal's public device flow and rotating inference JWTs. The host owns +// persistence; this module never reads Hermes's (or any other app's) files. +import { createHash } from "node:crypto" + +export const ID = "nous-portal" +export const PORTAL = "https://portal.nousresearch.com" +export const INFERENCE = "https://inference-api.nousresearch.com/v1" +export const WELCOME = "https://welcome-api.nousresearch.com/v1" +export const CLIENT_ID = "hermes-cli" +export const SCOPE = "inference:invoke" +export const LEAD = 120000 +const FALLBACK_LIFETIME = 60 * 60 * 1000 +const GRANT = "urn:ietf:params:oauth:grant-type:device_code" +const DEAD = new Set(["invalid_grant", "invalid_token", "refresh_token_reused"]) +const KNOWN = new Set([...DEAD, "access_denied", "expired_token", "authorization_pending", "slow_down", "invalid_client", "invalid_scope"]) +const text = (v) => typeof v === "string" ? v.trim() : "" +const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 +const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v) +const same = (a, b) => a?.type === b?.type && a?.access === b?.access && a?.refresh === b?.refresh + +export class AuthError extends Error { + constructor(code, expired = false, status = 0) { + // Never include a vendor's raw body, description, URL or token in an error. + super(`Nous Portal: ${code}${status ? ` (HTTP ${status})` : ""}. ${expired ? "Sign in again." : "Credentials kept; retry when the problem is resolved."}`) + this.code = code + this.signIn = expired ? "expired" : "kept" + } +} + +export function inferenceURL(value) { + // A network-provided address is not authority to receive the bearer. Keep + // only the two production bases used by Hermes; no custom ports or userinfo. + try { + const u = new URL(value) + if (!u.username && !u.password && !u.search && !u.hash && + [INFERENCE, WELCOME].includes(u.href.replace(/\/$/, ""))) return u.href.replace(/\/$/, "") + } catch {} + return INFERENCE +} + +function verificationURL(value) { + try { + const u = new URL(value) + if (u.origin === PORTAL && !u.username && !u.password && !u.hash) return u.href + } catch {} + throw new AuthError("invalid_verification_uri") +} + +export function claims(token) { + try { + const parts = token.split(".") + if (parts.length !== 3 || parts.some((p) => !p)) return {} + const value = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) + return object(value) ? value : {} + } catch { return {} } +} + +function scopes(value) { + return (Array.isArray(value) ? value : [value]).flatMap((s) => text(s).split(/[\s,]+/)) +} + +export function metadata(auth) { + try { + const m = JSON.parse(auth.refresh) + if (m?.version === 1 && text(m.token) && typeof m.scope === "string" && typeof m.tokenType === "string") { + return { ...m, baseURL: inferenceURL(m.baseURL) } + } + } catch {} + throw new AuthError("unreadable_saved_sign_in") +} + +function usable(a, now, lead = 0) { + const m = metadata(a) + const c = claims(a.access) + // Decoding is only a scope/expiry check, NOT signature verification. TLS + // protects the token exchange; the inference server verifies the signature. + return Object.keys(c).length > 0 && m.tokenType.toLowerCase() === "bearer" && + [...scopes(m.scope), ...scopes(c.scope), ...scopes(c.scp)].includes(SCOPE) && + positive(a.expires) && a.expires > now + lead && + (c.exp === undefined || (typeof c.exp === "number" && Number.isFinite(c.exp) && c.exp * 1000 > now + lead)) +} + +function assertUsable(a, now, lead = 0) { + if (!usable(a, now, lead)) throw new AuthError("unusable_inference_jwt") +} + +function token(body, old, started) { + const previous = old ? metadata(old) : {} + const access = text(body?.access_token) + const c = claims(access) + // An absent lifetime needs a stable renewal schedule, not expires=1. An + // explicitly expired or malformed bound must never be replaced by that default. + const expiries = [] + if (body?.expires_in !== undefined) expiries.push(typeof body.expires_in === "number" ? started + body.expires_in * 1000 : NaN) + if (c.exp !== undefined) expiries.push(typeof c.exp === "number" ? c.exp * 1000 : NaN) + let expires = started + FALLBACK_LIFETIME + if (expiries.length) expires = expiries.every(Number.isFinite) ? Math.max(1, Math.min(...expiries)) : 1 + const m = { + version: 1, + token: text(body?.refresh_token) || previous.token || "", + scope: typeof body?.scope === "string" ? body.scope : previous.scope ?? "", + tokenType: text(body?.token_type) || previous.tokenType || "Bearer", + baseURL: inferenceURL(body?.inference_base_url), + } + // Keep metadata in the standard refresh field, so OpenCode stores that keep + // only type/access/refresh/expires retain routing and the granted scope too. + const result = { access, refresh: JSON.stringify(m), expires } + if (!m.token) throw new AuthError("missing_refresh_token") + if (!usable(result, started)) result.expires = 1 + return result +} + +function transient(r) { + return r.status === 408 || r.status === 429 || r.status >= 500 || + (r.status === 403 && r.headers.has("x-vercel-mitigated")) +} + +function refused(r, refreshing = false) { + if (transient(r)) return new AuthError("temporarily_unavailable", false, r.status) + const raw = text(r.body?.error) + // A proxy or WAF can return 401/403 without the token endpoint seeing the + // grant. Only an explicit OAuth code is evidence that the grant is dead. + const code = KNOWN.has(raw) ? raw : "oauth_request_failed" + return new AuthError(code, refreshing && DEAD.has(code), r.status) +} + +function retryAfter(r, now) { + const value = r.headers.get("retry-after") + if (!value) return 0 + const seconds = Number(value) + return Number.isFinite(seconds) ? Math.max(0, seconds * 1000) : Math.max(0, Date.parse(value) - now) || 0 +} + +export function createAuth(client, { now = Date.now, clock = () => performance.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), request = (...args) => fetch(...args) } = {}) { + // Each fingerprint points at the SAME session through every known rotation. + // Old token bytes are not retained. No timer can evict an unsaved successor + // and make a stale caller spend an already-spent refresh token again. + const sessions = new Map() + const key = (a) => createHash("sha256").update(metadata(a).token).digest("hex") + const session = (a) => { + const k = key(a) + if (!sessions.has(k)) sessions.set(k, { fields: { access: a.access, refresh: a.refresh, expires: a.expires } }) + return sessions.get(k) + } + + async function post(path, form, extra = {}, timeout = 10000) { + let res + try { + res = await request(PORTAL + path, { + method: "POST", redirect: "error", + headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded", ...extra }, + body: new URLSearchParams(form).toString(), signal: AbortSignal.timeout(Math.max(1, Math.ceil(timeout))), + }) + } catch { throw new AuthError("token_endpoint_unavailable") } + let body + try { body = await res.json() } catch {} + return { ok: res.ok && object(body) && !body.error, status: res.status, headers: res.headers, body } + } + + function renew(s) { + if (s.pending) return s.pending + if (s.error && now() < s.retryAt) return Promise.reject(s.error) + s.pending = (async () => { + await s.saving?.catch(() => {}) + const started = now() + const r = await post("/api/oauth/token", { grant_type: "refresh_token", client_id: CLIENT_ID }, { + "x-nous-refresh-token": metadata(s.fields).token, + }) + if (!r.ok) throw refused(r, true) + const got = token(r.body, s.fields, started) + // Record the rotated pair BEFORE persistence or JWT validation. A bad + // JWT or a failed write must never make the old refresh token usable. + s.fields = got + sessions.set(key(got), s) + s.error = undefined + if (!usable(got, now(), LEAD)) { + s.error = new AuthError("unusable_inference_jwt") + s.retryAt = now() + 30000 + } + return got + })().catch((e) => { + s.error = e + s.retryAt = e.signIn === "expired" ? Infinity : now() + 30000 + throw e + }).finally(() => { s.pending = undefined }) + return s.pending + } + + async function read(getAuth) { + try { return await getAuth() } catch { throw new AuthError("could_not_read_sign_in") } + } + + function persist(s, getAuth, was) { + const saved = (s.saving ?? Promise.resolve()).catch(() => {}).then(async () => { + const current = await read(getAuth) + if (!same(current, was)) return undefined + const fields = s.fields + if (current.access === fields.access && current.refresh === fields.refresh && current.expires === fields.expires) return fields + try { + if (typeof client?.auth?.set !== "function") throw new Error() + const r = await client.auth.set({ path: { id: ID }, body: { ...current, ...fields, type: "oauth" } }) + if (r?.error) throw new Error() + } catch { throw new AuthError("could_not_save_rotated_token") } + return fields + }) + const finished = saved.finally(() => { if (s.saving === finished) s.saving = undefined }) + s.saving = finished + return finished + } + + async function fresh(getAuth, rejected) { + // Re-read after another writer wins rather than overwriting a new login. + // Magpie also guards the host-owned refresh save atomically; OpenCode's + // auth.set has no compare-and-swap interface, so this is an optimistic check. + for (let attempt = 0; attempt < 3; attempt++) { + const was = await read(getAuth) + if (was?.type !== "oauth") throw new AuthError("not_signed_in", true) + const s = session(was) + let a = s.fields + const force = rejected !== undefined && rejected === a.access + if (force || !usable(a, now(), LEAD)) { + try { a = await renew(s) } catch (e) { + if (!same(await read(getAuth), was)) continue + if (e.signIn === "expired" || force || !usable(a, now())) throw e + // A temporary early-refresh outage does not kill a still-valid JWT. + } + } + a = await persist(s, getAuth, was) + if (!a) continue + assertUsable(a, now()) + return { ...was, ...a, signIn: a.access !== was.access || a.refresh !== was.refresh ? "renewed" : "kept" } + } + throw new AuthError("sign_in_changed_during_refresh") + } + + async function refresh(auth) { + if (auth?.type !== "oauth") return undefined + const s = session(auth) + if (usable(s.fields, now(), LEAD)) return { ...s.fields } + // The host, not this hook, persists the result with its account identity + // guard. Return even an unusable successor so a rotated token is not lost; + // fresh() will not send that JWT, and a later refresh can recover it. + return { ...await renew(s) } + } + + async function authorize() { + const started = clock() + const r = await post("/api/oauth/device/code", { client_id: CLIENT_ID, scope: SCOPE }) + if (!r.ok) throw refused(r) + const b = r.body + if (!text(b.device_code) || !text(b.user_code) || !positive(b.expires_in) || + (b.interval !== undefined && !positive(b.interval))) throw new AuthError("invalid_device_code_response") + const plain = verificationURL(b.verification_uri) + const url = b.verification_uri_complete ? verificationURL(b.verification_uri_complete) : plain + const deadline = started + Math.min(b.expires_in * 1000, 30 * 60 * 1000) + let interval = (b.interval ?? 5) * 1000 + let wait = interval + let pending + const poll = async () => { + while (clock() < deadline) { + // RFC 8628: the advertised interval is a minimum, including the first + // poll. slow_down adds five seconds; never use Hermes's one-second cap. + await sleep(Math.min(wait, deadline - clock())) + if (clock() >= deadline) break + let answer + const at = now() + try { + answer = await post("/api/oauth/token", { grant_type: GRANT, client_id: CLIENT_ID, device_code: b.device_code }, {}, Math.min(10000, deadline - clock())) + } catch (e) { + if (e.code !== "token_endpoint_unavailable") throw e + wait = Math.max(interval, wait * 2) + continue + } + if (answer.ok) { + const got = token(answer.body, undefined, at) + assertUsable(got, now(), LEAD) + const subject = claims(got.access).sub + return { type: "success", ...got, ...(typeof subject === "string" && subject ? { accountId: subject } : {}) } + } + if (transient(answer)) { + wait = Math.max(interval, wait * 2, retryAfter(answer, now())) + continue + } + if (answer.body?.error === "authorization_pending") { wait = interval; continue } + if (answer.body?.error === "slow_down") { interval += 5000; wait = interval; continue } + throw refused(answer) + } + throw new AuthError("expired_token") + } + return { + url, method: "auto", + instructions: `Sign in to Nous Portal in your browser and confirm code ${b.user_code}. Finish any CAPTCHA in the browser. This finishes automatically.`, + callback() { + pending ??= poll().catch((e) => ({ type: "failed", error: e instanceof AuthError ? e.message : "Nous Portal sign-in failed; please retry." })) + return pending + }, + } + } + function current(auth) { + if (auth?.type !== "oauth") throw new AuthError("not_signed_in", true) + assertUsable(auth, now()) + return auth + } + return { authorize, refresh, fresh, current, read } +} diff --git a/packages/nous/package.json b/packages/nous/package.json new file mode 100644 index 0000000..c8eff93 --- /dev/null +++ b/packages/nous/package.json @@ -0,0 +1,12 @@ +{ + "name": "@magpie-community/opencode-nous-auth", + "version": "0.1.0", + "description": "Nous Portal OAuth with device sign-in and automatic token renewal in OpenCode and magpie", + "type": "module", + "main": "./index.mjs", + "exports": "./index.mjs", + "files": ["index.mjs", "oauth.mjs", "README.md"], + "keywords": ["opencode", "opencode-plugin", "magpie", "nous", "oauth"], + "license": "MIT", + "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/nous" } +} diff --git a/registry.json b/registry.json index a46b871..f29b260 100644 --- a/registry.json +++ b/registry.json @@ -34,6 +34,8 @@ "summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } }, { "package": "@magpie-community/opencode-opendesign-auth", "name": "Open Design", "providers": ["opendesign"], "community": true, "summary": { "en": "Open Design Cloud's Design Plan (open-design.ai): the account's device sign-in, the models the plan entitles it to, and the plan's 5-hour and 7-day allowance and wallet balance.", "zh": "Open Design Cloud 的 Design Plan(open-design.ai):账号设备登录、套餐可用的模型,以及 5 小时与 7 天额度、钱包余额。" } }, + { "package": "@magpie-community/opencode-nous-auth", "name": "Nous Portal (OAuth)", "icon": "nousresearch", "providers": ["nous-portal"], "community": true, + "summary": { "en": "Nous Portal models, with Nous Portal's device sign-in.", "zh": "通过 Nous Portal 自己的设备码登录使用 Nous Portal 模型。" } }, { "package": "@magpie-community/opencode-raccoon-auth", "name": "商汤小浣熊", "icon": "sensenova-color", "providers": ["raccoon"], "community": true, "summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } }, { "package": "@magpie-community/opencode-autoclaw-auth", "name": "AutoClaw", "providers": ["autoclaw", "autoclaw-cn"], "community": true,