GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(oauth/nous): enforce HTTPS base URL and single-use refresh rotati… · lidge-jun/opencodex@e9d9d9e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs-site/src/content/docs/ru/guides
    • providers.md
  • src/oauth
    • nous.ts
  • tests
    • nous-oauth-live.test.ts
    • nous-oauth.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs-site/src/content/docs/ru/guides/providers.md‎

Copy file name to clipboardExpand all lines: docs-site/src/content/docs/ru/guides/providers.md
+3-1Lines changed: 3 additions & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ account id, OpenAI beta/originator/session — см. [Адаптеры](/ru/refe
9393

9494
## 2. Вход по аккаунту (OAuth)
9595

96-
Семь пресетов провайдеров используют вход через OAuth — плюс GitHub Copilot через
96+
Восемь пресетов провайдеров используют вход через OAuth — плюс GitHub Copilot через
9797
экспериментальный неофициальный мост device flow. opencodex хранит их учётные данные в
9898
`~/.opencodex/auth.json` и обновляет их автоматически. CLI входа также принимает `chatgpt`: эта
9999
команда получает учётные данные ChatGPT и одновременно создаёт запись провайдера в режиме `forward`.
@@ -102,6 +102,7 @@ account id, OpenAI beta/originator/session — см. [Адаптеры](/ru/refe
102102
ocx login xai # xAI Grok
103103
ocx login anthropic # Anthropic Claude (Pro/Max)
104104
ocx login kimi # Moonshot Kimi
105+
ocx login nous # Nous Portal (device grant; модели free + paid)
105106
ocx login kiro # импорт учётных данных kiro-cli (с фолбэком на токен)
106107
ocx login google-antigravity
107108
ocx login cursor # отдельный PKCE-вход Cursor
@@ -116,6 +117,7 @@ ocx logout <provider>
116117
| `xai` | `openai-chat` | `https://api.x.ai/v1` | Каталог Grok загружается в реальном времени; фолбэк по умолчанию — `grok-4.5`. |
117118
| `anthropic` | `anthropic` | `https://api.anthropic.com` | Модели Claude; актуальный список моделей загружается из `/v1/models`. |
118119
| `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Модели Kimi K2.7/K2.6/K2.5 для кодинга. |
120+
| `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Шлюз подписки Nous Research (тот же бэкенд, что использует Hermes Agent). Вход по device grant против `portal.nousresearch.com`; access-токен — это JWT для каждого запроса к inference. Смешанный каталог платных + `:free` моделей (`tencent/hy3:free`, `stepfun/step-3.7-flash:free`, …) обнаруживается вживую по авторизованному аккаунту. Refresh-токены одноразовые и ротируются при каждом обновлении. |
119121
| `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | Первый вход импортирует существующую сессию после установки Kiro CLI (в Unix: `curl -fsSL https://cli.kiro.dev/install | bash`; в Windows PowerShell: `irm 'https://cli.kiro.dev/install.ps1' | iex`; затем выполните `kiro-cli login`). **Добавить аккаунт** выполняет выход из `kiro-cli`, запускает новый вход через браузер, переключает аккаунт самого `kiro-cli` и сохраняет метаданные профиля отдельно для каждого аккаунта. Существующие аккаунты OpenCodex сохраняются; при отмене или сбое восстанавливается предыдущая сессия `kiro-cli`. |
120122
| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth поверх протокола Cloud Code Assist. Живое обнаружение использует аутентифицированный CCA-эндпоинт `v1internal:fetchAvailableModels` и публикует только agent-модели, доступные текущему аккаунту; поддерживаемый каталог остаётся резервным вариантом. |
121123
| `cursor` | `cursor` | `https://api2.cursor.sh` | Экспериментальный PKCE-вход, живой транспорт HTTP/2 и обнаружение моделей с фильтрацией по аккаунту. |
Collapse file

‎src/oauth/nous.ts‎

Copy file name to clipboardExpand all lines: src/oauth/nous.ts
+69-5Lines changed: 69 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,45 @@ interface NousJwtPayload {
6464
[key: string]: unknown;
6565
}
6666

67+
/**
68+
* Normalize and hard-validate the Nous Portal OAuth base URL.
69+
*
70+
* Security: the portal accepts the bearer-equivalent single-use refresh token
71+
* in the `x-nous-refresh-token` header and returns the per-request inference
72+
* JWT as the access token. Sending either over cleartext (or to a
73+
* credential/query/fragment-laden URL) leaks credentials to a network
74+
* attacker. Validate the *complete* URL up front and throw before any
75+
* `fetch` is dispatched — both the device-grant and the refresh path call
76+
* this from inside their `fetch` arguments, so a thrown error guarantees the
77+
* network call never runs.
78+
*
79+
* Mirrors the allowlist discipline in Hermes `hermes_cli/auth.py`
80+
* (`_NOUS_PORTAL_ALLOWED_HOSTS`, https-only default
81+
* `DEFAULT_NOUS_PORTAL_URL`).
82+
*/
6783
function resolvePortalBaseUrl(): string {
68-
return (process.env.NOUS_PORTAL_BASE_URL || NOUS_PORTAL_BASE_URL).replace(/\/+$/, "");
84+
const raw = (process.env.NOUS_PORTAL_BASE_URL || NOUS_PORTAL_BASE_URL).trim();
85+
let url: URL;
86+
try {
87+
url = new URL(raw);
88+
} catch {
89+
throw new NousTokenError(undefined, undefined, `Nous Portal base URL is not a valid URL: ${raw}`);
90+
}
91+
if (url.protocol !== "https:") {
92+
throw new NousTokenError(undefined, undefined, `Nous Portal base URL must use HTTPS (got ${url.protocol}): ${raw}`);
93+
}
94+
if (url.username || url.password) {
95+
throw new NousTokenError(undefined, undefined, `Nous Portal base URL must not contain embedded credentials: ${raw}`);
96+
}
97+
if (url.search) {
98+
throw new NousTokenError(undefined, undefined, `Nous Portal base URL must not contain a query string: ${raw}`);
99+
}
100+
if (url.hash) {
101+
throw new NousTokenError(undefined, undefined, `Nous Portal base URL must not contain a fragment: ${raw}`);
102+
}
103+
// Origin only — no path/query/fragment — so callers cannot smuggle a
104+
// non-canonical endpoint through the override.
105+
return url.origin;
69106
}
70107

71108
function decodeJwtPayload(token: string): NousJwtPayload | undefined {
@@ -146,11 +183,38 @@ async function readTokenError(response: Response): Promise<NousTokenError> {
146183
return new NousTokenError(response.status, oauthError, `Nous Portal token request failed: ${response.status}${suffix}`);
147184
}
148185

149-
function parseTokenPayload(payload: NousTokenResponse, refreshFallback?: string): OAuthCredentials {
186+
/**
187+
* Build credentials from a token endpoint response.
188+
*
189+
* Nous refresh tokens are SINGLE-USE and rotated on every successful refresh
190+
* (see module docstring, matching Hermes `hermes_cli/auth.py`). A response
191+
* that omits `refresh_token`, or returns a replacement equal to the token we
192+
* just submitted, leaves us holding a consumed credential: the next refresh
193+
* would replay it and the Portal treats reuse as token theft
194+
* (`refresh_token_reused`), revoking the whole session. Reject both cases
195+
* rather than silently falling back to the submitted token.
196+
*
197+
* @param submittedRefreshToken the refresh token sent in the request; used only
198+
* to detect a no-rotation / consumed-token response, never as a fallback.
199+
*/
200+
function parseTokenPayload(payload: NousTokenResponse, submittedRefreshToken: string): OAuthCredentials {
150201
const access = nonEmptyString(payload.access_token);
151202
if (!access) throw new Error("Nous Portal token response did not include an access token");
152-
const refresh = nonEmptyString(payload.refresh_token) ?? refreshFallback;
153-
if (!refresh) throw new Error("Nous Portal token response did not include a refresh token");
203+
const refresh = nonEmptyString(payload.refresh_token);
204+
if (!refresh) {
205+
throw new NousTokenError(
206+
undefined,
207+
"refresh_token_reused",
208+
"Nous Portal did not return a replacement refresh token; refusing to reuse the consumed one (would trigger refresh_token_reused and revoke the session)",
209+
);
210+
}
211+
if (submittedRefreshToken && refresh === submittedRefreshToken) {
212+
throw new NousTokenError(
213+
undefined,
214+
"refresh_token_reused",
215+
"Nous Portal returned the same refresh token we submitted; refusing to reuse it (single-use rotation expected, session may be compromised)",
216+
);
217+
}
154218

155219
const jwtPayload = decodeJwtPayload(access);
156220
const expMs = jwtExpiryMs(jwtPayload);
@@ -225,7 +289,7 @@ async function pollForToken(
225289
signal: requestSignal(signal),
226290
});
227291
const payload = (await response.json().catch(() => ({}))) as NousTokenResponse;
228-
if (response.ok && nonEmptyString(payload.access_token)) return parseTokenPayload(payload);
292+
if (response.ok && nonEmptyString(payload.access_token)) return parseTokenPayload(payload, "");
229293
const error = payload.error;
230294
if (error === "authorization_pending") {
231295
await sleep(waitMs, signal);
Collapse file

‎tests/nous-oauth-live.test.ts‎

Copy file name to clipboard
+61Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Opt-in, NON-DESTRUCTIVE live verification for the Nous Portal provider.
3+
*
4+
* This file is skipped unless `NOUS_LIVE_TEST=1` is set, so it never runs in
5+
* CI and no credential ever travels off the local machine. It exists to let a
6+
* reviewer (or the author) prove the real-account refresh path and live
7+
* catalog discovery against the production Portal.
8+
*
9+
* Safety rules (no provider API key is ever shared):
10+
* - The refresh token is read ONLY from the local auth store on disk and is
11+
* NEVER printed. Only token *lengths* are reported.
12+
* - No value derived from a token (access/refresh/JWT) is echoed.
13+
* - This test REFRESHES but does NOT persist the rotated token back to the
14+
* store and does NOT call logout, so it cannot destroy the real session.
15+
* - It performs a single read-only GET against the live model catalog.
16+
*/
17+
import { describe, expect, test } from "bun:test";
18+
import { getCredential } from "../src/oauth/store";
19+
import { refreshNousToken } from "../src/oauth/nous";
20+
21+
const LIVE = process.env.NOUS_LIVE_TEST === "1";
22+
23+
// Redact: report only the kind and length of a secret, never the value.
24+
function len(label: string, v: string | undefined): void {
25+
if (v === undefined) {
26+
console.log(` ${label}: <absent>`);
27+
return;
28+
}
29+
console.log(` ${label}.len: ${v.length}`);
30+
}
31+
32+
describe.skipIf(!LIVE)("Nous Portal live verification (opt-in, no key shared)", () => {
33+
test("real-account refresh returns a rotated token and live catalog is reachable", async () => {
34+
const stored = getCredential("nous");
35+
expect(stored?.refresh, "expected a local nous refresh token; set NOUS_LIVE_TEST=1 with a logged-in account").toBeTruthy();
36+
37+
console.log("[live] using locally stored nous credential (tokens withheld):");
38+
len("stored.access", stored!.access);
39+
len("stored.refresh", stored!.refresh);
40+
len("stored.accountId", stored!.accountId);
41+
42+
// Refresh against the production Portal. Tokens are read back but redacted.
43+
const refreshed = await refreshNousToken(stored!.refresh);
44+
len("refreshed.access", refreshed.access);
45+
len("refreshed.refresh", refreshed.refresh);
46+
expect(refreshed.access.length).toBeGreaterThan(0);
47+
expect(refreshed.refresh.length).toBeGreaterThan(0);
48+
// Rotation must have produced a different refresh token (single-use contract).
49+
expect(refreshed.refresh).not.toBe(stored!.refresh);
50+
51+
// Read-only live catalog discovery (same endpoint the adapter uses).
52+
const res = await fetch("https://inference-api.nousresearch.com/v1/models", {
53+
headers: { Authorization: `Bearer ${refreshed.access}` },
54+
});
55+
expect(res.status).toBe(200);
56+
const models = (await res.json()) as Array<{ id?: string }>;
57+
const ids = models.map((m) => m.id).filter(Boolean) as string[];
58+
console.log(`[live] live catalog returned ${ids.length} models; free tier present: ${ids.some((id) => id.endsWith(":free"))}`);
59+
expect(ids.length).toBeGreaterThan(0);
60+
}, 60_000);
61+
});
Collapse file

‎tests/nous-oauth.test.ts‎

Copy file name to clipboardExpand all lines: tests/nous-oauth.test.ts
+117-7Lines changed: 117 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { getCredential, listAccounts, saveCredential } from "../src/oauth/store"
66
import type { OAuthController } from "../src/oauth/types";
77

88
const TEST_DIR = join(import.meta.dir, ".tmp-nous-oauth-test");
9-
const TEST_PORTAL = "http://portal.test";
9+
const TEST_PORTAL = "https://portal.test";
1010
let previousOpencodexHome: string | undefined;
1111
let previousPortalBase: string | undefined;
1212

@@ -159,15 +159,33 @@ describe("Nous device-flow error handling", () => {
159159
new Response(JSON.stringify({ error: "access_denied", error_description: "User denied the request" }), { status: 400 }),
160160
);
161161
const ctrl: OAuthController = { onAuth() {} };
162-
await expect(loginNous(ctrl)).rejects.toThrow("Nous Portal device authorization denied");
162+
let err: unknown;
163+
try {
164+
await loginNous(ctrl);
165+
} catch (e) {
166+
err = e;
167+
}
168+
expect(err).toBeInstanceOf(Error);
169+
expect((err as Error).message).toContain("Nous Portal device authorization denied");
170+
expect((err as { name?: string }).name).toBe("NousTokenError");
171+
expect((err as { oauthError?: string }).oauthError).toBe("access_denied");
163172
});
164173

165174
test("expired_token surfaces as a terminal NousTokenError", async () => {
166175
globalThis.fetch = deviceFlowFetch(() =>
167176
new Response(JSON.stringify({ error: "expired_token", error_description: "Code expired" }), { status: 400 }),
168177
);
169178
const ctrl: OAuthController = { onAuth() {} };
170-
await expect(loginNous(ctrl)).rejects.toThrow("Nous Portal device authorization expired");
179+
let err: unknown;
180+
try {
181+
await loginNous(ctrl);
182+
} catch (e) {
183+
err = e;
184+
}
185+
expect(err).toBeInstanceOf(Error);
186+
expect((err as Error).message).toContain("Nous Portal device authorization expired");
187+
expect((err as { name?: string }).name).toBe("NousTokenError");
188+
expect((err as { oauthError?: string }).oauthError).toBe("expired_token");
171189
});
172190

173191
test("slow_down backs off and resumes polling until success", async () => {
@@ -213,7 +231,68 @@ describe("Nous device-flow error handling", () => {
213231
}, 15_000);
214232
});
215233

216-
describe("Nous refresh fallback", () => {
234+
describe("Nous Portal base URL hardening", () => {
235+
test("an HTTP override fails before fetch is invoked", async () => {
236+
process.env.NOUS_PORTAL_BASE_URL = "http://portal.test";
237+
let fetchCalled = false;
238+
const realFetch = globalThis.fetch;
239+
globalThis.fetch = (async () => {
240+
fetchCalled = true;
241+
return new Response("{}", { status: 200 });
242+
}) as typeof fetch;
243+
try {
244+
const ctrl: OAuthController = { onAuth() {} };
245+
await expect(loginNous(ctrl)).rejects.toThrow(/must use HTTPS/);
246+
await expect(refreshNousToken("old-refresh")).rejects.toThrow(/must use HTTPS/);
247+
expect(fetchCalled).toBe(false);
248+
} finally {
249+
globalThis.fetch = realFetch;
250+
delete process.env.NOUS_PORTAL_BASE_URL;
251+
}
252+
});
253+
254+
test("a non-URL override fails before fetch is invoked", async () => {
255+
process.env.NOUS_PORTAL_BASE_URL = "not a url";
256+
let fetchCalled = false;
257+
const realFetch = globalThis.fetch;
258+
globalThis.fetch = (async () => {
259+
fetchCalled = true;
260+
return new Response("{}", { status: 200 });
261+
}) as typeof fetch;
262+
try {
263+
await expect(refreshNousToken("old-refresh")).rejects.toThrow(/not a valid URL/);
264+
expect(fetchCalled).toBe(false);
265+
} finally {
266+
globalThis.fetch = realFetch;
267+
delete process.env.NOUS_PORTAL_BASE_URL;
268+
}
269+
});
270+
271+
test("embedded credentials / query / fragment in the override are rejected", async () => {
272+
for (const bad of [
273+
"https://user:[email protected]",
274+
"https://portal.test?x=1",
275+
"https://portal.test#frag",
276+
]) {
277+
process.env.NOUS_PORTAL_BASE_URL = bad;
278+
const realFetch = globalThis.fetch;
279+
let fetchCalled = false;
280+
globalThis.fetch = (async () => {
281+
fetchCalled = true;
282+
return new Response("{}", { status: 200 });
283+
}) as typeof fetch;
284+
try {
285+
await expect(refreshNousToken("old-refresh")).rejects.toThrow(/base URL/);
286+
expect(fetchCalled).toBe(false);
287+
} finally {
288+
globalThis.fetch = realFetch;
289+
delete process.env.NOUS_PORTAL_BASE_URL;
290+
}
291+
}
292+
});
293+
});
294+
295+
describe("Nous refresh token safety", () => {
217296
const realFetch = globalThis.fetch;
218297

219298
beforeEach(() => {
@@ -227,7 +306,7 @@ describe("Nous refresh fallback", () => {
227306
else process.env.NOUS_PORTAL_BASE_URL = previousPortalBase;
228307
});
229308

230-
test("keeps the previous refresh token when the response omits a new one", async () => {
309+
test("rejecting a missing replacement refresh token does not reuse the consumed one", async () => {
231310
const access = jwtWithClaims({ sub: "wired-user", exp: Math.floor(Date.now() / 1000) + 3600 });
232311
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
233312
const observedHeader = (init?.headers as Record<string, string> | undefined)?.["x-nous-refresh-token"];
@@ -239,10 +318,41 @@ describe("Nous refresh fallback", () => {
239318
}), { status: 200 });
240319
}) as typeof fetch;
241320

242-
const cred = await refreshNousToken("old-refresh");
321+
await expect(refreshNousToken("old-refresh")).rejects.toMatchObject({
322+
name: "NousTokenError",
323+
oauthError: "refresh_token_reused",
324+
});
325+
});
326+
327+
test("rejecting a replacement equal to the submitted token (consumed-credential reuse)", async () => {
328+
const access = jwtWithClaims({ sub: "wired-user", exp: Math.floor(Date.now() / 1000) + 3600 });
329+
globalThis.fetch = (async () => new Response(JSON.stringify({
330+
access_token: access,
331+
refresh_token: "old-refresh", // identical to what was submitted
332+
expires_in: 3600,
333+
}), { status: 200 })) as typeof fetch;
334+
335+
await expect(refreshNousToken("old-refresh")).rejects.toMatchObject({
336+
name: "NousTokenError",
337+
oauthError: "refresh_token_reused",
338+
});
339+
});
243340

341+
test("a rotated replacement refresh token is kept", async () => {
342+
const access = jwtWithClaims({ sub: "wired-user", exp: Math.floor(Date.now() / 1000) + 3600 });
343+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
344+
const observedHeader = (init?.headers as Record<string, string> | undefined)?.["x-nous-refresh-token"];
345+
expect(observedHeader).toBe("old-refresh");
346+
return new Response(JSON.stringify({
347+
access_token: access,
348+
refresh_token: "rotated-refresh",
349+
expires_in: 3600,
350+
}), { status: 200 });
351+
}) as typeof fetch;
352+
353+
const cred = await refreshNousToken("old-refresh");
244354
expect(cred.access).toBe(access);
245-
expect(cred.refresh).toBe("old-refresh");
355+
expect(cred.refresh).toBe("rotated-refresh");
246356
expect(cred.accountId).toBe("wired-user");
247357
});
248358
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.