@amerged/ohmyhost-cli 0.1.75 → 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.
@@ -9,7 +9,6 @@ import {
9
9
  createSourceSnapshot,
10
10
  inspectSourceWorkspace,
11
11
  SourceWorkspaceError,
12
- type SourceWorkspace,
13
12
  } from "./source-workspace.js";
14
13
  import { publishSourceSnapshot } from "./source-publisher.js";
15
14
  import {
@@ -20,6 +19,9 @@ import {
20
19
  type LocalSourceMetadataDirectory,
21
20
  } from "./source-publication-store.js";
22
21
  import { readProjectLinks } from "./project-link-store.js";
22
+ import { DIRECT_OWNERSHIP, LoginGoneError, renewLogin } from "./credential-refresh.js";
23
+ import { LoginOwnershipTimeoutError } from "./login-ownership.js";
24
+ import { FileCredentialStoreRefusedError } from "./file-credential-store.js";
23
25
  import {
24
26
  parseProjectDatabaseWrite,
25
27
  assertProjectDatabaseWriteReceipt,
@@ -173,6 +175,9 @@ export interface TokenRevoker {
173
175
  revoke(refreshToken: string, signal: AbortSignal): Promise<void>;
174
176
  }
175
177
 
178
+ /** How the first-workspace request ended: made, refused for good, or not known to have ended. */
179
+ export type FirstWorkspaceOutcome = "created" | "refused" | "uncertain";
180
+
176
181
  export interface TokenRefresher {
177
182
  refresh(
178
183
  refreshToken: string,
@@ -265,7 +270,6 @@ export class PublicResponseTooLargeError extends Error {
265
270
  export interface ProductCliDependencies {
266
271
  readonly sourceDirectory?: string;
267
272
  readonly sourceMetadataDirectory?: LocalSourceMetadataDirectory;
268
- readonly sourceWorkspace?: () => Promise<SourceWorkspace>;
269
273
  readonly linkedSourceProvider?: "github" | "managed";
270
274
  readonly linkedProjectId?: string;
271
275
  readonly apiToken?: string;
@@ -294,6 +298,15 @@ export interface ProductCliDependencies {
294
298
  * keeping product mutation capabilities out of login.
295
299
  */
296
300
  readonly accountProfile: (accessToken: () => Promise<string>) => Promise<PublicAccount>;
301
+ /**
302
+ * The one request login may send: the first workspace of a verified account that has none. It is
303
+ * the portal's own request, so the portal and this login replay each other.
304
+ */
305
+ readonly firstWorkspace?: (
306
+ accessToken: () => Promise<string>,
307
+ userId: string,
308
+ signupSource: string | null,
309
+ ) => Promise<FirstWorkspaceOutcome>;
297
310
  /** Optional onboarding guidance uses only these narrow read-only SDK queries. */
298
311
  readonly githubConnectionStatus?: (
299
312
  accessToken: () => Promise<string>,
@@ -729,9 +742,29 @@ const retryAdvice = (command: string, keyed = true): string => {
729
742
  export const internalErrorAction = (command: string, keyed = true): string =>
730
743
  `The ohmyhost client stopped on an unexpected error; the stderr line starting with [ohmyhost: identifies it. Compare 'ohmyhost --version' with https://ohmyho.st/client-release.json and install the published client if it is older, then ${retryAdvice(command, keyed)}. If the current client fails the same way, report it with feedback submit (kind bug, error code internal_error) and quote that stderr line.`;
731
744
 
732
- /** The local credential store or saved-login index failed; a sandbox is the usual cause. */
733
- export const CREDENTIAL_STORE_UNAVAILABLE_ACTION =
734
- "This computer's credential store (for example macOS Keychain or Windows Credential Manager) or the saved-login list in ~/.ohmyhost/profiles could not be read or written; nothing was changed. If the agent runs in a sandbox, run the command with access to them before asking the customer to sign in again. If the store is locked, ask the customer to unlock it, then run the command again. On a server, container or CI runner without a credential store, do not run login: load OHMYHOST_TOKEN from a private env file with a token from the portal's API Tokens page.";
745
+ const FILE_STORE_REFUSAL: Readonly<Record<FileCredentialStoreRefusedError["reason"], string>> = {
746
+ symbolic_link: "it is a symbolic link",
747
+ another_owner: "it belongs to another user",
748
+ wrong_mode: "its mode is not allowed",
749
+ not_writable: "it could not be written",
750
+ };
751
+
752
+ /** One sentence that names the refused path and why, for a file store that cannot be used. */
753
+ export const describeFileStoreRefusal = (error: unknown): string | undefined =>
754
+ error instanceof FileCredentialStoreRefusedError
755
+ ? `The saved-login files at ~/${error.path} were refused (${FILE_STORE_REFUSAL[error.reason]}). Their directories must be yours with mode 700 and the ones above them neither symbolic links nor writable by others.`
756
+ : undefined;
757
+
758
+ /**
759
+ * The local credential store or the saved-login files failed. A login in a container is allowed:
760
+ * what remains are an agent sandbox without access to them, a locked desktop store and a refused
761
+ * file store.
762
+ */
763
+ export const credentialStoreUnavailableAction = (error?: unknown): string =>
764
+ `${
765
+ describeFileStoreRefusal(error) ??
766
+ "This computer's credential store (the macOS Keychain, the Windows Credential Manager) or the saved-login files in ~/.ohmyhost/profiles could not be read or written."
767
+ } Nothing was changed. If the agent runs in a sandbox, run the command with access to them before asking the customer to sign in again. If a desktop store is locked, ask the customer to unlock it. Then run the command again.`;
735
768
 
736
769
  const responseContractAction = (command: string, keyed = true): string =>
737
770
  `The ohmyho.st API answered in a form this client version does not accept, usually because the client is older than the service. Compare 'ohmyhost --version' with https://ohmyho.st/client-release.json; if it is older, install the published CLI and MCP and reload MCP. Then ${retryAdvice(command, keyed)}. If the current version answers this too, report it with feedback submit (kind bug, error code response_contract_invalid).`;
@@ -782,8 +815,13 @@ export const endedLoginAction = (
782
815
  export const refreshFailedAction = (
783
816
  commandPrefix: string,
784
817
  profile: LocalProfile | undefined,
818
+ record?: string,
785
819
  ): string =>
786
- `Renewing the saved login${profile === undefined ? "" : ` ${profile.name}`} at the sign-in service failed. Run the same command again in a minute, with the same --idempotency-key if it has one. If it fails again, run '${signInCommand(commandPrefix, profile)}' and send the customer the link and code.`;
820
+ `Renewing the saved login${profile === undefined ? "" : ` ${profile.name}`} at the sign-in service failed.${
821
+ record === undefined
822
+ ? ""
823
+ : ` Another process on this computer holds this login (record ${record}) and did not finish in time; nothing was sent to the sign-in service.`
824
+ } Run the same command again in a minute, with the same --idempotency-key if it has one. If it fails again, run '${signInCommand(commandPrefix, profile)}' and send the customer the link and code.`;
787
825
 
788
826
  /** The flags a failed login is repeated with; the boundary proof needs brace-free signatures. */
789
827
  interface LoginFlags {
@@ -1507,6 +1545,15 @@ export class ProductCli {
1507
1545
  false,
1508
1546
  profileLimitAction(this.dependencies.commandPrefix),
1509
1547
  );
1548
+ // Another process holds this login and did not finish in time: nothing was sent or removed.
1549
+ if (error instanceof LoginOwnershipTimeoutError)
1550
+ return failure(
1551
+ name,
1552
+ 5,
1553
+ "token_refresh_failed",
1554
+ true,
1555
+ refreshFailedAction(this.dependencies.commandPrefix, this.#profile, error.record),
1556
+ );
1510
1557
  this.recordDiagnostic(diagnosticDescriptor(error, signal));
1511
1558
  return classifyFailure(
1512
1559
  name,
@@ -1523,6 +1570,21 @@ export class ProductCli {
1523
1570
  return `Run '${this.dependencies.commandPrefix} github connect --organization ${organizationId} --idempotency-key KEY --json' once, then link repositories covered by the installation.`;
1524
1571
  }
1525
1572
 
1573
+ /**
1574
+ * The first deployment of a checkout that no project is saved for publishes the working
1575
+ * directory as it is, whether or not it has a GitHub remote and whether or not the workspace has
1576
+ * a GitHub installation; GitHub is the later step for deployment on every push.
1577
+ */
1578
+ private publishAction(organizationId: string, projectId: string | undefined): string {
1579
+ const prefix = this.dependencies.commandPrefix;
1580
+ const publish = `'${prefix} source publish --project ${projectId ?? "ULID"} --mode initialize --expected-source-generation 0 --message "Initial version" --idempotency-key KEY --wait --json'`;
1581
+ const first =
1582
+ projectId === undefined
1583
+ ? `This checkout has no saved project link here, which a new container never has even for an app that exists. First run '${prefix} project status --json' and '${prefix} project list --json' as the deploy Skill says, and create a project only if none of them is this app. Then publish this directory as it is, without GitHub: create the project with '${prefix} project create --organization ${organizationId} --name NAME --region eu --idempotency-key KEY --json' (EU or US is the customer's one answer), read its operation until it succeeds, then run ${publish}`
1584
+ : `This checkout is linked to project ${projectId}, which has no source yet. Publish this directory as it is, without GitHub: run ${publish}`;
1585
+ return `${first} and deploy the commit it returns; the deploy Skill lists every step. Deployment on every push is the later step: ${this.githubConnectAction(organizationId)}`;
1586
+ }
1587
+
1526
1588
  private async githubNextAction(
1527
1589
  api: Pick<ProductApi, "getGithubConnection"> & {
1528
1590
  readonly managedSource?: Pick<NonNullable<ProductApi["managedSource"]>, "getSource">;
@@ -1533,22 +1595,18 @@ export class ProductCli {
1533
1595
  // a scoped key cannot read source connections or the status endpoint is unavailable.
1534
1596
  try {
1535
1597
  let provider = this.dependencies.linkedSourceProvider;
1536
- if (this.dependencies.linkedProjectId !== undefined) {
1598
+ const linked = this.dependencies.linkedProjectId;
1599
+ if (linked !== undefined) {
1537
1600
  if (api.managedSource === undefined) return {};
1538
- const binding = await api.managedSource.getSource(this.dependencies.linkedProjectId);
1601
+ const binding = await api.managedSource.getSource(linked);
1539
1602
  if (binding !== null) parseProjectSourceBinding(binding);
1540
1603
  provider =
1541
1604
  binding === null ? undefined : (binding as { provider: "github" | "managed" }).provider;
1542
1605
  }
1543
1606
  if (provider === "managed") return {};
1544
- if (provider !== "github" && this.dependencies.sourceWorkspace !== undefined) {
1545
- const workspace = await this.dependencies.sourceWorkspace();
1546
- if (!workspace.git?.remotes.some((remote) => remote.githubRepository !== null))
1547
- return {
1548
- next_action:
1549
- "Ask once whether to deploy directly with ohmyho.st storing the versions or set up GitHub for this project. Inspect current source first; a missing GitHub connection does not require GitHub.",
1550
- };
1551
- }
1607
+ // A saved binding always wins: a project that uses GitHub goes on with GitHub. Anything else,
1608
+ // an unbound checkout or a linked project without a source, publishes the working directory.
1609
+ if (provider !== "github") return { next_action: this.publishAction(organizationId, linked) };
1552
1610
  const github = parseGithubOrganizationConnectionStatus(
1553
1611
  await api.getGithubConnection(organizationId),
1554
1612
  );
@@ -1612,9 +1670,18 @@ export class ProductCli {
1612
1670
  }
1613
1671
 
1614
1672
  /** The next step for a login that has no organization yet. */
1615
- private workspaceAction(selection: WorkspaceSelection): string {
1673
+ private workspaceAction(
1674
+ selection: WorkspaceSelection,
1675
+ unconfirmed?: { readonly userId: string; readonly signupSource: string | null },
1676
+ ): string {
1616
1677
  const prefix = this.dependencies.commandPrefix;
1617
1678
  const named = this.#profile === undefined ? "" : ` --profile-name ${this.#profile.name}`;
1679
+ // The first workspace may exist already: the identical request, as this caller, finds it or
1680
+ // makes it once, and it must not be answered with a second workspace.
1681
+ if (unconfirmed !== undefined && selection.outcome === "no_workspace")
1682
+ return `The first workspace was not confirmed. Run '${prefix} organization create --name "My workspace" --idempotency-key initial-workspace:${unconfirmed.userId}${
1683
+ unconfirmed.signupSource === null ? "" : ` --source ${unconfirmed.signupSource}`
1684
+ }${named} --json' to repeat the identical request: it returns the workspace or creates it once. Do not create another.`;
1618
1685
  return selection.outcome === "choice_required"
1619
1686
  ? `Ask the customer which workspace to use, then run '${prefix} organization use --organization ULID${named} --json'.`
1620
1687
  : `Run '${prefix} organization create --name NAME --idempotency-key KEY${named} --json' to create the first workspace.`;
@@ -1654,6 +1721,8 @@ export class ProductCli {
1654
1721
  const readIdentity = this.dependencies.currentIdentity;
1655
1722
  if (profiles === undefined || readIdentity === undefined)
1656
1723
  throw new ProviderCapabilityBlockedError();
1724
+ // The customer is asked to sign in only when the result can be saved.
1725
+ await profiles.prove();
1657
1726
  // A device code lives five minutes and the provider offers no way to lengthen it, so the
1658
1727
  // sign-in outlives the code instead: while this window lasts, a lapsed code is replaced.
1659
1728
  const signInDeadline = this.dependencies.now().getTime() + SIGN_IN_WINDOW_MS;
@@ -1729,7 +1798,7 @@ export class ProductCli {
1729
1798
  refreshToken: result.tokens.refreshToken,
1730
1799
  expiresAt,
1731
1800
  };
1732
- const account = await this.dependencies.accountProfile(async () => signedIn.accessToken);
1801
+ let account = await this.dependencies.accountProfile(async () => signedIn.accessToken);
1733
1802
  // A failed verification repeats this login with the flags it was given.
1734
1803
  const loginFlags = {
1735
1804
  organizationId,
@@ -1744,6 +1813,30 @@ export class ProductCli {
1744
1813
  false,
1745
1814
  `The browser signed in as user ${account.userId}, not ${expectedUserId}. Nothing was saved and every saved login is unchanged. Sign out of ohmyho.st in that browser or use the browser profile of ${expectedUserId}, then run '${this.dependencies.commandPrefix} login${organizationId === undefined ? "" : ` --organization ${organizationId}`} --user ${expectedUserId} --json' again.`,
1746
1815
  );
1816
+ // A verified account without a workspace gets its first one; whatever the answer, the account
1817
+ // is read again and decides, so a workspace that exists is found whoever created it.
1818
+ let creation: FirstWorkspaceOutcome | undefined;
1819
+ if (
1820
+ this.dependencies.firstWorkspace !== undefined &&
1821
+ organizationId === undefined &&
1822
+ account.emailVerified &&
1823
+ account.organizations.length === 0
1824
+ ) {
1825
+ creation = await this.dependencies.firstWorkspace(
1826
+ async () => signedIn.accessToken,
1827
+ account.userId,
1828
+ account.signupSource,
1829
+ );
1830
+ try {
1831
+ account = await this.dependencies.accountProfile(async () => signedIn.accessToken);
1832
+ } catch (error) {
1833
+ // The customer approved a code for this sign-in: a failed second read does not undo it.
1834
+ // The creation is then unconfirmed, and the repeat command finds out.
1835
+ throwIfAborted(signal);
1836
+ if (creation === "refused") throw error;
1837
+ creation = "uncertain";
1838
+ }
1839
+ }
1747
1840
  const selection = chooseWorkspace(account.organizations, organizationId);
1748
1841
  if (selection.outcome === "not_a_member") throw this.unknownWorkspace(selection);
1749
1842
  // The workspace lives in the access token, so a chosen one is requested before storing.
@@ -1811,6 +1904,7 @@ export class ProductCli {
1811
1904
  if (organization !== null)
1812
1905
  return success("login", {
1813
1906
  status: "authenticated",
1907
+ credential_store: profiles.kind,
1814
1908
  organization: publicWorkspace(organization),
1815
1909
  profile: publicProfile(profile),
1816
1910
  ...(readGithubConnection === undefined
@@ -1839,13 +1933,19 @@ export class ProductCli {
1839
1933
  });
1840
1934
  return success("login", {
1841
1935
  status: "authenticated",
1936
+ credential_store: profiles.kind,
1842
1937
  organization: null,
1843
1938
  profile: publicProfile(profile),
1844
1939
  organizations:
1845
1940
  selection.outcome === "choice_required"
1846
1941
  ? selection.organizations.map(publicWorkspace)
1847
1942
  : [],
1848
- next_action: this.workspaceAction(selection),
1943
+ next_action: this.workspaceAction(
1944
+ selection,
1945
+ creation === "uncertain" || creation === "created"
1946
+ ? { userId: account.userId, signupSource: account.signupSource }
1947
+ : undefined,
1948
+ ),
1849
1949
  });
1850
1950
  }
1851
1951
  }
@@ -1878,22 +1978,29 @@ export class ProductCli {
1878
1978
  throw new InteractiveSessionRequiredError();
1879
1979
  let bound: LocalProfile;
1880
1980
  try {
1881
- bound = await runBounded(
1882
- (bounded) =>
1883
- selectWorkspace(
1884
- {
1885
- store: profiles.credential(profile),
1886
- refresher: this.dependencies.tokenRefresher,
1887
- profiles,
1888
- profile,
1889
- },
1890
- organization,
1891
- bounded,
1892
- (accessToken) =>
1893
- this.dependencies.productApi(async () => accessToken).getCurrentIdentity(),
1981
+ // Ownership is taken before the bounded refresh starts, so waiting for another process cannot
1982
+ // use up the time the provider needs after it has rotated the refresh token.
1983
+ bound = await profiles.owning(
1984
+ [profile, { ...profile, organizationId: organization.id }],
1985
+ () =>
1986
+ runBounded(
1987
+ (bounded) =>
1988
+ selectWorkspace(
1989
+ {
1990
+ store: profiles.credential(profile),
1991
+ refresher: this.dependencies.tokenRefresher,
1992
+ profiles,
1993
+ profile,
1994
+ },
1995
+ organization,
1996
+ bounded,
1997
+ (accessToken) =>
1998
+ this.dependencies.productApi(async () => accessToken).getCurrentIdentity(),
1999
+ ),
2000
+ signal,
2001
+ this.dependencies.lifecycleTimeoutMs,
1894
2002
  ),
1895
2003
  signal,
1896
- this.dependencies.lifecycleTimeoutMs,
1897
2004
  );
1898
2005
  } catch (error) {
1899
2006
  if (error instanceof AccountVerificationError)
@@ -3425,44 +3532,58 @@ export class ProductCli {
3425
3532
  if (stored === undefined) {
3426
3533
  throw new ProductCliFailure(5, "authentication_required", false, this.loginAction());
3427
3534
  }
3428
- let refresh: { readonly credential: CurrentCredential; readonly refreshed: boolean };
3535
+ if (this.credentialUsable(stored)) return stored.accessToken;
3536
+ // The refresh token is spent at the provider before anything is written, so this process owns
3537
+ // the login first and reads its credential again as the owner.
3538
+ const profiles = this.dependencies.profiles;
3429
3539
  try {
3430
- refresh = await this.refreshIfExpired(stored, signal);
3540
+ const renewal = await renewLogin({
3541
+ // A shared file store reads the credential again as the owner; a native store need not.
3542
+ ...(profiles?.kind === "file" ? {} : { current: stored }),
3543
+ registry:
3544
+ profiles !== undefined && this.#profile !== undefined ? profiles : DIRECT_OWNERSHIP,
3545
+ login: this.#profile ?? "legacy",
3546
+ store,
3547
+ usable: (credential) => this.credentialUsable(credential),
3548
+ renew: (credential) => this.renewCredential(credential, signal),
3549
+ rejected: (error) => error instanceof TokenRefreshRejectedError,
3550
+ forget: () => this.forgetLogin(store),
3551
+ signal,
3552
+ });
3553
+ return renewal.credential.accessToken;
3431
3554
  } catch (error) {
3555
+ if (error instanceof LoginGoneError)
3556
+ throw new ProductCliFailure(5, "authentication_required", false, this.loginAction());
3557
+ if (error instanceof LoginOwnershipTimeoutError)
3558
+ throw new ProductCliFailure(
3559
+ 5,
3560
+ "token_refresh_failed",
3561
+ true,
3562
+ refreshFailedAction(this.dependencies.commandPrefix, this.#profile, error.record),
3563
+ );
3432
3564
  if (!(error instanceof TokenRefreshRejectedError)) throw error;
3433
- // The provider ended this login; only this saved login is removed.
3434
- const ended = this.#profile;
3435
- await this.forgetLogin(store);
3565
+ // The provider ended this login; only this saved login was removed.
3436
3566
  throw new ProductCliFailure(
3437
3567
  5,
3438
3568
  "authentication_required",
3439
3569
  false,
3440
- endedLoginAction(this.dependencies.commandPrefix, ended),
3570
+ endedLoginAction(this.dependencies.commandPrefix, this.#profile),
3441
3571
  );
3442
3572
  }
3443
- if (refresh.refreshed) await store.replace(refresh.credential);
3444
- return refresh.credential.accessToken;
3445
3573
  }
3446
3574
 
3447
- private async refreshIfExpired(
3448
- credential: StoredCredential,
3449
- signal: AbortSignal,
3450
- ): Promise<{ readonly credential: CurrentCredential; readonly refreshed: boolean }> {
3575
+ private credentialUsable(credential: StoredCredential): boolean {
3451
3576
  const expiresAt = credential.expiresAt === undefined ? NaN : Date.parse(credential.expiresAt);
3452
- if (
3577
+ return (
3453
3578
  Number.isFinite(expiresAt) &&
3454
3579
  expiresAt > this.dependencies.now().getTime() + this.dependencies.lifecycleTimeoutMs
3455
- ) {
3456
- return {
3457
- credential: {
3458
- accessToken: credential.accessToken,
3459
- refreshToken: credential.refreshToken,
3460
- expiresAt: credential.expiresAt as string,
3461
- ...workspaceOf(credential),
3462
- },
3463
- refreshed: false,
3464
- };
3465
- }
3580
+ );
3581
+ }
3582
+
3583
+ private async renewCredential(
3584
+ credential: StoredCredential,
3585
+ signal: AbortSignal,
3586
+ ): Promise<CurrentCredential> {
3466
3587
  try {
3467
3588
  const refreshed = await runBounded(
3468
3589
  (bounded) =>
@@ -3482,8 +3603,7 @@ export class ProductCli {
3482
3603
  throw new Error("invalid refreshed expiry");
3483
3604
  }
3484
3605
  // WorkOS returns a bare credential; the selection only survives if we carry it forward.
3485
- // WorkOS returns a bare credential; the selection only survives if we carry it forward.
3486
- return { credential: { ...refreshed, ...workspaceOf(credential) }, refreshed: true };
3606
+ return { ...refreshed, ...workspaceOf(credential) };
3487
3607
  } catch (error) {
3488
3608
  if (isCancellation(error) && signal.aborted) throw error;
3489
3609
  if (error instanceof ProviderCapabilityBlockedError) {
@@ -3661,7 +3781,7 @@ const classifyFailure = (
3661
3781
  3,
3662
3782
  "credential_store_unavailable",
3663
3783
  false,
3664
- CREDENTIAL_STORE_UNAVAILABLE_ACTION,
3784
+ credentialStoreUnavailableAction(error),
3665
3785
  );
3666
3786
  }
3667
3787
  if (error instanceof ResponseContractError) {