@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/dist/cli.js CHANGED
@@ -8,11 +8,11 @@ import { join, resolve, basename, dirname, relative, parse, extname, isAbsolute
8
8
  import { randomBytes, createHash, randomUUID } from 'crypto';
9
9
  import { tmpdir, homedir } from 'os';
10
10
  import * as tar from 'tar';
11
- import { createServer } from 'http';
12
11
  import { execFile, spawn, spawnSync } from 'child_process';
12
+ import { createServer } from 'http';
13
13
  import YAML2, { parse as parse$1 } from 'yaml';
14
14
  import { promisify } from 'util';
15
- import { validRange, minVersion, gte } from 'semver';
15
+ import { validRange, intersects, minVersion, gte } from 'semver';
16
16
  import ts from 'typescript';
17
17
 
18
18
  var EXCLUDED_NAMES = /* @__PURE__ */ new Set([".git", "node_modules", ".DS_Store", "PROMPT.md"]);
@@ -188,10 +188,10 @@ async function requestJson(baseUrl, path, options = {}) {
188
188
  ...init,
189
189
  headers: {
190
190
  Accept: "application/json",
191
- ...body !== void 0 && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {},
191
+ ...body instanceof URLSearchParams ? { "Content-Type": "application/x-www-form-urlencoded" } : body !== void 0 && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {},
192
192
  ...headers ?? {}
193
193
  },
194
- body: body === void 0 ? void 0 : body instanceof FormData ? body : JSON.stringify(body)
194
+ body: body === void 0 ? void 0 : body instanceof FormData || body instanceof URLSearchParams ? body : JSON.stringify(body)
195
195
  });
196
196
  const parsedBody = await parseResponseBody(response);
