Repository navigation
Expand file tree
/
Copy pathtest.js
More file actions
706 lines (671 loc) · 38.1 KB
/
Copy pathtest.js
File metadata and controls
706 lines (671 loc) · 38.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
"use strict";
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const test = require("node:test");
const vm = require("node:vm");
const { spawn, execFileSync } = require("node:child_process");
const { createAccountSwitcher } = require("./runtime");
const { applyMain, applyUi } = require("./patch");
const { loadLinuxFeaturePatchDescriptors, enabledLinuxFeaturePackagePlan } = require("../../scripts/lib/linux-features");
const { findWebviewAssetsContaining } = require("../../scripts/patches/lib/assets.js");
function credentials(name) {
const token = claims => `e30.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.signature`;
return JSON.stringify({ auth_mode: "chatgpt", tokens: {
id_token: token({ sub: `user-${name}`, email: `${name}@example.invalid`, "https://api.openai.com/auth": { chatgpt_plan_type: "plus" } }),
access_token: token({ "https://api.openai.com/auth": { chatgpt_account_id: `account-${name}`, chatgpt_user_id: `user-${name}` } }),
refresh_token: `private-refresh-${name}`, account_id: `account-${name}`,
}});
}
function fixture(t, options = {}) {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "account-switcher-test-"));
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
const authPath = path.join(home, "auth.json");
const vault = path.join(home, ".community-account-switcher/accounts.json");
fs.writeFileSync(authPath, credentials("first"), { mode: 0o600 });
const key = crypto.randomBytes(32);
const cipher = {
encryptString: text => {
const iv = crypto.randomBytes(12), cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const data = Buffer.concat([cipher.update(text), cipher.final()]);
return Buffer.concat([iv, cipher.getAuthTag(), data]);
},
decryptString: buffer => {
const decipher = crypto.createDecipheriv("aes-256-gcm", key, buffer.subarray(0, 12));
decipher.setAuthTag(buffer.subarray(12, 28));
return Buffer.concat([decipher.update(buffer.subarray(28)), decipher.final()]).toString();
},
};
const dialogs = [], menus = [], choices = [], calls = [];
let notification, active = "first", restartFails = false;
let ready = options.lazyConnection !== true;
const dialog = { showMessageBox: async settings => {
dialogs.push(settings);
if (settings.signal) {
if (options.login) {
const name = options.login;
fs.writeFileSync(authPath, credentials(name)); active = name;
notification({ method: "account/login/completed", params: { loginId: "login-1", success: true } });
return new Promise(resolve => settings.signal.addEventListener("abort", () => resolve({ response: 0 }), { once: true }));
}
return { response: 0 };
}
return { response: choices.shift() ?? settings.cancelId ?? 0 };
}};
const client = {
hostConfig: { id: "local", kind: "local" },
ensureReady: async () => { ready = true; calls.push("ensureReady"); },
getConnectionState: () => ready ? "connected" : "disconnected",
getPendingRequestCount: async () => options.pending ?? 0,
getAuthenticatedPrincipal: async () => ({ accountId: `account-${active}`, userId: `user-${active}` }),
restart: async () => {
calls.push("restart");
const name = JSON.parse(fs.readFileSync(authPath)).tokens.account_id.slice(8);
if (restartFails && name === "second") throw new Error("secret upstream error");
active = name;
},
registerInternalNotificationHandler: callback => { notification = callback; return () => { notification = undefined; }; },
sendInternalRequest: async request => {
if (!ready) throw new Error("Codex app-server is not available");
calls.push(request.method);
if (options.rpcFails) return { error: { message: "upstream-secret" } };
switch (request.method) {
case "thread/loaded/list": return { result: { data: options.activeTask ? ["working"] : [], nextCursor: null } };
case "thread/read": return { result: { thread: { status: { type: "active" } } } };
case "account/read": return { result: { account: { type: "chatgpt" } } };
case "account/login/start": return { result: { type: "chatgpt", loginId: "login-1", authUrl: options.authUrl ?? "https://auth.openai.com/oauth/authorize?test=1" } };
case "account/login/cancel": return { result: {} };
default: throw new Error(`unexpected request: ${request.method}`);
}
},
};
client.sendAppServerRequest = async (method, params) => {
await client.ensureReady();
const response = await client.sendInternalRequest({ method, params });
if (response.error) throw new Error("sensitive upstream error");
return response.result;
};
const electron = { get safeStorage() { throw new Error("No such binding was linked: electron_browser_safe_storage"); }, dialog, shell: { openExternal: async url => calls.push(url) }, Menu: {
buildFromTemplate: template => ({ popup: ({ callback }) => {
menus.push(template);
const selectable = template.filter(item => item.value !== undefined && item.enabled !== false);
const selected = selectable[choices.shift()];
if (selected) selected.click();
callback();
} }),
}};
const keyringCalls = [];
let savedKey = options.keyInitiallyMissing ? null : key.toString("hex");
const runSecretTool = async (args, input) => {
keyringCalls.push({ args, input });
if (options.missingExecutable) { const e = new Error("sensitive test error"); e.code = "ENOENT"; throw e; }
if (options.keyringUnavailable) return { code: 2, stdout: "" };
if (args[0] === "store") {
if (options.storeFails) return { code: 1, stdout: "" };
if (!options.keyRetainFails) savedKey = input;
return { code: 0, stdout: "" };
}
return { code: savedKey ? 0 : 1, stdout: options.malformedKey ? "invalid" : savedKey ?? "" };
};
const clients = [client];
const runtime = createAccountSwitcher({ electron, clients: () => clients, home, runSecretTool });
return {
home, authPath, vault, cipher, keyringCalls, dialogs, menus, choices, calls, runtime, client, clients,
open: async response => { choices.push(response); await runtime.open(client); },
seedSecond: () => {
const stored = JSON.parse(fs.readFileSync(vault));
const text = credentials("second");
const id = crypto.createHash("sha256").update(JSON.stringify(["user-second", "account-second"])).digest("hex");
stored.accounts.push({ id, encrypted: cipher.encryptString(text).toString("base64") });
fs.writeFileSync(vault, JSON.stringify(stored));
},
failSecondRestart: () => { restartFails = true; },
};
}
test("feature is opt-in, has both contracts and rejects a shared server", t => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "account-switcher-config-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const config = path.join(dir, "features.json");
const options = { featuresRoot: path.resolve(__dirname, ".."), featuresConfigPath: config };
fs.writeFileSync(config, JSON.stringify({ enabled: [] }));
assert.deepEqual(loadLinuxFeaturePatchDescriptors(options), []);
fs.writeFileSync(config, JSON.stringify({ enabled: ["account-switcher"] }));
assert.equal(loadLinuxFeaturePatchDescriptors(options).length, 2);
fs.writeFileSync(config, JSON.stringify({ enabled: ["account-switcher", "shared-app-server-socket"] }));
assert.throws(() => loadLinuxFeaturePatchDescriptors(options), /conflict/);
});
for (const options of [{ keyringUnavailable: true }, { keyInitiallyMissing: true, storeFails: true }]) {
test(`rejects unsafe encryption ${JSON.stringify(options)}`, async t => {
const f = fixture(t, options);
await f.open(1);
assert.equal(fs.existsSync(f.vault), false);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
assert.match(f.dialogs.at(-1).detail, /keyring/);
});
}
test("cancel stores only encrypted tokens, with private permissions", async t => {
const f = fixture(t);
await f.open(3);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
const stored = fs.readFileSync(f.vault, "utf8");
assert.ok(!stored.includes("private-refresh-first"));
assert.ok(!stored.includes("access_token"));
assert.equal(fs.statSync(f.vault).mode & 0o777, 0o600);
assert.equal(fs.statSync(path.dirname(f.vault)).mode & 0o777, 0o700);
});
test("creates and verifies a profile-specific Secret Service key without putting it in argv", async t => {
const f = fixture(t, { keyInitiallyMissing: true });
await f.open(3);
assert.equal(f.dialogs.length, 0);
assert.equal(JSON.parse(fs.readFileSync(f.vault)).version, 2);
assert.deepEqual(f.keyringCalls.map(call => call.args[0]), ["lookup", "store", "lookup"]);
const stored = f.keyringCalls[1];
assert.match(stored.input, /^[a-f0-9]{64}$/);
assert.ok(!JSON.stringify(stored.args).includes(stored.input));
assert.ok(!JSON.stringify(f.keyringCalls).includes("private-refresh-first"));
assert.equal(stored.args.at(-1), crypto.createHash("sha256").update(fs.realpathSync(f.home)).digest("hex"));
});
for (const options of [{ malformedKey: true }, { keyInitiallyMissing: true, keyRetainFails: true }]) {
test(`keyring failure leaves credentials unchanged ${JSON.stringify(options)}`, async t => {
const f = fixture(t, options);
await f.open(3);
assert.equal(fs.existsSync(f.vault), false);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
assert.equal(f.menus.length, 0);
assert.match(f.dialogs.at(-1).detail, /key/);
});
}
test("missing key never replaces an existing vault; corrupted ciphertext is rejected", async t => {
const f = fixture(t, { keyInitiallyMissing: true });
fs.mkdirSync(path.dirname(f.vault), { mode: 0o700 });
fs.writeFileSync(f.vault, '{"version":2,"accounts":[]}', { mode: 0o600 });
await f.open(3);
assert.deepEqual(f.keyringCalls.map(call => call.args[0]), ["lookup"]);
assert.match(f.dialogs.at(-1).detail, /key is unavailable/);
const g = fixture(t);
await g.open(3);
const saved = JSON.parse(fs.readFileSync(g.vault));
const ciphertext = Buffer.from(saved.accounts[0].encrypted, "base64");
ciphertext[15] ^= 1;
saved.accounts[0].encrypted = ciphertext.toString("base64");
const corrupted = JSON.stringify(saved);
fs.writeFileSync(g.vault, corrupted);
await g.open(3);
assert.equal(fs.readFileSync(g.vault, "utf8"), corrupted);
assert.match(g.dialogs.at(-1).detail, /could not be decrypted/);
});
test("missing secret-tool reports the dependency without touching login credentials", t => {
const f = fixture(t);
const program = `const {createAccountSwitcher}=require(${JSON.stringify(path.join(__dirname, "runtime.js"))});
const dialogs=[];const runtime=createAccountSwitcher({home:process.argv[1],clients:()=>[],
electron:{dialog:{showMessageBox:async o=>dialogs.push(o.detail)},Menu:{},shell:{}}});
runtime.open({}).then(()=>process.stdout.write(JSON.stringify(dialogs)));`;
const result = execFileSync(process.execPath, ["-e", program, f.home], { env: { ...process.env, PATH: "" }, timeout: 5_000 });
assert.match(JSON.parse(result)[0], /Install secret-tool/);
assert.equal(fs.existsSync(f.vault), false);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
});
test("native package plans declare the Secret Service CLI dependency", t => {
const f = fixture(t);
const config = path.join(f.home, "features.json");
fs.writeFileSync(config, JSON.stringify({ enabled: ["account-switcher"] }));
for (const [format, dependency] of [["deb", "libsecret-tools"], ["rpm", "libsecret"], ["pacman", "libsecret"]]) {
const plan = enabledLinuxFeaturePackagePlan({ packageFormat: format, featuresConfigPath: config });
assert.ok(plan.dependencies.includes(dependency), format);
assert.equal(plan.resources.length, 0);
}
assert.throws(() => require("../../scripts/lib/gentoo-feature-support").gentooFeaturePlan({ featuresConfigPath: config }),
/Gentoo does not support.*account-switcher/);
});
test("switches to a saved account and restores refreshed current credentials later", async t => {
const f = fixture(t);
await f.open(3); f.seedSecond();
const refreshed = credentials("first").replace("private-refresh-first", "refreshed-private-first");
fs.writeFileSync(f.authPath, refreshed);
await f.open(1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("second"));
await f.open(0);
assert.equal(fs.readFileSync(f.authPath, "utf8"), refreshed);
});
test("switching waits for the principal invalidated by the reconnect", async t => {
const f = fixture(t);
await f.open(3); f.seedSecond();
const settled = f.client.getAuthenticatedPrincipal;
let lookupsAfterRestart = 0;
f.client.getAuthenticatedPrincipal = async () => {
if (!f.calls.includes("restart")) return settled();
return ++lookupsAfterRestart < 3 ? null : settled();
};
await f.open(1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("second"));
assert.equal(f.calls.filter(c => c === "restart").length, 1);
assert.equal(lookupsAfterRestart, 3);
});
test("failed selected-account restart rolls back without exposing upstream errors", async t => {
const f = fixture(t);
await f.open(3); f.seedSecond(); f.failSecondRestart();
await f.open(1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
assert.equal(f.calls.filter(c => c === "restart").length, 2);
assert.match(f.dialogs.at(-1).detail, /previous account was restored/);
assert.ok(!f.dialogs.at(-1).detail.includes("secret"));
});
for (const options of [{ activeTask: true }, { pending: 1 }, { rpcFails: true }]) {
test(`busy or unverifiable backend refuses switching ${JSON.stringify(options)}`, async t => {
const f = fixture(t, options);
await f.open(3); f.seedSecond();
await f.open(1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
assert.equal(f.calls.includes("restart"), false);
assert.equal(f.dialogs.at(-1).type, "error");
});
}
test("cancelled browser login returns to the remembered account", async t => {
const f = fixture(t);
await f.open(1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
assert.ok(f.calls.includes("account/login/cancel"));
});
test("successful official login remembers the new account without logging out the old one", async t => {
const f = fixture(t, { login: "second" });
await f.open(1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("second"));
assert.equal(JSON.parse(fs.readFileSync(f.vault)).accounts.length, 2);
assert.ok(!f.calls.includes("account/logout"));
});
test("login completion waits for the principal invalidated by upstream account notifications", async t => {
const f = fixture(t, { login: "second" });
const settled = f.client.getAuthenticatedPrincipal;
let lookupsAfterLogin = 0;
f.client.getAuthenticatedPrincipal = async () => {
if (!fs.readFileSync(f.authPath, "utf8").includes("account-second")) return settled();
return ++lookupsAfterLogin < 3 ? null : settled();
};
await f.open(1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("second"));
assert.equal(JSON.parse(fs.readFileSync(f.vault)).accounts.length, 2);
});
test("adding an account initializes a lazy backend before checking tasks and starting OAuth", async t => {
const f = fixture(t, { lazyConnection: true });
await f.open(1);
assert.equal(f.dialogs.filter(dialog => dialog.type === "error").length, 0);
assert.ok(f.calls.includes("account/login/start"));
assert.ok(f.calls.includes("account/login/cancel"));
assert.ok(f.calls.indexOf("ensureReady") < f.calls.indexOf("thread/loaded/list"));
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
});
for (const action of ["add", "switch"]) {
for (const pending of [0, 1]) {
test(`cloud work in other apps does not gate ${action}; own pending requests=${pending}`, async t => {
const f = fixture(t);
const reads = [];
f.clients.push({
hostConfig: { id: "durable", kind: "local" },
getConnectionState: () => "connected",
getPendingRequestCount: async () => pending,
sendAppServerRequest: async method => {
reads.push(method);
// A catalog would contain a permanently active task from another
// profile. Even an unavailable cloud catalog must not gate login.
if (method === "thread/list") return { data: [{ status: { type: "active" } }], nextCursor: null };
throw new Error("gateway unavailable; sensitive upstream response");
},
});
if (action === "switch") { await f.open(3); f.seedSecond(); }
await f.open(1);
assert.deepEqual(reads, [], "do not query or cancel independent cloud work");
if (pending === 0) {
assert.equal(f.dialogs.filter(dialog => dialog.type === "error").length, 0);
if (action === "add") assert.ok(f.calls.includes("account/login/start"));
else assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("second"));
} else {
assert.equal(f.calls.includes("account/login/start"), false);
assert.equal(f.calls.includes("restart"), false);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
assert.match(f.dialogs.at(-1).detail, /pending requests/);
}
});
}
}
test("disconnected durable host is not opened during idle checks", async t => {
for (const action of ["switch", "add"]) {
const f = fixture(t, action === "add" ? { login: "second" } : {});
let durableOpened = false;
f.clients.push({
hostConfig: { id: "durable", kind: "local" },
getConnectionState: () => "disconnected",
getPendingRequestCount: async () => { durableOpened = true; return 0; },
});
if (action === "switch") { await f.open(3); f.seedSecond(); }
await f.open(1);
assert.equal(durableOpened, false, `disconnected durable host must not be opened during ${action}`);
assert.equal(f.dialogs.filter(dialog => dialog.type === "error").length, 0);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("second"));
}
});
test("login setup errors name the phase without exposing upstream error details", async t => {
const f = fixture(t);
f.client.registerInternalNotificationHandler = () => { throw new Error("private-error-token"); };
await f.open(1);
const detail = f.dialogs.at(-1).detail;
assert.match(detail, /subscribing to login completion/);
assert.ok(!detail.includes("private-error-token"));
assert.ok(!f.calls.includes("account/login/start"));
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
});
test("refuses an unexpected OAuth destination and restores current login", async t => {
const f = fixture(t, { authUrl: "https://example.invalid/steal" });
await f.open(1);
assert.ok(!f.calls.some(c => c.startsWith("https://")));
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
});
test("forget only removes saved credentials and cannot remove the active account", async t => {
const f = fixture(t);
await f.open(3); f.seedSecond(); f.choices.push(3, 0);
await f.runtime.open(f.client);
assert.equal(JSON.parse(fs.readFileSync(f.vault)).accounts.length, 1);
assert.equal(fs.readFileSync(f.authPath, "utf8"), credentials("first"));
assert.equal(f.calls.includes("restart"), false);
});
test("does not follow credential symlinks or overwrite corrupt vaults", async t => {
const f = fixture(t);
await f.open(3);
fs.writeFileSync(f.vault, "corrupt");
await f.open(1);
assert.equal(fs.readFileSync(f.vault, "utf8"), "corrupt");
fs.rmSync(f.authPath);
const target = path.join(f.home, "untouched.json");
fs.writeFileSync(target, credentials("first"), { mode: 0o600 });
fs.symlinkSync(target, f.authPath);
fs.rmSync(f.vault);
await f.open(1);
assert.equal(fs.existsSync(f.vault), false);
assert.equal(fs.readFileSync(target, "utf8"), credentials("first"));
});
test("refuses mismatched active authority rather than saving a stale login", async t => {
const f = fixture(t);
f.client.getAuthenticatedPrincipal = async () => ({ accountId: "different", userId: "different" });
await f.open(1);
assert.equal(fs.existsSync(f.vault), false);
assert.match(f.dialogs.at(-1).detail, /does not match/);
});
test("identity uses the current desktop user_id authority ahead of chatgpt_user_id", async t => {
const f = fixture(t);
const auth = JSON.parse(credentials("first"));
const claims = { "https://api.openai.com/auth": { chatgpt_account_id: "account-first", user_id: "canonical-user", chatgpt_user_id: "legacy-user" } };
auth.tokens.access_token = `e30.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.signature`;
fs.writeFileSync(f.authPath, JSON.stringify(auth));
f.client.getAuthenticatedPrincipal = async () => ({ accountId: "account-first", userId: "canonical-user" });
await f.open(3);
assert.equal(JSON.parse(fs.readFileSync(f.vault)).accounts.length, 1);
assert.equal(f.dialogs.length, 0);
});
// rspack/SWC webview chunk: module factories keyed by hashed ids, imports as
// module-scope `var x=n("id")` bindings, double-quoted strings. The sidebar
// branch reuses the menu-item module alias for the pet callback.
const UI_MODULE = 'Ab12(e,t,n){n.d(t,{Profile:()=>Profile});var UI=n("jsx"),Menu=n("menu"),Bus=n("bus"),Text=n("text");' +
'function Profile(props){let label,settings,group,{sidebarFooter:footer,onClose:close}=props,fmt=intl();' +
'fmt.formatMessage({id:"codex.profileDropdown.copyUserIdForEmail",defaultMessage:"Copy user ID for {email}"},{email:"a"});' +
'label=(0,UI.jsx)(Text.A,{id:"codex.profileDropdown.settingsPage",defaultMessage:"Settings",description:"Menu item to open Codex settings page"});' +
'settings=(0,UI.jsx)(Menu.tJ,{leftIconAsset:asset.T,keyboardShortcut:shortcut,onClick:settingsClick,children:label});' +
'group=(0,UI.jsxs)(UI.Fragment,{children:[divider,identity,null,settings]});' +
'if(null!=footer){let Menu=petEnabled?()=>{close(),Bus.O1.dispatchMessage("avatar-overlay-open",{})}:void 0;' +
'return(0,UI.jsx)(Layout,{accountIcon:icon,accountSwitcher:switcher,additionalItems:items,onCloseMenu:close,onTogglePet:Menu})}' +
'return(0,UI.jsxs)("div",{children:[group,workspace,analytics,more]})}}';
const UI_CHUNK = `export const __rspack_esm_id=1;export const __rspack_esm_ids=[1];export const __webpack_modules__={Zz99(e,t,n){n.d(t,{other:()=>1})},${UI_MODULE}};`;
// Loads the fixture chunk like the rspack runtime: run the module factory with
// a require function resolving its import bindings.
function loadProfile(source, context, imports) {
const sandbox = { ...context };
vm.runInNewContext(source.replace(/export const /g, "var "), sandbox);
const exports = {};
const load = id => imports[id];
load.d = (target, getters) => {
for (const [key, getter] of Object.entries(getters)) Object.defineProperty(target, key, { get: getter });
};
sandbox.__webpack_modules__.Ab12({}, exports, load);
return exports.Profile;
}
test("semantic contracts preserve renamed symbols, reject partial drift, and route the Polish menu action", async () => {
const main = 'async function handle(view,message){switch(message.type){case"mcp-request":{log().debug("app_server.bridge_received",{safe:{messageType:"mcp-request",requestId:String(message.request.id),method:message.request.method,originWebcontentsId:view.id,originHostId:message.hostId}});this.sendAppServerResponseToView();this.appServerConnectionRegistry.getAllHostIds();break}}}async function config(options){return[...(0,helpers.computeConfig)(options.globalState,options.hostConfig),...await options.secretAuthStorageConfigOverrides,...await extras(options)]}';
for (const [source, apply, drift] of [[main, applyMain, "secretAuthStorageConfigOverrides"], [UI_CHUNK, applyUi, "accountSwitcher"]]) {
const patched = apply(source);
assert.notEqual(patched, source);
new vm.Script(patched.replace(/export const /g, "var "));
assert.equal(apply(patched), patched);
assert.equal(apply(source + source), source + source);
assert.equal(apply(source.replace(drift, "retired")), source.replace(drift, "retired"));
}
const config = vm.runInNewContext(applyMain(main) + ";config", {
helpers: { computeConfig: () => ["base"] }, extras: async () => ["extras"],
});
for (const id of ["local", "ssh-test", "durable"]) {
const overrides = await config({ hostConfig: { id }, globalState: {}, secretAuthStorageConfigOverrides: ["policy"] });
assert.deepEqual(Array.from(overrides), ["base", "policy", "extras",
...(id === "local" ? ['cli_auth_credentials_store="file"', "features.secret_auth_storage=false"] : [])]);
}
// The retired pre-26.1021 config list with a trailing call is no longer accepted.
const retiredConfig = main.replace("await extras(options)]", "await extras(options),mode(options)]");
assert.equal(applyMain(retiredConfig), retiredConfig);
const invalid = {
unboundMenuModule: UI_CHUNK.replace('Menu=n("menu"),', ""),
unboundBus: UI_CHUNK.replace(',Bus=n("bus")', ""),
// Sites split across module factories cannot share the injected helper.
splitModules: UI_CHUNK.replace('fmt.formatMessage({id:"codex.profileDropdown.copyUserIdForEmail"', 'fmt.x}},Cd34(e,t,n){fmt.formatMessage({id:"codex.profileDropdown.copyUserIdForEmail"').replace("other:()=>1})}", "other:()=>1})}"),
retiredTemplateLiterals: UI_CHUNK.replace('"avatar-overlay-open"', "`avatar-overlay-open`"),
};
for (const [name, source] of Object.entries(invalid)) assert.equal(applyUi(source), source, name);
const renamed = UI_CHUNK.replace(/\bMenu\b/g, "RenamedMenu").replaceAll(".tJ", ".zQ").replace(/\bBus\b/g, "Wire").replaceAll(".O1", ".k9");
assert.match(applyUi(renamed), /\(0,UI\.jsx\)\(RenamedMenu\.zQ,\{onClick:\(\)=>\{close\(\);Wire\.k9\.dispatchMessage\("mcp-request"/);
const patched = applyUi(UI_CHUNK);
assert.equal(patched.match(/method:"community\/accountSwitcher"/g).length, 1);
assert.match(patched, /additionalItems:codexLinuxAccountSwitcherItems\(items,close,fmt\),/);
assert.match(patched, /children:\[divider,identity,null,settings,codexLinuxAccountSwitcherRow\(close,fmt\)\]/);
});
test("rendering either profile layout cannot invoke a shadowing pet callback", () => {
const patched = applyUi(UI_CHUNK);
assert.notEqual(patched, UI_CHUNK);
for (const sidebarFooter of [null, {}]) for (const petEnabled of [true, false]) {
const sent = [], rows = [];
let closed = 0, petClick;
const jsx = (type, props) => ({ type, props });
const MenuItem = props => { rows.push(props); return null; };
const profile = loadProfile(patched, {
petEnabled, intl: () => ({ locale: "pl", formatMessage() {} }),
Layout: props => { petClick = props.onTogglePet; return props.additionalItems; },
asset: { T: null }, shortcut: null, settingsClick() {}, icon: null, switcher: null,
items: null, identity: null, divider: null, workspace: null, analytics: null, more: null,
}, {
jsx: { jsx, jsxs: jsx, Fragment: "fragment" }, menu: { tJ: MenuItem },
bus: { O1: { dispatchMessage: (...args) => sent.push(args) } }, text: { A: () => null },
});
const render = node => {
if (Array.isArray(node)) return node.forEach(render);
if (!node || typeof node !== "object") return;
if (typeof node.type === "function") render(node.type(node.props));
else render(node.props.children);
};
for (let opening = 0; opening < 3; opening++) {
rows.length = 0;
render(profile({ sidebarFooter, onClose: () => closed++ }));
assert.equal(closed, 0, "opening the menu must not close it");
assert.equal(sent.length, 0, "rendering must not open the pet or switch accounts");
assert.equal(rows.filter(row => row.children === "Przełącz konto…").length, 1);
}
rows.find(row => row.children === "Przełącz konto…").onClick();
assert.equal(closed, 1);
assert.equal(sent.length, 1);
assert.equal(sent[0][0], "mcp-request");
assert.equal(sent[0][1].hostId, "local");
assert.equal(sent[0][1].request.method, "community/accountSwitcher");
assert.equal(sent[0][1].request.params.locale, "pl");
if (sidebarFooter && petEnabled) {
petClick();
assert.equal(closed, 2);
assert.equal(sent[1][0], "avatar-overlay-open", "the explicit pet action must remain available");
}
}
});
test("native account menu follows the app locale and marks the current account", async t => {
const f = fixture(t);
f.choices.push(3);
await f.runtime.open(f.client, undefined, "pl-PL");
assert.equal(f.menus[0][0].label, "Przełącz konto ChatGPT");
assert.equal(f.menus[0].filter(item => item.checked).length, 1);
assert.ok(f.menus[0].some(item => item.label === "Dodaj konto…"));
});
test("latest bundled CLI decodes the isolated OAuth file and supports the idle-check protocol", {
skip: !process.env.CODEX_ACCOUNT_SWITCHER_CLI,
timeout: 20_000,
}, async t => {
const f = fixture(t);
const env = { ...process.env, CODEX_HOME: f.home };
// login status parses the synthetic file locally. A real server login cannot
// be simulated: initialization discovers workspace routing on OpenAI's API.
execFileSync(process.env.CODEX_ACCOUNT_SWITCHER_CLI, ["login", "status"], { env, stdio: "pipe", timeout: 5_000 });
fs.rmSync(f.authPath);
const child = spawn(process.env.CODEX_ACCOUNT_SWITCHER_CLI, ["app-server", "-c", 'cli_auth_credentials_store="file"', "-c", "features.secret_auth_storage=false"], {
env, stdio: ["pipe", "pipe", "pipe"],
});
t.after(() => child.kill()); // Only this disposable test's child process.
let buffer = "", id = 0;
const pending = new Map();
child.stdout.on("data", bytes => {
buffer += bytes;
for (;;) {
const end = buffer.indexOf("\n");
if (end < 0) break;
const message = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1);
const response = pending.get(message.id);
if (response) { pending.delete(message.id); response(message); }
}
});
child.stderr.resume();
const request = (method, params) => new Promise(resolve => {
const requestId = ++id; pending.set(requestId, resolve);
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: requestId, method, params }) + "\n");
});
const initialized = await request("initialize", { clientInfo: { name: "community_account_switcher_test", version: "1" }, capabilities: { experimentalApi: true } });
assert.equal(initialized.error, undefined);
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
const loaded = await request("thread/loaded/list", { cursor: null, limit: 100 });
assert.equal(loaded.error, undefined);
assert.deepEqual(loaded.result.data, []);
const account = await request("account/read", { refreshToken: false });
assert.equal(account.error, undefined);
assert.equal(account.result.account, null);
// Generate and immediately cancel only this disposable server's OAuth flow.
// Never launch a browser or send real account credentials in this test.
const login = await request("account/login/start", { type: "chatgpt", appBrand: "chatgpt", useHostedLoginSuccessPage: true });
assert.ok(!login.error, "The bundled server must accept the browser-login parameters");
assert.equal(login.result.type, "chatgpt");
assert.equal(new URL(login.result.authUrl).hostname, "auth.openai.com");
const cancelled = await request("account/login/cancel", { loginId: login.result.loginId });
assert.ok(!cancelled.error, "The disposable login flow must cancel successfully");
});
// Use exact current signed-bundle fixtures when supplied by local or CI validation.
const official = process.env.CODEX_ACCOUNT_SWITCHER_OFFICIAL_DIR;
const signedApp = process.env.CODEX_SIGNED_EXTRACTED_APP;
test("official main and profile dropdown chunks patch uniquely and remain valid JavaScript", { skip: !official && !signedApp }, () => {
const { descriptors } = require("./patch");
const needles = descriptors.find(descriptor => descriptor.id === "account-switcher-profile-menu").assetNeedles;
for (const [kind, apply] of [["main", applyMain], ["webview", applyUi]]) {
const directory = official || path.join(signedApp, kind === "main" ? ".vite/build" : "webview/assets");
// rspack spreads the main process and the webview over chunks; exactly one must hold the contract.
const names = kind === "main"
? fs.readdirSync(directory).filter(file => file.startsWith("early-bootstrap") && file.endsWith(".js"))
: official ? fs.readdirSync(directory).filter(file => file.endsWith(".js"))
: findWebviewAssetsContaining(signedApp, needles);
const changed = names.filter(name => {
const source = fs.readFileSync(path.join(directory, name), "utf8");
return apply(source) !== source;
});
assert.equal(changed.length, 1, `expected a unique ${kind} chunk`);
const source = fs.readFileSync(path.join(directory, changed[0]), "utf8");
const patched = apply(source);
assert.notEqual(patched, source);
assert.equal(apply(patched), patched);
if (kind === "main") {
new vm.Script(patched);
assert.equal(patched.split("app.quit(").length, source.split("app.quit(").length);
assert.equal(patched.split("app.relaunch(").length, source.split("app.relaunch(").length);
} else {
assert.equal(patched.match(/method:"community\/accountSwitcher"/g).length, 1);
assert.equal(patched.match(/codexLinuxAccountSwitcherItems\(/g).length, 2);
assert.equal(patched.match(/codexLinuxAccountSwitcherRow\(/g).length, 3);
execFileSync(process.execPath, ["--input-type=module", "--check"], { input: patched, stdio: "pipe" });
// Execute the injected module-scope rows with inert JSX and transport
// bindings named exactly as the signed module's import bindings.
const ident = "[A-Za-z_$][\\w$]*";
const helper = patched.match(new RegExp(
`/\\*codexLinuxAccountSwitcherUi\\*/function codexLinuxAccountSwitcherRow\\(close,intl\\)\\{return\\(0,(${ident})\\.jsx\\)\\((${ident})\\.(${ident}),` +
`\\{onClick:\\(\\)=>\\{close\\(\\);(${ident})\\.(${ident})\\.dispatchMessage[\\s\\S]*?function codexLinuxAccountSwitcherItems\\(items,close,intl\\)\\{[^{}]*\\{[^{}]*\\}\\)\\}`));
assert.ok(helper, "injected module-scope helper");
const [code, jsxAlias, menuModule, menuExport, busModule, busExport] = helper;
for (const name of [jsxAlias, menuModule, busModule]) {
assert.match(source, new RegExp(`[,\\s]${name.replace(/\$/g, "\\$")}=[A-Za-z_$][\\w$]*\\("[^"]+"\\)`), `${name} is a module import binding`);
}
const sent = [], rendered = [];
let closed = 0;
const component = props => { rendered.push(props); return null; };
const jsx = (type, props) => ({ type, props });
const items = vm.runInNewContext(`${code};codexLinuxAccountSwitcherItems`, {
[jsxAlias]: { jsx, jsxs: jsx, Fragment: "fragment" }, [menuModule]: { [menuExport]: component },
[busModule]: { [busExport]: { dispatchMessage: (...args) => sent.push(args) } },
});
const element = items("existing", () => closed++, { locale: "pl" });
assert.equal(element.props.children[0], "existing");
const row = element.props.children[1];
assert.equal(row.type, component);
row.type(row.props);
assert.equal(rendered.length, 1);
assert.equal(rendered[0].children, "Przełącz konto…");
assert.equal(closed, 0);
assert.equal(sent.length, 0);
rendered[0].onClick();
assert.equal(closed, 1);
assert.deepEqual([sent.length, sent[0][0], sent[0][1].request.method], [1, "mcp-request", "community/accountSwitcher"]);
}
for (const invalid of [source + source, source.replaceAll("mcp-request", "retired-request").replaceAll("accountSwitcher", "retiredSwitcher")]) {
assert.equal(apply(invalid), invalid);
}
}
});
test("official Owl reaches OAuth and reopens an encrypted vault without querying independent cloud work", {
skip: !process.env.CODEX_ACCOUNT_SWITCHER_NATIVE_APP || !process.env.CODEX_ACCOUNT_SWITCHER_ASAR_CLI,
timeout: 30_000,
}, t => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "account-native-"));
const app = process.env.CODEX_ACCOUNT_SWITCHER_NATIVE_APP;
const home = path.join(dir, "home"), profile = path.join(dir, "profile");
const probe = path.join(dir, "app"), source = path.join(dir, "source");
fs.mkdirSync(path.join(probe, "resources"), { recursive: true });
fs.mkdirSync(source);
t.after(() => {
if (fs.existsSync(home)) {
const id = crypto.createHash("sha256").update(fs.realpathSync(home)).digest("hex");
try { execFileSync("secret-tool", ["clear", "application", "codex-desktop", "feature", "account-switcher", "profile", id], { stdio: "ignore", timeout: 5_000 }); } catch {}
}
fs.rmSync(dir, { recursive: true, force: true });
});
fs.copyFileSync(path.join(app, "ChatGPT"), path.join(probe, "ChatGPT"));
fs.chmodSync(path.join(probe, "ChatGPT"), 0o755);
for (const name of fs.readdirSync(app)) {
if (["ChatGPT", "resources", "start.sh", ".codex-linux"].includes(name)) continue;
fs.symlinkSync(path.join(app, name), path.join(probe, name));
}
for (const name of ["owl-app.ini", "owl-electron-app.json"]) fs.copyFileSync(path.join(app, "resources", name), path.join(probe, "resources", name));
fs.copyFileSync(path.join(__dirname, "native-probe.js"), path.join(source, "probe.js"));
fs.writeFileSync(path.join(source, "package.json"), JSON.stringify({ name: "account-native-probe", version: "1.0.0", main: "probe.js" }));
execFileSync(process.execPath, [process.env.CODEX_ACCOUNT_SWITCHER_ASAR_CLI, "pack", source, path.join(probe, "resources/app.asar")], { stdio: "pipe", timeout: 5_000 });
const result = path.join(dir, "result.json");
execFileSync(path.join(probe, "ChatGPT"), [`--user-data-dir=${profile}`], {
env: { ...process.env, TMPDIR: process.env.XDG_RUNTIME_DIR || "/tmp", CODEX_HOME: home, CODEX_ELECTRON_USER_DATA_PATH: profile,
ACCOUNT_SWITCHER_PROBE_RUNTIME: process.env.CODEX_ACCOUNT_SWITCHER_PROBE_RUNTIME || path.join(__dirname, "runtime.js"), ACCOUNT_SWITCHER_PROBE_RESULT: result,
ACCOUNT_SWITCHER_PROBE_NATIVE_APP: app },
stdio: "pipe", timeout: 20_000,
});
assert.deepEqual(JSON.parse(fs.readFileSync(result)), { menus: 3, encryptedVault: true, errors: [], openedLogin: 1, readyChecks: 4, cloudUntouched: true });
});