惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
L
LangChain Blog
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
MongoDB | Blog
MongoDB | Blog
Hugging Face - Blog
Hugging Face - Blog
G
Google Developers Blog
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
博客园 - 三生石上(FineUI控件)
D
DataBreaches.Net
Recent Announcements
Recent Announcements
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

Recent Commits to openclaw:main

test: merge chat side-result checks · openclaw/openclaw@ddd2c2a test: merge cron history checks · openclaw/openclaw@f7eb746 test: merge responsive navigation shell checks · openclaw/openclaw@c2e4b47 docs(changelog): add codex oauth fixes · openclaw/openclaw@628e6cd test: merge navigation routing cases · openclaw/openclaw@5d8cecb Tests: mock channel registry bundled fallback · openclaw/openclaw@2b08233 Secrets: avoid broad web search discovery for single plugin config · openclaw/openclaw@a464f59 test: merge config view browser checks · openclaw/openclaw@20cf511 fix(status): align oauth health with runtime · openclaw/openclaw@eed7116 feat: add macOS screen snapshots for monitor preview (#67954) thanks … · openclaw/openclaw@f377db1 fix: report shared auth scopes in hello-ok (#67810) thanks @BunsDev · openclaw/openclaw@0b6c39b Auto-reply: avoid eager bundled route fallback · openclaw/openclaw@3ea1bf4 Tests: narrow session binding contract setup · openclaw/openclaw@54e4e16 fix(macOS): enable undo/redo in webchat composer text input (#34962) · openclaw/openclaw@00951dc Tests: speed up channel setup promotion · openclaw/openclaw@82b529a Docs: refresh agent instructions · openclaw/openclaw@5775fe2 fix(auth): serialize OAuth refresh across agents to fix #26322 (#67876) · openclaw/openclaw@8e79080 test: allow ollama public surface boundary test · openclaw/openclaw@7d4f1a6 Docs: add test performance guardrails · openclaw/openclaw@89706d3 Tests: restore context-engine usage proof · openclaw/openclaw@e4c4f95 Tests: slim context engine runtime coverage · openclaw/openclaw@74c198f ci: retry failed custom checkouts · openclaw/openclaw@0ee5baf test: trim duplicate provider auth onboarding cases · openclaw/openclaw@1ffc02e matrix: fix sessions_spawn --thread subagent session spawning (#67643) · openclaw/openclaw@1ce2596 test: reduce auth choice fixture churn · openclaw/openclaw@857b9cd test: mock health status config boundaries · openclaw/openclaw@9d5ab4a test: mock onboard config io boundary · openclaw/openclaw@299694d test: mock legacy state plugin boundaries · openclaw/openclaw@2713089 test: mock channel install boundaries · openclaw/openclaw@b945248 test: mock doctor preview channel boundaries · openclaw/openclaw@b1a3ad4
feat(xai): add device code oauth login · openclaw/opencla...
fuller-stack · 2026-05-19 · via Recent Commits to openclaw:main

@@ -1,9 +1,10 @@

1-

import { describe, expect, it, vi } from "vitest";

1+

import { afterEach, describe, expect, it, vi } from "vitest";

22

import {

33

buildXaiOAuthAuthorizationCodeTokenBody,

44

buildXaiOAuthAuthorizeUrl,

55

fetchXaiOAuthDiscovery,

66

isTrustedXaiOAuthEndpoint,

7+

loginXaiDeviceCode,

78

refreshXaiOAuthCredential,

89

XAI_OAUTH_CALLBACK_CORS_ORIGIN_ALLOWLIST,

910

XAI_OAUTH_CALLBACK_PORT,

@@ -20,7 +21,26 @@ function jsonResponse(value: unknown, init?: ResponseInit): Response {

2021

});

2122

}

222324+

function createJwt(payload: Record<string, unknown>): string {

25+

const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");

26+

const body = Buffer.from(JSON.stringify(payload)).toString("base64url");

27+

return `${header}.${body}.signature`;

28+

}

29+30+

function requireStringBody(init: RequestInit | undefined): string {

31+

if (typeof init?.body !== "string") {

32+

throw new Error("expected request body to be a string");

33+

}

34+

return init.body;

35+

}

36+2337

