openyida 2026.10.27 → 2026.10.28-beta.1

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.
package/README.md CHANGED
@@ -143,6 +143,27 @@ openyida login --check-only --json
143
143
  openyida auth status
144
144
  ```
145
145
 
146
+ In QwenWork web, `openyida login --qwenwork --json` (or ordinary `login`) sends the sandbox Agent Token and gateway origin directly to the selected YiDA authentication endpoint. YiDA validates the identity through the trusted gateway’s fixed `/api/agent-gw/yida/user_info` endpoint, then issues its own short-lived session. This login flow no longer calls the legacy exchange or `/user/info` endpoints. Login preparation stays silent; failures stop without browser OAuth. Desktop and other hosts retain their existing authentication paths.
147
+
148
+ For QwenWork cloud identity diagnostics, run inside the actual cloud execution environment:
149
+
150
+ ```bash
151
+ openyida auth qwenwork user-info --json
152
+ ```
153
+
154
+ This command exchanges the injected `QWENWORK_AGENT_TOKEN` (legacy: `MULE_AGENT_TOKEN` / `AGENT_TOKEN`) at `QWENWORK_GATEWAY_URL` (legacy: `MULE_GATEWAY_URL`), then queries `/user/info` on the same origin. It reports identity and scope metadata without printing or persisting either credential. It does not create an OpenYida login session, and QwenWork organization IDs are not YiDA `corpId` values. Existing OAuth/profile behavior is unchanged.
155
+
156
+ Programmatic callers can use `exchangeQwenWorkAgentToken`, `getQwenWorkUserInfo` and `getQwenWorkIdentity` from `lib/auth/qwenwork-client.js`. The exchange function returns an in-memory `access_token` credential for the identity query or a future server-side login exchange; callers must not log or persist it.
157
+
158
+ ```js
159
+ const { exchangeQwenWorkAgentToken, getQwenWorkUserInfo } = require('openyida/lib/auth/qwenwork-client');
160
+ async function readCloudUser() {
161
+ const credential = await exchangeQwenWorkAgentToken();
162
+ // The result contains QwenWork identifiers, not YiDA IDs.
163
+ return getQwenWorkUserInfo(credential);
164
+ }
165
+ ```
166
+
146
167
  To reuse an existing shared login profile for the current project, switch first instead of starting a new OAuth login:
147
168
 
148
169
  ```bash
@@ -457,9 +478,9 @@ When preparing a PR that needs a personal Fork, or when you ask how to support t
457
478
 
458
479
  | Command | Description |
459
480
  |---------|-------------|
460
- | `openyida login [target-url] [--env <name>\|--intl\|--overseas\|--global\|--yidaapps\|--alibaba] [--client-id <clientId>] [--endpoint <url>] [--no-browser]` | Login with OAuth token mode |
481
+ | `openyida login [--qwenwork] [target-url] [--env <name>\|--intl\|--overseas\|--global\|--yidaapps\|--alibaba] [--client-id <clientId>] [--endpoint <url>] [--no-browser]` | Login with OAuth token mode |
461
482
  | `openyida logout` | Logout / unbind current project auth |
462
- | `openyida auth <status\|login\|refresh\|logout\|profiles\|profile switch>` | Token login state and profile management |
483
+ | `openyida auth <status\|login\|refresh\|logout\|profiles\|profile switch\|qwenwork user-info> [--json]` | Token login state and profile management |
463
484
  | `openyida org <list\|switch> [--json] [--corp-id <corpId>]` | Organization management (list / switch existing profiles first) |
464
485
  | `openyida env [--json\|setup\|list\|show\|switch\|add\|remove] [options]` | Detect AI tool environment & token login state |
465
486
 
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+ const config = require('../package.json').openyidaLocalBeta;
6
+ // PRE beta 消费包内测试默认值,真实凭据仍由原认证模块管理。
7
+ process.env.OPENYIDA_ENDPOINT ||= config.baseUrl;
8
+ process.env.OPENYIDA_ENV ||= config.environment;
9
+ process.env.OPENYIDA_AUTH_DIR ||= path.join(os.homedir(), '.openyida', config.authDirectory);
10
+ process.env.OPENYIDA_SKIP_UPDATE_CHECK = '1';
11
+ require('./yida.js');
package/bin/yida.js CHANGED
@@ -598,7 +598,23 @@ async function main() {
598
598
  });
599
599
  assertManagedInvocation(command, rawArgs);
600
600
  applyQuietFlag();
601
+ // 一次性票据只在当前进程消费,不能先自更新并重启命令。
602
+ switch (command) {
603
+ case 'login-qwenwork':
604
+ await require('../lib/auth/qwenwork-desktop').run(args);
605
+ return;
606
+ }
601
607
  applyGlobalEnvironmentFlags();
