@aivin-labs/cli 1.0.51 → 1.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/bin/cli.mjs +2215 -2211
  2. package/bin/lib/auth.mjs +119 -88
  3. package/bin/lib/context.mjs +58 -5
  4. package/bin/lib/loginHandoff.mjs +87 -0
  5. package/bin/lib/openFile.mjs +29 -4
  6. package/bin/lib/remote/agentContract.mjs +370 -0
  7. package/bin/lib/remote/agentEvidence.mjs +409 -0
  8. package/bin/lib/remote/autoStart.mjs +640 -623
  9. package/bin/lib/remote/client.mjs +55 -17
  10. package/bin/lib/remote/codingAgents.mjs +594 -293
  11. package/bin/lib/remote/constants.mjs +1 -1
  12. package/bin/lib/remote/credentials.mjs +131 -125
  13. package/bin/lib/remote/desktop/castAuth.mjs +44 -19
  14. package/bin/lib/remote/desktop/castConsent.mjs +79 -14
  15. package/bin/lib/remote/desktop/castInput.mjs +3 -0
  16. package/bin/lib/remote/desktop/castTrust.mjs +221 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
  21. package/bin/lib/remote/desktop/strings.mjs +26 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
  23. package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
  24. package/bin/lib/remote/dpapiHelper.mjs +91 -0
  25. package/bin/lib/remote/gui/index.mjs +422 -68
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
  27. package/bin/lib/remote/humanInput.mjs +7 -0
  28. package/bin/lib/remote/localConfirm.mjs +2 -2
  29. package/bin/lib/remote/tokenStore.mjs +19 -2
  30. package/bin/lib/remote/toolHandlers.mjs +861 -859
  31. package/docs/CLI.md +1606 -1602
  32. package/package.json +1 -1
package/bin/lib/auth.mjs CHANGED
@@ -6,6 +6,11 @@ import { randomBytes } from 'crypto';
6
6
  import inquirer from 'inquirer';
7
7
  import axios from 'axios';
8
8
  import { DEFAULT_AIVIN_BASE_URL, saveActiveContext } from './context.mjs';
9
+ import {
10
+ LoginApp, LoginOutcome, buildLoginUrl, createPkcePair, normalizeLoginApp, parseCallback, resultLang, resultPageHtml,
11
+ } from './loginHandoff.mjs';
12
+
13
+ export { LoginApp };
9
14
 
10
15
  // ── Login - get an API key saved once, machine-wide ─────────────────────────
11
16
 
@@ -42,82 +47,124 @@ export function openBrowser(url) {
42
47
  console.log(chalk.yellow('Could not open a browser automatically - open this URL manually:'));
43
48
  console.log(chalk.cyan(` ${url}`));
44
49
  };
45
- const command = browserCommand(url);
50
+ // `AIVIN_NO_BROWSER=1`: máy không có trình duyệt / test — chỉ in URL.
51
+ const command = process.env.AIVIN_NO_BROWSER === '1' ? null : browserCommand(url);
46
52
  if (!command) return showManually();
47
53
  execFile(command.file, command.args, (error) => { if (error) showManually(); });
48
54
  }
49
55
 