describe("xAI OAuth", () => {

38+

afterEach(() => {

39+

vi.unstubAllGlobals();

40+

vi.unstubAllEnvs();

41+

vi.useRealTimers();

42+

});

43+2444

it("accepts only trusted xAI OAuth endpoints", () => {

2545

expect(isTrustedXaiOAuthEndpoint("https://auth.x.ai/oauth2/token")).toBe(true);

2646

expect(isTrustedXaiOAuthEndpoint("https://accounts.x.ai/oauth2/token")).toBe(true);

@@ -80,12 +100,14 @@ describe("xAI OAuth", () => {

80100

const fetchImpl = vi.fn(async () =>

81101

jsonResponse({

82102

authorization_endpoint: "https://auth.x.ai/oauth2/authorize",

103+

device_authorization_endpoint: "https://auth.x.ai/oauth2/device/code",

83104

token_endpoint: "https://auth.x.ai/oauth2/token",

84105

}),

85106

) as unknown as typeof fetch;

8610787108

await expect(fetchXaiOAuthDiscovery({ fetchImpl })).resolves.toEqual({

88109

authorizationEndpoint: "https://auth.x.ai/oauth2/authorize",

110+

deviceAuthorizationEndpoint: "https://auth.x.ai/oauth2/device/code",

89111

tokenEndpoint: "https://auth.x.ai/oauth2/token",

90112

});

91113

@@ -99,6 +121,7 @@ describe("xAI OAuth", () => {

99121

const poisonedFetch = vi.fn(async () =>

100122

jsonResponse({

101123

authorization_endpoint: "https://auth.x.ai/oauth2/authorize",

124+

device_authorization_endpoint: "https://auth.x.ai/oauth2/device/code",

102125

token_endpoint: "https://evil.test/oauth2/token",

103126

}),

104127

) as unknown as typeof fetch;

@@ -143,4 +166,98 @@ describe("xAI OAuth", () => {

143166

expect(refreshed.expires).toBe(121_000);

144167

vi.unstubAllEnvs();

145168

});

169+170+

it("logs in with xAI device code without a localhost callback", async () => {

171+

vi.stubEnv("OPENCLAW_VERSION", "2026.3.22");

172+

const progress = {

173+

update: vi.fn(),

174+

stop: vi.fn(),

175+

};

176+

const fetchImpl = vi

177+

.fn<typeof fetch>()

178+

.mockResolvedValueOnce(

179+

jsonResponse({

180+

authorization_endpoint: "https://auth.x.ai/oauth2/authorize",

181+

device_authorization_endpoint: "https://auth.x.ai/oauth2/device/code",

182+

token_endpoint: "https://auth.x.ai/oauth2/token",

183+

}),

184+

)

185+

.mockResolvedValueOnce(

186+

jsonResponse({

187+

device_code: "device-code-1",

188+

user_code: "ABCD-1234",

189+

verification_uri: "https://accounts.x.ai/oauth2/device",

190+

verification_uri_complete: "https://accounts.x.ai/oauth2/device?user_code=ABCD-1234",

191+

expires_in: 900,

192+

interval: 5,

193+

}),

194+

)

195+

.mockResolvedValueOnce(

196+

jsonResponse({

197+

access_token: createJwt({ exp: 4, sub: "acct-1" }),

198+

refresh_token: "refresh-1",

199+

id_token: createJwt({

200+

sub: "acct-1",

201+

email: "dev@example.com",

202+

name: "Dev User",

203+

}),

204+

expires_in: 120,

205+

}),

206+

);

207+

vi.stubGlobal("fetch", fetchImpl);

208+

const ctx = {

209+

config: {},

210+

isRemote: true,

211+

openUrl: vi.fn(async () => {}),

212+

prompter: {

213+

progress: vi.fn(() => progress),

214+

note: vi.fn(async () => {}),

215+

},

216+

runtime: {

217+

log: vi.fn(),

218+

},

219+

oauth: {},

220+

};

221+222+

const result = await loginXaiDeviceCode(ctx as never);

223+224+

expect(ctx.openUrl).not.toHaveBeenCalled();

225+

expect(ctx.prompter.note).toHaveBeenCalledWith(

226+

expect.stringContaining("ABCD-1234"),

227+

"xAI device code",

228+

);

229+

const remoteLog = ctx.runtime.log.mock.calls[0]?.[0];

230+

expect(remoteLog).toContain("https://accounts.x.ai/oauth2/device");

231+

expect(remoteLog).not.toContain("ABCD-1234");

232+

const deviceRequest = fetchImpl.mock.calls[1]?.[1];

233+

expect(deviceRequest?.method).toBe("POST");

234+

const deviceBody = requireStringBody(deviceRequest);

235+

expect(deviceBody).toContain(`client_id=${encodeURIComponent(XAI_OAUTH_CLIENT_ID)}`);

236+

expect(deviceBody).toContain(`scope=${encodeURIComponent(XAI_OAUTH_SCOPE)}`);

237+238+

const tokenRequest = fetchImpl.mock.calls[2]?.[1];

239+

expect(tokenRequest?.method).toBe("POST");

240+

const tokenBody = requireStringBody(tokenRequest);

241+

expect(tokenBody).toContain(

242+

"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code",

243+

);

244+

expect(tokenBody).toContain("device_code=device-code-1");

245+246+

const credential = result.profiles[0]?.credential as Record<string, unknown> | undefined;

247+

expect(credential).toMatchObject({

248+

type: "oauth",

249+

provider: "xai",

250+

refresh: "refresh-1",

251+

email: "dev@example.com",

252+

displayName: "Dev User",

253+

tokenEndpoint: "https://auth.x.ai/oauth2/token",

254+

deviceAuthorizationEndpoint: "https://auth.x.ai/oauth2/device/code",

255+

issuer: "https://auth.x.ai",

256+

authFlow: "device-code",

257+

accountId: "acct-1",

258+

});

259+

expect(credential?.access).toEqual(expect.any(String));

260+

expect(progress.update).toHaveBeenCalledWith("Waiting for xAI device authorization...");

261+

expect(progress.stop).toHaveBeenCalledWith("xAI device code complete");

262+

});

146263

});