608
+ // 网页态由 CLI 消费宿主凭据;桌面态继续消费宿主准备的登录态。
609
+ const webLogin = (command === 'login' || (command === 'auth' && args[0] === 'login')) &&
610
+ require('../lib/core/qwenwork-login-guidance').isQwenWorkWebRuntime(require('../lib/core/utils').detectRuntimeCapabilities());
611
+ if ((command === 'login' && args.includes('--qwenwork')) || webLogin) {
612
+ const loginArgs = applyLoginEnvironmentFlags(command === 'auth' ? args.slice(1) : args, { inferTargetUrl: true });
613
+ if (hasHelpFlag(loginArgs)) { printLoginHelp(); return; }
614
+ assertNoUnsupportedLegacyLoginFlags(rawArgs, loginArgs);
615
+ await require('../lib/auth/qwenwork-login').run(loginArgs, buildTokenLoginOptions(loginArgs));
616
+ return;
617
+ }
602
618
 
603
619
  const { maybeAutoUpdate } = require('../lib/core/update');
604
620
  const updateResult = await maybeAutoUpdate({
@@ -718,6 +734,10 @@ async function main() {
718
734
 
719
735
  case 'auth': {
720
736
  const subCommand = args[0];
737
+ if (subCommand === 'qwenwork') {
738
+ await require('../lib/auth/qwenwork').run(args.slice(1));
739
+ break;
740
+ }
721
741
  const authArgs = applyLoginEnvironmentFlags(args.slice(1), { inferTargetUrl: true });
722
742
  const { getAuthStatus } = require('../lib/core/utils');
723
743
  const { tokenLogin, tokenLogout, tokenRefresh } = require('../lib/auth/token-auth');
@@ -0,0 +1,190 @@
1
+ 'use strict';
2
+
3
+ const { CliError } = require('../core/cli-error');
4
+ const { t } = require('../core/i18n');
5
+
6
+ const DEFAULT_TIMEOUT_MS = 20000;
7
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
8
+
9
+ function failure(code, message, stage, details = {}) {
10
+ return new CliError(t(`qwenwork.${message}`), {
11
+ code: `QWENWORK_${code}`,
12
+ details: { stage, ...details },
13
+ });
14
+ }
15
+
16
+ function pick(env, names) {
17
+ for (const name of names) {
18
+ const value = String(env[name] || '').trim();
19
+ if (value) {
20
+ return { name, value };
21
+ }
22
+ }
23
+ return null;
24
+ }
25
+
26
+ function normalizeBaseUrl(value) {
27
+ try {
28
+ const url = new URL(value);
29
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
30
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
31
+ url.username || url.password || url.search || url.hash) {
32
+ throw new Error('invalid_url');
33
+ }
34
+ return url.href.replace(/\/+$/, '');
35
+ } catch {
36
+ throw failure('INVALID_GATEWAY', 'invalid_url', 'resolve_credentials');
37
+ }
38
+ }
39
+
40
+ function isObject(value) {
41
+ return !!value && typeof value === 'object' && !Array.isArray(value);
42
+ }
43
+
44
+ // Do not include upstream bodies, headers or exception messages in diagnostics:
45
+ // an authentication endpoint may echo credentials even in an error response.
46
+ async function requestJson(method, url, accessToken, options, stage) {
47
+ const timeoutMs = options.timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : options.timeoutMs;
48
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
49
+ throw failure('INVALID_TIMEOUT', 'request_failed', stage);
50
+ }
51
+ const controller = new globalThis.AbortController();
52
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
53
+ try {
54
+ const response = await globalThis.fetch(url, {
55
+ method,
56
+ headers: { accept: 'application/json', authorization: `Bearer ${accessToken}` },
57
+ redirect: 'manual',
58
+ signal: controller.signal,
59
+ });
60
+ if (!response.ok) {
61
+ if (response.body) {
62
+ await response.body.cancel();
63
+ }
64
+ throw failure('HTTP_ERROR', 'request_failed', stage, { status_code: response.status });
65
+ }
66
+ const chunks = [];
67
+ let size = 0;
68
+ if (response.body) {
69
+ const reader = response.body.getReader();
70
+ let next = await reader.read();
71
+ while (!next.done) {
72
+ const { value } = next;
73
+ size += value.byteLength;
74
+ if (size > MAX_RESPONSE_BYTES) {
75
+ await reader.cancel();
76
+ throw failure('RESPONSE_TOO_LARGE', 'invalid_response', stage);
77
+ }
78
+ chunks.push(Buffer.from(value));
79
+ next = await reader.read();
80
+ }
81
+ }
82
+ let payload;
83
+ try {
84
+ payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
85
+ } catch {
86
+ throw failure('INVALID_RESPONSE', 'invalid_response', stage);
87
+ }
88
+ if (!isObject(payload) || (payload.code !== undefined && payload.code !== 'ok')) {
89
+ throw failure('INVALID_RESPONSE', 'invalid_response', stage);
90
+ }
91
+ return payload;
92
+ } catch (error) {
93
+ if (error && error.isCliError) {
94
+ throw error;
95
+ }
96
+ throw controller.signal.aborted
97
+ ? failure('TIMEOUT', 'request_timeout', stage)
98
+ : failure('NETWORK_ERROR', 'request_failed', stage);
99
+ } finally {
100
+ clearTimeout(timer);
101
+ }
102
+ }
103
+
104
+ function decodeClaims(token) {
105
+ try {
106
+ const value = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
107
+ return isObject(value) ? value : {};
108
+ } catch {
109
+ return {};
110
+ }
111
+ }
112
+
113
+ /** Exchange a cloud Agent credential for an in-memory scoped user credential.
114
+ * This does not issue or persist an OpenYida session.
115
+ */
116
+ async function exchangeQwenWorkAgentToken(options = {}) {
117
+ const env = options.env || process.env;
118
+ const agent = pick(env, ['QWENWORK_AGENT_TOKEN', 'MULE_AGENT_TOKEN', 'AGENT_TOKEN']);
119
+ if (!agent || /[\r\n]/.test(agent.value)) {
120
+ throw failure('CREDENTIAL_MISSING', 'credential_missing', 'resolve_credentials');
121
+ }
122
+ const gateway = pick(env, ['QWENWORK_GATEWAY_URL', 'MULE_GATEWAY_URL']);
123
+ if (!gateway) {
124
+ throw failure('GATEWAY_MISSING', 'gateway_missing', 'resolve_credentials');
125
+ }
126
+ const baseUrl = normalizeBaseUrl(gateway.value);
127
+ const response = await requestJson('POST', `${baseUrl}/api/agent-gw/token/exchange`, agent.value, options, 'exchange');
128
+ // The current cloud endpoint returns {token, scope, ttl} without an envelope.
129
+ const payload = isObject(response.data) ? response.data : response;
130
+ if (typeof payload.token !== 'string' || !payload.token.trim() || /\s/.test(payload.token) ||
131
+ typeof payload.scope !== 'string' || !Number.isFinite(payload.ttl) || payload.ttl <= 0) {
132
+ throw failure('INVALID_RESPONSE', 'invalid_response', 'exchange');
133
+ }
134
+ const decoded = decodeClaims(payload.token);
135
+ if (typeof decoded.exp === 'number' && decoded.exp * 1000 <= Date.now()) {
136
+ throw failure('TOKEN_EXPIRED', 'expired_token', 'exchange');
137
+ }
138
+ return {
139
+ access_token: payload.token,
140
+ base_url: baseUrl,
141
+ credential_source: agent.name,
142
+ scope: payload.scope,
143
+ expires_in: payload.ttl,
144
+ expires_at: typeof decoded.exp === 'number' ? decoded.exp * 1000 : Date.now() + payload.ttl * 1000,
145
+ };
146
+ }
147
+
148
+ /** Query the credential's own origin; never infer a YiDA endpoint or organization. */
149
+ async function getQwenWorkUserInfo(credential, options = {}) {
150
+ const accessToken = credential && credential.access_token;
151
+ if (typeof accessToken !== 'string' || !accessToken || /[\r\n]/.test(accessToken)) {
152
+ throw failure('CREDENTIAL_MISSING', 'credential_missing', 'user_info');
153
+ }
154
+ const baseUrl = normalizeBaseUrl(credential.base_url);
155
+ const response = await requestJson('GET', `${baseUrl}/user/info`, accessToken, options, 'user_info');
156
+ if (response.code !== 'ok' || !isObject(response.data) ||
157
+ typeof response.data.user_id !== 'string' || !response.data.user_id.trim()) {
158
+ throw failure('INVALID_RESPONSE', 'invalid_response', 'user_info');
159
+ }
160
+ const env = options.env || process.env;
161
+ const decoded = decodeClaims(accessToken);
162
+ // Decoding is not local signature verification. The authenticated /user/info
163
+ // response establishes identity; these comparisons catch context drift.
164
+ for (const expected of [env.QWENWORK_USER_ID, env.MULE_USER_ID, decoded.user_id, decoded.sub]) {
165
+ if (expected && String(expected) !== response.data.user_id) {
166
+ throw failure('IDENTITY_MISMATCH', 'identity_mismatch', 'user_info');
167
+ }
168
+ }
169
+ const orgId = response.data.biz && response.data.biz.org_id;
170
+ if (orgId && decoded.biz_org_id && orgId !== decoded.biz_org_id) {
171
+ throw failure('IDENTITY_MISMATCH', 'identity_mismatch', 'user_info');
172
+ }
173
+ return response.data;
174
+ }
175
+
176
+ /** Safe composition for identity consumers: the returned object has no credential. */
177
+ async function getQwenWorkIdentity(options = {}) {
178
+ const credential = await exchangeQwenWorkAgentToken(options);
179
+ const profile = await getQwenWorkUserInfo(credential, options);
180
+ return {
181
+ base_url: credential.base_url,
182
+ credential_source: credential.credential_source,
183
+ scope: credential.scope,
184
+ expires_in: credential.expires_in,
185
+ expires_at: credential.expires_at,
186
+ profile,
187
+ };
188
+ }
189
+
190
+ module.exports = { exchangeQwenWorkAgentToken, getQwenWorkUserInfo, getQwenWorkIdentity };
@@ -0,0 +1,93 @@
1
+ 'use strict';
2
+
3
+ const { CliError } = require('../core/cli-error');
4
+ const { t } = require('../core/i18n');
5
+ const { DINGTALK_OAUTH_CLIENT_ID } = require('../core/env-manager');
6
+ const { resolveTokenBaseUrl } = require('./token-auth');
7
+
8
+ function failure(code, details = {}) {
9
+ return new CliError(t('qwenwork.login_check_failed'), { code: `QWENWORK_CLOUD_${code}`, details });
10
+ }
11
+
12
+ function origin(value) {
13
+ try {
14
+ const url = new URL(value);
15
+ if (typeof value !== 'string' || value.length > 2048 || /\s/.test(value) || url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) { throw new Error(); }
16
+ return url.origin;
17
+ } catch { throw failure('ENDPOINT_INVALID'); }
18
+ }
19
+
20
+ async function exchangeSession(credential, baseUrl, options) {
21
+ const controller = new AbortController();
22
+ const timeoutMs = options.timeoutMs === undefined ? 15000 : options.timeoutMs;
23
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { throw failure('INVALID_TIMEOUT'); }
24
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
25
+ try {
26
+ const response = await (options.fetch || globalThis.fetch)(`${baseUrl}/openapi/cli/v1/auth/qwenwork/token`, {
27
+ method: 'POST', redirect: 'error', signal: controller.signal,
28
+ headers: { authorization: `Bearer ${credential.access_token}`, accept: 'application/json', 'content-type': 'application/json' },
29
+ body: JSON.stringify({ gateway_url: credential.base_url, ...(options.corpId ? { corp_id: options.corpId } : {}) }),
30
+ });
31
+ if (!response.ok) {
32
+ await response.body?.cancel();
33
+ throw failure('HTTP_ERROR', { stage: 'yida_exchange', status_code: response.status });
34
+ }
35
+ const reader = response.body?.getReader();
36
+ if (!reader) { throw failure('RESPONSE_INVALID'); }
37
+ const chunks = []; let bytes = 0;
38
+ try {
39
+ for (let part = await reader.read(); !part.done; part = await reader.read()) {
40
+ bytes += part.value.byteLength;
41
+ if (bytes > 65536) { await reader.cancel(); throw failure('RESPONSE_INVALID'); }
42
+ chunks.push(part.value);
43
+ }
44
+ } finally { reader.releaseLock(); }
45
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
46
+ } catch (error) {
47
+ // 上游正文和异常可能回显凭据,仅保留本模块生成的固定错误码。
48
+ if (error instanceof CliError && /^QWENWORK_CLOUD_/.test(error.code)) { throw error; }
49
+ throw failure(controller.signal.aborted ? 'REQUEST_TIMED_OUT' : 'REQUEST_FAILED');
50
+ } finally { clearTimeout(timer); }
51
+ }
52
+
53
+ /** 只读取本次沙箱凭据,由宜搭服务端向受信任网关验证身份。 */
54
+ function sandboxCredential(options) {
55
+ const env = options.env || process.env;
56
+ const token = ['QWENWORK_AGENT_TOKEN', 'MULE_AGENT_TOKEN', 'AGENT_TOKEN'].map(name => env[name]).find(value => typeof value === 'string' && value);
57
+ if (!token) { throw new CliError(t('qwenwork.login_check_failed'), { code: 'QWENWORK_CREDENTIAL_MISSING' }); }
58
+ if (token.length > 4096 || /\s/.test(token)) { throw failure('CREDENTIAL_INVALID'); }
59
+ const gateway = env.QWENWORK_GATEWAY_URL || env.MULE_GATEWAY_URL;
60
+ if (!gateway) { throw new CliError(t('qwenwork.login_check_failed'), { code: 'QWENWORK_GATEWAY_MISSING' }); }
61
+ return { access_token: token, base_url: origin(gateway) };
62
+ }
63
+
64
+ /** 只向宜搭提交 Agent Token 和网关地址;返回会话供调用方校验后保存。 */
65
+ async function exchangeQwenWorkCloudSession(options = {}) {
66
+ const baseUrl = origin(options.endpoint || (options.env || process.env).OPENYIDA_ENDPOINT || resolveTokenBaseUrl(options));
67
+ const credential = sandboxCredential(options);
68
+ try {
69
+ const startedAt = Date.now();
70
+ const value = await exchangeSession(credential, baseUrl, options);
71
+ if (!value || value.status !== 'ok' || value.auth_mode !== 'token' || value.can_auto_use !== true ||
72
+ value.token_type !== 'Bearer' || value.credential_source !== 'qwenwork_cloud' ||
73
+ typeof value.access_token !== 'string' || !value.access_token || /\s/.test(value.access_token) || value.access_token.length > 32768 ||
74
+ value.access_token === credential.access_token ||
75
+ ['QWENWORK_AGENT_TOKEN', 'MULE_AGENT_TOKEN', 'AGENT_TOKEN'].some(name => value.access_token === (options.env || process.env)[name]) ||
76
+ !Number.isInteger(value.expires_in) || value.expires_in <= 0 || value.expires_in > 1800 ||
77
+ typeof value.corp_id !== 'string' || !/^(?:ding[0-9a-f]{32}|dingd8e1123006514592)$/.test(value.corp_id) ||
78
+ typeof value.user_id !== 'string' || !value.user_id || value.user_id.trim() !== value.user_id || value.user_id.length > 256 ||
79
+ (options.corpId && value.corp_id !== options.corpId) ||
80
+ (options.userId && value.user_id !== options.userId) ||
81
+ 'exchange_ticket' in value) { throw failure('RESPONSE_INVALID'); }
82
+ return {
83
+ auth_mode: 'token', credential_source: 'qwenwork_cloud', token_type: 'Bearer',
84
+ // 可信宜搭签发服务决定业务域名;认证请求仍只发往最初选择的 origin。
85
+ access_token: value.access_token, base_url: value.base_url === undefined ? baseUrl : origin(value.base_url),
86
+ client_id: options.clientId || DINGTALK_OAUTH_CLIENT_ID,
87
+ corp_id: value.corp_id, user_id: value.user_id,
88
+ expires_at: startedAt + value.expires_in * 1000,
89
+ };
90
+ } finally { credential.access_token = undefined; }
91
+ }
92
+
93
+ module.exports = { exchangeQwenWorkCloudSession };
@@ -0,0 +1,154 @@
1
+ 'use strict';
2
+
3
+ const { CliError } = require('../core/cli-error');
4
+ const { buildQwenWorkLoginInvocation } = require('../core/qwenwork-login-guidance');
5
+ const { t } = require('../core/i18n');
6
+ const { DINGTALK_OAUTH_CLIENT_ID } = require('../core/env-manager');
7
+ const { saveTokenSession, loadTokenSession, isEnvTokenAuthMode } = require('./token-store');
8
+ const { readManagedContext } = require('../agent/managed-context');
9
+
10
+ const TICKET_ENV = 'OPENYIDA_QWENWORK_EXCHANGE_TICKET';
11
+ const TICKET_CONTEXT_ENV = 'OPENYIDA_QWENWORK_EXCHANGE_TICKET_CONTEXT';
12
+ const CONSUME_PATH = '/openapi/cli/v1/auth/qwenwork/desktop/consume';
13
+ const MAX_RESPONSE_BYTES = 65536;
14
+
15
+ function fail(code) {
16
+ return new CliError(t('qwenwork.desktop_login_failed'), {
17
+ code: `QWENWORK_DESKTOP_${code}`,
18
+ details: { invocation: buildQwenWorkLoginInvocation() },
19
+ });
20
+ }
21
+
22
+ function parseTicket(raw, context) {
23
+ try {
24
+ if (typeof raw !== 'string' || !raw || /\s/.test(raw) || raw.length > 32768 || typeof context !== 'string' || context.length > 8192) { throw new Error(); }
25
+ const value = JSON.parse(context);
26
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
27
+ !Number.isSafeInteger(value.expires_at) || value.expires_at <= Date.now() || value.expires_at > Date.now() + 300000 ||
28
+ typeof value.corp_id !== 'string' || !value.corp_id || typeof value.user_id !== 'string' || !value.user_id ||
29
+ typeof value.exchange_id !== 'string' || !value.exchange_id ||
30
+ 'access_token' in value || 'refresh_token' in value || 'accessToken' in value || 'refreshToken' in value) { throw new Error(); }
31
+ return { ...value, exchange_ticket: raw };
32
+ } catch {
33
+ throw fail('TICKET_MISSING_OR_INVALID');
34
+ }
35
+ }
36
+
37
+ function origin(value) {
38
+ try {
39
+ const url = new URL(value);
40
+ if (typeof value !== 'string' || value.length > 2048 || /\s/.test(value) || url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') { throw new Error(); }
41
+ return url.origin;
42
+ } catch {
43
+ throw fail('ENDPOINT_INVALID');
44
+ }
45
+ }
46
+
47
+ async function requestJson(url, init, options) {
48
+ const controller = new AbortController();
49
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs || 15000);
50
+ try {
51
+ const response = await (options.fetch || globalThis.fetch)(url, { ...init, redirect: 'error', signal: controller.signal });
52
+ if (!response.ok) {
53
+ if (response.body) { await response.body.cancel(); }
54
+ throw fail('REQUEST_REJECTED');
55
+ }
56
+ const reader = response.body && response.body.getReader();
57
+ if (!reader) { throw fail('RESPONSE_INVALID'); }
58
+ const chunks = [];
59
+ let bytes = 0;
60
+ try {
61
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
62
+ bytes += next.value.byteLength;
63
+ if (bytes > MAX_RESPONSE_BYTES) { await reader.cancel(); throw fail('RESPONSE_INVALID'); }
64
+ chunks.push(next.value);
65
+ }
66
+ } finally {
67
+ reader.releaseLock();
68
+ }
69
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
70
+ if (!value || typeof value !== 'object' || Array.isArray(value)) { throw fail('RESPONSE_INVALID'); }
71
+ return value;
72
+ } catch (error) {
73
+ // 服务端和网络异常可能回显凭据,只透传本模块生成的固定错误。
74
+ if (error instanceof CliError && /^QWENWORK_DESKTOP_/.test(error.code)) { throw error; }
75
+ throw fail(controller.signal.aborted ? 'REQUEST_TIMED_OUT' : 'REQUEST_FAILED');
76
+ } finally {
77
+ clearTimeout(timer);
78
+ }
79
+ }
80
+
81
+ /** 客户端内部入口:消费一次性兑换票并持久化双 Token,不调用或重启普通 login。 */
82
+ async function loginQwenWork(options = {}) {
83
+ const env = options.env || process.env;
84
+ const raw = options.exchangeTicket || env[TICKET_ENV];
85
+ const context = options.ticketContext || env[TICKET_CONTEXT_ENV];
86
+ delete env[TICKET_ENV];
87
+ delete env[TICKET_CONTEXT_ENV];
88
+ if (isEnvTokenAuthMode(env) || readManagedContext(env)) { throw fail('MANAGED_AUTH_CONFLICT'); }
89
+ const ticket = parseTicket(raw, context);
90
+ const baseUrl = origin(ticket.base_url);
91
+ const expectedEndpoint = options.endpoint || env.OPENYIDA_ENDPOINT;
92
+ if (expectedEndpoint && origin(expectedEndpoint) !== baseUrl) { throw fail('ENDPOINT_MISMATCH'); }
93
+ if (options.corpId && options.corpId !== ticket.corp_id) { throw fail('IDENTITY_MISMATCH'); }
94
+ const startedAt = Date.now();
95
+ const value = await requestJson(`${baseUrl}${CONSUME_PATH}`, {
96
+ method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json', authorization: `Bearer ${ticket.exchange_ticket}` },
97
+ body: '{}',
98
+ }, options);
99
+ const expiresAt = startedAt + Number(value.expires_in) * 1000;
100
+ if (value.status !== 'ok' || value.auth_mode !== 'token' || value.can_auto_use !== true ||
101
+ value.token_type !== 'Bearer' || value.credential_source !== 'qwenwork_desktop' ||
102
+ 'refreshToken' in value || 'exchange_ticket' in value ||
103
+ typeof value.access_token !== 'string' || !value.access_token || /\s/.test(value.access_token) || value.access_token.length > 32768 ||
104
+ !Number.isInteger(value.expires_in) || value.expires_in < 1 || value.expires_in > 1800 ||
105
+ typeof value.refresh_token !== 'string' || !value.refresh_token || /\s/.test(value.refresh_token) || value.refresh_token.length > 32768 ||
106
+ !Number.isInteger(value.refresh_token_expires_in) || value.refresh_token_expires_in < 1 ||
107
+ (value.client_id && value.client_id !== DINGTALK_OAUTH_CLIENT_ID) ||
108
+ value.corp_id !== ticket.corp_id || value.user_id !== ticket.user_id || value.exchange_id !== ticket.exchange_id) { throw fail('CREDENTIAL_INVALID'); }
109
+ // 票据仍在原签票 origin 消费,业务域名仅来自受信的消费响应。
110
+ const businessBaseUrl = value.base_url === undefined ? baseUrl : origin(value.base_url);
111
+ const verified = await requestJson(`${businessBaseUrl}/openapi/cli/v1/auth/status`, {
112
+ method: 'GET', headers: { authorization: `Bearer ${value.access_token}`, accept: 'application/json' },
113
+ }, options);
114
+ if (verified.status !== 'ok' || verified.auth_mode !== 'token' || verified.can_auto_use !== true ||
115
+ verified.corp_id !== value.corp_id || verified.user_id !== value.user_id || expiresAt <= Date.now()) { throw fail('IDENTITY_MISMATCH'); }
116
+ const session = saveTokenSession({
117
+ auth_mode: 'token', token_type: 'Bearer', access_token: value.access_token, refresh_token: value.refresh_token,
118
+ expires_at: expiresAt, base_url: businessBaseUrl, client_id: DINGTALK_OAUTH_CLIENT_ID,
119
+ corp_id: value.corp_id, user_id: value.user_id, credential_source: 'qwenwork_desktop',
120
+ }, options);
121
+ const restored = loadTokenSession(options);
122
+ if (!['user', 'project'].includes(session.persistence_scope) || !restored ||
123
+ restored.access_token !== value.access_token || restored.refresh_token !== value.refresh_token || restored.base_url !== businessBaseUrl ||
124
+ restored.corp_id !== value.corp_id || restored.user_id !== value.user_id) { throw fail('PERSISTENCE_FAILED'); }
125
+ // 身份、环境和存储细节仅用于内部校验,不进入模型可见的登录结果。
126
+ return { ok: true, status: 'ok', can_auto_use: true };
127
+ }
128
+
129
+ async function run(args, options = {}) {
130
+ if (args.includes('--help') || args.includes('-h')) {
131
+ const invocation = buildQwenWorkLoginInvocation();
132
+ if (args.includes('--json')) { console.log(JSON.stringify({ usage: t('qwenwork.desktop_login_usage'), invocation })); }
133
+ else { console.log(`${t('qwenwork.desktop_login_usage')}\n${t('qwenwork.desktop_login_standalone', invocation.command)}`); }
134
+ return;
135
+ }
136
+ const parsed = {};
137
+ const seen = new Set();
138
+ for (let index = 0; index < args.length; index++) {
139
+ const flag = args[index];
140
+ if (seen.has(flag)) { throw new CliError(t('qwenwork.desktop_login_usage'), { code: 'CLI_USAGE_ERROR', exitCode: 2, details: { invocation: buildQwenWorkLoginInvocation() } }); }
141
+ seen.add(flag);
142
+ if (['--json', '--quiet'].includes(flag)) { continue; }
143
+ const key = flag === '--corp-id' ? 'corpId' : flag === '--endpoint' ? 'endpoint'
144
+ : flag === '--exchange-ticket' ? 'exchangeTicket' : flag === '--ticket-context' ? 'ticketContext' : null;
145
+ const value = args[++index];
146
+ if (!key || !value || value.startsWith('--')) { throw new CliError(t('qwenwork.desktop_login_usage'), { code: 'CLI_USAGE_ERROR', exitCode: 2, details: { invocation: buildQwenWorkLoginInvocation() } }); }
147
+ parsed[key] = value;
148
+ }
149
+ const result = await loginQwenWork({ ...options, ...parsed });
150
+ if (args.includes('--json') && !args.includes('--quiet') && (options.env || process.env).YIDA_QUIET !== '1') { console.log(JSON.stringify({ ...result, next_action: 'continue_business_operation_silently', user_visible: false })); }
151
+ return result;
152
+ }
153
+
154
+ module.exports = { TICKET_ENV, TICKET_CONTEXT_ENV, loginQwenWork, run };
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+ const { t } = require('../core/i18n');
3
+ const { CliError } = require('../core/cli-error');
4
+ const { loadTokenSession, resolveTokenSession, isEnvTokenAuthMode, hasEnvTokenCredential, saveTokenSession } = require('./token-store');
5
+ const { detectRuntimeCapabilities } = require('../core/utils');
6
+ const { isQwenWorkWebRuntime } = require('../core/qwenwork-login-guidance');
7
+ const { exchangeQwenWorkCloudSession } = require('./qwenwork-cloud');
8
+ const { tokenLogin, tokenRefresh, isRefreshAuthRequired } = require('./token-auth');
9
+
10
+ function failure(code) {
11
+ return new CliError(t('qwenwork.login_check_failed'), { code });
12
+ }
13
+ function summary(ok) { return { ok, status: ok ? 'ok' : 'not_logged_in', can_auto_use: ok }; }
14
+
15
+ /** 以服务端状态为准;网络异常不能触发浏览器登录。 */
16
+ async function verify(session, options = {}) {
17
+ if (!session || !session.access_token) { return false; }
18
+ const controller = new AbortController();
19
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs || 15000);
20
+ try {
21
+ const response = await (options.fetch || globalThis.fetch)(`${session.base_url.replace(/\/$/, '')}/openapi/cli/v1/auth/status`, {
22
+ headers: { authorization: `Bearer ${session.access_token}`, accept: 'application/json' },
23
+ redirect: 'error', signal: controller.signal,
24
+ });
25
+ if ([401, 403].includes(response.status)) { await response.body?.cancel(); return false; }
26
+ if (!response.ok) { await response.body?.cancel(); throw failure('QWENWORK_LOGIN_CHECK_FAILED'); }
27
+ const reader = response.body?.getReader();
28
+ if (!reader) { throw failure('QWENWORK_LOGIN_CHECK_FAILED'); }
29
+ const chunks = []; let size = 0;
30
+ try {
31
+ for (let part = await reader.read(); !part.done; part = await reader.read()) {
32
+ size += part.value.byteLength;
33
+ if (size > 65536) { await reader.cancel(); throw failure('QWENWORK_LOGIN_CHECK_FAILED'); }
34
+ chunks.push(part.value);
35
+ }
36
+ } finally { reader.releaseLock(); }
37
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
38
+ if (value.status !== 'ok' || value.can_auto_use !== true || value.auth_mode !== 'token') {
39
+ if (['not_logged_in', 'invalid_access_token', 'token_expired', 'auth_required'].includes(value.status)) { return false; }
40
+ throw failure('QWENWORK_LOGIN_CHECK_FAILED');
41
+ }
42
+ if (value.corp_id !== session.corp_id || value.user_id !== session.user_id ||
43
+ (options.corpId && value.corp_id !== options.corpId)) { throw failure('QWENWORK_LOGIN_IDENTITY_MISMATCH'); }
44
+ return true;
45
+ } catch (error) {
46
+ if (error instanceof CliError) { throw error; }
47
+ throw failure('QWENWORK_LOGIN_CHECK_FAILED');
48
+ } finally { clearTimeout(timer); }
49
+ }
50
+
51
+ /** 网页态消费宿主凭据;其他宿主保留已有登录态与前台 OAuth 流程。 */
52
+ async function ensureQwenWorkLogin(options = {}, dependencies = {}) {
53
+ const env = options.env || process.env;
54
+ const runtime = options.runtime || detectRuntimeCapabilities({ env });
55
+ if (isQwenWorkWebRuntime(runtime) && !isEnvTokenAuthMode(env) && !hasEnvTokenCredential(env)) {
56
+ if (options.checkOnly) { return summary(await verify(loadTokenSession(options), options)); }
57
+ const selectedProfile = options.authProfile || options.profile || env.OPENYIDA_AUTH_PROFILE;
58
+ const selectedSession = selectedProfile ? loadTokenSession(options) : null;
59
+ if (selectedProfile && !selectedSession) { throw failure('AUTH_PROFILE_REQUIRED'); }
60
+ const cloudOptions = {
61
+ ...options,
62
+ endpoint: options.endpoint || env.OPENYIDA_ENDPOINT || selectedSession?.base_url,
63
+ corpId: options.corpId || env.OPENYIDA_AUTH_CORP_ID || selectedSession?.corp_id,
64
+ userId: options.userId || env.OPENYIDA_AUTH_USER_ID || selectedSession?.user_id,
65
+ };
66
+ const session = await exchangeQwenWorkCloudSession(cloudOptions);
67
+ if (!await verify(session, options)) { throw failure('QWENWORK_LOGIN_CHECK_FAILED'); }
68
+ saveTokenSession(session, options);
69
+ return summary(true);
70
+ }
71
+ const resolution = resolveTokenSession(options);
72
+ if (resolution.status === 'profile_required') { throw failure('AUTH_PROFILE_REQUIRED'); }
73
+ let session = loadTokenSession(options);
74
+ if (session && options.endpoint && new URL(session.base_url).origin !== new URL(options.endpoint).origin) {
75
+ session = null;
76
+ }
77
+ if (await verify(session, options)) { return summary(true); }
78
+ if (session?.refresh_token) {
79
+ try {
80
+ const refreshed = await (dependencies.refresh || tokenRefresh)(options);
81
+ if (refreshed && refreshed.ok !== false && refreshed.access_token) {
82
+ if (await verify(refreshed, options)) { return summary(true); }
83
+ } else if (!isRefreshAuthRequired(refreshed)) { throw failure('QWENWORK_LOGIN_REFRESH_FAILED'); }
84
+ } catch (error) {
85
+ if (!isRefreshAuthRequired(error) && ![401, 403].includes(error.statusCode)) {
86
+ if (error instanceof CliError) { throw error; }
87
+ throw failure('QWENWORK_LOGIN_REFRESH_FAILED');
88
+ }
89
+ }
90
+ }
91
+ if (options.checkOnly) { return summary(false); }
92
+ if (isEnvTokenAuthMode(env) || isQwenWorkWebRuntime(runtime)) { throw failure('QWENWORK_LOGIN_FAILED'); }
93
+ const result = await (dependencies.login || tokenLogin)(options);
94
+ if (!result || result.ok === false || !result.access_token || !await verify(result, options)) {
95
+ throw failure('QWENWORK_LOGIN_FAILED');
96
+ }
97
+ return summary(true);
98
+ }
99
+
100
+ async function run(args, options = {}) {
101
+ const result = await ensureQwenWorkLogin({ ...options, checkOnly: args.includes('--check-only') });
102
+ if (args.includes('--json') && !args.includes('--quiet') && process.env.YIDA_QUIET !== '1') {
103
+ console.log(JSON.stringify(result));
104
+ }
105
+ if (!result.ok) { process.exitCode = 1; }
106
+ return result;
107
+ }
108
+ module.exports = { ensureQwenWorkLogin, run };