@amerged/ohmyhost-cli 0.1.74 → 0.1.76

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.
@@ -27,7 +27,7 @@ import {
27
27
  ProductCli,
28
28
  classifyCliFailure,
29
29
  cliMetadataResult,
30
- CREDENTIAL_STORE_UNAVAILABLE_ACTION,
30
+ credentialStoreUnavailableAction,
31
31
  endedLoginAction,
32
32
  helpTopicKnown,
33
33
  internalErrorAction,
@@ -57,12 +57,14 @@ import {
57
57
  type CurrentCredential,
58
58
  type StoredCredential,
59
59
  } from "./credential-store.js";
60
+ import { LoginGoneError, renewLogin } from "./credential-refresh.js";
61
+ import { LoginOwnershipTimeoutError } from "./login-ownership.js";
60
62
  import { GeneratedSdkProductApi, type ProductApi } from "./product-api.js";
61
63
  import {
64
+ createProfileRegistry,
62
65
  defaultProfileName,
63
66
  describeProfile,
64
67
  isProfileName,
65
- NativeKeyringProfileRegistry,
66
68
  ProfileLimitError,
67
69
  profileLimitAction,
68
70
  ProfileSelectionError,
@@ -71,6 +73,7 @@ import {
71
73
  selectProfile,
72
74
  selectProfileForOrganization,
73
75
  type LocalProfile,
76
+ type LoginRef,
74
77
  type ProfileRegistry,
75
78
  type ProfileRequest,
76
79
  type ProfileSelector,
@@ -108,8 +111,10 @@ export interface ProductCliIo {
108
111
  }
109
112
 
110
113
  export interface ProductCliCompositionOverrides {
111
- /** Saved logins; the native credential store of the selected platform environment by default. */
114
+ /** Saved logins; the credential store of this platform and environment by default. */
112
115
  readonly profiles?: ProfileRegistry;
116
+ /** The operating system that picks the store: owner-only files on Linux, the native store else. */
117
+ readonly platform?: NodeJS.Platform;
113
118
  /** Directory whose project link supplies a missing --project; defaults to the process directory. */
114
119
  readonly workingDirectory?: string;
115
120
  readonly readSecretValue?: (signal: AbortSignal) => Promise<string>;
@@ -128,6 +133,8 @@ export interface ProfileRequestInput {
128
133
  export interface AuthenticatedProductApiOverrides {
129
134
  readonly environment?: ProductCliEnvironment;
130
135
  readonly profiles?: ProfileRegistry;
136
+ /** The operating system that picks the store; see the composition overrides. */
137
+ readonly platform?: NodeJS.Platform;
131
138
  readonly request?: ProfileRequestInput;
132
139
  /** How the caller names a login in its error guidance: a CLI flag or an MCP argument. */
133
140
  readonly selector?: ProfileSelector;
@@ -144,6 +151,8 @@ export class ProductApiAuthenticationError extends Error {
144
151
  | "token_refresh_failed"
145
152
  | "invalid_environment_token"
146
153
  | "invalid_profile_binding",
154
+ /** The record of the process that holds the login, when a renewal had to give up waiting. */
155
+ readonly record?: string,
147
156
  ) {
148
157
  super(code);
149
158
  this.name = "ProductApiAuthenticationError";
@@ -237,7 +246,7 @@ export const createAuthenticatedProductTransport = async (
237
246
  MAX_PUBLIC_RESPONSE_BYTES,
238
247
  );
239
248
  const registry =
240
- overrides.profiles ?? new NativeKeyringProfileRegistry(undefined, platform.credentialService);
249
+ overrides.profiles ?? createProfileRegistry(platform.credentialService, overrides.platform);
241
250
  const binding = overrides.request?.bindOrganization === true;
242
251
  const request = profileRequest(overrides.request, bound);
243
252
  if (apiToken !== undefined) {
@@ -286,8 +295,15 @@ export const createAuthenticatedProductTransport = async (
286
295
  const store = registry.credential(profile);
287
296
  const stored = await store.read();
288
297
  if (stored === undefined) throw missingLogin(profile, platform.commandPrefix);
289
- const credential = await currentCredential(stored, store, signal, now, refresher, () =>
290
- registry.remove(profile),
298
+ const credential = await currentCredential(
299
+ stored,
300
+ store,
301
+ signal,
302
+ now,
303
+ refresher,
304
+ registry,
305
+ profile,
306
+ () => registry.remove(profile),
291
307
  );
292
308
  return {
293
309
  baseUrl,
@@ -311,7 +327,7 @@ export const listSavedProfiles = async (
311
327
  const apiToken = environmentToken(overrides.environment);
312
328
  const bound = environmentProfile(overrides.environment);
313
329
  const registry =
314
- overrides.profiles ?? new NativeKeyringProfileRegistry(undefined, platform.credentialService);
330
+ overrides.profiles ?? createProfileRegistry(platform.credentialService, overrides.platform);
315
331
  const now = overrides.now ?? (() => new Date());
316
332
  const profiles =
317
333
  apiToken === undefined
@@ -353,37 +369,52 @@ const currentCredential = async (
353
369
  signal: AbortSignal,
354
370
  now: () => Date,
355
371
  tokenRefresher: TokenRefresher,
372
+ registry: ProfileRegistry,
373
+ login: LoginRef,
356
374
  forget: () => Promise<void>,
357
375
  ): Promise<CurrentCredential> => {
358
- const expiresAt = stored.expiresAt === undefined ? NaN : Date.parse(stored.expiresAt);
359
- if (Number.isFinite(expiresAt) && expiresAt > now().getTime() + REQUEST_TIMEOUT_MS) {
360
- return stored as CurrentCredential;
361
- }
376
+ const usable = (credential: StoredCredential): boolean => {
377
+ const expiresAt = credential.expiresAt === undefined ? NaN : Date.parse(credential.expiresAt);
378
+ return Number.isFinite(expiresAt) && expiresAt > now().getTime() + REQUEST_TIMEOUT_MS;
379
+ };
380
+ if (usable(stored)) return stored as CurrentCredential;
362
381
  try {
363
- const refreshed = await tokenRefresher.refresh(
364
- stored.refreshToken,
365
- boundedSignal(signal, REQUEST_TIMEOUT_MS),
366
- stored.workosOrganizationId,
367
- );
368
- const refreshedExpiry = Date.parse(refreshed.expiresAt);
369
- if (
370
- refreshed.accessToken.length === 0 ||
371
- refreshed.refreshToken.length === 0 ||
372
- !Number.isFinite(refreshedExpiry) ||
373
- refreshedExpiry <= now().getTime()
374
- ) {
375
- throw new Error("invalid refreshed credential");
376
- }
377
- // WorkOS returns a bare credential; the selection only survives if we carry it forward.
378
- const carried = { ...refreshed, ...workspaceOf(stored) };
379
- await store.replace(carried);
380
- return carried;
382
+ const renewal = await renewLogin({
383
+ // A shared file store reads the credential again as the owner; a native store need not.
384
+ ...(registry.kind === "file" ? {} : { current: stored }),
385
+ registry,
386
+ login,
387
+ store,
388
+ usable,
389
+ renew: async (credential) => {
390
+ const refreshed = await tokenRefresher.refresh(
391
+ credential.refreshToken,
392
+ boundedSignal(signal, REQUEST_TIMEOUT_MS),
393
+ credential.workosOrganizationId,
394
+ );
395
+ const refreshedExpiry = Date.parse(refreshed.expiresAt);
396
+ if (
397
+ refreshed.accessToken.length === 0 ||
398
+ refreshed.refreshToken.length === 0 ||
399
+ !Number.isFinite(refreshedExpiry) ||
400
+ refreshedExpiry <= now().getTime()
401
+ ) {
402
+ throw new Error("invalid refreshed credential");
403
+ }
404
+ // WorkOS returns a bare credential; the selection only survives if we carry it forward.
405
+ return { ...refreshed, ...workspaceOf(credential) };
406
+ },
407
+ rejected: (error) => error instanceof TokenRefreshRejectedError,
408
+ forget,
409
+ signal,
410
+ });
411
+ return renewal.credential as CurrentCredential;
381
412
  } catch (error) {
382
- if (error instanceof TokenRefreshRejectedError) {
383
- // The provider ended this login; only this saved login is removed.
384
- await forget();
413
+ // The provider ended this login (the owner removed only this saved login), or it is gone.
414
+ if (error instanceof TokenRefreshRejectedError || error instanceof LoginGoneError)
385
415
  throw new ProductApiAuthenticationError("authentication_required");
386
- }
416
+ if (error instanceof LoginOwnershipTimeoutError)
417
+ throw new ProductApiAuthenticationError("token_refresh_failed", error.record);
387
418
  throw new ProductApiAuthenticationError("token_refresh_failed");
388
419
  }
389
420
  };
@@ -424,6 +455,8 @@ const migrateLegacyLogin = async (
424
455
  context.signal,
425
456
  context.now,
426
457
  context.refresher,
458
+ registry,
459
+ "legacy",
427
460
  () => legacy.clear(),
428
461
  );
429
462
  } catch (error) {
@@ -458,9 +491,17 @@ const migrateLegacyLogin = async (
458
491
  { name: defaultProfileName(await registry.list(), login), ...login },
459
492
  credential,
460
493
  );
461
- await legacy.clear();
494
+ await registry.owning(["legacy"], () => legacy.clear());
462
495
  };
463
496
 
497
+ const httpStatusOf = (error: unknown): number | undefined =>
498
+ typeof error === "object" &&
499
+ error !== null &&
500
+ "status" in error &&
501
+ typeof error.status === "number"
502
+ ? error.status
503
+ : undefined;
504
+
464
505
  const isProblem = (error: unknown, code: string): boolean =>
465
506
  typeof error === "object" && error !== null && "code" in error && error.code === code;
466
507
 
@@ -603,7 +644,7 @@ export const runProductionCli = async (
603
644
  ? []
604
645
  : await (
605
646
  overrides.profiles ??
606
- new NativeKeyringProfileRegistry(undefined, platform.credentialService)
647
+ createProfileRegistry(platform.credentialService, overrides.platform)
607
648
  ).list();
608
649
  // The login a command names picks that organization's link of this checkout.
609
650
  return chooseLinkedProject(
@@ -632,7 +673,7 @@ export const runProductionCli = async (
632
673
  3,
633
674
  "credential_store_unavailable",
634
675
  false,
635
- CREDENTIAL_STORE_UNAVAILABLE_ACTION,
676
+ credentialStoreUnavailableAction(error),
636
677
  ),
637
678
  );
638
679
  const result =
@@ -767,7 +808,7 @@ export const runProductionCli = async (
767
808
  ),
768
809
  );
769
810
  const registry =
770
- overrides.profiles ?? new NativeKeyringProfileRegistry(undefined, platform.credentialService);
811
+ overrides.profiles ?? createProfileRegistry(platform.credentialService, overrides.platform);
771
812
  const linkDirectory = join(selectedSourceDirectory, platform.linkDirectory);
772
813
  const projectId = commandProjectId(command);
773
814
  // A command that named its project read no link yet, but the link still says whose project it is.
@@ -904,7 +945,6 @@ export const runProductionCli = async (
904
945
  const cli = new ProductCli({
905
946
  sourceDirectory: workingDirectory,
906
947
  sourceMetadataDirectory: platform.linkDirectory,
907
- sourceWorkspace: () => inspectSourceWorkspace(workingDirectory),
908
948
  ...(boundSource === undefined
909
949
  ? {}
910
950
  : {
@@ -937,6 +977,33 @@ export const runProductionCli = async (
937
977
  accessToken,
938
978
  boundedFetch(),
939
979
  ).getAccountProfile(),
980
+ firstWorkspace: async (accessToken, userId, signupSource) => {
981
+ try {
982
+ await new GeneratedSdkProductApi(
983
+ productApiOrigin,
984
+ accessToken,
985
+ boundedFetch(),
986
+ ).createOrganization({
987
+ name: "My workspace",
988
+ idempotencyKey: `initial-workspace:${userId}`,
989
+ ...(signupSource === null ? {} : { signupSource }),
990
+ });
991
+ return "created";
992
+ } catch (error) {
993
+ if (signal.aborted) throw error;
994
+ // The portal's rule: only a refusal for good ends the request; anything else may have been
995
+ // applied, so it is not retried blindly.
996
+ const status = httpStatusOf(error);
997
+ // A 4xx other than a timeout or a rate limit will be answered the same way again.
998
+ return status !== undefined &&
999
+ status >= 400 &&
1000
+ status < 500 &&
1001
+ status !== 408 &&
1002
+ status !== 429
1003
+ ? "refused"
1004
+ : "uncertain";
1005
+ }
1006
+ },
940
1007
  currentIdentity: async (accessToken) =>
941
1008
  await new GeneratedSdkProductApi(
942
1009
  productApiOrigin,
@@ -1060,6 +1127,14 @@ const compositionFailure = (
1060
1127
  false,
1061
1128
  profileLimitAction(commandPrefix),
1062
1129
  );
1130
+ if (error instanceof LoginOwnershipTimeoutError)
1131
+ return errorDocument(
1132
+ command,
1133
+ 5,
1134
+ "token_refresh_failed",
1135
+ true,
1136
+ refreshFailedAction(commandPrefix, profile, error.record),
1137
+ );
1063
1138
  if (error instanceof ProductApiAuthenticationError)
1064
1139
  return error.code === "authentication_required"
1065
1140
  ? errorDocument(
@@ -1074,7 +1149,7 @@ const compositionFailure = (
1074
1149
  5,
1075
1150
  "token_refresh_failed",
1076
1151
  true,
1077
- refreshFailedAction(commandPrefix, profile),
1152
+ refreshFailedAction(commandPrefix, profile, error.record),
1078
1153
  );
1079
1154
  return classifyCliFailure(command, error, signal);
1080
1155
  };
@@ -1543,7 +1618,7 @@ const runOfflineLogout = async (
1543
1618
  request.bound === undefined
1544
1619
  ) {
1545
1620
  // Nothing is saved under a name: a login of an earlier client goes, and none is logged out.
1546
- await registry.legacy().clear();
1621
+ await registry.owning(["legacy"], () => registry.legacy().clear());
1547
1622
  result = resultDocument("logout", 0, "logged_out");
1548
1623
  } else {
1549
1624
  const failure = profileSelectionError(selection, request, commandPrefix, "cli");
@@ -1555,20 +1630,29 @@ const runOfflineLogout = async (
1555
1630
  failure.suggestedAction,
1556
1631
  );
1557
1632
  }
1558
- } catch {
1633
+ } catch (error) {
1559
1634
  diagnostics.record({
1560
1635
  correlationId: randomUUID(),
1561
1636
  category: "credential_store",
1562
1637
  subsystem: "credential_store",
1563
1638
  errorKind: "unavailable",
1564
1639
  });
1565
- result = errorDocument(
1566
- "logout",
1567
- 3,
1568
- "credential_store_unavailable",
1569
- false,
1570
- CREDENTIAL_STORE_UNAVAILABLE_ACTION,
1571
- );
1640
+ result =
1641
+ error instanceof LoginOwnershipTimeoutError
1642
+ ? errorDocument(
1643
+ "logout",
1644
+ 5,
1645
+ "token_refresh_failed",
1646
+ true,
1647
+ `Another process on this computer holds this login (record ${error.record}) and did not finish in time; nothing was removed. Run the same command again in a minute.`,
1648
+ )
1649
+ : errorDocument(
1650
+ "logout",
1651
+ 3,
1652
+ "credential_store_unavailable",
1653
+ false,
1654
+ credentialStoreUnavailableAction(error),
1655
+ );
1572
1656
  }
1573
1657
  io.writeStdout(result.stdout);
1574
1658
  return result.exitCode;
@@ -0,0 +1,65 @@
1
+ import type { CredentialStore, CurrentCredential, StoredCredential } from "./credential-store.js";
2
+ import type { LoginRef, ProfileRegistry } from "./profile-store.js";
3
+
4
+ /** The saved credential disappeared while this process waited to renew it; nothing was written. */
5
+ export class LoginGoneError extends Error {
6
+ public constructor() {
7
+ super("The saved login has no credential any more");
8
+ this.name = "LoginGoneError";
9
+ }
10
+ }
11
+
12
+ /** Ownership for a store that is not shared between processes: the operation simply runs. */
13
+ export const DIRECT_OWNERSHIP: Pick<ProfileRegistry, "owning"> = {
14
+ owning: (_logins, operation) => operation(),
15
+ };
16
+
17
+ export interface LoginRenewal {
18
+ readonly registry: Pick<ProfileRegistry, "owning">;
19
+ readonly login: LoginRef;
20
+ readonly store: CredentialStore;
21
+ /** Whether a credential can be used as it is, without asking the provider. */
22
+ readonly usable: (credential: StoredCredential) => boolean;
23
+ /** Spends the credential's refresh token and answers the renewed credential, ready to save. */
24
+ readonly renew: (credential: StoredCredential) => Promise<CurrentCredential>;
25
+ /** Whether an error is the provider's final rejection of this login. */
26
+ readonly rejected: (error: unknown) => boolean;
27
+ /** Removes this login; it runs only after the provider rejected it. */
28
+ readonly forget: () => Promise<void>;
29
+ readonly signal?: AbortSignal;
30
+ /**
31
+ * The credential this call has just read, where ownership is a direct call and no other process
32
+ * can have renewed it meanwhile: it spares the native store a second read. A shared file store
33
+ * leaves it out, because the credential is read again as the owner.
34
+ */
35
+ readonly current?: StoredCredential;
36
+ }
37
+
38
+ /**
39
+ * Renews a saved login as its single owner. A refresh token is spent at the provider before
40
+ * anything is written, so ownership is taken first and the credential is read again as the owner: one
41
+ * that another process renewed meanwhile is used as it is and the provider is not asked, and one
42
+ * that is gone ends the call with nothing written. Only the provider's own rejection, seen as the
43
+ * owner, removes the login.
44
+ */
45
+ export const renewLogin = async (
46
+ input: LoginRenewal,
47
+ ): Promise<{ readonly credential: StoredCredential; readonly refreshed: boolean }> =>
48
+ await input.registry.owning(
49
+ [input.login],
50
+ async () => {
51
+ const current = input.current ?? (await input.store.read());
52
+ if (current === undefined) throw new LoginGoneError();
53
+ if (input.usable(current)) return { credential: current, refreshed: false };
54
+ let renewed: CurrentCredential;
55
+ try {
56
+ renewed = await input.renew(current);
57
+ } catch (error) {
58
+ if (input.rejected(error)) await input.forget();
59
+ throw error;
60
+ }
61
+ await input.store.replace(renewed);
62
+ return { credential: renewed, refreshed: true };
63
+ },
64
+ input.signal,
65
+ );