50
- /**
51
- * Default `aivin login` flow: opens the platform's actual web app (not the API) so the user logs
52
- * in exactly the way they normally would - custom-domain org, password, Google, OTP, whatever
53
- * applies to their account - none of that multi-tenant login logic is reimplemented here. A tiny
54
- * local HTTP server waits for the browser to hand back a freshly-minted API key. The web app side
55
- * of this handoff lives in ApiKeysTab.jsx (mint + redirect) and ProfileHook.jsx (auto-open the tab) -
56
- * see docs/CLI.md#aivin-login.
57
- */
58
- export async function browserLogin() {
59
- // Defaults to the production web app - override with AIVIN_WEB_URL only if you're pointing at a
60
- // local/dev/staging frontend instead.
61
- const webBaseUrl = process.env.AIVIN_WEB_URL || 'https://app.aivin.cloud';
56
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
57
+ const EXCHANGE_PATH = '/apikey/cli-login/exchange';
58
+ const CODE_PATH = '/apikey/cli-login/code';
59
+ /** Gợi ý quyền truy cập khi máy chưa ghép (chưa có tệp ghép máy). */
60
+ const ACCESS_NOT_PAIRED = 'none';
61
+
62
+ /** Mã máy (để máy chủ thay đúng khoá cũ của máy này khi đăng nhập lại) + chính sách hiện tại trên máy (chỉ để màn cấp quyền nói đúng). */
63
+ async function machineLoginContext(serverUrl) {
64
+ const [{ getOrCreateDeviceId, pairedAccess }, { loadLocalPolicy }] = await Promise.all([
65
+ import('./remote/credentials.mjs'),
66
+ import('./remote/localPolicy.mjs'),
67
+ ]);
68
+ let deviceId;
69
+ try { deviceId = getOrCreateDeviceId(); } catch { /* không ghi được ~/.aivin: vẫn đăng nhập, chỉ không thay được khoá cũ */ }
70
+ let hints = {};
71
+ try {
72
+ const policy = loadLocalPolicy();
73
+ hints = { access: pairedAccess(serverUrl) || ACCESS_NOT_PAIRED, confirm: policy.confirm, cast: policy.cast_consent };
74
+ } catch { /* thiếu gợi ý thì web nói chung chung */ }
75
+ return { deviceId, hints };
76
+ }
62
77
 
63
- const state = randomBytes(16).toString('hex');
64
- let resolveKey, rejectKey;
65
- const keyPromise = new Promise((resolve, reject) => {
66
- resolveKey = resolve;
67
- rejectKey = reject;
68
- });
69
- // If `server.listen()` itself errors below, this promise gets rejected via rejectKey() but the
70
- // function throws from the port-await first (before `return keyPromise` is ever reached) - leaving
71
- // it as an unobserved rejection. This passive handler only silences that warning; it doesn't
72
- // consume keyPromise's rejection for the normal caller, who awaits the promise returned below.
73
- keyPromise.catch(() => {});
78
+ /** Đổi mã một lần + verifier lấy khoá qua máy chủ. */
79
+ async function exchangeLoginCode({ serverUrl, code, verifier, deviceId }) {
80
+ try {
81
+ const body = { code, code_verifier: verifier, ...(deviceId ? { device_id: deviceId } : {}) };
82
+ const res = await axios.post(`${serverUrl}${EXCHANGE_PATH}`, body, { timeout: 30_000 });
83
+ const data = res.data?.data ?? res.data;
84
+ if (!data?.api_key) throw new Error('Server did not return an API key');
85
+ return data.api_key;
86
+ } catch (error) {
87
+ const message = error.response?.data?.message || error.response?.data?.i18n || error.message;
88
+ throw new Error(`Could not finish login: ${message}`, { cause: error });
89
+ }
90
+ }
74
91
 
75
- let timeout;
76
- const server = http.createServer((req, res) => {
92
+ /**
93
+ * Trình duyệt quay về `/callback`: trả trang kết quả đúng ngôn ngữ / đúng app và báo kết quả cho `browserLogin`. Lời gọi sai `state` chỉ
94
+ * nhận trang báo lỗi, KHÔNG huỷ lần đăng nhập đang chờ.
95
+ */
96
+ function createCallbackHandler({ state, app, serverUrl, verifier, deviceId, settle }) {
97
+ let finished = false;
98
+ return async (req, res) => {
77
99
  let url;
78
- try {
79
- url = new URL(req.url, 'http://127.0.0.1');
80
- } catch {
81
- res.writeHead(400).end();
82
- return;
100
+ try { url = new URL(req.url, 'http://127.0.0.1'); } catch { res.writeHead(400).end(); return; }
101
+ if (url.pathname !== '/callback') { res.writeHead(404).end(); return; }
102
+ const lang = resultLang(url.searchParams.get('lang'));
103
+ const reply = (outcome, status = 200) => {
104
+ res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
105
+ res.end(resultPageHtml({ outcome, app, lang }));
106
+ };
107
+ const parsed = parseCallback(url.searchParams, state);
108
+ if (parsed.kind === LoginOutcome.BAD_REQUEST || finished) return reply(LoginOutcome.BAD_REQUEST, 400);
109
+ finished = true;
110
+ if (parsed.kind === LoginOutcome.CANCELLED) {
111
+ reply(LoginOutcome.CANCELLED);
112
+ return settle(new Error('Login was cancelled in the browser'));
113
+ }
114
+ if (parsed.kind === 'key') {
115
+ reply(LoginOutcome.OK);
116
+ return settle(null, parsed.key);
83
117
  }
84
- if (url.pathname !== '/callback') {
85
- res.writeHead(404).end();
86
- return;
118
+ if (parsed.kind !== 'code') {
119
+ reply(LoginOutcome.FAILED);
120
+ return settle(new Error('Login callback carried no code'));
121
+ }
122
+ try {
123
+ const key = await exchangeLoginCode({ serverUrl, code: parsed.code, verifier, deviceId });
124
+ reply(LoginOutcome.OK);
125
+ settle(null, key);
126
+ } catch (error) {
127
+ reply(LoginOutcome.FAILED);
128
+ settle(error);
87
129
  }
130
+ };
131
+ }
88
132
 
89
- const key = url.searchParams.get('key');
90
- const receivedState = url.searchParams.get('state');
91
- const ok = !!key && receivedState === state;
92
-
93
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
94
- res.end(
95
- '<html><body style="font-family:sans-serif;text-align:center;padding-top:4rem">' +
96
- (ok
97
- ? '<h2>Login successful</h2><p>You can close this window and return to your terminal.</p>'
98
- : '<h2>Login failed</h2><p>Close this window and retry <code>aivin login</code>.</p>') +
99
- // Only works on tabs opened via script (window.open), not a typed/clicked URL - harmless
100
- // no-op otherwise, hence the fallback "you can close this" text above regardless.
101
- '<script>window.close();</script>' +
102
- '</body></html>',
103
- );
104
-
105
- clearTimeout(timeout);
106
- server.close();
107
- if (ok) resolveKey(key);
108
- else rejectKey(new Error('Login callback was missing a key or had a state mismatch'));
133
+ /**
134
+ * Default `aivin login` flow: opens the platform's actual web app (not the API) so the user logs in exactly the way they normally would
135
+ * (custom-domain org, password, Google, OTP…). A tiny local HTTP server waits for the browser to come back with a ONE-TIME CODE, which
136
+ * this process exchanges (with a PKCE verifier only it holds) for the API key — the key itself never travels through the browser, so it
137
+ * never lands in browser history. Web side: fe ProfileHook.jsx + CliAuthPrompt.jsx; server side: be CliLoginService.
138
+ * `app`: which app is asking (shown on the consent screen). `serverUrl`: the API host the code is exchanged at.
139
+ */
140
+ export async function browserLogin({ app = LoginApp.CLI, serverUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL } = {}) {
141
+ // Defaults to the production web app - override with AIVIN_WEB_URL only if you're pointing at a local/dev/staging frontend instead.
142
+ const webBaseUrl = process.env.AIVIN_WEB_URL || 'https://app.aivin.cloud';
143
+ const loginApp = normalizeLoginApp(app);
144
+ const state = randomBytes(16).toString('hex');
145
+ const { verifier, challenge } = createPkcePair();
146
+ const { deviceId, hints } = await machineLoginContext(serverUrl);
147
+
148
+ let timeout;
149
+ let settle;
150
+ const keyPromise = new Promise((resolve, reject) => {
151
+ settle = (error, key) => {
152
+ clearTimeout(timeout);
153
+ server.close();
154
+ if (error) reject(error); else resolve(key);
155
+ };
109
156
  });
110
- server.on('error', (err) => rejectKey(err));
157
+ // If `server.listen()` itself errors below, keyPromise is rejected but this function throws from the port-await first — this passive
158
+ // handler only silences the unobserved-rejection warning; the normal caller still awaits keyPromise below.
159
+ keyPromise.catch(() => {});
160
+ const server = http.createServer(createCallbackHandler({ state, app: loginApp, serverUrl, verifier, deviceId, settle: (e, k) => settle(e, k) }));
161
+ server.on('error', (err) => settle(err));
111
162
 
112
163
  const port = await new Promise((resolve, reject) => {
113
164
  server.once('error', reject);
114
165
  server.listen(0, '127.0.0.1', () => resolve(server.address().port));
115
166
  });
116
-
117
- const authUrl = new URL('/', webBaseUrl);
118
- authUrl.searchParams.set('cli_redirect', `http://127.0.0.1:${port}/callback`);
119
- authUrl.searchParams.set('cli_state', state);
120
- authUrl.searchParams.set('cli_name', os.hostname());
167
+ const authUrl = buildLoginUrl({ webBaseUrl, port, state, name: os.hostname(), app: loginApp, challenge, hints });
121
168
 
122
169
  console.log(chalk.blue('🌐 Opening your browser to log in...'));
123
170
  console.log(chalk.gray(` ${authUrl.toString()}`));
@@ -125,11 +172,7 @@ export async function browserLogin() {
125
172
  console.log(chalk.gray(' Waiting for you to confirm in the browser (5 min timeout)...'));
126
173
  openBrowser(authUrl.toString());
127
174
 
128
- timeout = setTimeout(() => {
129
- server.close();
130
- rejectKey(new Error('Timed out waiting for browser login (5 minutes)'));
131
- }, 5 * 60 * 1000);
132
-
175
+ timeout = setTimeout(() => settle(new Error('Timed out waiting for browser login (5 minutes)')), LOGIN_TIMEOUT_MS);
133
176
  return keyPromise;
134
177
  }
135
178
 
@@ -194,37 +237,25 @@ export async function obtainAccessToken(options) {
194
237
  }
195
238
 
196
239
  /**
197
- * `aivin login --basic`: the login-specific half of the flow above - exchange credentials for a
198
- * JWT, then mint (replacing any previous same-named key) the one API key that gets saved to
199
- * `~/.aivin/credentials`.
240
+ * `aivin login --basic`: exchange credentials for a session JWT, then go through the same one-time code + PKCE issuance as the browser
241
+ * flow (be CliLoginService) — the key is bound to this machine's device id, expires when unused, and replaces ONLY this machine's
242
+ * previous login key. (Before: listed the whole organization's keys and revoked whichever one had this hostname as its name.)
200
243
  */
201
244
  export async function basicLogin(options) {
202
245
  const { serverUrl, accessToken } = await obtainAccessToken(options);
203
- const authHeaders = { headers: { Authorization: `Bearer ${accessToken}` } };
204
- const deviceName = os.hostname();
205
-
206
- // Replace (not accumulate) a previous key from this same device - `aivin login` re-run on the
207
- // same machine used to create yet another "Aivin CLI - <host>" entry every time, cluttering the
208
- // key list with duplicates. Best-effort: if listing/revoking fails for any reason, still proceed
209
- // to mint a new key rather than blocking login on it.
246
+ const authHeaders = { headers: { Authorization: `Bearer ${accessToken}` }, timeout: 30_000 };
247
+ const { verifier, challenge } = createPkcePair();
248
+ const { deviceId } = await machineLoginContext(serverUrl);
249
+ let code;
210
250
  try {
211
- const listRes = await axios.get(`${serverUrl}/apikey`, authHeaders);
212
- const existing = (listRes.data?.items || []).find((k) => k.name === deviceName);
213
- if (existing) {
214
- await axios.delete(`${serverUrl}/apikey/${existing.id || existing._id}`, authHeaders);
215
- }
216
- } catch (error) {
217
- console.log(chalk.gray(` (couldn't check for an existing key to replace: ${error.message})`));
218
- }
219
-
220
- try {
221
- const keyRes = await axios.post(`${serverUrl}/apikey`, { name: deviceName }, authHeaders);
222
- if (!keyRes.data?.plainKey) throw new Error('Response did not include an API key');
223
- return keyRes.data.plainKey;
251
+ const res = await axios.post(`${serverUrl}${CODE_PATH}`, { name: os.hostname(), code_challenge: challenge, app: LoginApp.CLI }, authHeaders);
252
+ code = (res.data?.data ?? res.data)?.code;
253
+ if (!code) throw new Error('Response did not include a login code');
224
254
  } catch (error) {
225
255
  const message = error.response?.data?.message || error.message;
226
256
  throw new Error(`Failed to create API key: ${message}`, { cause: error });
227
257
  }
258
+ return exchangeLoginCode({ serverUrl, code, verifier, deviceId });
228
259
  }
229
260
 
230
261
  // ── API key management - named keys for your account, separate from `aivin login`'s one ───────
@@ -4,6 +4,8 @@ import os from 'os';
4
4
  import axios from 'axios';
5
5
  import { execFileSync } from 'child_process';
6
6
  import { readActiveServer, resolveServerUrl, serverKey, setActiveServer, webUrlForServer } from './servers.mjs';
7
+ import { TokenStoreKind, forgetToken, openToken, preferredTokenStore, sealToken } from './remote/tokenStore.mjs';
8
+ import { isStandaloneBinary } from './update/versions.mjs';
7
9
 
8
10
  export const GLOBAL_CREDENTIALS_PATH = path.join(os.homedir(), '.aivin', 'credentials');
9
11
  export const DEFAULT_AIVIN_BASE_URL = 'https://api.aivin.cloud';
@@ -23,11 +25,56 @@ export async function fetchWebUrl(baseUrl) {
23
25
  } catch { return null; }
24
26
  }
25
27
 
28
+ /**
29
+ * Khoá API cất trong kho bí mật của hệ điều hành (13/11/2026), như token thiết bị: tệp chỉ giữ `api_key_sealed` (bản mã DPAPI / dấu
30
+ * Keychain, libsecret). Trước đây `api_key` nằm dạng chữ thường — chép thư mục `.aivin` (sao lưu, đồng bộ đám mây) là mang theo được khoá
31
+ * toàn quyền tài khoản. Máy không có kho (`TokenStoreKind.FILE`) hoặc kho lỗi → giữ chữ thường như cũ.
32
+ * Không chống được mã độc chạy dưới chính tài khoản người dùng (gọi được cùng API) — xem tokenStore.mjs.
33
+ */
34
+ const apiKeyAccount = (url) => `api-key:${serverKey(url)}`;
35
+
36
+ function sealApiKey(apiKey, url) {
37
+ if (preferredTokenStore() === TokenStoreKind.FILE) return { api_key: apiKey };
38
+ const account = apiKeyAccount(url);
39
+ const { fallback_reason: _why, device_token: plain, ...sealed } = sealToken(apiKey, { account });
40
+ return plain ? { api_key: plain } : { api_key_sealed: { ...sealed, token_account: account } };
41
+ }
42
+
43
+ /** Khoá của một ngữ cảnh; bản mã không giải được (tệp chép từ máy khác) → `null` = coi như chưa đăng nhập. */
44
+ function openApiKey(ctx) {
45
+ if (ctx?.api_key_sealed) return openToken({ ...ctx.api_key_sealed, device_id: ctx.api_key_sealed.token_account });
46
+ return ctx?.api_key || null;
47
+ }
48
+
49
+ function forgetApiKey(ctx) {
50
+ if (ctx?.api_key_sealed) forgetToken({ ...ctx.api_key_sealed, device_id: ctx.api_key_sealed.token_account });
51
+ }
52
+
53
+ const hasKey = (ctx) => Boolean(ctx?.api_key || ctx?.api_key_sealed);
54
+
55
+ /**
56
+ * Ngữ cảnh còn khoá chữ thường (tệp cũ) → cất lại vào kho. Lỗi thì thôi: lần sau thử lại, vẫn dùng được khoá.
57
+ * CHỈ bản phát hành đã cài (`AIVIN_CLI_BINARY`) mới tự chuyển: chạy từ mã nguồn / trong test trên cùng máy với một bản cài đời cũ thì bản
58
+ * cũ không đọc được `api_key_sealed` và coi như chưa đăng nhập (gặp thật 13/11/2026: bộ test chạy mã nguồn đã chuyển tệp thật).
59
+ * Đăng nhập mới (`saveActiveContext`) thì luôn cất vào kho.
60
+ */
61
+ function migratePlainKey(store, key, apiKey) {
62
+ const ctx = store.contexts[key];
63
+ if (!ctx?.api_key || !isStandaloneBinary() || preferredTokenStore() === TokenStoreKind.FILE) return;
64
+ try {
65
+ const { api_key: _plain, ...rest } = ctx;
66
+ const sealed = sealApiKey(apiKey, ctx.base_url);
67
+ if (!sealed.api_key_sealed) return;
68
+ store.contexts[key] = { ...rest, ...sealed };
69
+ writeCredentialStore(store);
70
+ } catch { /* để lần sau */ }
71
+ }
72
+
26
73
  function readCredentialStore() {
27
74
  try {
28
75
  const parsed = JSON.parse(fs.readFileSync(GLOBAL_CREDENTIALS_PATH, 'utf8'));
29
76
  if (parsed?.contexts && typeof parsed.contexts === 'object') return parsed;
30
- if (!parsed?.api_key) return null;
77
+ if (!hasKey(parsed)) return null;
31
78
  const base_url = resolveServerUrl(parsed.base_url || DEFAULT_AIVIN_BASE_URL);
32
79
  return { version: 2, contexts: { [serverKey(base_url)]: { ...parsed, base_url } } };
33
80
  } catch { return null; }
@@ -41,11 +88,16 @@ function writeCredentialStore(store) {
41
88
 
42
89
  export function loadActiveContext(baseUrl) {
43
90
  const target = resolveServerUrl(baseUrl || process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
44
- const ctx = readCredentialStore()?.contexts?.[serverKey(target)];
45
- if (!ctx?.api_key) return null;
91
+ const store = readCredentialStore();
92
+ const key = serverKey(target);
93
+ const ctx = store?.contexts?.[key];
94
+ if (!hasKey(ctx)) return null;
95
+ const apiKey = openApiKey(ctx);
96
+ if (!apiKey) return null;
97
+ if (ctx.api_key) migratePlainKey(store, key, apiKey);
46
98
  return {
47
99
  base_url: target,
48
- api_key: ctx.api_key,
100
+ api_key: apiKey,
49
101
  sdk_endpoint: ctx.sdk_endpoint || deriveSdkEndpoint(target),
50
102
  logged_in_at: ctx.logged_in_at || null,
51
103
  email: ctx.email || null,
@@ -69,6 +121,7 @@ export function clearActiveContext(baseUrl) {
69
121
  const target = resolveServerUrl(baseUrl || process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
70
122
  const store = readCredentialStore();
71
123
  if (!store?.contexts?.[serverKey(target)]) return false;
124
+ forgetApiKey(store.contexts[serverKey(target)]);
72
125
  delete store.contexts[serverKey(target)];
73
126
  if (!Object.keys(store.contexts).length) fs.rmSync(GLOBAL_CREDENTIALS_PATH, { force: true });
74
127
  else writeCredentialStore(store);
@@ -82,7 +135,7 @@ export function saveActiveContext(baseUrl, apiKey, identity = {}) {
82
135
  store.contexts ||= {};
83
136
  store.contexts[serverKey(normalized)] = {
84
137
  base_url: normalized,
85
- api_key: apiKey,
138
+ ...sealApiKey(apiKey, normalized),
86
139
  sdk_endpoint: deriveSdkEndpoint(normalized),
87
140
  logged_in_at: new Date().toISOString(),
88
141
  email: identity.email || null,
@@ -0,0 +1,87 @@
1
+ import { createHash, randomBytes } from 'crypto';
2
+
3
+ /**
4
+ * Hàm thuần cho đăng nhập qua trình duyệt (auth.mjs `browserLogin`), 13/11/2026.
5
+ * Trước đây web trả thẳng khoá toàn quyền về `127.0.0.1:<cổng>/callback?key=…` → khoá nằm trong lịch sử trình duyệt (đồng bộ theo tài
6
+ * khoản Chrome sang máy khác). Nay web chỉ trả MÃ dùng một lần; app đổi mã + verifier PKCE (chỉ app giữ) lấy khoá qua máy chủ
7
+ * (`POST /apikey/cli-login/exchange`). Mã trong lịch sử trình duyệt vô dụng: đã dùng / hết hạn sau 2 phút / thiếu verifier.
8
+ */
9
+
10
+ /** App đang xin đăng nhập — web dựa vào đây để gọi đúng tên (FE `CliApp`, BE `CliLoginApp`). */
11
+ export const LoginApp = Object.freeze({ CLI: 'cli', DESKTOP: 'desktop' });
12
+
13
+ /** Kết quả hiện trên trang cuối ở trình duyệt. */
14
+ export const LoginOutcome = Object.freeze({ OK: 'ok', FAILED: 'failed', CANCELLED: 'cancelled', BAD_REQUEST: 'bad_request' });
15
+
16
+ export const normalizeLoginApp = (app) => (Object.values(LoginApp).includes(app) ? app : LoginApp.CLI);
17
+
18
+ /** PKCE S256 (RFC 7636): verifier 43 ký tự base64url, challenge = base64url(sha256(verifier)). */
19
+ export function createPkcePair() {
20
+ const verifier = randomBytes(32).toString('base64url');
21
+ return { verifier, challenge: createHash('sha256').update(verifier).digest('base64url') };
22
+ }
23
+
24
+ /**
25
+ * URL trang web mở cho người dùng. `hints`: chính sách hiện tại trên máy (chỉ để màn cấp quyền nói đúng mức máy còn hỏi lại — sai thì chỉ
26
+ * hiện sai chữ, không đổi quyền thật): `access` full | folders | none (chưa ghép), `confirm` never | risky | always, `cast` off | ask | unattended.
27
+ */
28
+ export function buildLoginUrl({ webBaseUrl, port, state, name, app, challenge, hints = {} }) {
29
+ const url = new URL('/', webBaseUrl);
30
+ url.searchParams.set('cli_redirect', `http://127.0.0.1:${port}/callback`);
31
+ url.searchParams.set('cli_state', state);
32
+ url.searchParams.set('cli_name', name);
33
+ url.searchParams.set('cli_app', normalizeLoginApp(app));
34
+ url.searchParams.set('cli_challenge', challenge);
35
+ if (hints.access) url.searchParams.set('cli_access', hints.access);
36
+ if (hints.confirm) url.searchParams.set('cli_confirm', hints.confirm);
37
+ if (hints.cast) url.searchParams.set('cli_cast', hints.cast);
38
+ return url;
39
+ }
40
+
41
+ /** Trình duyệt quay về `/callback`: phân loại lời gọi. Sai `state` → bỏ qua (không huỷ đăng nhập đang chờ vì một lời gọi lạ). */
42
+ export function parseCallback(searchParams, expectedState) {
43
+ if (searchParams.get('state') !== expectedState) return { kind: LoginOutcome.BAD_REQUEST };
44
+ if (searchParams.get('error') === 'cancelled') return { kind: LoginOutcome.CANCELLED };
45
+ const code = searchParams.get('code');
46
+ if (code) return { kind: 'code', code };
47
+ // Web đời cũ (chưa có luồng mã) vẫn trả khoá thẳng.
48
+ const key = searchParams.get('key');
49
+ if (key) return { kind: 'key', key };
50
+ return { kind: LoginOutcome.FAILED };
51
+ }
52
+
53
+ const TEXT = Object.freeze({
54
+ vi: {
55
+ [LoginOutcome.OK]: ['Đã đăng nhập', { [LoginApp.DESKTOP]: 'Bạn có thể đóng cửa sổ này và quay lại AIVIN Bot.', [LoginApp.CLI]: 'Bạn có thể đóng cửa sổ này và quay lại cửa sổ dòng lệnh.' }],
56
+ [LoginOutcome.FAILED]: ['Đăng nhập không thành công', { [LoginApp.DESKTOP]: 'Đóng cửa sổ này rồi bấm kết nối lại từ biểu tượng AIVIN Bot trên khay.', [LoginApp.CLI]: 'Đóng cửa sổ này rồi chạy lại aivin login.' }],
57
+ [LoginOutcome.CANCELLED]: ['Đã huỷ đăng nhập', { [LoginApp.DESKTOP]: 'Chưa cấp quyền nào. Bạn có thể đóng cửa sổ này.', [LoginApp.CLI]: 'Chưa cấp quyền nào. Bạn có thể đóng cửa sổ này.' }],
58
+ [LoginOutcome.BAD_REQUEST]: ['Liên kết không hợp lệ', { [LoginApp.DESKTOP]: 'Liên kết này không thuộc lần đăng nhập đang chờ.', [LoginApp.CLI]: 'Liên kết này không thuộc lần đăng nhập đang chờ.' }],
59
+ },
60
+ en: {
61
+ [LoginOutcome.OK]: ['Signed in', { [LoginApp.DESKTOP]: 'You can close this window and go back to AIVIN Bot.', [LoginApp.CLI]: 'You can close this window and go back to your terminal.' }],
62
+ [LoginOutcome.FAILED]: ['Sign-in failed', { [LoginApp.DESKTOP]: 'Close this window and connect again from the AIVIN Bot icon in the system tray.', [LoginApp.CLI]: 'Close this window and run aivin login again.' }],
63
+ [LoginOutcome.CANCELLED]: ['Sign-in cancelled', { [LoginApp.DESKTOP]: 'No access was granted. You can close this window.', [LoginApp.CLI]: 'No access was granted. You can close this window.' }],
64
+ [LoginOutcome.BAD_REQUEST]: ['Invalid link', { [LoginApp.DESKTOP]: 'This link does not belong to the sign-in in progress.', [LoginApp.CLI]: 'This link does not belong to the sign-in in progress.' }],
65
+ },
66
+ });
67
+
68
+ /** Ngôn ngữ trang cuối: web gửi `lang` theo giao diện người dùng; không có thì theo máy. Chỉ có vi / en, còn lại tiếng Anh. */
69
+ export function resultLang(langParam, systemLocale = Intl.DateTimeFormat().resolvedOptions().locale) {
70
+ const tag = String(langParam || systemLocale || '').toLowerCase();
71
+ return tag.startsWith('vi') ? 'vi' : 'en';
72
+ }
73
+
74
+ const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
75
+
76
+ export function resultPageHtml({ outcome, app, lang }) {
77
+ const dict = TEXT[lang] || TEXT.en;
78
+ const [title, bodies] = dict[outcome] || dict[LoginOutcome.FAILED];
79
+ const body = bodies[normalizeLoginApp(app)];
80
+ return '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
81
+ + `<title>${escapeHtml(title)}</title></head>`
82
+ + '<body style="font-family:system-ui,sans-serif;text-align:center;padding:4rem 16px;color:#1d2129">'
83
+ + `<h2 style="font-size:20px">${escapeHtml(title)}</h2><p style="font-size:15px;color:#4e5969">${escapeHtml(body)}</p>`
84
+ // Chỉ đóng được tab mở bằng script; không đóng được thì chữ trên vẫn đủ.
85
+ + (outcome === LoginOutcome.BAD_REQUEST ? '' : '<script>setTimeout(function(){window.close()},1200)</script>')
86
+ + '</body></html>';
87
+ }
@@ -8,7 +8,7 @@ import { defaultWebUrl } from './servers.mjs';
8
8
  import { startPreviewServer } from './localPreview.mjs';
9
9
  import { missionAuthHeaders, missionServerUrl, resolveWorkspace } from './workspace.mjs';
10
10
  import { spawn } from 'child_process';
11
- import { browserLogin, openBrowser, saveGlobalApiKey, tryFetchWhoami } from './auth.mjs';
11
+ import { LoginApp, browserLogin, openBrowser, saveGlobalApiKey, tryFetchWhoami } from './auth.mjs';
12
12
  import { LOCAL_BROWSERS, detectDefaultBrowserId, resolveBrowserInstall } from './localBrowser.mjs';
13
13
  import { mascotLang } from './remote/mascot/strings.mjs';
14
14
 
@@ -162,11 +162,35 @@ export function appWindowCommand(url, { defaultId = detectDefaultBrowserId(), re
162
162
  return install ? { exe: install.exe, args: ['--start-maximized', `--app=${url}`] } : null;
163
163
  }
164
164
 
165
+ /**
166
+ * Windows: `--start-maximized` chỉ có hiệu lực khi trình duyệt KHỞI ĐỘNG. Edge/Chrome đang chạy (Edge còn chạy nền sẵn nhờ startup boost) thì
167
+ * tiến trình mới chỉ chuyển lệnh cho tiến trình cũ → cờ bị bỏ qua, cửa sổ app mở cỡ mặc định. Nên PowerShell mở trình duyệt rồi tự phóng to
168
+ * cửa sổ mới lên trước (cùng cách khay LaunchPlatformApp). Đường dẫn + tham số qua biến môi trường, không phải lo thoát ký tự.
169
+ */
170
+ const WINDOWS_MAXIMIZE_SCRIPT = [
171
+ "$sig = '[DllImport(\"user32.dll\")] public static extern IntPtr GetForegroundWindow(); [DllImport(\"user32.dll\")] public static extern bool ShowWindowAsync(IntPtr h, int c); [DllImport(\"user32.dll\")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint p);'",
172
+ '$w = Add-Type -MemberDefinition $sig -Name AivinOpenWindow -Namespace Aivin -PassThru',
173
+ '$before = $w::GetForegroundWindow()',
174
+ '$name = [IO.Path]::GetFileNameWithoutExtension($env:AIVIN_OPEN_EXE)',
175
+ '[void][Diagnostics.Process]::Start($env:AIVIN_OPEN_EXE, $env:AIVIN_OPEN_ARGS)',
176
+ 'for ($i = 0; $i -lt 60; $i++) { Start-Sleep -Milliseconds 100; $h = $w::GetForegroundWindow(); if ($h -ne [IntPtr]::Zero -and $h -ne $before) { $p = [uint32]0; [void]$w::GetWindowThreadProcessId($h, [ref]$p); try { if ((Get-Process -Id $p).ProcessName -eq $name) { [void]$w::ShowWindowAsync($h, 3); break } } catch { } } }',
177
+ ].join('; ');
178
+
179
+ function spawnDirect(cmd, url) {
180
+ const child = spawn(cmd.exe, cmd.args, { detached: true, stdio: 'ignore' });
181
+ child.on('error', () => openBrowser(url));
182
+ child.unref();
183
+ }
184
+
165
185
  function openInWindow(url) {
166
186
  const cmd = appWindowCommand(url);
167
187
  if (!cmd) return openBrowser(url);
168
- const child = spawn(cmd.exe, cmd.args, { detached: true, stdio: 'ignore' });
169
- child.on('error', () => openBrowser(url));
188
+ if (process.platform !== 'win32') return spawnDirect(cmd, url);
189
+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_MAXIMIZE_SCRIPT], {
190
+ detached: true, stdio: 'ignore', windowsHide: true,
191
+ env: { ...process.env, AIVIN_OPEN_EXE: cmd.exe, AIVIN_OPEN_ARGS: cmd.args.map((a) => `"${a}"`).join(' ') },
192
+ });
193
+ child.on('error', () => spawnDirect(cmd, url));
170
194
  child.unref();
171
195
  }
172
196
 
@@ -211,7 +235,8 @@ const isAuthRejected = (error) => (error?.cause?.response?.status ?? error?.resp
211
235
  async function loginAndUpload(filePath, workspace) {
212
236
  const serverUrl = missionServerUrl();
213
237
  if (!process.env.AIVIN_WEB_URL) process.env.AIVIN_WEB_URL = await resolveWebUrl(serverUrl);
214
- const apiKey = await browserLogin();
238
+ // Trang xem mở từ "Mở bằng AIVIN Bot": người dùng đang ở app desktop, không phải terminal.
239
+ const apiKey = await browserLogin({ app: LoginApp.DESKTOP, serverUrl });
215
240
  saveGlobalApiKey(apiKey, serverUrl, await tryFetchWhoami(serverUrl, apiKey));
216
241
  process.env.API_KEY = apiKey;
217
242
  const { url } = await openLocalFile(filePath, { workspace, display: OpenDisplay.NONE });