@amaster.ai/cli 1.1.61-beta.1 → 1.1.61

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
@@ -10,6 +10,7 @@
10
10
  - 默认 registry:`helige` -> `https://www.helige.cn`
11
11
  - 内置别名:`helige-int` -> `https://www.helige-int.cn`
12
12
  - 默认 registry 可通过环境变量 `AMASTER_CLI_REGISTRY` 覆盖
13
+ - IAM 地址可通过 `AMASTER_CLI_IAM_URL` 覆盖;内置 registry 和 `.local` 环境会自动解析 `account.*` 地址
13
14
  - 临时切换其他环境时使用 `--registry`
14
15
 
15
16
  ## 认证
@@ -20,17 +21,22 @@ export AMASTER_CLI_REGISTRY=amaster.local
20
21
  amaster login
21
22
  amaster login --registry helige-int --browser
22
23
  amaster login --registry helige-int
23
- amaster login --registry https://demo.example.com --email admin@amaster.ai --password password
24
+ amaster login --registry https://demo.example.com --iam-url https://account.example.com --email admin@amaster.ai --password password
25
+ amaster login --registry helige-int --organization-id <iam-organization-id>
24
26
  amaster whoami
25
27
  amaster logout
26
28
  ```
27
29
 
28
30
  登录流程:
29
31
 
30
- 1. `--browser`:打开 `/login?redirect=/api/oauth/authorize...`,通过本地 `http://127.0.0.1:18147/oauth/callback` 接收授权码
31
- 2. 默认密码模式:先登录 `/api/auth/login`
32
- 3. 再用 `amaster-cli` 这个 public PKCE OAuth client 兑换 Addon 写接口可用的 Bearer Token
33
- 4. 本地 session 按 registry 隔离保存到 `~/.amaster/cli/config.json`
32
+ 1. `--browser`:直接打开 IAM `/oauth/authorize`,通过本地 `http://127.0.0.1:18147/oauth/callback` 接收授权码
33
+ 2. 默认密码模式:调用 IAM `/api/oauth2/native/password`,只获取与 PKCE S256 绑定的一次性授权码
34
+ 3. CLI 保存 IAM identity access/refresh token,并通过两次 RFC 8693 Token Exchange 获取短期 Platform product token
35
+ 4. Addon 写接口只使用 `aud=urn:helige:api`、`client_id=amaster-cli` 的 product token
36
+ 5. 本地 session 按 registry 隔离保存到 `~/.amaster/cli/config.json`
37
+
38
+ IAM native 登录只允许有效且已认证的企业组织。账号属于多个可用企业组织时,必须通过
39
+ `--organization-id` 指定 IAM Organization ID。
34
40
 
35
41
  ## Addon 命令
36
42
 
package/dist/cli.cjs CHANGED
@@ -10,8 +10,8 @@ var path = require('path');
10
10
  var crypto = require('crypto');
11
11
  var os = require('os');
12
12
  var tar = require('tar');
13
- var http = require('http');
14
13
  var child_process = require('child_process');
14
+ var http = require('http');
15
15
  var YAML2 = require('yaml');
16
16
  var util = require('util');
17
17
  var semver = require('semver');
@@ -215,10 +215,10 @@ async function requestJson(baseUrl, path, options = {}) {
215
215
  ...init,
216
216
  headers: {
217
217
  Accept: "application/json",
218
- ...body !== void 0 && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {},
218
+ ...body instanceof URLSearchParams ? { "Content-Type": "application/x-www-form-urlencoded" } : body !== void 0 && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {},
219
219
  ...headers ?? {}
220
220
  },
221
- body: body === void 0 ? void 0 : body instanceof FormData ? body : JSON.stringify(body)
221
+ body: body === void 0 ? void 0 : body instanceof FormData || body instanceof URLSearchParams ? body : JSON.stringify(body)
222
222
  });
223
223
  const parsedBody = await parseResponseBody(response);