197
197
  if (!response.ok) {
@@ -222,6 +222,11 @@ async function requestBuffer(baseUrl, path, options = {}) {
222
222
  // src/marketplace/auth.ts
223
223
  var OAUTH_CLIENT_ID = "amaster-cli";
224
224
  var OAUTH_REDIRECT_URI = "http://127.0.0.1:18147/oauth/callback";
225
+ var OAUTH_SCOPE = "openid profile email organizations offline_access";
226
+ var RFC8693_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
227
+ var ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
228
+ var HELIGE_EXCHANGE_AUDIENCE = "urn:helige:token-exchange";
229
+ var HELIGE_API_RESOURCE = "urn:helige:api";
225
230
  var REFRESH_AHEAD_MS = 60 * 1e3;
226
231
  var BROWSER_LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
227
232
  function buildPkcePair() {
@@ -230,110 +235,83 @@ function buildPkcePair() {
230
235
  return { codeVerifier, codeChallenge };
231
236
  }
232
237
  function buildExpiresAt(expiresIn) {
233
- if (!expiresIn || expiresIn <= 0) {
234
- return void 0;
235
- }
238
+ if (!expiresIn || expiresIn <= 0) return void 0;
236
239
  return new Date(Date.now() + expiresIn * 1e3).toISOString();
237
240
  }
238
- function isSessionFreshEnough(session) {
239
- if (!session.expiresAt) {
240
- return true;
241
- }
242
- return new Date(session.expiresAt).getTime() - Date.now() > REFRESH_AHEAD_MS;
241
+ function isFreshEnough(expiresAt) {
242
+ if (!expiresAt) return true;
243
+ return new Date(expiresAt).getTime() - Date.now() > REFRESH_AHEAD_MS;
243
244
  }
244
- function buildAuthorizationUrl(input) {
245
- const authorizeUrl = new URL("/api/oauth/authorize", `${input.registry}/`);
245
+ function buildAuthorizationUrl(identityBaseUrl, state, codeChallenge) {
246
+ const authorizeUrl = new URL("/oauth/authorize", `${identityBaseUrl}/`);
246
247
  authorizeUrl.searchParams.set("response_type", "code");
247
248
  authorizeUrl.searchParams.set("client_id", OAUTH_CLIENT_ID);
248
249
  authorizeUrl.searchParams.set("redirect_uri", OAUTH_REDIRECT_URI);
249
- authorizeUrl.searchParams.set("scope", "openid profile email");
250
- authorizeUrl.searchParams.set("state", input.state);
251
- authorizeUrl.searchParams.set("code_challenge", input.codeChallenge);
250
+ authorizeUrl.searchParams.set("scope", OAUTH_SCOPE);
251
+ authorizeUrl.searchParams.set("state", state);
252
+ authorizeUrl.searchParams.set("nonce", randomBytes(32).toString("hex"));
253
+ authorizeUrl.searchParams.set("code_challenge", codeChallenge);
252
254
  authorizeUrl.searchParams.set("code_challenge_method", "S256");
253
- if (input.responseMode) {
254
- authorizeUrl.searchParams.set("response_mode", input.responseMode);
255
- }
256
255
  return authorizeUrl;
257
256
  }
258
- async function resolveBrowserLoginUrl(authorizeUrl) {
259
- const response = await fetch(authorizeUrl, {
257
+ async function fetchIamUserInfo(identityBaseUrl, accessToken) {
258
+ return await requestJson(identityBaseUrl, "/api/oauth2/userinfo", {
260
259
  method: "GET",
261
- redirect: "manual"
260
+ headers: { Authorization: `Bearer ${accessToken}` },
261
+ unwrapData: true
262
262
  });
263
- if (response.status >= 300 && response.status < 400) {
264
- const location = response.headers.get("location");
265
- if (location) {
266
- return new URL(location, authorizeUrl).toString();
267
- }
268
- }
269
- if (response.ok) {
270
- return authorizeUrl.toString();
271
- }
272
- throw new CliError(`Failed to start browser login: ${response.status} ${response.statusText}`, response.status);
273
263
  }
274
- async function fetchOAuthUserInfo(registry, accessToken) {
264
+ async function fetchLegacyPlatformUserInfo(registry, accessToken) {
275
265
  return await requestJson(registry, "/api/oauth/userinfo", {
276
266
  method: "GET",
277
- headers: {
278
- Authorization: `Bearer ${accessToken}`
279
- },
267
+ headers: { Authorization: `Bearer ${accessToken}` },
280
268
  unwrapData: true
281
269
  });
282
270
  }
283
- async function exchangeAuthorizationCodeForOAuthToken(input) {
284
- return await requestJson(input.registry, "/api/oauth/token", {
271
+ async function exchangeAuthorizationCodeForIdentityToken(input) {
272
+ return await requestJson(input.identityBaseUrl, "/api/oauth2/token", {
285
273
  method: "POST",
286
- body: {
274
+ body: new URLSearchParams({
287
275
  grant_type: "authorization_code",
288
276
  client_id: OAUTH_CLIENT_ID,
289
277
  code: input.code,
290
278
  redirect_uri: OAUTH_REDIRECT_URI,
291
279
  code_verifier: input.codeVerifier
292
- },
280
+ }),
293
281
  unwrapData: true
294
282
  });
295
283
  }
296
- async function exchangePasswordLoginForOAuthToken(registry, platformAccessToken) {
297
- const { codeVerifier, codeChallenge } = buildPkcePair();
298
- const state = randomBytes(16).toString("hex");
299
- const authorizeUrl = buildAuthorizationUrl({
300
- registry,
301
- state,
302
- codeChallenge,
303
- responseMode: "json"
284
+ async function exchangeIdentityForProductToken(input) {
285
+ const subjectToken = await requestJson(input.identityBaseUrl, "/api/oauth2/token", {
286
+ method: "POST",
287
+ body: new URLSearchParams({
288
+ grant_type: RFC8693_GRANT,
289
+ client_id: OAUTH_CLIENT_ID,
290
+ subject_token: input.identityAccessToken,
291
+ subject_token_type: ACCESS_TOKEN_TYPE,
292
+ requested_token_type: ACCESS_TOKEN_TYPE,
293
+ audience: HELIGE_EXCHANGE_AUDIENCE
294
+ }),
295
+ unwrapData: true
304
296
  });
305
- const authorizeResponse = await requestJson(
306
- registry,
307
- `${authorizeUrl.pathname}${authorizeUrl.search}`,
308
- {
309
- method: "GET",
310
- headers: {
311
- Authorization: `Bearer ${platformAccessToken}`
312
- },
313
- unwrapData: false
314
- }
315
- );
316
- const redirectUrl = authorizeResponse.redirectUrl ? new URL(authorizeResponse.redirectUrl) : (() => {
317
- throw new Error("OAuth authorize response missing redirectUrl");
318
- })();
319
- const code = redirectUrl.searchParams.get("code");
320
- if (!code) {
321
- throw new Error("OAuth authorize response missing code");
322
- }
323
- return await exchangeAuthorizationCodeForOAuthToken({
324
- registry,
325
- code,
326
- codeVerifier
297
+ return await requestJson(input.registry, "/api/oauth/token", {
298
+ method: "POST",
299
+ body: new URLSearchParams({
300
+ grant_type: RFC8693_GRANT,
301
+ client_id: OAUTH_CLIENT_ID,
302
+ subject_token: subjectToken.access_token,
303
+ subject_token_type: ACCESS_TOKEN_TYPE,
304
+ requested_token_type: ACCESS_TOKEN_TYPE,
305
+ resource: HELIGE_API_RESOURCE
306
+ }),
307
+ unwrapData: true
327
308
  });
328
309
  }
329
310
  function openUrlInBrowser(url) {
330
311
  const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
331
312
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
332
313
  return new Promise((resolve6, reject) => {
333
- const child = spawn(command, args, {
334
- detached: true,
335
- stdio: "ignore"
336
- });
314
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
337
315
  child.once("error", reject);
338
316
  child.once("spawn", () => {
339
317
  child.unref();
@@ -358,25 +336,12 @@ function waitForBrowserAuthorizationCode(input) {
358
336
  const state = requestUrl.searchParams.get("state");
359
337
  const error = requestUrl.searchParams.get("error");
360
338
  const errorDescription = requestUrl.searchParams.get("error_description");
361
- if (error) {
362
- response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
363
- response.end(`AMaster CLI login failed: ${errorDescription || error}`);
364
- cleanup();
365
- reject(new Error(errorDescription || error));
366
- return;
367
- }
368
- if (!code) {
369
- response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
370
- response.end("AMaster CLI login failed: missing authorization code");
371
- cleanup();
372
- reject(new Error("OAuth callback missing code"));
373
- return;
374
- }
375
- if (state !== input.expectedState) {
339
+ if (error || !code || state !== input.expectedState) {
340
+ const message = errorDescription || error || (!code ? "OAuth callback missing code" : "OAuth callback state mismatch");
376
341
  response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
377
- response.end("AMaster CLI login failed: invalid state");
342
+ response.end(`AMaster CLI login failed: ${message}`);
378
343
  cleanup();
379
- reject(new Error("OAuth callback state mismatch"));
344
+ reject(new Error(message));
380
345
  return;
381
346
  }
382
347
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", Connection: "close" });
@@ -396,16 +361,12 @@ function waitForBrowserAuthorizationCode(input) {
396
361
  closed = true;
397
362
  server.close();
398
363
  }
399
- for (const socket of sockets) {
400
- socket.destroy();
401
- }
364
+ for (const socket of sockets) socket.destroy();
402
365
  sockets.clear();
403
366
  }
404
367
  server.on("connection", (socket) => {
405
368
  sockets.add(socket);
406
- socket.once("close", () => {
407
- sockets.delete(socket);
408
- });
369
+ socket.once("close", () => sockets.delete(socket));
409
370
  });
410
371
  server.once("error", (error) => {
411
372
  cleanup();
@@ -414,122 +375,179 @@ function waitForBrowserAuthorizationCode(input) {
414
375
  server.listen(Number(redirectUrl.port), redirectUrl.hostname);
415
376
  });
416
377
  }
417
- async function loginWithBrowser(options) {
418
- const { codeVerifier, codeChallenge } = buildPkcePair();
419
- const state = randomBytes(16).toString("hex");
420
- const authorizeUrl = buildAuthorizationUrl({
421
- registry: options.registry,
422
- state,
423
- codeChallenge
378
+ async function createIamSession(input) {
379
+ const user = await fetchIamUserInfo(input.identityBaseUrl, input.identityToken.access_token);
380
+ const productToken = await exchangeIdentityForProductToken({
381
+ registry: input.registry,
382
+ identityBaseUrl: input.identityBaseUrl,
383
+ identityAccessToken: input.identityToken.access_token
424
384
  });
425
- const codePromise = options.waitForCode ? options.waitForCode(state) : waitForBrowserAuthorizationCode({
426
- expectedState: state,
427
- timeoutMs: options.timeoutMs
428
- });
429
- const browserUrl = await (options.resolveLoginUrl ?? resolveBrowserLoginUrl)(authorizeUrl);
430
- await (options.openUrl ?? openUrlInBrowser)(browserUrl);
431
- const code = await codePromise;
432
- const oauthToken = await exchangeAuthorizationCodeForOAuthToken({
433
- registry: options.registry,
434
- code,
435
- codeVerifier
436
- });
437
- const user = await fetchOAuthUserInfo(options.registry, oauthToken.access_token);
438
385
  const session = {
439
- registry: options.registry,
440
- accessToken: oauthToken.access_token,
441
- refreshToken: oauthToken.refresh_token,
442
- expiresAt: buildExpiresAt(oauthToken.expires_in),
386
+ authMode: "iam",
387
+ registry: input.registry,
388
+ identityBaseUrl: input.identityBaseUrl,
389
+ identityAccessToken: input.identityToken.access_token,
390
+ identityRefreshToken: input.identityToken.refresh_token,
391
+ identityExpiresAt: buildExpiresAt(input.identityToken.expires_in),
392
+ accessToken: productToken.access_token,
393
+ expiresAt: buildExpiresAt(productToken.expires_in),
443
394
  obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
444
395
  user
445
396
  };
446
397
  saveStoredSession(session);
447
398
  return session;
448
399
  }
400
+ async function loginWithBrowser(options) {
401
+ const { codeVerifier, codeChallenge } = buildPkcePair();
402
+ const state = randomBytes(16).toString("hex");
403
+ const codePromise = options.waitForCode ? options.waitForCode(state) : waitForBrowserAuthorizationCode({ expectedState: state, timeoutMs: options.timeoutMs });
404
+ await (options.openUrl ?? openUrlInBrowser)(buildAuthorizationUrl(options.identityBaseUrl, state, codeChallenge).toString());
405
+ const identityToken = await exchangeAuthorizationCodeForIdentityToken({
406
+ identityBaseUrl: options.identityBaseUrl,
407
+ code: await codePromise,
408
+ codeVerifier
409
+ });
410
+ return await createIamSession({ registry: options.registry, identityBaseUrl: options.identityBaseUrl, identityToken });
411
+ }
449
412
  async function loginWithPassword(options) {
450
- const { registry, email, username, password } = options;
451
- if (!email && !username) {
452
- throw new Error("Either email or username is required");
413
+ const identifier = options.email || options.username;
414
+ if (!identifier) throw new Error("Either email or username is required");
415
+ const { codeVerifier, codeChallenge } = buildPkcePair();
416
+ const state = options.state ?? randomBytes(16).toString("hex");
417
+ const nonce = options.nonce ?? randomBytes(32).toString("hex");
418
+ const authorization = await requestJson(
419
+ options.identityBaseUrl,
420
+ "/api/oauth2/native/password",
421
+ {
422
+ method: "POST",
423
+ body: {
424
+ identifier,
425
+ password: options.password,
426
+ ...options.organizationId ? { organization_id: options.organizationId } : {},
427
+ client_id: OAUTH_CLIENT_ID,
428
+ redirect_uri: OAUTH_REDIRECT_URI,
429
+ scope: OAUTH_SCOPE,
430
+ state,
431
+ nonce,
432
+ code_challenge: codeChallenge,
433
+ code_challenge_method: "S256"
434
+ },
435
+ unwrapData: true
436
+ }
437
+ );
438
+ if (!authorization.code || authorization.state !== state) {
439
+ throw new Error("IAM native authorization response is invalid");
440
+ }
441
+ const identityToken = await exchangeAuthorizationCodeForIdentityToken({
442
+ identityBaseUrl: options.identityBaseUrl,
443
+ code: authorization.code,
444
+ codeVerifier
445
+ });
446
+ return await createIamSession({
447
+ registry: options.registry,
448
+ identityBaseUrl: options.identityBaseUrl,
449
+ identityToken
450
+ });
451
+ }
452
+ async function refreshIdentitySession(session) {
453
+ if (!session.identityBaseUrl || !session.identityRefreshToken) {
454
+ throw new Error(`IAM session for ${session.registry} has expired and cannot be refreshed`);
453
455
  }
454
- const platformLogin = await requestJson(registry, "/api/auth/login", {
456
+ const refreshed = await requestJson(session.identityBaseUrl, "/api/oauth2/token", {
455
457
  method: "POST",
456
- body: {
457
- ...email ? { email } : {},
458
- ...username ? { username } : {},
459
- password
460
- },
458
+ body: new URLSearchParams({
459
+ grant_type: "refresh_token",
460
+ client_id: OAUTH_CLIENT_ID,
461
+ refresh_token: session.identityRefreshToken
462
+ }),
461
463
  unwrapData: true
462
464
  });
463
- if (!platformLogin.accessToken) {
464
- throw new Error("Password login succeeded but no platform access token was returned");
465
- }
466
- const oauthToken = await exchangePasswordLoginForOAuthToken(registry, platformLogin.accessToken);
467
- const user = await fetchOAuthUserInfo(registry, oauthToken.access_token);
468
- const session = {
469
- registry,
470
- accessToken: oauthToken.access_token,
471
- refreshToken: oauthToken.refresh_token,
472
- expiresAt: buildExpiresAt(oauthToken.expires_in),
473
- obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
474
- user
465
+ const nextSession = {
466
+ ...session,
467
+ identityAccessToken: refreshed.access_token,
468
+ identityRefreshToken: refreshed.refresh_token ?? session.identityRefreshToken,
469
+ identityExpiresAt: buildExpiresAt(refreshed.expires_in),
470
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
475
471
  };
476
- saveStoredSession(session);
477
- return session;
472
+ saveStoredSession(nextSession);
473
+ return nextSession;
478
474
  }
479
- async function refreshStoredSession(session) {
480
- if (!session.refreshToken) {
481
- throw new Error(`Session for ${session.registry} has expired and cannot be refreshed`);
475
+ async function ensureIdentitySession(session) {
476
+ if (!session.identityAccessToken || !session.identityBaseUrl) {
477
+ throw new Error(`IAM session for ${session.registry} is incomplete. Run login again.`);
482
478
  }
479
+ return isFreshEnough(session.identityExpiresAt) ? session : await refreshIdentitySession(session);
480
+ }
481
+ async function refreshProductSession(session) {
482
+ const identitySession = await ensureIdentitySession(session);
483
+ const productToken = await exchangeIdentityForProductToken({
484
+ registry: identitySession.registry,
485
+ identityBaseUrl: identitySession.identityBaseUrl,
486
+ identityAccessToken: identitySession.identityAccessToken
487
+ });
488
+ const nextSession = {
489
+ ...identitySession,
490
+ accessToken: productToken.access_token,
491
+ expiresAt: buildExpiresAt(productToken.expires_in),
492
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
493
+ };
494
+ saveStoredSession(nextSession);
495
+ return nextSession;
496
+ }
497
+ async function refreshLegacySession(session) {
498
+ if (!session.refreshToken) throw new Error(`Session for ${session.registry} has expired and cannot be refreshed`);
483
499
  const refreshed = await requestJson(session.registry, "/api/oauth/token", {
484
500
  method: "POST",
485
- body: {
501
+ body: new URLSearchParams({
486
502
  grant_type: "refresh_token",
487
503
  client_id: OAUTH_CLIENT_ID,
488
504
  refresh_token: session.refreshToken
489
- },
505
+ }),
490
506
  unwrapData: true
491
507
  });
492
508
  const nextSession = {
493
509
  ...session,
510
+ authMode: "legacy-platform",
494
511
  accessToken: refreshed.access_token,
495
512
  refreshToken: refreshed.refresh_token ?? session.refreshToken,
496
513
  expiresAt: buildExpiresAt(refreshed.expires_in),
497
514
  obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
498
515
  };
499
- try {
500
- nextSession.user = await fetchOAuthUserInfo(session.registry, nextSession.accessToken);
501
- } catch {
502
- nextSession.user = session.user;
503
- }
504
516
  saveStoredSession(nextSession);
505
517
  return nextSession;
506
518
  }
507
519
  async function getActiveSession(registry) {
508
520
  const stored = getStoredSession(registry);
509
- if (!stored) {
510
- throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
511
- }
512
- if (isSessionFreshEnough(stored)) {
513
- return stored;
514
- }
515
- return await refreshStoredSession(stored);
521
+ if (!stored) throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
522
+ if (isFreshEnough(stored.expiresAt)) return stored;
523
+ return stored.authMode === "iam" ? await refreshProductSession(stored) : await refreshLegacySession(stored);
516
524
  }
517
525
  async function withAccessToken(registry, runner) {
518
526
  let session = await getActiveSession(registry);
519
527
  try {
520
528
  return await runner(session.accessToken);
521
529
  } catch (error) {
522
- if (session.refreshToken && error instanceof CliError && (error.statusCode === 401 || error.statusCode === 403)) {
523
- session = await refreshStoredSession(session);
524
- return await runner(session.accessToken);
530
+ if (!(error instanceof CliError) || error.statusCode !== 401 && error.statusCode !== 403) throw error;
531
+ if (session.authMode === "iam") {
532
+ session = await refreshProductSession(session);
533
+ } else if (session.refreshToken) {
534
+ session = await refreshLegacySession(session);
535
+ } else {
536
+ throw error;
525
537
  }
526
- throw error;
538
+ return await runner(session.accessToken);
527
539
  }
528
540
  }
529
541
  async function getCurrentUser(registry) {
530
- return await withAccessToken(registry, async (accessToken) => {
531
- return await fetchOAuthUserInfo(registry, accessToken);
532
- });
542
+ const stored = getStoredSession(registry);
543
+ if (!stored) throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
544
+ if (stored.authMode === "iam") {
545
+ const session = await ensureIdentitySession(stored);
546
+ const user = await fetchIamUserInfo(session.identityBaseUrl, session.identityAccessToken);
547
+ saveStoredSession({ ...session, user });
548
+ return user;
549
+ }
550
+ return await withAccessToken(registry, (accessToken) => fetchLegacyPlatformUserInfo(registry, accessToken));
533
551
  }
534
552
  function logout(registry) {
535
553
  clearStoredSession(registry);
@@ -1363,6 +1381,9 @@ function isExistingNpmDependencyCompatible(existingVersion, requestedVersion) {
1363
1381
  if (!existingRange || !requestedRange) {
1364
1382
  return false;
1365
1383
  }
1384
+ if (intersects(existingRange, requestedRange, { includePrerelease: true })) {
1385
+ return true;
1386
+ }
1366
1387
  const existingMinimum = minVersion(existingRange);
1367
1388
  const requestedMinimum = minVersion(requestedRange);
1368
1389
  if (!existingMinimum || !requestedMinimum) {
@@ -3086,6 +3107,7 @@ var REGISTRY_ALIASES = {
3086
3107
  };
3087
3108
  var DEFAULT_REGISTRY_ALIAS = "helige";
3088
3109
  var DEFAULT_REGISTRY_ENV = "AMASTER_CLI_REGISTRY";
3110
+ var DEFAULT_IDENTITY_ENV = "AMASTER_CLI_IAM_URL";
3089
3111
  function normalizeRegistryUrl(input) {
3090
3112
  const trimmed = input.trim();
3091
3113
  if (!trimmed) {
@@ -3133,6 +3155,29 @@ function resolveRegistry(input) {
3133
3155
  }
3134
3156
  return normalizeRegistryUrl(DEFAULT_REGISTRY_ALIAS);
3135
3157
  }
3158
+ function resolveIdentityBaseUrl(registry, input) {
3159
+ const configured = input?.trim() || process.env[DEFAULT_IDENTITY_ENV]?.trim();
3160
+ if (configured) {
3161
+ return normalizeRegistryUrl(configured);
3162
+ }
3163
+ const url = new URL(registry);
3164
+ if (url.hostname === "www.helige.cn") {
3165
+ url.hostname = "account.helige.cn";
3166
+ } else if (url.hostname === "www.helige-int.cn") {
3167
+ url.hostname = "account.helige-int.cn";
3168
+ } else if (url.hostname.endsWith(".local")) {
3169
+ const baseHostname = url.hostname.replace(/^(www|platform)\./, "");
3170
+ url.hostname = `account.${baseHostname}`;
3171
+ } else {
3172
+ throw new Error(
3173
+ `IAM URL cannot be inferred from ${registry}. Provide --iam-url or ${DEFAULT_IDENTITY_ENV}.`
3174
+ );
3175
+ }
3176
+ url.pathname = "";
3177
+ url.search = "";
3178
+ url.hash = "";
3179
+ return url.toString().replace(/\/$/, "");
3180
+ }
3136
3181
  var DEFAULT_ROUTES_FILE = "src/routes.tsx";
3137
3182
  var REACT_VITE_DEV_TIMEOUT = 15e3;
3138
3183
  var REACT_VITE_BUILD_TIMEOUT = 3e4;
@@ -4493,9 +4538,10 @@ function requireStack(value) {
4493
4538
  }
4494
4539
  var program = new Command();
4495
4540
  program.name("amaster-cli").description("AMaster CLI").version(resolveCliVersion()).showHelpAfterError();
4496
- 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) => {
4541
+ 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) => {
4497
4542
  const registry = resolveRegistryFromOptions(options);
4498
- const session = options.browser ? await loginWithBrowser({ registry }) : await (async () => {
4543
+ const identityBaseUrl = resolveIdentityBaseUrl(registry, options.iamUrl);
4544
+ const session = options.browser ? await loginWithBrowser({ registry, identityBaseUrl }) : await (async () => {
4499
4545
  const credentials = await promptForMissingCredentials({
4500
4546
  email: options.email,
4501
4547
  username: options.username,
@@ -4503,9 +4549,11 @@ addJsonOption(addRegistryOption(program.command("login").description("Login to a
4503
4549
  });
4504
4550
  return await loginWithPassword({
4505
4551
  registry,
4552
+ identityBaseUrl,
4506
4553
  email: credentials.email,
4507
4554
  username: credentials.username,
4508
- password: credentials.password
4555
+ password: credentials.password,
4556
+ organizationId: options.organizationId
4509
4557
  });
4510
4558
  })();
4511
4559
  const result = {