224
224
  if (!response.ok) {
@@ -249,6 +249,11 @@ async function requestBuffer(baseUrl, path, options = {}) {
249
249
  // src/marketplace/auth.ts
250
250
  var OAUTH_CLIENT_ID = "amaster-cli";
251
251
  var OAUTH_REDIRECT_URI = "http://127.0.0.1:18147/oauth/callback";
252
+ var OAUTH_SCOPE = "openid profile email organizations offline_access";
253
+ var RFC8693_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
254
+ var ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
255
+ var HELIGE_EXCHANGE_AUDIENCE = "urn:helige:token-exchange";
256
+ var HELIGE_API_RESOURCE = "urn:helige:api";
252
257
  var REFRESH_AHEAD_MS = 60 * 1e3;
253
258
  var BROWSER_LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
254
259
  function buildPkcePair() {
@@ -257,110 +262,83 @@ function buildPkcePair() {
257
262
  return { codeVerifier, codeChallenge };
258
263
  }
259
264
  function buildExpiresAt(expiresIn) {
260
- if (!expiresIn || expiresIn <= 0) {
261
- return void 0;
262
- }
265
+ if (!expiresIn || expiresIn <= 0) return void 0;
263
266
  return new Date(Date.now() + expiresIn * 1e3).toISOString();
264
267
  }
265
- function isSessionFreshEnough(session) {
266
- if (!session.expiresAt) {
267
- return true;
268
- }
269
- return new Date(session.expiresAt).getTime() - Date.now() > REFRESH_AHEAD_MS;
268
+ function isFreshEnough(expiresAt) {
269
+ if (!expiresAt) return true;
270
+ return new Date(expiresAt).getTime() - Date.now() > REFRESH_AHEAD_MS;
270
271
  }
271
- function buildAuthorizationUrl(input) {
272
- const authorizeUrl = new URL("/api/oauth/authorize", `${input.registry}/`);
272
+ function buildAuthorizationUrl(identityBaseUrl, state, codeChallenge) {
273
+ const authorizeUrl = new URL("/oauth/authorize", `${identityBaseUrl}/`);
273
274
  authorizeUrl.searchParams.set("response_type", "code");
274
275
  authorizeUrl.searchParams.set("client_id", OAUTH_CLIENT_ID);
275
276
  authorizeUrl.searchParams.set("redirect_uri", OAUTH_REDIRECT_URI);
276
- authorizeUrl.searchParams.set("scope", "openid profile email");
277
- authorizeUrl.searchParams.set("state", input.state);
278
- authorizeUrl.searchParams.set("code_challenge", input.codeChallenge);
277
+ authorizeUrl.searchParams.set("scope", OAUTH_SCOPE);
278
+ authorizeUrl.searchParams.set("state", state);
279
+ authorizeUrl.searchParams.set("nonce", crypto.randomBytes(32).toString("hex"));
280
+ authorizeUrl.searchParams.set("code_challenge", codeChallenge);
279
281
  authorizeUrl.searchParams.set("code_challenge_method", "S256");
280
- if (input.responseMode) {
281
- authorizeUrl.searchParams.set("response_mode", input.responseMode);
282
- }
283
282
  return authorizeUrl;
284
283
  }
285
- async function resolveBrowserLoginUrl(authorizeUrl) {
286
- const response = await fetch(authorizeUrl, {
284
+ async function fetchIamUserInfo(identityBaseUrl, accessToken) {
285
+ return await requestJson(identityBaseUrl, "/api/oauth2/userinfo", {
287
286
  method: "GET",
288
- redirect: "manual"
287
+ headers: { Authorization: `Bearer ${accessToken}` },
288
+ unwrapData: true
289
289
  });
290
- if (response.status >= 300 && response.status < 400) {
291
- const location = response.headers.get("location");
292
- if (location) {
293
- return new URL(location, authorizeUrl).toString();
294
- }
295
- }
296
- if (response.ok) {
297
- return authorizeUrl.toString();
298
- }
299
- throw new CliError(`Failed to start browser login: ${response.status} ${response.statusText}`, response.status);
300
290
  }
301
- async function fetchOAuthUserInfo(registry, accessToken) {
291
+ async function fetchLegacyPlatformUserInfo(registry, accessToken) {
302
292
  return await requestJson(registry, "/api/oauth/userinfo", {
303
293
  method: "GET",
304
- headers: {
305
- Authorization: `Bearer ${accessToken}`
306
- },
294
+ headers: { Authorization: `Bearer ${accessToken}` },
307
295
  unwrapData: true
308
296
  });
309
297
  }
310
- async function exchangeAuthorizationCodeForOAuthToken(input) {
311
- return await requestJson(input.registry, "/api/oauth/token", {
298
+ async function exchangeAuthorizationCodeForIdentityToken(input) {
299
+ return await requestJson(input.identityBaseUrl, "/api/oauth2/token", {
312
300
  method: "POST",
313
- body: {
301
+ body: new URLSearchParams({
314
302
  grant_type: "authorization_code",
315
303
  client_id: OAUTH_CLIENT_ID,
316
304
  code: input.code,
317
305
  redirect_uri: OAUTH_REDIRECT_URI,
318
306
  code_verifier: input.codeVerifier
319
- },
307
+ }),
320
308
  unwrapData: true
321
309
  });
322
310
  }
323
- async function exchangePasswordLoginForOAuthToken(registry, platformAccessToken) {
324
- const { codeVerifier, codeChallenge } = buildPkcePair();
325
- const state = crypto.randomBytes(16).toString("hex");
326
- const authorizeUrl = buildAuthorizationUrl({
327
- registry,
328
- state,
329
- codeChallenge,
330
- responseMode: "json"
311
+ async function exchangeIdentityForProductToken(input) {
312
+ const subjectToken = await requestJson(input.identityBaseUrl, "/api/oauth2/token", {
313
+ method: "POST",
314
+ body: new URLSearchParams({
315
+ grant_type: RFC8693_GRANT,
316
+ client_id: OAUTH_CLIENT_ID,
317
+ subject_token: input.identityAccessToken,
318
+ subject_token_type: ACCESS_TOKEN_TYPE,
319
+ requested_token_type: ACCESS_TOKEN_TYPE,
320
+ audience: HELIGE_EXCHANGE_AUDIENCE
321
+ }),
322
+ unwrapData: true
331
323
  });
332
- const authorizeResponse = await requestJson(
333
- registry,
334
- `${authorizeUrl.pathname}${authorizeUrl.search}`,
335
- {
336
- method: "GET",
337
- headers: {
338
- Authorization: `Bearer ${platformAccessToken}`
339
- },
340
- unwrapData: false
341
- }
342
- );
343
- const redirectUrl = authorizeResponse.redirectUrl ? new URL(authorizeResponse.redirectUrl) : (() => {
344
- throw new Error("OAuth authorize response missing redirectUrl");
345
- })();
346
- const code = redirectUrl.searchParams.get("code");
347
- if (!code) {
348
- throw new Error("OAuth authorize response missing code");
349
- }
350
- return await exchangeAuthorizationCodeForOAuthToken({
351
- registry,
352
- code,
353
- codeVerifier
324
+ return await requestJson(input.registry, "/api/oauth/token", {
325
+ method: "POST",
326
+ body: new URLSearchParams({
327
+ grant_type: RFC8693_GRANT,
328
+ client_id: OAUTH_CLIENT_ID,
329
+ subject_token: subjectToken.access_token,
330
+ subject_token_type: ACCESS_TOKEN_TYPE,
331
+ requested_token_type: ACCESS_TOKEN_TYPE,
332
+ resource: HELIGE_API_RESOURCE
333
+ }),
334
+ unwrapData: true
354
335
  });
355
336
  }
356
337
  function openUrlInBrowser(url) {
357
338
  const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
358
339
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
359
340
  return new Promise((resolve6, reject) => {
360
- const child = child_process.spawn(command, args, {
361
- detached: true,
362
- stdio: "ignore"
363
- });
341
+ const child = child_process.spawn(command, args, { detached: true, stdio: "ignore" });
364
342
  child.once("error", reject);
365
343
  child.once("spawn", () => {
366
344
  child.unref();
@@ -385,25 +363,12 @@ function waitForBrowserAuthorizationCode(input) {
385
363
  const state = requestUrl.searchParams.get("state");
386
364
  const error = requestUrl.searchParams.get("error");
387
365
  const errorDescription = requestUrl.searchParams.get("error_description");
388
- if (error) {
389
- response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
390
- response.end(`AMaster CLI login failed: ${errorDescription || error}`);
391
- cleanup();
392
- reject(new Error(errorDescription || error));
393
- return;
394
- }
395
- if (!code) {
396
- response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
397
- response.end("AMaster CLI login failed: missing authorization code");
398
- cleanup();
399
- reject(new Error("OAuth callback missing code"));
400
- return;
401
- }
402
- if (state !== input.expectedState) {
366
+ if (error || !code || state !== input.expectedState) {
367
+ const message = errorDescription || error || (!code ? "OAuth callback missing code" : "OAuth callback state mismatch");
403
368
  response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
404
- response.end("AMaster CLI login failed: invalid state");
369
+ response.end(`AMaster CLI login failed: ${message}`);
405
370
  cleanup();
406
- reject(new Error("OAuth callback state mismatch"));
371
+ reject(new Error(message));
407
372
  return;
408
373
  }
409
374
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", Connection: "close" });
@@ -423,16 +388,12 @@ function waitForBrowserAuthorizationCode(input) {
423
388
  closed = true;
424
389
  server.close();
425
390
  }
426
- for (const socket of sockets) {
427
- socket.destroy();
428
- }
391
+ for (const socket of sockets) socket.destroy();
429
392
  sockets.clear();
430
393
  }
431
394
  server.on("connection", (socket) => {
432
395
  sockets.add(socket);
433
- socket.once("close", () => {
434
- sockets.delete(socket);
435
- });
396
+ socket.once("close", () => sockets.delete(socket));
436
397
  });
437
398
  server.once("error", (error) => {
438
399
  cleanup();
@@ -441,122 +402,179 @@ function waitForBrowserAuthorizationCode(input) {
441
402
  server.listen(Number(redirectUrl.port), redirectUrl.hostname);
442
403
  });
443
404
  }
444
- async function loginWithBrowser(options) {
445
- const { codeVerifier, codeChallenge } = buildPkcePair();
446
- const state = crypto.randomBytes(16).toString("hex");
447
- const authorizeUrl = buildAuthorizationUrl({
448
- registry: options.registry,
449
- state,
450
- codeChallenge
405
+ async function createIamSession(input) {
406
+ const user = await fetchIamUserInfo(input.identityBaseUrl, input.identityToken.access_token);
407
+ const productToken = await exchangeIdentityForProductToken({
408
+ registry: input.registry,
409
+ identityBaseUrl: input.identityBaseUrl,
410
+ identityAccessToken: input.identityToken.access_token
451
411
  });
452
- const codePromise = options.waitForCode ? options.waitForCode(state) : waitForBrowserAuthorizationCode({
453
- expectedState: state,
454
- timeoutMs: options.timeoutMs
455
- });
456
- const browserUrl = await (options.resolveLoginUrl ?? resolveBrowserLoginUrl)(authorizeUrl);
457
- await (options.openUrl ?? openUrlInBrowser)(browserUrl);
458
- const code = await codePromise;
459
- const oauthToken = await exchangeAuthorizationCodeForOAuthToken({
460
- registry: options.registry,
461
- code,
462
- codeVerifier
463
- });
464
- const user = await fetchOAuthUserInfo(options.registry, oauthToken.access_token);
465
412
  const session = {
466
- registry: options.registry,
467
- accessToken: oauthToken.access_token,
468
- refreshToken: oauthToken.refresh_token,
469
- expiresAt: buildExpiresAt(oauthToken.expires_in),
413
+ authMode: "iam",
414
+ registry: input.registry,
415
+ identityBaseUrl: input.identityBaseUrl,
416
+ identityAccessToken: input.identityToken.access_token,
417
+ identityRefreshToken: input.identityToken.refresh_token,
418
+ identityExpiresAt: buildExpiresAt(input.identityToken.expires_in),
419
+ accessToken: productToken.access_token,
420
+ expiresAt: buildExpiresAt(productToken.expires_in),
470
421
  obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
471
422
  user
472
423
  };
473
424
  saveStoredSession(session);
474
425
  return session;
475
426
  }
427
+ async function loginWithBrowser(options) {
428
+ const { codeVerifier, codeChallenge } = buildPkcePair();
429
+ const state = crypto.randomBytes(16).toString("hex");
430
+ const codePromise = options.waitForCode ? options.waitForCode(state) : waitForBrowserAuthorizationCode({ expectedState: state, timeoutMs: options.timeoutMs });
431
+ await (options.openUrl ?? openUrlInBrowser)(buildAuthorizationUrl(options.identityBaseUrl, state, codeChallenge).toString());
432
+ const identityToken = await exchangeAuthorizationCodeForIdentityToken({
433
+ identityBaseUrl: options.identityBaseUrl,
434
+ code: await codePromise,
435
+ codeVerifier
436
+ });
437
+ return await createIamSession({ registry: options.registry, identityBaseUrl: options.identityBaseUrl, identityToken });
438
+ }
476
439
  async function loginWithPassword(options) {
477
- const { registry, email, username, password } = options;
478
- if (!email && !username) {
479
- throw new Error("Either email or username is required");
440
+ const identifier = options.email || options.username;
441
+ if (!identifier) throw new Error("Either email or username is required");
442
+ const { codeVerifier, codeChallenge } = buildPkcePair();
443
+ const state = options.state ?? crypto.randomBytes(16).toString("hex");
444
+ const nonce = options.nonce ?? crypto.randomBytes(32).toString("hex");
445
+ const authorization = await requestJson(
446
+ options.identityBaseUrl,
447
+ "/api/oauth2/native/password",
448
+ {
449
+ method: "POST",
450
+ body: {
451
+ identifier,
452
+ password: options.password,
453
+ ...options.organizationId ? { organization_id: options.organizationId } : {},
454
+ client_id: OAUTH_CLIENT_ID,
455
+ redirect_uri: OAUTH_REDIRECT_URI,
456
+ scope: OAUTH_SCOPE,
457
+ state,
458
+ nonce,
459
+ code_challenge: codeChallenge,
460
+ code_challenge_method: "S256"
461
+ },
462
+ unwrapData: true
463
+ }
464
+ );
465
+ if (!authorization.code || authorization.state !== state) {
466
+ throw new Error("IAM native authorization response is invalid");
467
+ }
468
+ const identityToken = await exchangeAuthorizationCodeForIdentityToken({
469
+ identityBaseUrl: options.identityBaseUrl,
470
+ code: authorization.code,
471
+ codeVerifier
472
+ });
473
+ return await createIamSession({
474
+ registry: options.registry,
475
+ identityBaseUrl: options.identityBaseUrl,
476
+ identityToken
477
+ });
478
+ }
479
+ async function refreshIdentitySession(session) {
480
+ if (!session.identityBaseUrl || !session.identityRefreshToken) {
481
+ throw new Error(`IAM session for ${session.registry} has expired and cannot be refreshed`);
480
482
  }
481
- const platformLogin = await requestJson(registry, "/api/auth/login", {
483
+ const refreshed = await requestJson(session.identityBaseUrl, "/api/oauth2/token", {
482
484
  method: "POST",
483
- body: {
484
- ...email ? { email } : {},
485
- ...username ? { username } : {},
486
- password
487
- },
485
+ body: new URLSearchParams({
486
+ grant_type: "refresh_token",
487
+ client_id: OAUTH_CLIENT_ID,
488
+ refresh_token: session.identityRefreshToken
489
+ }),
488
490
  unwrapData: true
489
491
  });
490
- if (!platformLogin.accessToken) {
491
- throw new Error("Password login succeeded but no platform access token was returned");
492
- }
493
- const oauthToken = await exchangePasswordLoginForOAuthToken(registry, platformLogin.accessToken);
494
- const user = await fetchOAuthUserInfo(registry, oauthToken.access_token);
495
- const session = {
496
- registry,
497
- accessToken: oauthToken.access_token,
498
- refreshToken: oauthToken.refresh_token,
499
- expiresAt: buildExpiresAt(oauthToken.expires_in),
500
- obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
501
- user
492
+ const nextSession = {
493
+ ...session,
494
+ identityAccessToken: refreshed.access_token,
495
+ identityRefreshToken: refreshed.refresh_token ?? session.identityRefreshToken,
496
+ identityExpiresAt: buildExpiresAt(refreshed.expires_in),
497
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
502
498
  };
503
- saveStoredSession(session);
504
- return session;
499
+ saveStoredSession(nextSession);
500
+ return nextSession;
505
501
  }
506
- async function refreshStoredSession(session) {
507
- if (!session.refreshToken) {
508
- throw new Error(`Session for ${session.registry} has expired and cannot be refreshed`);
502
+ async function ensureIdentitySession(session) {
503
+ if (!session.identityAccessToken || !session.identityBaseUrl) {
504
+ throw new Error(`IAM session for ${session.registry} is incomplete. Run login again.`);
509
505
  }
506
+ return isFreshEnough(session.identityExpiresAt) ? session : await refreshIdentitySession(session);
507
+ }
508
+ async function refreshProductSession(session) {
509
+ const identitySession = await ensureIdentitySession(session);
510
+ const productToken = await exchangeIdentityForProductToken({
511
+ registry: identitySession.registry,
512
+ identityBaseUrl: identitySession.identityBaseUrl,
513
+ identityAccessToken: identitySession.identityAccessToken
514
+ });
515
+ const nextSession = {
516
+ ...identitySession,
517
+ accessToken: productToken.access_token,
518
+ expiresAt: buildExpiresAt(productToken.expires_in),
519
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
520
+ };
521
+ saveStoredSession(nextSession);
522
+ return nextSession;
523
+ }
524
+ async function refreshLegacySession(session) {
525
+ if (!session.refreshToken) throw new Error(`Session for ${session.registry} has expired and cannot be refreshed`);
510
526
  const refreshed = await requestJson(session.registry, "/api/oauth/token", {
511
527
  method: "POST",
512
- body: {
528
+ body: new URLSearchParams({
513
529
  grant_type: "refresh_token",
514
530
  client_id: OAUTH_CLIENT_ID,
515
531
  refresh_token: session.refreshToken
516
- },
532
+ }),
517
533
  unwrapData: true
518
534
  });
519
535
  const nextSession = {
520
536
  ...session,
537
+ authMode: "legacy-platform",
521
538
  accessToken: refreshed.access_token,
522
539
  refreshToken: refreshed.refresh_token ?? session.refreshToken,
523
540
  expiresAt: buildExpiresAt(refreshed.expires_in),
524
541
  obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
525
542
  };
526
- try {
527
- nextSession.user = await fetchOAuthUserInfo(session.registry, nextSession.accessToken);
528
- } catch {
529
- nextSession.user = session.user;
530
- }
531
543
  saveStoredSession(nextSession);
532
544
  return nextSession;
533
545
  }
534
546
  async function getActiveSession(registry) {
535
547
  const stored = getStoredSession(registry);
536
- if (!stored) {
537
- throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
538
- }
539
- if (isSessionFreshEnough(stored)) {
540
- return stored;
541
- }
542
- return await refreshStoredSession(stored);
548
+ if (!stored) throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
549
+ if (isFreshEnough(stored.expiresAt)) return stored;
550
+ return stored.authMode === "iam" ? await refreshProductSession(stored) : await refreshLegacySession(stored);
543
551
  }
544
552
  async function withAccessToken(registry, runner) {
545
553
  let session = await getActiveSession(registry);
546
554
  try {
547
555
  return await runner(session.accessToken);
548
556
  } catch (error) {
549
- if (session.refreshToken && error instanceof CliError && (error.statusCode === 401 || error.statusCode === 403)) {
550
- session = await refreshStoredSession(session);
551
- return await runner(session.accessToken);
557
+ if (!(error instanceof CliError) || error.statusCode !== 401 && error.statusCode !== 403) throw error;
558
+ if (session.authMode === "iam") {
559
+ session = await refreshProductSession(session);
560
+ } else if (session.refreshToken) {
561
+ session = await refreshLegacySession(session);
562
+ } else {
563
+ throw error;
552
564
  }
553
- throw error;
565
+ return await runner(session.accessToken);
554
566
  }
555
567
  }
556
568
  async function getCurrentUser(registry) {
557
- return await withAccessToken(registry, async (accessToken) => {
558
- return await fetchOAuthUserInfo(registry, accessToken);
559
- });
569
+ const stored = getStoredSession(registry);
570
+ if (!stored) throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
571
+ if (stored.authMode === "iam") {
572
+ const session = await ensureIdentitySession(stored);
573
+ const user = await fetchIamUserInfo(session.identityBaseUrl, session.identityAccessToken);
574
+ saveStoredSession({ ...session, user });
575
+ return user;
576
+ }
577
+ return await withAccessToken(registry, (accessToken) => fetchLegacyPlatformUserInfo(registry, accessToken));
560
578
  }
561
579
  function logout(registry) {
562
580
  clearStoredSession(registry);
@@ -1390,6 +1408,9 @@ function isExistingNpmDependencyCompatible(existingVersion, requestedVersion) {
1390
1408
  if (!existingRange || !requestedRange) {
1391
1409
  return false;
1392
1410
  }
1411
+ if (semver.intersects(existingRange, requestedRange, { includePrerelease: true })) {
1412
+ return true;
1413
+ }
1393
1414
  const existingMinimum = semver.minVersion(existingRange);
1394
1415
  const requestedMinimum = semver.minVersion(requestedRange);
1395
1416
  if (!existingMinimum || !requestedMinimum) {
@@ -3113,6 +3134,7 @@ var REGISTRY_ALIASES = {
3113
3134
  };
3114
3135
  var DEFAULT_REGISTRY_ALIAS = "helige";
3115
3136
  var DEFAULT_REGISTRY_ENV = "AMASTER_CLI_REGISTRY";
3137
+ var DEFAULT_IDENTITY_ENV = "AMASTER_CLI_IAM_URL";
3116
3138
  function normalizeRegistryUrl(input) {
3117
3139
  const trimmed = input.trim();
3118
3140
  if (!trimmed) {
@@ -3160,6 +3182,29 @@ function resolveRegistry(input) {
3160
3182
  }
3161
3183
  return normalizeRegistryUrl(DEFAULT_REGISTRY_ALIAS);
3162
3184
  }
3185
+ function resolveIdentityBaseUrl(registry, input) {
3186
+ const configured = input?.trim() || process.env[DEFAULT_IDENTITY_ENV]?.trim();
3187
+ if (configured) {
3188
+ return normalizeRegistryUrl(configured);
3189
+ }
3190
+ const url = new URL(registry);
3191
+ if (url.hostname === "www.helige.cn") {
3192
+ url.hostname = "account.helige.cn";
3193
+ } else if (url.hostname === "www.helige-int.cn") {
3194
+ url.hostname = "account.helige-int.cn";
3195
+ } else if (url.hostname.endsWith(".local")) {
3196
+ const baseHostname = url.hostname.replace(/^(www|platform)\./, "");
3197
+ url.hostname = `account.${baseHostname}`;
3198
+ } else {
3199
+ throw new Error(
3200
+ `IAM URL cannot be inferred from ${registry}. Provide --iam-url or ${DEFAULT_IDENTITY_ENV}.`
3201
+ );
3202
+ }
3203
+ url.pathname = "";
3204
+ url.search = "";
3205
+ url.hash = "";
3206
+ return url.toString().replace(/\/$/, "");
3207
+ }
3163
3208
  var DEFAULT_ROUTES_FILE = "src/routes.tsx";
3164
3209
  var REACT_VITE_DEV_TIMEOUT = 15e3;
3165
3210
  var REACT_VITE_BUILD_TIMEOUT = 3e4;
@@ -4520,9 +4565,10 @@ function requireStack(value) {
4520
4565
  }
4521
4566
  var program = new commander.Command();
4522
4567
  program.name("amaster-cli").description("AMaster CLI").version(resolveCliVersion()).showHelpAfterError();
4523
- addJsonOption(addRegistryOption(program.command("login").description("Login to an AMaster registry"))).option("--browser", "Login with browser OAuth flow").option("-e, --email <email>", "Email").option("-u, --username <username>", "Username").option("-p, --password <password>", "Password").action(async (options) => {
4568
+ addJsonOption(addRegistryOption(program.command("login").description("Login to an AMaster registry"))).option("--browser", "Login with browser OAuth flow").option("--iam-url <url>", "IAM identity service URL").option("--organization-id <id>", "IAM organization ID for accounts with multiple business organizations").option("-e, --email <email>", "Email").option("-u, --username <username>", "Username").option("-p, --password <password>", "Password").action(async (options) => {
4524
4569
  const registry = resolveRegistryFromOptions(options);
4525
- const session = options.browser ? await loginWithBrowser({ registry }) : await (async () => {
4570
+ const identityBaseUrl = resolveIdentityBaseUrl(registry, options.iamUrl);
4571
+ const session = options.browser ? await loginWithBrowser({ registry, identityBaseUrl }) : await (async () => {
4526
4572
  const credentials = await promptForMissingCredentials({
4527
4573
  email: options.email,
4528
4574
  username: options.username,
@@ -4530,9 +4576,11 @@ addJsonOption(addRegistryOption(program.command("login").description("Login to a
4530
4576
  });
4531
4577
  return await loginWithPassword({
4532
4578
  registry,
4579
+ identityBaseUrl,
4533
4580
  email: credentials.email,
4534
4581
  username: credentials.username,
4535
- password: credentials.password
4582
+ password: credentials.password,
4583
+ organizationId: options.organizationId
4536
4584
  });
4537
4585
  })();
4538
4586
  const result = {