From 7acc81817a4095b9e28c74a0091a4bbc23556a08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Tue, 13 Oct 2026 21:15:52 +0200 Subject: [PATCH 1/9] Vault: each Environment owns its vault in its network's Vaultwarden MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root decision 0198 (DEV-6631 task 638a, contract C3): the Environment's technical account, which the handover's new `vault` member names (contract C2), registers itself, creates the Environment's own organization with POST /api/organizations (the organization key RSA-OAEP-encrypted to the account's own public key, the organization key pair, the billing e-mail, the handover's name and a first collection "Agenti"), remembers it by ID and renames it when the handover's name changes. The account and the vault come from the handover only; the guessed vaultwarden@
account, the vault derived from Headscale and every collection-name match are gone. State is keyed by the account, so a 0197 pilot's directory stays readable beside it. The Admin-approval and fingerprint-confirmation flow, its states, the four-step dialog and the disconnect are removed. `lazurio vault setup` replaces `connect`; the Launchpad runs the same setup at its start where the vault needs it (the Executor pattern). The Tools row shows the state, "Otevřít trezor" and one action only where a setup can move the vault on. Environments connected the 0197 way keep working read only through the frozen subset in src/vault/legacy-0197/ (status, the shared session and F46 from the recorded collection) until their handover names a vault and task 649 moves their items. F46 reads the own vault: the one item named exactly like the secret anywhere in it; a work Environment serves its Organization's apps, a personal one the Personalspace's. Work in progress: the tests and the docs follow in the next commits. Co-Authored-By: Claude Opus 5.5 --- src/cli.ts | 11 +- src/launchpad/catalog-view.ts | 1 + src/launchpad/index.html | 25 +- src/launchpad/messages.ts | 187 +-- src/launchpad/server.ts | 31 +- src/launchpad/tools-panel.ts | 37 +- src/launchpad/vault-panel.ts | 623 ++------- src/launchpad/vault-routes.ts | 167 ++- src/launchpad/vault-view.ts | 374 ++---- src/machine/context.ts | 13 + src/machine/lazurio-machine.v1.schema.json | 13 + src/modules/module-cli.ts | 23 +- src/modules/runtime-secrets.ts | 94 +- src/organizations/catalog.ts | 19 +- src/recover/private-values.ts | 8 +- src/recover/sanitize.ts | 6 + src/tools/catalog.ts | 33 +- src/tools/cli.ts | 4 +- src/tools/curated-cli.ts | 8 +- src/update/cli.ts | 6 + src/vault/bw.ts | 51 +- src/vault/cli.ts | 164 +-- src/vault/context.ts | 207 +-- src/vault/flow.ts | 1366 +++++++------------- src/vault/host.ts | 51 +- src/vault/legacy-0197/README.md | 36 + src/vault/legacy-0197/context.ts | 92 ++ src/vault/legacy-0197/pilot.ts | 319 +++++ src/vault/organization.ts | 252 ++++ src/vault/register.ts | 255 +++- src/vault/session.ts | 233 ++++ src/vault/status.ts | 206 +++ src/vault/store.ts | 135 +- 33 files changed, 2601 insertions(+), 2449 deletions(-) create mode 100644 src/vault/legacy-0197/README.md create mode 100644 src/vault/legacy-0197/context.ts create mode 100644 src/vault/legacy-0197/pilot.ts create mode 100644 src/vault/organization.ts create mode 100644 src/vault/session.ts create mode 100644 src/vault/status.ts diff --git a/src/cli.ts b/src/cli.ts index b82a94cba..df8750c4e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -101,6 +101,7 @@ import { selfCheckCommand, updateEnvironment, updateHelp, + vaultAtStart, versionCommand, } from "./update/cli"; import { selectActivator } from "./update/launchpad-activation"; @@ -117,7 +118,8 @@ function emit(output: CommandOutput): number { // The installed Launchpad of this base answers the updater's health question // and serves the update pill on the same update core and service the CLI uses. // Where install and update only report Executor, it sets Executor up after -// it starts (decision F44, addendum of 2026-10-11). +// it starts (decision F44, addendum of 2026-10-11), and the Environment's own +// vault where it needs it (decision F52). async function installedLaunchpad(explicitBase: string, folder: string) { const context = processContext(); const base = installBase(context, explicitBase); @@ -135,6 +137,7 @@ async function installedLaunchpad(explicitBase: string, folder: string) { }), }), executorAtStart: executorAtStart(context, base), + vaultAtStart: vaultAtStart(context, base), }; } @@ -314,9 +317,9 @@ async function runOtherCommand(args: string[]): Promise { // its view. if (args[0] === "browser") return emit(await runBrowserCommand(args.slice(1), processContext())); - // The Environment vault (decision F43): `vault env` prints the shell - // exports alone on stdout, for `eval "$(lazurio vault env)"`; connect's - // steps and every refusal go to stderr. + // The Environment's vault (decisions F43, F52): `vault env` prints the + // shell exports alone on stdout, for `eval "$(lazurio vault env)"`; + // setup's steps and every refusal go to stderr. if (args[0] === "vault") return emit( await runVaultCommand(args.slice(1), { diff --git a/src/launchpad/catalog-view.ts b/src/launchpad/catalog-view.ts index 566c75530..cda9d083a 100644 --- a/src/launchpad/catalog-view.ts +++ b/src/launchpad/catalog-view.ts @@ -76,6 +76,7 @@ const reasonKeys: Readonly< const secretReasonKeys: Readonly> = { personalspace: "runtimeSecretPersonalspace", + "personal-environment": "runtimeSecretPersonalEnvironment", workstation: "runtimeSecretWorkstation", "no-vault-identity": "runtimeSecretNoVaultIdentity", "other-organization": "runtimeSecretOtherOrganization", diff --git a/src/launchpad/index.html b/src/launchpad/index.html index 73d5a5a4a..a727f1938 100644 --- a/src/launchpad/index.html +++ b/src/launchpad/index.html @@ -479,28 +479,10 @@ the four steps of its dialog, the collection and the account address on one quiet card, each value on one line with a quiet copy button, and the fingerprint phrase. */ -.vault-steps { display: grid; gap: 0.25rem; margin: 0; padding: 0; list-style: none; } -.vault-step { display: grid; grid-template-columns: 1.5rem minmax(0, 1fr); gap: 0.75rem; padding: 0.5rem 0; } -.vault-mark { display: grid; width: 1.5rem; height: 1.5rem; place-items: center; border: 1px solid var(--lz-line); border-radius: 50%; color: var(--muted-fg); font-size: 12px; font-weight: var(--lz-weight-akce); } -.vault-mark .icon { width: 13px; height: 13px; } -.vault-step[data-mark="current"] .vault-mark { border-color: var(--fg); color: var(--fg); } -.vault-step[data-mark="done"] .vault-mark { border-color: transparent; background: var(--success-bg); color: var(--success-fg); } -.vault-step-body { display: grid; gap: 0.6rem; min-width: 0; } -.vault-step-title { min-height: 1.5rem; display: flex; align-items: center; font-size: 15px; font-weight: var(--lz-weight-akce); } -.vault-step[data-mark="next"] .vault-step-title { color: var(--muted-fg); } -.vault-card { display: grid; gap: 0.6rem; padding: 0.75rem; border: 1px solid var(--lz-line-faint); border-radius: var(--radius-control); background: var(--muted); } -.vault-value { display: flex; align-items: center; gap: 0.5rem; min-width: 0; } -.vault-value-text { display: grid; gap: 2px; flex: 1; min-width: 0; } -.vault-value-label { color: var(--muted-fg); font-size: 12px; } -.vault-value-code { overflow: hidden; color: var(--fg); font: 13px/1.4 var(--font-mono); text-overflow: ellipsis; white-space: nowrap; } -button.vault-copy { flex: none; width: 30px; padding: 0; } -.vault-phrase { display: block; padding: 0.6rem 0.75rem; border: 1px solid var(--lz-line-faint); border-radius: var(--radius-control); background: var(--muted); font: 600 15px/1.4 var(--font-mono); overflow-wrap: anywhere; user-select: all; } -.vault-failure { color: var(--destructive); font-size: 13.5px; font-weight: var(--lz-weight-akce); } -.vault-waiting { color: var(--muted-fg); font-size: 13px; } .vault-list { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 0.25rem 0.75rem; margin: 0; font-size: 13px; } .vault-list dt { color: var(--muted-fg); } .vault-list dd { margin: 0; overflow-wrap: anywhere; } -.vault-facts a.button .icon, #tools-vault a.button .icon { width: 14px; height: 14px; } +.vault-facts a.button .icon, .row-control a.button .icon { width: 14px; height: 14px; } /* Files (decision F35): the Documents folder as a list of rows, the path as links, the upload queue and the drop overlay. Below 36 rem of the list's @@ -1228,11 +1210,6 @@

- -

-
-
-
diff --git a/src/launchpad/messages.ts b/src/launchpad/messages.ts index 5aa4b8294..fa651cfa3 100644 --- a/src/launchpad/messages.ts +++ b/src/launchpad/messages.ts @@ -655,23 +655,26 @@ const en = { moduleReasonRequiredSlotMissing: "The app requires {file}, which is not in this Environment beside it, so it was not started. Synchronize the Organization, or ask for access to that module, and start again.", moduleReasonRuntimeSecretUnavailable: - "The app was not started: it needs secrets that this Environment's vault did not give it. {secrets}. Values are never shown; add or fix the item named exactly like the secret in the Environment's collection and start again.", + "The app was not started: it needs secrets that this Environment's vault did not give it. {secrets}. Values are never shown; add or fix the item named exactly like the secret in the Environment's vault and start again.", moduleSecretsNotProvided: "Started without these optional secrets, so the capabilities that need them are off: {secrets}.", - runtimeSecretPersonalspace: "a Personalspace module has no vault yet", + runtimeSecretPersonalspace: + "a Personalspace app reads secrets only in its person's personal Environment", + runtimeSecretPersonalEnvironment: + "the vault of a personal Environment serves only Personalspace apps", runtimeSecretWorkstation: "this computer has no Environment vault yet", - runtimeSecretNoVaultIdentity: "this Environment has no vault account", + runtimeSecretNoVaultIdentity: "this Environment has no vault yet", runtimeSecretOtherOrganization: "the app belongs to another Organization than the one that owns this Environment and its vault", runtimeSecretNotConnected: - "the vault is not connected (Settings → Tools → bitwarden)", + "the vault is not set up yet (Settings → Tools → bitwarden)", runtimeSecretLocked: "the vault could not be unlocked", runtimeSecretBusy: "the vault is busy; try again", runtimeSecretUnreachable: "the vault cannot be reached", runtimeSecretVaultFailed: "the vault did not answer as expected", - runtimeSecretMissing: "no item of this name in the Environment's collection", + runtimeSecretMissing: "no item of this name in the Environment's vault", runtimeSecretAmbiguous: - "more than one item of this name in the Environment's collection", + "more than one item of this name in the Environment's vault", runtimeSecretEmpty: "its item has no password", moduleApplication: "Application", moduleStart: "Start", @@ -976,83 +979,29 @@ const en = { "The connection to Google: Gmail, Calendar and Drive, when you do not want Composio.", toolsDescriptionNeon: "The connection to Neon databases, mainly for developing apps.", - toolsDescriptionBitwarden: - "Passwords and access you share with this Environment in your Vaultwarden vault.", + toolsDescriptionBitwarden: "Passwords and other items for agents.", toolsDescriptionExecutor: "Agents use the apps connected directly from this Environment through it. Lazurio installs it and keeps it running.", toolsNotOffered: "Not offered in this Environment; agents do not use it.", vaultRowChecking: "Checking…", - vaultRowNone: "Not connected", - vaultRowConfirming: "Waiting for the confirmation in the vault", - vaultRowCollection: "Confirmed, waiting for the collection", vaultRowConnected: "Connected", + vaultRowNotSetUp: "Not set up yet", + vaultRowNotAllowed: "The network has not allowed its account yet", + vaultRowRemoved: "The vault was removed", vaultRowRevoked: "Access removed in the vault", vaultRowUnreachable: "The vault does not answer", + vaultRowFailed: "The setup did not finish", + vaultRowNoVault: "This Environment has no vault yet", vaultRowSecondWave: "Soon · second wave", vaultRowUnavailable: "Not available in this Environment", - vaultActionConnect: "Connect", - vaultActionContinue: "Continue", - vaultActionReconnect: "Connect again", + vaultPhaseInstall: "Installing Bitwarden…", + vaultPhaseAccount: "Preparing the vault's account…", + vaultPhaseVault: "Preparing the vault…", + vaultPhaseSignIn: "Signing in…", + vaultActionSetUp: "Set up", vaultActionRetry: "Try again", - vaultActionDisconnect: "Disconnect", vaultActionNamed: "{action}: bitwarden", - vaultOpen: "Open Vaultwarden", - vaultSync: "Synchronize", - vaultTitle: "Connect Bitwarden", - vaultStepInvite: "Invite the account in the vault", - vaultStepConnect: "The Environment connects", - vaultStepConfirm: "Confirm the account in the vault", - vaultStepCollection: "Share the collection with the account", - vaultStepDone: "Connected", - vaultInviteText: - "Create a collection, named as you like (this name, for instance), and invite this address into it with edit rights.", - vaultInviteAgainText: - "Invite this address into the collection again with edit rights.", - vaultAdminHint: - "Only an Admin or Owner of the vault's organization can invite and confirm.", - vaultTeamHint: "The whole Team sees the collection.", - vaultCollectionLabel: "Collection", - vaultAccountLabel: "Account address", - vaultCopy: "Copy", - vaultCopyNamed: "Copy: {label}", - vaultCopied: "Copied", - vaultInvited: "Invited", - vaultNotInvited: "The address is not invited in the vault yet.", - vaultRevokedConnect: - "The account does not see the collection it was connected to. Invite it into that collection again, or disconnect the Environment and connect it to another one.", - vaultUnreachableLine: "The vault does not answer.", - vaultPhaseInstall: "Installing Bitwarden", - vaultPhaseAccount: "Creating the account", - vaultPhaseSignIn: "Signing in", - vaultPasswordHint: "Only this Environment knows the account's password.", - vaultConfirmText: "Confirm the new member in the vault.", - vaultFingerprintHint: "The fingerprint in the vault must be the same:", - vaultWaiting: "Waiting for the confirmation…", - vaultCollectionText: - "Confirmed. Now share this Environment's collection with the account in the vault, with edit rights.", - vaultCollectionHint: - "If the account sees several collections, it recognizes its own by this name.", - vaultWaitingCollection: "Waiting for the collection…", - vaultSees: "It sees {seen}.", - vaultFailed: "Connecting did not finish ({stage}: {reason}).", - vaultDisconnectTitle: "Disconnect Bitwarden", - vaultDisconnectText: - "Agents here stop using the vault. You end the access completely by removing the account in the vault.", - vaultDisconnected: - "Disconnected. The account stays in the vault; Connect signs it in again.", - vaultCancel: "Cancel", - vaultDetails: "Vault", - vaultDetailAccount: "Account", - vaultDetailVault: "Vault", - vaultDetailOrganization: "Organization", - vaultDetailCollection: "Collection", - vaultDetailFingerprint: "Fingerprint", - vaultCollectionsOne: "{count} collection", - vaultCollectionsFew: "{count} collections", - vaultCollectionsMany: "{count} collections", - vaultItemsOne: "{count} item", - vaultItemsFew: "{count} items", - vaultItemsMany: "{count} items", + vaultOpen: "Open the vault", vaultLoadFailed: "The vault's state could not be read.", executorRowChecking: "Checking…", executorRowRunning: "Running", @@ -2083,22 +2032,25 @@ const cs: Record = { moduleReasonRequiredSlotMissing: "Aplikace potřebuje {file}, který na tomto Environmentu vedle ní není, proto nebyla spuštěna. Synchronizujte Organizaci nebo si požádejte o přístup k tomu modulu a spusťte ji znovu.", moduleReasonRuntimeSecretUnavailable: - "Aplikace nebyla spuštěna: potřebuje tajné údaje, které jí trezor tohoto Environmentu nedal. {secrets}. Hodnoty se nikdy nezobrazují; v kolekci Environmentu přidejte nebo opravte položku pojmenovanou přesně jako ten údaj a spusťte ji znovu.", + "Aplikace nebyla spuštěna: potřebuje tajné údaje, které jí trezor tohoto Environmentu nedal. {secrets}. Hodnoty se nikdy nezobrazují; v trezoru Environmentu přidejte nebo opravte položku pojmenovanou přesně jako ten údaj a spusťte ji znovu.", moduleSecretsNotProvided: "Spuštěno bez těchto volitelných tajných údajů, takže schopnosti, které je potřebují, jsou vypnuté: {secrets}.", - runtimeSecretPersonalspace: "modul Personalspace zatím trezor nemá", + runtimeSecretPersonalspace: + "aplikace z Personalspace čte tajné údaje jen v osobním Environmentu svého člověka", + runtimeSecretPersonalEnvironment: + "trezor osobního Environmentu slouží jen aplikacím z Personalspace", runtimeSecretWorkstation: "tento počítač zatím trezor Environmentu nemá", - runtimeSecretNoVaultIdentity: "tento Environment nemá účet v trezoru", + runtimeSecretNoVaultIdentity: "tento Environment zatím trezor nemá", runtimeSecretOtherOrganization: "aplikace patří jiné Organizaci, než která vlastní tento Environment a jeho trezor", runtimeSecretNotConnected: - "trezor není připojený (Nastavení → Nástroje → bitwarden)", + "trezor ještě není nastavený (Nastavení → Nástroje → bitwarden)", runtimeSecretLocked: "trezor se nepodařilo odemknout", runtimeSecretBusy: "trezor je právě zaneprázdněný; zkuste to znovu", runtimeSecretUnreachable: "trezor není dostupný", runtimeSecretVaultFailed: "trezor neodpověděl tak, jak má", - runtimeSecretMissing: "v kolekci Environmentu není položka tohoto názvu", - runtimeSecretAmbiguous: "v kolekci Environmentu je víc položek tohoto názvu", + runtimeSecretMissing: "v trezoru Environmentu není položka tohoto názvu", + runtimeSecretAmbiguous: "v trezoru Environmentu je víc položek tohoto názvu", runtimeSecretEmpty: "jeho položka nemá heslo", moduleApplication: "Aplikace", moduleStart: "Spustit", @@ -2402,82 +2354,29 @@ const cs: Record = { "Připojení na Google: Gmail, Kalendář a Disk, když nechcete Composio.", toolsDescriptionNeon: "Připojení na databáze Neon, hlavně pro vývoj aplikací.", - toolsDescriptionBitwarden: - "Hesla a přístupy, které Environmentu nasdílíte ve svém trezoru Vaultwarden.", + toolsDescriptionBitwarden: "Hesla a další položky pro agenty.", toolsDescriptionExecutor: "Přes něj agenti používají aplikace připojené přímo z tohoto Environmentu. Instaluje ho a udržuje v chodu Lazurio.", toolsNotOffered: "V tomhle Environmentu se nenabízí; agenti ho nepoužívají.", vaultRowChecking: "Zjišťuji stav…", - vaultRowNone: "Nepřipojeno", - vaultRowConfirming: "Čeká na potvrzení v trezoru", - vaultRowCollection: "Potvrzeno, čeká na kolekci", vaultRowConnected: "Připojeno", + vaultRowNotSetUp: "Zatím nenastaveno", + vaultRowNotAllowed: "Síť zatím účet trezoru nepovolila", + vaultRowRemoved: "Trezor byl odebrán", vaultRowRevoked: "Přístup odebrán v trezoru", vaultRowUnreachable: "Trezor neodpovídá", + vaultRowFailed: "Nastavení se nedokončilo", + vaultRowNoVault: "Tento Environment zatím trezor nemá", vaultRowSecondWave: "Brzy · druhá vlna", - vaultRowUnavailable: "V tomhle Environmentu není k dispozici", - vaultActionConnect: "Připojit", - vaultActionContinue: "Pokračovat", - vaultActionReconnect: "Připojit znovu", + vaultRowUnavailable: "V tomto Environmentu není k dispozici", + vaultPhaseInstall: "Instaluje se Bitwarden…", + vaultPhaseAccount: "Připravuje se účet trezoru…", + vaultPhaseVault: "Připravuje se trezor…", + vaultPhaseSignIn: "Přihlašuje se…", + vaultActionSetUp: "Nastavit", vaultActionRetry: "Zkusit znovu", - vaultActionDisconnect: "Odpojit", vaultActionNamed: "{action}: bitwarden", - vaultOpen: "Otevřít Vaultwarden", - vaultSync: "Synchronizovat", - vaultTitle: "Připojit Bitwarden", - vaultStepInvite: "Pozvěte účet v trezoru", - vaultStepConnect: "Environment se připojí", - vaultStepConfirm: "Potvrďte účet v trezoru", - vaultStepCollection: "Nasdílejte účtu kolekci", - vaultStepDone: "Připojeno", - vaultInviteText: - "Založte kolekci, pojmenujte ji, jak chcete (třeba takhle), a pozvěte do ní tuhle adresu s právem úprav.", - vaultInviteAgainText: "Pozvěte tuhle adresu znovu do kolekce s právem úprav.", - vaultAdminHint: - "Pozvat a potvrdit může Admin nebo Owner organizace v trezoru.", - vaultTeamHint: "Kolekci uvidí celý Team.", - vaultCollectionLabel: "Kolekce", - vaultAccountLabel: "Adresa účtu", - vaultCopy: "Kopírovat", - vaultCopyNamed: "Kopírovat: {label}", - vaultCopied: "Zkopírováno", - vaultInvited: "Pozváno", - vaultNotInvited: "Adresa ještě není v trezoru pozvaná.", - vaultRevokedConnect: - "Účet nevidí kolekci, ke které byl připojený. Pozvěte ho do ní znovu, nebo Environment odpojte a připojte ho k jiné kolekci.", - vaultUnreachableLine: "Trezor neodpovídá.", - vaultPhaseInstall: "Instaluji Bitwarden", - vaultPhaseAccount: "Zakládám účet", - vaultPhaseSignIn: "Přihlašuji", - vaultPasswordHint: "Heslo účtu zná jen tento Environment.", - vaultConfirmText: "Potvrďte v trezoru nového člena.", - vaultFingerprintHint: "Otisk v trezoru musí být stejný:", - vaultWaiting: "Čekám na potvrzení…", - vaultCollectionText: - "Potvrzeno. Ještě účtu v trezoru nasdílejte kolekci tohoto Environmentu s právem úprav.", - vaultCollectionHint: - "Vidí-li účet víc kolekcí, pozná tu svou podle tohohle názvu.", - vaultWaitingCollection: "Čekám na kolekci…", - vaultSees: "Vidí {seen}.", - vaultFailed: "Připojení se nedokončilo ({stage}: {reason}).", - vaultDisconnectTitle: "Odpojit Bitwarden", - vaultDisconnectText: - "Agenti tu přestanou trezor používat. Přístup úplně ukončíte odebráním účtu v trezoru.", - vaultDisconnected: - "Odpojeno. Účet v trezoru zůstává; Připojit ho přihlásí znovu.", - vaultCancel: "Zrušit", - vaultDetails: "Trezor", - vaultDetailAccount: "Účet", - vaultDetailVault: "Trezor", - vaultDetailOrganization: "Organizace", - vaultDetailCollection: "Kolekce", - vaultDetailFingerprint: "Otisk", - vaultCollectionsOne: "{count} kolekce", - vaultCollectionsFew: "{count} kolekce", - vaultCollectionsMany: "{count} kolekcí", - vaultItemsOne: "{count} položka", - vaultItemsFew: "{count} položky", - vaultItemsMany: "{count} položek", + vaultOpen: "Otevřít trezor", vaultLoadFailed: "Stav trezoru se nepodařilo přečíst.", executorRowChecking: "Zjišťuji stav…", executorRowRunning: "Běží", diff --git a/src/launchpad/server.ts b/src/launchpad/server.ts index 80532991c..738c90d74 100644 --- a/src/launchpad/server.ts +++ b/src/launchpad/server.ts @@ -402,6 +402,10 @@ export async function startLaunchpad( * it, a supervised base for the hosted operator (`executorAtStart`). * Absent: it never does. */ executorAtStart?: (() => Promise) | undefined; + /** Whether this Launchpad sets the Environment's own vault up after it + * starts (decision F52): the same rule as Executor's + * (`vaultAtStart`). Absent: it never does. */ + vaultAtStart?: (() => Promise) | undefined; }>, hostedOptions: HostedOptions = {}, // Where the tools screen reads its live facts: this process's PATH and @@ -446,9 +450,9 @@ export async function startLaunchpad( openWindow: (session: string) => ensureThreadWindow(session, undefined, cdpSeams(process.env, runProcess)), }), - // Where the Environment vault runs (decision F43): this process's home and - // the handover, for the Folder this Launchpad serves. Trusted composition, - // never HTTP input; tests supply a fake vault and a fake bw. + // Where the Environment's vault runs (decisions F43, F52): this process's + // home and the handover, for the Folder this Launchpad serves. Trusted + // composition, never HTTP input; tests supply a fake vault and a fake bw. vaultHost?: VaultHost | undefined, // Where Executor is set up (decision F44): this process's home, user // manager and harnesses, for the handover's declared operator. Trusted @@ -554,8 +558,8 @@ export async function startLaunchpad( }; // The Files page (decision F35): the Operator's Documents folder. const files = createFilesRoutes({ host: documentsHost, headers }); - // The Environment vault (decision F43): its routes journal the operation, - // the outcome and a fixed reason, never a value. + // The Environment's vault (decisions F43, F52): its routes journal the + // operation, the outcome and a fixed reason, never a value. const vaultJournal = (entry: object) => console.log(JSON.stringify({ scope: "tools-vault", ...entry })); const defaultVault = @@ -573,6 +577,8 @@ export async function startLaunchpad( vaultHost === undefined ? (defaultVault as VaultHost) : { ...vaultHost, journal: vaultHost.journal ?? vaultJournal }, + // A closing Launchpad starts no setup (`start` asks it last). + closing: () => closing, }); // Executor (decision F44): its setup journals the outcome and a fixed // reason, never a path, an output or a value. @@ -1506,11 +1512,11 @@ export async function startLaunchpad( ); } if (vault.handles(url.pathname)) { - // The Environment vault (decision F43): `{}`, or a connect's - // `{job}`; a connect answers within a second and goes on + // The Environment's vault (decisions F43, F52): `{}`, or a setup's + // `{job}`; a setup answers within a second and goes on // (vault-routes.ts). const withJob = - url.pathname === "/api/tools/bitwarden/connect" && + url.pathname === "/api/tools/bitwarden/setup" && ownDataValue(input, "job") !== undefined; const value = stateFields(input, withJob ? ["job"] : []); if (withJob && !isVaultJob(value.job)) @@ -1882,6 +1888,15 @@ export async function startLaunchpad( void (async () => { if ((await executorAtStart()) && !closing) await executor.atStart(); })().catch(() => undefined); + // The Environment's own vault (decision F52), by the same pattern: where + // the vault needs it, the one setup of Settings → Tools runs in the + // background once the Launchpad listens; never awaited, never a reason for + // the start to fail, one attempt per start. + const vaultAtStart = installed?.vaultAtStart; + if (vaultAtStart !== undefined) + void (async () => { + if ((await vaultAtStart()) && !closing) await vault.atStart(); + })().catch(() => undefined); let closePending: ReturnType< ReturnType["close"] > | null = null; diff --git a/src/launchpad/tools-panel.ts b/src/launchpad/tools-panel.ts index 8924f531d..7cfb910d6 100644 --- a/src/launchpad/tools-panel.ts +++ b/src/launchpad/tools-panel.ts @@ -101,15 +101,16 @@ export function createToolsPanel( const loginStatus = find("#tools-login-status"); const loginBody = find("#tools-login-body"); const loginClose = find("#tools-login-close"); - // The Environment vault's row and dialog (decision F43): its own state, - // read beside the tools; a connect that reaches "Připojeno" turns the - // agents' switch on, as a completed sign-in does. + // The Environment's own vault (decision F52): its own state, read beside + // the tools; the Environment sets it up itself, and a setup this page + // followed that ends connected turns the agents' switch on, as a completed + // sign-in does. const vault = createVaultPanel({ post: options.post, copy: options.copy, changed: () => render(), connected: () => { - // Connecting is the next act on the row: the notice before it ends. + // The setup is the next act on the row: the notice before it ends. endNotice(vaultToolName); void refresh().then(() => { const tool = overview?.tools.find( @@ -119,28 +120,6 @@ export function createToolsPanel( void toggle(tool, true); }); }, - // Disconnecting is the vault's sign-out: the notice before it ends too. - disconnected: () => endNotice(vaultToolName), - agent: () => { - const tool = overview?.tools.find( - (entry) => entry.name === vaultToolName, - ); - if (tool === undefined) return; - const copy = options.copy(); - openPrompt( - fill(copy.toolsPromptTitle, { name: tool.name }), - copy.toolsPromptHint, - tool.prompt, - groups.querySelector( - `[data-tool="${tool.name}"][data-control="agent"]`, - ) ?? mcpButton, - ); - }, - // Not while another dialog took over (the agent's prompt). - focus: () => { - if (!busy && !dialog.open && !loginDialog.open) - focusRow({ name: vaultToolName, control: "vault" }); - }, }); // Executor (decision F44): its own state, read beside the tools; Lazurio @@ -1096,9 +1075,9 @@ export function createToolsPanel( notice !== null && notice.name === tool.name ? notice : null; const said = recorded === null ? null : toolNoticeView(recorded, tool, copy); - // The Environment vault (decision F43) and Executor (F44) say their own - // state and offer their own steps: an account of the Environment and a - // service Lazurio runs, not a person's sign-in. + // The Environment's vault (decision F52) and Executor (F44) say their + // own state and offer their own steps: an account of the Environment and + // a service Lazurio runs, not a person's sign-in. const vaultRow = tool.name === vaultToolName ? vault.row(copy) diff --git a/src/launchpad/vault-panel.ts b/src/launchpad/vault-panel.ts index 0856164bc..e13141393 100644 --- a/src/launchpad/vault-panel.ts +++ b/src/launchpad/vault-panel.ts @@ -3,22 +3,12 @@ import type { MessageKey } from "./messages"; import { answerWithin } from "./tools-view"; import { fill } from "./update-view"; import { - parseVaultConnecting, + parseVaultSettingUp, parseVaultStatus, - type VaultAction, - type VaultStep, - vaultActions, - vaultAfterConnect, - vaultAwaitsCollection, - vaultConnectPollMs, - vaultLink, - vaultPhaseMarks, - vaultPollMs, + vaultAction, + vaultOpenLink, vaultRowLine, - vaultSeen, - vaultStartStep, - vaultSteps, - vaultStepTitles, + vaultSetupPollMs, } from "./vault-view"; type Copy = Readonly>; @@ -27,13 +17,12 @@ type Post = ( body: unknown, ) => Promise<{ value: unknown; ok: boolean }>; -// The Environment vault's row and dialog on the tools screen (decision F43, -// the wireframe of prototypes-lazurio#24). The row says the state and offers -// the one next step; the dialog walks the four steps: the operator invites -// the account in the vault, the Environment connects by itself, the operator -// confirms the member by its fingerprint, connected. The server holds the -// connect: closing the dialog stops only this page's polling, never the -// work. Everything shown is text. +// The Environment's own vault on the tools screen (decision F52, the +// wireframe of prototypes-lazurio#33): the row says the state, opens the +// vault ("Otevřít trezor") once it is connected, and offers one action only +// where a setup can move it on. The Environment sets the vault up itself, at +// the Launchpad's start: the row follows a setup that runs, whoever started +// it, by the state the server reads, never a state it remembers. const answerMs = 45_000; @@ -43,30 +32,15 @@ export function createVaultPanel( copy: () => Copy; /** The vault's state changed: the tools section draws again. */ changed: () => void; - /** The dialog reached "Připojeno": the agents' switch turns on. */ + /** A setup this page followed ended connected: the agents' switch turns + * on, as after a sign-in completed in this Launchpad session. */ connected: () => void; - /** "Odpojit" went through: the row's notice of an earlier act ends. */ - disconnected: () => void; - /** "Dokončit s agentem": the tool's prepared prompt. */ - agent: () => void; - /** The dialog closed: the focus returns to the row. */ - focus: () => void; }>, ) { - const find = (selector: string): T => { - const element = document.querySelector(selector); - if (!element) throw new Error("Missing vault UI"); - return element; - }; - const dialog = find("#tools-vault"); - const title = find("#tools-vault-title"); - const body = find("#tools-vault-body"); - const close = find("#tools-vault-close"); - let status: VaultStatus | null = null; let unreadable = false; let reading = 0; - let busy = false; + let running: VaultPhase | null = null; const element = ( tag: K, @@ -87,27 +61,12 @@ export function createVaultPanel( node.append(use); return node; }; - const button = (label: string, className: string, action: () => void) => { - const node = element("button", className, label); - node.type = "button"; - node.addEventListener("click", action); - return node; - }; - const vaultAnchor = (href: string, className: string) => { - const copy = options.copy(); - const anchor = element("a", className, copy.vaultOpen); - anchor.href = href; - anchor.target = "_blank"; - anchor.rel = "noopener noreferrer"; - anchor.append(svg("external")); - return anchor; - }; /** Reads the vault's state; `sync` asks the vault itself (on the first - * read, on Refresh status and in the dialog). */ - async function read(sync: boolean): Promise { + * read and on Refresh status). A setup that runs is followed. */ + async function read(sync: boolean): Promise { const turn = ++reading; - let parsed: VaultStatus | null = null; + let value: unknown = null; try { const answer = await answerWithin( options.post( @@ -116,504 +75,94 @@ export function createVaultPanel( ), answerMs, ); - parsed = answer.answered ? parseVaultStatus(answer.value) : null; + value = answer.answered ? answer.value : null; } catch {} - if (turn !== reading) return status; + if (turn !== reading) return; + const pending = parseVaultSettingUp(value); + if (pending !== null) { + void setup(pending); + return; + } + const parsed = parseVaultStatus(value); unreadable = parsed === null; if (parsed !== null) status = parsed; options.changed(); - return parsed; } - // ---- The row --------------------------------------------------------- + /** Starts the setup, or joins the one that runs (`joined`: the one a + * reading found), and asks again until it ends; the answer is the state + * it ended in. */ + async function setup( + joined?: Readonly<{ job: string; phase: VaultPhase }>, + ): Promise { + if (running !== null) return; + running = joined?.phase ?? "install"; + options.changed(); + let body: unknown = joined === undefined ? {} : { job: joined.job }; + for (;;) { + let value: unknown = null; + try { + const answer = await answerWithin( + options.post("/api/tools/bitwarden/setup", body), + answerMs, + ); + value = answer.answered ? answer.value : null; + } catch {} + const pending = parseVaultSettingUp(value); + if (pending !== null) { + running = pending.phase; + options.changed(); + body = { job: pending.job }; + await new Promise((resolve) => setTimeout(resolve, vaultSetupPollMs)); + continue; + } + const parsed = parseVaultStatus(value); + // The setup's answer is the newest state: a read that started before + // it ended is dropped when it arrives (`read` compares its turn). + reading++; + running = null; + unreadable = parsed === null; + if (parsed !== null) status = parsed; + options.changed(); + if (parsed?.state === "connected") options.connected(); + return; + } + } - /** The status line, the controls and the details of the bitwarden row. */ + /** The status line and the controls of the bitwarden row; no details. */ function row(copy: Copy): Readonly<{ line: Readonly<{ text: string; state: string }>; controls: readonly HTMLElement[]; details: HTMLElement | null; }> { - const line = unreadable - ? { text: copy.vaultLoadFailed, state: "unknown" } - : vaultRowLine(status, copy); - const actions = vaultActions(status, copy); + const line = + unreadable && running === null + ? { text: copy.vaultLoadFailed, state: "unknown" } + : vaultRowLine(status, running, copy); const controls: HTMLElement[] = []; - if (actions.primary !== null) { - const primary = actions.primary; - const node = button(primary.label, "primary", () => - primary.action === "retry" ? void retry() : open(primary.action), - ); + const action = vaultAction(status, running, copy); + if (action !== null) { + const node = element("button", "primary", action); + node.type = "button"; node.dataset.tool = "bitwarden"; node.dataset.control = "vault"; - node.setAttribute( - "aria-label", - fill(copy.vaultActionNamed, { action: primary.label }), - ); - node.disabled = busy; - controls.push(node); - } - if (actions.disconnect) { - const node = button(copy.vaultActionDisconnect, "destructive", () => - open("disconnect"), - ); - node.dataset.tool = "bitwarden"; - node.dataset.control = "vault-disconnect"; - node.setAttribute( - "aria-label", - fill(copy.vaultActionNamed, { action: copy.vaultActionDisconnect }), - ); - node.disabled = busy; + node.setAttribute("aria-label", fill(copy.vaultActionNamed, { action })); + node.addEventListener("click", () => void setup()); controls.push(node); } - return { line, controls, details: details(copy) }; - } - - /** The account, the vault, the organization and the collection, once - * there is an account to speak of. */ - function details(copy: Copy): HTMLElement | null { - if (status === null || status.state === "unsupported") return null; - const current = status; - const section = element("section", "vault-facts"); - section.append(element("h4", "", copy.vaultDetails)); - const facts = element("dl", "vault-list"); - const fact = (label: string, value: string | HTMLElement) => { - const term = element("dt", "", label); - const description = element("dd"); - description.append(value); - facts.append(term, description); - }; - fact(copy.vaultDetailAccount, current.account); - const link = vaultLink(current.vault); - fact(copy.vaultDetailVault, current.vault.replace(/^https:\/\//, "")); - if ( - (current.state === "connected" || current.state === "confirming") && - current.organization !== null - ) - fact(copy.vaultDetailOrganization, current.organization); - fact(copy.vaultDetailCollection, current.collection); - if ( - (current.state === "connected" || - current.state === "confirming" || - current.state === "revoked") && - current.fingerprint !== null - ) - fact(copy.vaultDetailFingerprint, current.fingerprint); - section.append(facts); - const actions = element("p", "tool-actions"); - if (link !== null) actions.append(vaultAnchor(link, "button")); - if ( - current.state === "connected" || - current.state === "revoked" || - current.state === "unreachable" - ) { - const sync = button(copy.vaultSync, "", () => void retry()); - sync.disabled = busy; - actions.append(sync); - } - section.append(actions); - return section; - } - - async function retry() { - if (busy) return; - busy = true; - options.changed(); - await read(true); - busy = false; - options.changed(); - } - - // ---- The dialog ----------------------------------------------------- - - type Flow = { - mode: "connect" | "disconnect"; - step: VaultStep; - reconnect: boolean; - phase: VaultPhase | "done" | null; - failure: string | null; - agent: boolean; - working: boolean; - copied: string | null; - timer: ReturnType | null; - turn: number; - }; - let flow: Flow | null = null; - - function stop() { - if (flow?.timer) clearTimeout(flow.timer); - if (flow) flow.timer = null; - } - - function open(action: VaultAction | "disconnect") { - if (status === null || status.state === "unsupported") return; - const copy = options.copy(); - flow = { - mode: action === "disconnect" ? "disconnect" : "connect", - step: action === "disconnect" ? "done" : vaultStartStep(status, action), - reconnect: action === "reconnect", - phase: null, - failure: null, - agent: false, - working: false, - copied: null, - timer: null, - turn: 0, - }; - title.textContent = - action === "disconnect" ? copy.vaultDisconnectTitle : copy.vaultTitle; - if (typeof dialog.showModal === "function") dialog.showModal(); - else dialog.setAttribute("open", ""); - title.focus(); - render(); - if (flow.step === "connect") void connect(); - if (flow.step === "confirm") poll(); - } - - function render() { - const current = flow; - if (current === null || status === null || status.state === "unsupported") - return; - const copy = options.copy(); - if (current.mode === "disconnect") { - const actions = element("p", "tool-actions"); - const cancel = button(copy.vaultCancel, "", () => dialog.close()); - const confirm = button( - copy.vaultActionDisconnect, - "destructive", - () => void disconnect(), - ); - confirm.disabled = current.working; - actions.append(cancel, confirm); - body.replaceChildren( - element("p", "", copy.vaultDisconnectText), - ...(current.failure === null - ? [] - : [element("p", "tools-warning", current.failure)]), - actions, - ); - return; - } - const titles = vaultStepTitles(status, copy); - const at = vaultSteps.indexOf(current.step); - const list = element("ol", "vault-steps"); - vaultSteps.forEach((step, index) => { - const mark = - current.step === "done" || index < at - ? "done" - : index === at - ? "current" - : "next"; - const item = element("li", "vault-step"); - item.dataset.mark = mark; - if (index === at) item.setAttribute("aria-current", "step"); - const badge = element("span", "vault-mark"); - badge.setAttribute("aria-hidden", "true"); - if (mark === "done") badge.append(svg("check")); - else badge.textContent = String(index + 1); - const content = element("div", "vault-step-body"); - content.append(element("p", "vault-step-title", titles[step])); - if (index === at) content.append(...stepBody(step, copy)); - item.append(badge, content); - list.append(item); - }); - body.replaceChildren(list); - } - - function value(label: string, text: string, id: string): HTMLElement { - const current = flow; - const copy = options.copy(); - const box = element("div", "vault-value"); - const words = element("div", "vault-value-text"); - const shown = element("code", "vault-value-code", text); - // One line; a long value keeps its whole text on hover and in the copy. - shown.title = text; - words.append(element("span", "vault-value-label", label), shown); - const copied = current?.copied === id; - const action = button("", "ghost vault-copy", () => { - void navigator.clipboard?.writeText(text).then( - () => { - if (flow !== null) { - flow.copied = id; - render(); - } - }, - () => undefined, - ); - }); - action.append(svg(copied ? "check" : "copy")); - action.setAttribute("aria-label", fill(copy.vaultCopyNamed, { label })); - action.title = copied ? copy.vaultCopied : copy.vaultCopy; - box.append(words, action); - return box; - } - - function stepBody(step: VaultStep, copy: Copy): HTMLElement[] { - const current = flow; - if (current === null || status === null || status.state === "unsupported") - return []; - const facts = status; - const link = vaultLink(facts.vault); - const failure = - current.failure === null - ? [] - : [element("p", "vault-failure", current.failure)]; - for (const node of failure) node.setAttribute("role", "alert"); - if (step === "invite") { - const card = element("div", "vault-card"); - card.append( - value(copy.vaultCollectionLabel, facts.collection, "collection"), - value(copy.vaultAccountLabel, facts.account, "account"), - ); - const actions = element("p", "tool-actions"); - if (link !== null) actions.append(vaultAnchor(link, "button")); - const invited = button( - current.failure === null ? copy.vaultInvited : copy.vaultActionRetry, - "primary", - () => void connect(), - ); - invited.disabled = current.working; - actions.append(invited); - return [ - element( - "p", - "", - current.reconnect ? copy.vaultInviteAgainText : copy.vaultInviteText, - ), - card, - element("p", "tools-muted", copy.vaultAdminHint), - ...(facts.team - ? [element("p", "tools-muted", copy.vaultTeamHint)] - : []), - ...failure, - actions, - ]; - } - if (step === "connect") { - const list = element("ol", "content-steps"); - for (const entry of vaultPhaseMarks(current.phase, copy)) { - const item = element("li", "content-step"); - item.dataset.mark = - current.failure !== null && entry.mark === "running" - ? "failed" - : entry.mark; - const mark = element("span", "content-mark"); - mark.setAttribute("aria-hidden", "true"); - if (entry.mark === "done") mark.append(svg("check")); - else if (current.failure !== null && entry.mark === "running") - mark.append(svg("x")); - else if (entry.mark === "running") - mark.append(element("span", "spinner")); - item.append(mark, element("span", "", entry.label)); - if (entry.mark === "running") item.setAttribute("aria-current", "step"); - list.append(item); - } - const nodes: HTMLElement[] = [ - list, - element("p", "tools-muted", copy.vaultPasswordHint), - ...failure, - ]; - if (current.failure !== null) { - const actions = element("p", "tool-actions"); - if (current.agent) - actions.append( - button(copy.toolsFinishWithAgent, "", () => { - dialog.close(); - options.agent(); - }), - ); - actions.append( - button(copy.vaultActionRetry, "primary", () => void connect()), - ); - nodes.push(actions); - } - return nodes; - } - if (step === "confirm") { - const actions = element("p", "tool-actions"); - if (link !== null) actions.append(vaultAnchor(link, "button")); - // Confirmed in an organization, but the Environment's collection is - // not shared with the account (or has another name): that is the one - // thing left to do in the vault, so the fingerprint is gone. - if (vaultAwaitsCollection(facts)) { - const card = element("div", "vault-card"); - card.append( - value(copy.vaultCollectionLabel, facts.collection, "collection"), - ); - const waiting = element( - "p", - "vault-waiting", - copy.vaultWaitingCollection, - ); - waiting.setAttribute("role", "status"); - return [ - element("p", "", copy.vaultCollectionText), - card, - element("p", "tools-muted", copy.vaultCollectionHint), - actions, - ...failure, - waiting, - ]; - } - const fingerprint = - facts.state === "confirming" || facts.state === "connected" - ? facts.fingerprint - : null; - const waiting = element("p", "vault-waiting", copy.vaultWaiting); - waiting.setAttribute("role", "status"); - return [ - element("p", "", copy.vaultConfirmText), - ...(fingerprint === null - ? [] - : [ - element("p", "tools-muted", copy.vaultFingerprintHint), - element("code", "vault-phrase", fingerprint), - ]), - element("p", "tools-muted", copy.vaultAdminHint), - actions, - ...failure, - waiting, - ]; - } - const done = button(copy.toolsLoginDone, "primary", () => dialog.close()); - const row = element("p", "tool-actions"); - row.append(done); - return [ - ...(facts.state === "connected" && - facts.collections !== null && - facts.items !== null - ? [ - element( - "p", - "", - fill(copy.vaultSees, { - seen: vaultSeen(facts.collections, facts.items, copy), - }), - ), - ] - : []), - row, - ]; - } - - /** "Pozváno", "Připojit" of an existing account, or "Zkusit znovu": the - * server's one connect, asked again while it runs. */ - async function connect() { - const current = flow; - if (current === null || current.working) return; - const copy = options.copy(); - stop(); - const turn = ++current.turn; - current.working = true; - current.failure = null; - current.agent = false; - current.step = "connect"; - current.phase = "install"; - render(); - let job: string | null = null; - for (;;) { - const answer = await answerWithin( - options.post( - "/api/tools/bitwarden/connect", - job === null ? {} : { job }, - ), - answerMs, - ); - if (flow !== current || current.turn !== turn) return; - const running = answer.answered - ? parseVaultConnecting(answer.value) - : null; - if (running !== null) { - job = running.job; - current.phase = running.phase; - render(); - await new Promise((resolve) => setTimeout(resolve, vaultConnectPollMs)); - if (flow !== current || current.turn !== turn) return; - continue; - } - const parsed = answer.answered ? parseVaultStatus(answer.value) : null; - current.working = false; - if (parsed === null) { - current.failure = copy.vaultLoadFailed; - render(); - return; - } - status = parsed; - options.changed(); - const next = vaultAfterConnect(parsed, copy); - current.step = next.step; - current.failure = next.failure; - current.agent = next.agent; - current.phase = next.step === "connect" ? current.phase : "done"; - render(); - if (next.step === "confirm") poll(); - if (next.step === "done") options.connected(); - return; - } - } - - /** The confirmation step asks the vault every few seconds while the - * dialog is open. */ - function poll() { - const current = flow; - if (current === null) return; - stop(); - const turn = current.turn; - current.timer = setTimeout(async () => { - const parsed = await read(true); - if (flow !== current || current.turn !== turn) return; - if (parsed?.state === "connected") { - current.step = "done"; - current.failure = null; - render(); - options.connected(); - return; - } - if (parsed?.state === "unreachable") - current.failure = options.copy().vaultUnreachableLine; - else if (parsed?.state === "confirming") current.failure = null; - render(); - poll(); - }, vaultPollMs); - } - - async function disconnect() { - const current = flow; - if (current === null || current.working) return; - current.working = true; - render(); - let parsed: VaultStatus | null = null; - try { - const answer = await answerWithin( - options.post("/api/tools/bitwarden/disconnect", {}), - answerMs, - ); - parsed = answer.answered ? parseVaultStatus(answer.value) : null; - } catch {} - if (flow !== current) return; - current.working = false; - if (parsed === null || parsed.state === "failed") { - current.failure = options.copy().vaultLoadFailed; - render(); - return; + const link = running === null ? vaultOpenLink(status) : null; + if (link !== null) { + const anchor = element("a", "button", copy.vaultOpen); + anchor.href = link; + anchor.target = "_blank"; + anchor.rel = "noopener noreferrer"; + anchor.dataset.tool = "bitwarden"; + anchor.dataset.control = "vault-open"; + anchor.append(svg("external")); + controls.push(anchor); } - status = parsed; - options.disconnected(); - options.changed(); - dialog.close(); + return { line, controls, details: null }; } - close.addEventListener("click", () => dialog.close()); - dialog.addEventListener("close", () => { - // The event of an earlier closing may come after the dialog was opened - // again: it then belongs to nothing that is shown. - if (dialog.open) return; - // Only this page's polling ends: a connect goes on in the Launchpad. - stop(); - flow = null; - body.replaceChildren(); - // The row is drawn again with what is read now; then it takes the focus. - void read(false).then(() => options.focus()); - }); - - return Object.freeze({ read, row }); + return Object.freeze({ read, row, setup }); } diff --git a/src/launchpad/vault-routes.ts b/src/launchpad/vault-routes.ts index fba693761..24da5fdfd 100644 --- a/src/launchpad/vault-routes.ts +++ b/src/launchpad/vault-routes.ts @@ -1,39 +1,44 @@ import { randomBytes } from "node:crypto"; import { + setUpAtStart, type VaultHost, + type VaultJournalEntry, type VaultPhase, - vaultConnect, - vaultDisconnect, vaultRefresh, + vaultSetup, vaultStatus, } from "../vault/flow"; -// The Environment vault in the Launchpad (decision F43): Settings → Tools → -// bitwarden over the same core as `lazurio vault`. Four routes behind the -// admission of every route: +// The Environment's own vault in the Launchpad (decisions F43, F52): Settings +// → Tools → bitwarden over the same core as `lazurio vault`. Three routes +// behind the admission of every route: // -// POST /api/tools/bitwarden/status {} the local status (no network) -// POST /api/tools/bitwarden/refresh {} a sync, then the status -// POST /api/tools/bitwarden/connect {} starts the one connect, or -// joins the one that runs -// {job} asks how that one goes -// POST /api/tools/bitwarden/disconnect {} signs the account out here +// POST /api/tools/bitwarden/status {} the local status (no network), +// or the setup that runs +// POST /api/tools/bitwarden/refresh {} a sync, then the status, or the +// setup that runs +// POST /api/tools/bitwarden/setup {} starts the one setup, or joins +// the one that runs +// {job} asks how that one goes // -// A connect installs, creates the account and signs it in, which may take a -// minute: the route answers within a second, `202 {kind: "vault-connecting", -// job, phase}` while it runs and the status once it ended; the page asks -// again with the job. It runs in this process and a closed dialog never -// cancels it. +// A setup installs bw, registers the account, creates the vault and signs it +// in, which may take a minute: the route answers within a second, +// `202 {kind: "vault-setting-up", job, phase}` while it runs and the status +// once it ended; the page asks again with the job. It runs in this process +// and a closed page never cancels it. The Launchpad's start runs the same one +// where the vault needs it (`atStart`, the pattern of Executor's, decision +// F44's addendum of 2026-10-11), so status and refresh answer a running setup +// with its job too: the row follows it whoever started it. A closing +// Launchpad starts none. export const vaultRoutePaths = Object.freeze({ status: "/api/tools/bitwarden/status", refresh: "/api/tools/bitwarden/refresh", - connect: "/api/tools/bitwarden/connect", - disconnect: "/api/tools/bitwarden/disconnect", + setup: "/api/tools/bitwarden/setup", }); -export type VaultConnecting = Readonly<{ - kind: "vault-connecting"; +export type VaultSettingUp = Readonly<{ + kind: "vault-setting-up"; job: string; phase: VaultPhase; }>; @@ -52,31 +57,60 @@ const failed: VaultAnswer = Object.freeze({ body: Object.freeze({ error: "operation-failed" }), }); +const closingAnswer: VaultAnswer = Object.freeze({ + status: 503, + body: Object.freeze({ + kind: "blocked", + reason: "closing", + tool: "bitwarden", + }), +}); + /** A job handle as the page sends it back. */ export const isVaultJob = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{32}$/.test(value); +const settingUp = (job: Job): VaultAnswer => ({ + status: 202, + body: { + kind: "vault-setting-up", + job: job.id, + phase: job.phase, + } satisfies VaultSettingUp, +}); + export function createVaultRoutes( options: Readonly<{ host: () => VaultHost; - /** How long a connect request waits before it answers 202. */ + /** How long a setup request waits before it answers 202. */ answerWithinMs?: number | undefined; + /** Whether the Launchpad is closing: then no setup starts. */ + closing?: (() => boolean) | undefined; }>, ) { - // The connect that runs or ran last; only its handle asks about it, and a - // request without one starts the next when none runs. let current: Job | null = null; - function start(): Job { + /** The one setup, or none while the Launchpad closes: asked here, after + * whatever its caller waited for. The start's journals + * `trigger: "start"`. */ + function start(trigger?: VaultJournalEntry["trigger"]): Job | null { + if (options.closing?.() === true) return null; + const host = options.host(); + const journal = host.journal; const started: Job = { id: randomBytes(16).toString("hex"), phase: "install", done: Promise.resolve(failed), ended: false, }; - started.done = vaultConnect(options.host(), (phase) => { - started.phase = phase; - }) + started.done = vaultSetup( + trigger === undefined || journal === undefined + ? host + : { ...host, journal: (entry) => journal({ ...entry, trigger }) }, + (phase) => { + started.phase = phase; + }, + ) .then( (result): VaultAnswer => ({ status: 200, body: result }), () => failed, @@ -87,54 +121,43 @@ export function createVaultRoutes( return started; } - const read = async (operation: () => Promise) => { - try { - return { status: 200, body: await operation() }; - } catch { - return failed; - } - }; - - async function answer(current: Job): Promise { + async function answer(job: Job): Promise { let late: ReturnType | undefined; const ended = await Promise.race([ - current.done, + job.done, new Promise((resolve) => { late = setTimeout(() => resolve(null), options.answerWithinMs ?? 1_000); }), ]).finally(() => clearTimeout(late)); - if (ended !== null) return ended; - return { - status: 202, - body: { - kind: "vault-connecting", - job: current.id, - phase: current.phase, - } satisfies VaultConnecting, - }; + return ended ?? settingUp(job); } + const read = async (operation: () => Promise) => { + try { + return { status: 200, body: await operation() }; + } catch { + return failed; + } + }; + return Object.freeze({ handles(path: string): boolean { return (Object.values(vaultRoutePaths) as string[]).includes(path); }, - /** `job` only with a connect: the handle a 202 answered. */ + /** `job` only with a setup: the handle a 202 answered. */ async handle(path: string, job?: string): Promise { - if (path === vaultRoutePaths.status) - return read(() => vaultStatus(options.host())); - if (path === vaultRoutePaths.refresh) - return read(() => vaultRefresh(options.host())); - if (path === vaultRoutePaths.disconnect) { - if (current !== null && !current.ended) - return { - status: 409, - body: { kind: "blocked", reason: "busy", tool: "bitwarden" }, - }; - return read(() => vaultDisconnect(options.host())); + if (path === vaultRoutePaths.status || path === vaultRoutePaths.refresh) { + // A setup that runs is the state the row shows, whoever started it. + if (current !== null && !current.ended) return settingUp(current); + return read(() => + path === vaultRoutePaths.status + ? vaultStatus(options.host()) + : vaultRefresh(options.host()), + ); } if (job !== undefined) { - // Asking about a connect: only the one this Launchpad runs or ran - // last; any other handle is unknown and the page starts again. + // Only the setup this Launchpad runs or ran last; any other handle is + // unknown and the page starts again. if (current === null || current.id !== job) return { status: 404, @@ -142,11 +165,29 @@ export function createVaultRoutes( }; return answer(current); } - // A new connect, or the one that runs: never two at once. - if (current === null || current.ended) current = start(); + // A new setup, or the one that runs: never two at once. + if (current === null || current.ended) { + const started = start(); + if (started === null) return closingAnswer; + current = started; + } return answer(current); }, - /** The connect that runs or ran last, for tests. */ + /** After the Launchpad's start: the state is read once and, where the + * vault needs it (`setUpAtStart`), the one setup starts. Never beside a + * running one, never once the Launchpad closes and never again: a setup + * that stops leaves the row's action. Whether one started; it runs on + * in the background. */ + async atStart(): Promise { + if (current !== null && !current.ended) return false; + if (!setUpAtStart(await vaultStatus(options.host()))) return false; + if (current !== null && !current.ended) return false; + const started = start("start"); + if (started === null) return false; + current = started; + return true; + }, + /** The setup that runs or ran last, for tests. */ async settled(): Promise { await current?.done; }, diff --git a/src/launchpad/vault-view.ts b/src/launchpad/vault-view.ts index 29c54aeee..22fb12a9f 100644 --- a/src/launchpad/vault-view.ts +++ b/src/launchpad/vault-view.ts @@ -1,21 +1,20 @@ import type { VaultUnsupportedReason } from "../vault/context"; import type { VaultPhase, VaultStatus } from "../vault/flow"; import type { MessageKey } from "./messages"; -import { fill } from "./update-view"; -// The Environment vault on the tools screen (decision F43, the wireframe of -// prototypes-lazurio#24): pure, so it is testable without a DOM. The server's -// answers are accepted only in their exact form; everything returned is text -// for `textContent`, never markup. +// The Environment's own vault on the tools screen (decision F52, the +// wireframe of prototypes-lazurio#33): the row says the state and opens the +// vault; the Environment sets the vault up itself. Pure, so it is testable +// without a DOM. The server's answers are accepted only in their exact form; +// everything returned is text for `textContent` or an https link, never +// markup. type Copy = Readonly>; const states = [ "unsupported", - "not-installed", - "none", - "awaiting-invite", - "confirming", + "not-set-up", + "not-allowed", "connected", "revoked", "unreachable", @@ -28,11 +27,18 @@ const unsupportedReasons: readonly VaultUnsupportedReason[] = [ "handover-missing", "handover-unreadable", "not-operator", - "no-address", - "no-network", - "vault-unknown", + "no-vault", ]; +const phases: readonly VaultPhase[] = [ + "install", + "account", + "vault", + "sign-in", +]; + +const stages = [...phases, "sync", "status"] as const; + const plain = (value: unknown, max = 512): value is string => typeof value === "string" && value.length > 0 && @@ -45,29 +51,37 @@ const count = (value: unknown): value is number | null => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0); const code = (value: unknown): value is string => typeof value === "string" && /^[a-z0-9-]{1,80}$/.test(value); -const phrase = (value: unknown): value is string => +const id = (value: unknown): value is string => typeof value === "string" && - value.length <= 160 && - /^[a-z]+(?:-[a-z]+){4,9}$/.test(value); + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value); -/** The vault's own address: only `https://vaultwarden.`. */ -export function vaultLink(value: unknown): string | null { +/** A vault's own origin: https, a host, nothing else. */ +function vaultOrigin(value: unknown): string | null { if (typeof value !== "string") return null; try { const url = new URL(value); return url.protocol === "https:" && - url.hostname.startsWith("vaultwarden.") && url.port === "" && url.username === "" && url.password === "" && - `${url.origin}` === value.replace(/\/$/, "") - ? `${url.origin}/` + url.origin === value + ? url.origin : null; } catch { return null; } } +/** "Otevřít trezor": the network's web vault filtered to the Environment's + * vault, once it is connected. */ +export function vaultOpenLink(status: VaultStatus | null): string | null { + if (status?.state !== "connected") return null; + const origin = vaultOrigin(status.vault); + return origin === null || !id(status.organizationId) + ? null + : `${origin}/#/vault?organizationId=${status.organizationId}`; +} + /** A status answer of the server, only in its exact form. */ export function parseVaultStatus(input: unknown): VaultStatus | null { if (!input || typeof input !== "object" || Array.isArray(input)) return null; @@ -83,93 +97,69 @@ export function parseVaultStatus(input: unknown): VaultStatus | null { } : null; if ( - vaultLink(value.vault) === null || + vaultOrigin(value.vault) === null || !plain(value.account, 320) || - !plain(value.collection) || - !plain(value.name, 128) || - typeof value.team !== "boolean" + !nullable(value.name) || + typeof value.team !== "boolean" || + (value.origin !== "own" && value.origin !== "pilot-0197") ) return null; const facts = { vault: value.vault as string, account: value.account, - collection: value.collection, name: value.name, team: value.team, + origin: value.origin as "own" | "pilot-0197", }; - const locked = value.locked === true ? { locked: true as const } : {}; - if (value.locked !== undefined && value.locked !== true) return null; switch (value.state) { - case "not-installed": - case "none": - return typeof value.registered === "boolean" - ? { - kind: "vault-status", - state: value.state, - ...facts, - registered: value.registered, - } - : null; - case "awaiting-invite": - return { kind: "vault-status", state: "awaiting-invite", ...facts }; - case "confirming": - return phrase(value.fingerprint) && nullable(value.organization) + case "not-set-up": + return phases.includes(value.next as VaultPhase) ? { kind: "vault-status", - state: "confirming", + state: "not-set-up", ...facts, - fingerprint: value.fingerprint, - organization: value.organization, - ...locked, + next: value.next as VaultPhase, } : null; + case "not-allowed": + return { kind: "vault-status", state: "not-allowed", ...facts }; case "connected": - return phrase(value.fingerprint) && + if (value.locked !== undefined && value.locked !== true) return null; + return id(value.organizationId) && + id(value.collectionId) && nullable(value.organization) && - count(value.collections) && count(value.items) ? { kind: "vault-status", state: "connected", ...facts, - fingerprint: value.fingerprint, + organizationId: value.organizationId, + collectionId: value.collectionId, organization: value.organization, - collections: value.collections, items: value.items, - ...locked, + ...(value.locked === true ? { locked: true as const } : {}), } : null; case "revoked": - return value.fingerprint === null || phrase(value.fingerprint) - ? { - kind: "vault-status", - state: "revoked", - ...facts, - fingerprint: value.fingerprint, - } - : null; + return { kind: "vault-status", state: "revoked", ...facts }; case "unreachable": - return (value.fingerprint === null || phrase(value.fingerprint)) && - code(value.reason) + return code(value.reason) ? { kind: "vault-status", state: "unreachable", ...facts, - fingerprint: value.fingerprint, reason: value.reason, } : null; case "failed": - return ["install", "account", "sign-in", "sync", "status"].includes( - value.stage as string, - ) && + return stages.includes(value.stage as never) && code(value.reason) && value.fallback === "agent" ? { kind: "vault-status", state: "failed", ...facts, - stage: value.stage as "install", + stage: value.stage as (typeof stages)[number], reason: value.reason, fallback: "agent", } @@ -179,46 +169,20 @@ export function parseVaultStatus(input: unknown): VaultStatus | null { } } -/** A running connect: `202 {kind: "vault-connecting", job, phase}`. */ -export function parseVaultConnecting( +/** A running setup: `202 {kind: "vault-setting-up", job, phase}`. */ +export function parseVaultSettingUp( input: unknown, ): Readonly<{ job: string; phase: VaultPhase }> | null { if (!input || typeof input !== "object" || Array.isArray(input)) return null; const value = input as Record; - return value.kind === "vault-connecting" && + return value.kind === "vault-setting-up" && typeof value.job === "string" && /^[0-9a-f]{32}$/.test(value.job) && - (value.phase === "install" || - value.phase === "account" || - value.phase === "sign-in") - ? { job: value.job, phase: value.phase } + phases.includes(value.phase as VaultPhase) + ? { job: value.job, phase: value.phase as VaultPhase } : null; } -/** Czech plurals: 1, 2–4, 0 and 5 and more; English: 1 and the rest. */ -function plural( - value: number, - copy: Copy, - keys: readonly [MessageKey, MessageKey, MessageKey], -): string { - const key = - value === 1 ? keys[0] : value >= 2 && value <= 4 ? keys[1] : keys[2]; - return fill(copy[key], { count: String(value) }); -} - -/** "2 kolekce · 14 položek": what the account sees. */ -export function vaultSeen( - collections: number, - items: number, - copy: Copy, -): string { - return `${plural(collections, copy, [ - "vaultCollectionsOne", - "vaultCollectionsFew", - "vaultCollectionsMany", - ])} · ${plural(items, copy, ["vaultItemsOne", "vaultItemsFew", "vaultItemsMany"])}`; -} - export type VaultRowLine = Readonly<{ text: string; /** The colour of the line: `signed-in` (success), `signed-out` @@ -226,17 +190,22 @@ export type VaultRowLine = Readonly<{ state: "signed-in" | "signed-out" | "unknown"; }>; -/** Confirmed in an organization, but the Environment's collection is not - * visible: what is left is sharing the collection (or giving it its name), - * which the row, the third step's title and its body all say. */ -export const vaultAwaitsCollection = (status: VaultStatus | null): boolean => - status?.state === "confirming" && status.organization !== null; +const phaseKeys: Readonly> = { + install: "vaultPhaseInstall", + account: "vaultPhaseAccount", + vault: "vaultPhaseVault", + "sign-in": "vaultPhaseSignIn", +}; -/** The state under the row's name (the wireframe's row states). */ +/** The state under the row's name: the step of a setup that runs, or the + * state the server read. */ export function vaultRowLine( status: VaultStatus | null, + running: VaultPhase | null, copy: Copy, ): VaultRowLine { + if (running !== null) + return { text: copy[phaseKeys[running]], state: "unknown" }; if (status === null) return { text: copy.vaultRowChecking, state: "unknown" }; switch (status.state) { case "unsupported": @@ -244,192 +213,51 @@ export function vaultRowLine( text: status.reason === "workstation" ? copy.vaultRowSecondWave - : copy.vaultRowUnavailable, + : status.reason === "no-vault" + ? copy.vaultRowNoVault + : copy.vaultRowUnavailable, state: "unknown", }; - case "not-installed": - case "none": - case "awaiting-invite": - case "failed": - return { text: copy.vaultRowNone, state: "unknown" }; - case "confirming": - return { - text: vaultAwaitsCollection(status) - ? copy.vaultRowCollection - : copy.vaultRowConfirming, - state: "signed-out", - }; + case "not-set-up": + return { text: copy.vaultRowNotSetUp, state: "unknown" }; + case "not-allowed": + return { text: copy.vaultRowNotAllowed, state: "signed-out" }; case "connected": + return { text: copy.vaultRowConnected, state: "signed-in" }; + case "revoked": return { text: - status.collections === null || status.items === null - ? copy.vaultRowConnected - : `${copy.vaultRowConnected} · ${vaultSeen(status.collections, status.items, copy)}`, - state: "signed-in", + status.origin === "own" ? copy.vaultRowRemoved : copy.vaultRowRevoked, + state: "signed-out", }; - case "revoked": - return { text: copy.vaultRowRevoked, state: "signed-out" }; case "unreachable": return { text: copy.vaultRowUnreachable, state: "signed-out" }; - } -} - -export type VaultAction = "connect" | "continue" | "reconnect" | "retry"; - -export type VaultActions = Readonly<{ - primary: Readonly<{ action: VaultAction; label: string }> | null; - disconnect: boolean; -}>; - -/** The row's controls in each state: one next step, and "Odpojit" once an - * account is signed in here. */ -export function vaultActions( - status: VaultStatus | null, - copy: Copy, -): VaultActions { - if (status === null || status.state === "unsupported") - return { primary: null, disconnect: false }; - switch (status.state) { - case "not-installed": - case "none": - case "awaiting-invite": case "failed": - return { - primary: { action: "connect", label: copy.vaultActionConnect }, - disconnect: false, - }; - case "confirming": - return { - primary: { action: "continue", label: copy.vaultActionContinue }, - disconnect: true, - }; - case "connected": - return { primary: null, disconnect: true }; - case "revoked": - return { - primary: { action: "reconnect", label: copy.vaultActionReconnect }, - disconnect: true, - }; - case "unreachable": - return { - primary: { action: "retry", label: copy.vaultActionRetry }, - disconnect: true, - }; + return { text: copy.vaultRowFailed, state: "signed-out" }; } } -/** The four steps of the dialog. */ -export type VaultStep = "invite" | "connect" | "confirm" | "done"; -export const vaultSteps: readonly VaultStep[] = [ - "invite", - "connect", - "confirm", - "done", -]; - -/** The steps' titles. Once the member is confirmed and only the collection - * is missing, the third step asks for the collection, not the confirmation. */ -export function vaultStepTitles( +/** The row's one action besides "Otevřít trezor": set the own vault up + * when nothing set it up yet, or try again after a setup that stopped. A + * vault the network has not allowed or has revoked waits for a person of the + * network, and a 0197 pilot is only read: neither offers one. */ +export function vaultAction( status: VaultStatus | null, + running: VaultPhase | null, copy: Copy, -): Readonly> { - return { - invite: copy.vaultStepInvite, - connect: copy.vaultStepConnect, - confirm: vaultAwaitsCollection(status) - ? copy.vaultStepCollection - : copy.vaultStepConfirm, - done: copy.vaultStepDone, - }; -} - -/** Where "Připojit", "Pokračovat" or "Připojit znovu" opens the dialog: an - * account that exists only signs in again, a revoked one is invited again. */ -export function vaultStartStep( - status: VaultStatus, - action: VaultAction, -): VaultStep { - if (action === "continue") return "confirm"; - if (action === "reconnect") return "invite"; +): string | null { if ( - (status.state === "none" || status.state === "not-installed") && - status.registered + running !== null || + status === null || + status.state === "unsupported" || + status.origin !== "own" ) - return "connect"; - return "invite"; -} - -/** The step a connect's answer leads to, and the line it says. */ -export function vaultAfterConnect( - status: VaultStatus, - copy: Copy, -): Readonly<{ step: VaultStep; failure: string | null; agent: boolean }> { - switch (status.state) { - case "confirming": - return { step: "confirm", failure: null, agent: false }; - case "connected": - return { step: "done", failure: null, agent: false }; - case "awaiting-invite": - return { step: "invite", failure: copy.vaultNotInvited, agent: false }; - case "revoked": - // Its collection is kept (0193 addendum): another one needs a - // disconnect first. - return { - step: "invite", - failure: copy.vaultRevokedConnect, - agent: false, - }; - case "unreachable": - return { - step: "connect", - failure: copy.vaultUnreachableLine, - agent: false, - }; - case "failed": - return { - step: "connect", - failure: fill(copy.vaultFailed, { - stage: status.stage, - reason: status.reason, - }), - agent: true, - }; - case "unsupported": - return { - step: "invite", - failure: copy.vaultRowUnavailable, - agent: false, - }; - default: - return { step: "invite", failure: null, agent: false }; - } -} - -/** The automatic steps of "Environment se připojí", marked by the phase the - * connect reports. */ -export function vaultPhaseMarks( - phase: VaultPhase | "done" | null, - copy: Copy, -): readonly Readonly<{ label: string; mark: "done" | "running" | "next" }>[] { - const order: readonly VaultPhase[] = ["install", "account", "sign-in"]; - const labels: Readonly> = { - install: copy.vaultPhaseInstall, - account: copy.vaultPhaseAccount, - "sign-in": copy.vaultPhaseSignIn, - }; - const at = - phase === "done" - ? order.length - : phase === null - ? -1 - : order.indexOf(phase); - return order.map((step, index) => ({ - label: labels[step], - mark: index < at ? "done" : index === at ? "running" : "next", - })); + return null; + if (status.state === "not-set-up") return copy.vaultActionSetUp; + return status.state === "failed" || status.state === "unreachable" + ? copy.vaultActionRetry + : null; } -/** How often the confirmation step asks the vault again. */ -export const vaultPollMs = 5_000; -/** How soon a running connect is asked again. */ -export const vaultConnectPollMs = 1_000; +/** How soon a running setup is asked again. */ +export const vaultSetupPollMs = 1_000; diff --git a/src/machine/context.ts b/src/machine/context.ts index 41e67107c..1367c3baa 100644 --- a/src/machine/context.ts +++ b/src/machine/context.ts @@ -70,6 +70,17 @@ export type MachineEntry = Readonly<{ browser?: Readonly<{ external_origin: string; listen_port: number }>; environment_relay?: Readonly<{ socket: string }>; }>; +// This Environment's own vault (root decision 0198 point 1, DEV-6631 contract +// C2): the network's Lazurio Vaultwarden, the technical account the network +// generated and pre-allowed for this Environment alone, and the vault's name. +// Optional and closed on both branches: Machines writes it only for a +// Platform release that reads it, because a reader vendoring an earlier +// schema refuses the whole document (as for `entry` and its members). +export type MachineVault = Readonly<{ + server_url: string; + account: string; + name: string; +}>; type MachineInstalled = Readonly<{ machines_release: Readonly<{ repository: string; @@ -104,6 +115,7 @@ export type OrganizationWorkspaceContext = Readonly<{ network?: MachineNetwork; relationships?: MachineRelationships<"work">; entry?: MachineEntry; + vault?: MachineVault; installed: MachineInstalled; account: null; }>; @@ -130,6 +142,7 @@ export type PersonalMachineContext = Readonly<{ network: MachineNetwork; relationships?: MachineRelationships<"personal">; entry?: MachineEntry; + vault?: MachineVault; installed: MachineInstalled; account: null; }>; diff --git a/src/machine/lazurio-machine.v1.schema.json b/src/machine/lazurio-machine.v1.schema.json index 97e044f33..3b31083ca 100644 --- a/src/machine/lazurio-machine.v1.schema.json +++ b/src/machine/lazurio-machine.v1.schema.json @@ -49,6 +49,7 @@ "network": { "$ref": "#/$defs/network" }, "relationships": { "allOf": [{ "$ref": "#/$defs/relationships" }, { "type": "object", "properties": { "zone": { "const": "work" } } }] }, "entry": { "$ref": "#/$defs/entry" }, + "vault": { "$ref": "#/$defs/vault" }, "installed": { "$ref": "#/$defs/installed" }, "account": { "$ref": "#/$defs/account" } } @@ -95,6 +96,7 @@ "network": { "$ref": "#/$defs/network" }, "relationships": { "allOf": [{ "$ref": "#/$defs/relationships" }, { "type": "object", "properties": { "zone": { "const": "personal" } } }] }, "entry": { "$ref": "#/$defs/entry" }, + "vault": { "$ref": "#/$defs/vault" }, "installed": { "$ref": "#/$defs/installed" }, "account": { "$ref": "#/$defs/account" } } @@ -280,6 +282,17 @@ } } }, + "vault": { + "description": "This Environment's own vault (root decision 0198 point 1, DEV-6631 contract C2): its network's Lazurio Vaultwarden, the technical account the network generated and pre-allowed for this Environment alone, and the name of the Environment's vault there. The Environment registers the account itself and creates its own organization with it. The account address is a one-time enrollment capability until it is registered (root decision 0197 point 3). Omitted until the Machine runs a LazurioPlatform release that reads it; a reader vendoring an earlier schema refuses a document carrying it.", + "type": "object", + "additionalProperties": false, + "required": ["server_url", "account", "name"], + "properties": { + "server_url": { "description": "Origin of the network's Lazurio Vaultwarden.", "$ref": "#/$defs/https_origin" }, + "account": { "description": "The Environment's technical account: vaultwarden-<26 lowercase base32 characters>@.", "type": "string", "maxLength": 254, "pattern": "^vaultwarden-[a-z2-7]{26}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\\.lazurio\\.io$" }, + "name": { "description": "Name of the Environment's vault, : letters, digits and single spaces, unique within the network.", "type": "string", "maxLength": 50, "pattern": "^[\\p{L}\\p{Nd}]+(?: [\\p{L}\\p{Nd}]+)*$" } + } + }, "account": { "description": "Reserved for the Machine's Lazurio account identity issued by the Dashboard; null until that contract exists.", "type": "null" diff --git a/src/modules/module-cli.ts b/src/modules/module-cli.ts index 792512846..521609613 100644 --- a/src/modules/module-cli.ts +++ b/src/modules/module-cli.ts @@ -46,16 +46,17 @@ export const moduleHelp = `module start / [--app with the slot); a required sibling module workspace/ with an HTTP default app is passed as LAZURIO_RUNTIME_SIBLING__ORIGIN, its loopback address. Every secret the app declares (lazurio.runtime secrets - and optional_secrets, names only) is read from this Environment's vault - before every start: the login password of the one item of exactly that - name in the Environment's collection, passed to the app's own process - only as LAZURIO_RUNTIME_SECRET_. Only an app of the Organization - that owns the Environment reads them. A required secret without a value - refuses the start (runtime-secret-unavailable, with each name and why: - missing, ambiguous, empty, not-connected, unreachable, other-organization, - personalspace, workstation, …); an optional one whose item is not there, - or that an unusable vault does not give, is only reported, and the app - starts without it. Values are never printed. An app whose package + and optional_secrets, names only) is read from this Environment's own + vault before every start: the login password of the one item of exactly + that name anywhere in the vault, passed to the app's own process only as + LAZURIO_RUNTIME_SECRET_. On a work Environment only an app of the + Organization that owns it reads them, on a personal Environment only a + Personalspace app. A required secret without a value refuses the start + (runtime-secret-unavailable, with each name and why: missing, ambiguous, + empty, not-connected, unreachable, other-organization, personalspace, + personal-environment, workstation, …); an optional one whose item is not + there, or that an unusable vault does not give, is only reported, and the + app starts without it. Values are never printed. An app whose package declares no lazurio.preparation is prepared by default first: bun install --frozen-lockfile from the bun.lock beside its package.json, which leaves registry dependencies as they are when node_modules already matches it (local file: dependencies are copied @@ -148,7 +149,7 @@ const explanations: Readonly> = { "required-slot-missing": "The app requires this slot, which is not checked out in this Environment beside it; nothing was started. Synchronize the Organization (lazurio update) or ask for access to that repository, then start again.", "runtime-secret-unavailable": - "The app needs these secrets and the Environment's vault did not give them, so nothing was started. Each is the login password of the one item named exactly like it in this Environment's collection (lazurio vault status); add or fix the item and start again. Values are never shown.", + "The app needs these secrets and the Environment's vault did not give them, so nothing was started. Each is the login password of the one item named exactly like it in this Environment's vault (lazurio vault status); add or fix the item and start again. Values are never shown.", "preparation-script-failed": "The prepare_script this package declares failed after the dependencies were installed; nothing was started. Fix the module's preparation and start (or lazurio module prepare) again.", "application-running": diff --git a/src/modules/runtime-secrets.ts b/src/modules/runtime-secrets.ts index a4caac2ef..162933529 100644 --- a/src/modules/runtime-secrets.ts +++ b/src/modules/runtime-secrets.ts @@ -1,4 +1,5 @@ import { + type SecretApplication, type VaultHost, type VaultSecretAbsence, type VaultSecretsRefusal, @@ -10,9 +11,12 @@ import { // The secrets an application declares in `lazurio.runtime` (root decision // 0177, decision F46): its required `secrets` and its `optional_secrets` // (root decision 0196, the Environment ceiling), names only. Before every -// start their values are read from the Environment vault and passed to the -// application's own process as `LAZURIO_RUNTIME_SECRET_`, and to no -// other process. A required secret that cannot be read keeps the +// start their values are read from the Environment's own vault (decision F52) +// and passed to the application's own process as +// `LAZURIO_RUNTIME_SECRET_`, and to no other process. Which +// applications may read it is the vault's rule (flow.ts): on a work +// Environment the owning Organization's, on a personal one the +// Personalspace's. A required secret that cannot be read keeps the // application from starting with a typed finding; an optional one whose // item is not in the collection, or that a vault the application cannot use // does not provide, is only noted. A value never reaches an error, a @@ -22,8 +26,10 @@ import { * application at all, the same for each of its names, or why its own item * gives none. */ export const runtimeSecretReasons = [ - /** A Personalspace module: its secrets have no vault yet (DEV-6631). */ + /** A Personalspace module on a work Environment. */ "personalspace", + /** An Organization's module on a personal Environment. */ + "personal-environment", "workstation", "no-vault-identity", "other-organization", @@ -35,11 +41,7 @@ export const runtimeSecretReasons = [ "missing", "ambiguous", "empty", -] as const satisfies readonly ( - | "personalspace" - | VaultSecretsRefusal - | VaultSecretAbsence -)[]; +] as const satisfies readonly (VaultSecretsRefusal | VaultSecretAbsence)[]; export type RuntimeSecretReason = (typeof runtimeSecretReasons)[number]; /** One declared name without a value, and why. Never a value. */ @@ -63,11 +65,13 @@ export class RuntimeSecretUnavailable extends Error { /** Where the values come from: the Environment vault in the product, a fake * in tests. */ export type RuntimeSecretSource = Readonly<{ - /** Known without the vault's items: may an application of `company` read - * from this Environment's vault at all? Null when it may. */ - admit: (company: string) => Promise; + /** Known without the vault's items: may this application read from this + * Environment's vault at all? Null when it may. */ + admit: ( + application: SecretApplication, + ) => Promise; read: ( - input: Readonly<{ company: string; names: readonly string[] }>, + input: SecretApplication & Readonly<{ names: readonly string[] }>, ) => Promise; }>; @@ -75,8 +79,9 @@ export const vaultRuntimeSecretSource = ( host: VaultHost, ): RuntimeSecretSource => Object.freeze({ - admit: (company: string) => vaultSecretsAdmission(host, company), - read: (input: Readonly<{ company: string; names: readonly string[] }>) => + admit: (application: SecretApplication) => + vaultSecretsAdmission(host, application), + read: (input: SecretApplication & Readonly<{ names: readonly string[] }>) => vaultSecrets(host, input), }); @@ -88,7 +93,8 @@ type Declaration = Readonly<{ type Input = Readonly<{ runtime: Declaration; - /** A Personalspace module: no vault serves it (decision F46). */ + /** A Personalspace module: the vault decides whether it reads (decision + * F52 point 4: on its person's personal Environment). */ personalspace: boolean; /** None where no vault is composed: as an Environment without one. */ source?: RuntimeSecretSource | undefined; @@ -112,17 +118,19 @@ export const runtimeSecretVariable = (name: string) => /** Before anything is installed for a start: refuses an application whose * required secrets the vault cannot give it for a reason known without its - * items (a Personalspace module, an Environment without a vault identity, an - * application of another Organization). Optional secrets never refuse. */ + * items (an Environment without a vault, an application the vault does not + * serve). Optional secrets never refuse. */ export async function admitRuntimeSecrets(input: Input): Promise { const required = input.runtime.secrets; if (required.length === 0) return; - const reason: RuntimeSecretReason | null = input.personalspace - ? "personalspace" - : input.source === undefined + const reason: RuntimeSecretReason | null = + input.source === undefined ? "no-vault-identity" : await input.source - .admit(input.runtime.company) + .admit({ + company: input.runtime.company, + personalspace: input.personalspace, + }) .catch((): RuntimeSecretReason => "vault-failed"); if (reason !== null) throw new RuntimeSecretUnavailable( @@ -140,11 +148,8 @@ export async function readRuntimeSecrets( const required = input.runtime.secrets; const optional = input.runtime.optional_secrets; if (required.length === 0 && optional.length === 0) return none; - let unusable: RuntimeSecretReason | null = input.personalspace - ? "personalspace" - : input.source === undefined - ? "no-vault-identity" - : null; + let unusable: RuntimeSecretReason | null = + input.source === undefined ? "no-vault-identity" : null; let result: VaultSecretsResult | null = null; if (unusable === null && input.source !== undefined) { // A throw of the source is a vault that did not answer as expected; @@ -152,6 +157,7 @@ export async function readRuntimeSecrets( result = await input.source .read({ company: input.runtime.company, + personalspace: input.personalspace, names: [...required, ...optional], }) .catch( @@ -210,11 +216,13 @@ export type SecretEnvironment = | Readonly<{ kind: "unknown" }>; /** The catalog's answer for an app's declared secrets, known without the - * vault's items and without running anything: a required secret the vault + * vault's items and without running anything, by the vault's rule (decision + * F52 point 4): a work Environment serves the apps of the Organization that + * owns it, a personal one the Personalspace's. A required secret the vault * cannot give this app refuses its start (`runtime-secret-unavailable`, as * a preparation finding: the running app is still read and stopped); an * optional one is a note. Empty when the vault may serve the app, or when - * that is only known at the start (connected, reachable, the item there). */ + * that is only known at the start (set up, reachable, the item there). */ export async function declaredSecretsFinding( runtime: Declaration, personalspace: boolean, @@ -229,19 +237,21 @@ export async function declaredSecretsFinding( const required = runtime.secrets; const optional = runtime.optional_secrets; if (required.length === 0 && optional.length === 0) return {}; - let reason: RuntimeSecretReason | null = "personalspace"; - if (!personalspace) { - const place = await environment(); - reason = - place.kind === "workstation" - ? "workstation" - : place.kind === "hosted" && - (place.organization === null || - place.organization.toLowerCase() !== - runtime.company.toLowerCase()) - ? "other-organization" - : null; - } + const place = await environment(); + const reason: RuntimeSecretReason | null = + place.kind === "workstation" + ? "workstation" + : place.kind === "unknown" + ? null + : place.organization === null + ? personalspace + ? null + : "personal-environment" + : personalspace + ? "personalspace" + : place.organization.toLowerCase() !== runtime.company.toLowerCase() + ? "other-organization" + : null; if (reason === null) return {}; const why: RuntimeSecretReason = reason; const findings = ( diff --git a/src/organizations/catalog.ts b/src/organizations/catalog.ts index 9d569afd9..59de62b4a 100644 --- a/src/organizations/catalog.ts +++ b/src/organizations/catalog.ts @@ -689,6 +689,9 @@ function isolateDuplicates( async function readCatalogPersonalspace( folder: string, holder: PersonalspaceHolderRead, + /** What the Folder records of the Environment, for the declared secrets + * (decision F46 as F52 amends it). */ + environment: () => Promise, ): Promise { const decided = await holder(folder).catch(() => ({ kind: "blocked" as const, @@ -743,11 +746,9 @@ async function readCatalogPersonalspace( apps, moduleDirectory, space, - // A Personalspace module: no vault serves it (decision F46). - (runtime) => - declaredSecretsFinding(runtime, true, async () => ({ - kind: "unknown", - })), + // A Personalspace module: the personal Environment's vault serves it + // (decision F52 point 4), no other. + (runtime) => declaredSecretsFinding(runtime, true, environment), ); const { reason, file, preparationRefused } = own; return Object.freeze({ @@ -791,7 +792,12 @@ export async function readFolderCatalog( throw error; }, ); - const personalspace = await readCatalogPersonalspace(folder, holder); + const environment = folderSecretEnvironment(folder); + const personalspace = await readCatalogPersonalspace( + folder, + holder, + environment, + ); const withPersonalspace = personalspace === undefined ? {} : { personalspace }; if (!present) @@ -815,7 +821,6 @@ export async function readFolderCatalog( ) .map((entry) => entry.name) .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); - const environment = folderSecretEnvironment(folder); const organizations = await Promise.all( names.map((name) => readCatalogOrganization(join(root, name), name, environment), diff --git a/src/recover/private-values.ts b/src/recover/private-values.ts index 49a8b3484..048837b7e 100644 --- a/src/recover/private-values.ts +++ b/src/recover/private-values.ts @@ -189,7 +189,7 @@ export function bindingValues(binding: MachineBinding | null): PrivateValue[] { * that failed. */ export function contextValues(context: MachineContext | null): PrivateValue[] { if (context === null) return []; - const { machine, owner, operator, host, network, installed } = context; + const { machine, owner, operator, host, network, installed, vault } = context; return [ ...value("machine", machine.id), ...value("machine", machine.name), @@ -226,6 +226,12 @@ export function contextValues(context: MachineContext | null): PrivateValue[] { ...value("tailnet-node", network?.headscale_hostname), ...peerValues(context.relationships?.peers), ...repositoryValues(installed.machines_release.repository), + // The Environment's own vault (decision F52): its technical account (a + // one-time enrollment capability before it registers, contract C2), the + // vault's name and the network vault's host. + ...value("vault-account", vault?.account), + ...value("vault-name", vault?.name), + ...value("hostname", hostOf(vault?.server_url ?? "")), ]; } diff --git a/src/recover/sanitize.ts b/src/recover/sanitize.ts index ae0a2ae27..f22aae16a 100644 --- a/src/recover/sanitize.ts +++ b/src/recover/sanitize.ts @@ -39,6 +39,8 @@ export const privateKinds = [ "team", "github-login", "github-id", + "vault-account", + "vault-name", "tailnet-node", "machine-host", "peer", @@ -78,6 +80,8 @@ const single: Partial> = { home: "~", user: "", host: "", + "vault-account": "", + "vault-name": "", }; const numbered: Record = { folder: "folder", @@ -91,6 +95,8 @@ const numbered: Record = { team: "team", "github-login": "login", "github-id": "github-id", + "vault-account": "vault-account", + "vault-name": "vault-name", "tailnet-node": "node", "machine-host": "machine-host", peer: "peer", diff --git a/src/tools/catalog.ts b/src/tools/catalog.ts index 477e07c67..62e7b7b1f 100644 --- a/src/tools/catalog.ts +++ b/src/tools/catalog.ts @@ -318,11 +318,14 @@ export const toolCatalog: readonly ToolEntry[] = Object.freeze([ ), }, }), - // The Environment vault (decision F43, root decision 0193): the Bitwarden - // CLI signed in to the Environment's own account in its network's - // Vaultwarden, pinned per Platform release and set up by Settings → Tools - // → bitwarden or `lazurio vault connect`. bw writes its store on every - // start, so even its version command gets a data directory of its own. + // The Environment's own vault (decisions F43 and F52; root decisions 0193, + // 0197 and 0198): the Bitwarden CLI signed in to the Environment's + // technical account, which owns the Environment's vault in its network's + // Lazurio Vaultwarden; pinned per Platform release and set up by the + // Launchpad at its start or `lazurio vault setup`. bw writes its store on + // every start, so even its version command gets a data directory of its + // own. The agents' texts are the minimal correct ones of DEV-6631 task + // 638; how a secret reaches the vault (0198 point 9) follows with task 652. tool({ name: "bitwarden", command: "bw", @@ -335,20 +338,20 @@ export const toolCatalog: readonly ToolEntry[] = Object.freeze([ setup: "launchpad", offered: "hosted-linux", task: { - cs: "Úkol: připoj trezor tohoto Environmentu, nástroj `bitwarden` (příkaz `bw`): účet Environmentu v trezoru jeho sítě, přihlášený a odemčený pro agenty. Nejdřív zjisti skutečný stav příkazem `lazurio vault status --json`; co už funguje, neměň. Pozvat adresu účtu a potvrdit nového člena může jen Admin nebo Owner organizace v trezoru: tyhle dva kroky dělá Operátor (nebo jeho Admin) sám v trezoru, ty mu řekneš přesně co.", - en: "Task: connect this Environment's vault, the tool `bitwarden` (command `bw`): the Environment's account in its network's vault, signed in and unlocked for agents. First read the actual state with `lazurio vault status --json`; change nothing that already works. Only an Admin or Owner of the vault's organization can invite the account's address and confirm the new member: the Operator (or their Admin) does these two steps in the vault, and you tell them exactly what.", + cs: "Úkol: dokonči trezor tohoto Environmentu, nástroj `bitwarden` (příkaz `bw`): vlastní trezor Environmentu v Lazurio Vaultwardenu jeho sítě, s účtem Environmentu přihlášeným a odemčeným pro agenty. Nejdřív zjisti skutečný stav příkazem `lazurio vault status --json`; co už funguje, neměň.", + en: "Task: finish this Environment's vault, the tool `bitwarden` (command `bw`): the Environment's own vault in its network's Lazurio Vaultwarden, with the Environment's account signed in and unlocked for agents. First read the actual state with `lazurio vault status --json`; change nothing that already works.", }, installation: installation( - `Cílový stav: Bitwarden CLI ve verzi, kterou připíná Lazurio (${bitwardenPin.version}, sestavení OSS z oficiálních vydání https://github.com/bitwarden/clients), spouští \`~/.local/bin/bw\` a účet tohoto Environmentu \`vaultwarden@\` je v trezoru jeho sítě založený, přihlášený a odemčený. Udělá to příkaz \`lazurio vault connect --json\`: nainstaluje připnuté \`bw\`, založí účet s heslem, které vznikne tady a nezná ho žádný člověk, přihlásí ho API klíčem a vrátí stav. Hlásí-li \`awaiting-invite\`, řekni Operátorovi, že Admin nebo Owner organizace v trezoru musí pozvat adresu účtu s právem úprav do kolekce \`Environmenty/ · \` (přesné hodnoty jsou ve výstupu příkazu), a pak příkaz spusť znovu. Hlásí-li \`confirming\`, Admin v trezoru potvrdí nového člena podle otisku z výstupu. Jinou verzi \`bw\` neinstaluj, \`~/.local/bin/bw\`, který není Lazuria, nepřepisuj a heslo účtu, API klíč ani relaci nikam nekopíruj. Důkaz: \`lazurio vault refresh --json\` hlásí \`connected\`.`, - `Target state: the Bitwarden CLI at the version Lazurio pins (${bitwardenPin.version}, the OSS build of the official releases https://github.com/bitwarden/clients) runs as \`~/.local/bin/bw\`, and this Environment's account \`vaultwarden@\` exists in its network's vault, signed in and unlocked. The command \`lazurio vault connect --json\` does it: it installs the pinned \`bw\`, creates the account with a password generated here that no person knows, signs it in with its API key and returns the state. When it reports \`awaiting-invite\`, tell the Operator that an Admin or Owner of the vault's organization must invite the account's address with edit rights into the collection \`Environmenty/ · \` (the exact values are in the command's output), then run the command again. When it reports \`confirming\`, an Admin confirms the new member in the vault by the fingerprint in the output. Install no other version of \`bw\`, never overwrite a \`~/.local/bin/bw\` that is not Lazurio's, and copy the account's password, API key or session nowhere. Proof: \`lazurio vault refresh --json\` reports \`connected\`.`, + `Cílový stav: Bitwarden CLI ve verzi, kterou připíná Lazurio (${bitwardenPin.version}, sestavení OSS z oficiálních vydání https://github.com/bitwarden/clients), spouští \`~/.local/bin/bw\`; účet tohoto Environmentu, jehož adresu jmenuje handover Mašiny, je v trezoru jeho sítě založený, má vlastní trezor Environmentu (organizaci s kolekcí Agenti) a je přihlášený a odemčený. Udělá to příkaz \`lazurio vault setup --json\` (totéž dělá Launchpad při svém startu): nainstaluje připnuté \`bw\`, založí účet s heslem, které vznikne tady a nezná ho žádný člověk, založí trezor, přihlásí účet API klíčem a vrátí stav. Hlásí-li \`unsupported\` s důvodem \`no-vault\`, handover zatím žádný trezor nejmenuje; hlásí-li \`not-allowed\`, síť adresu účtu zatím nepovolila; hlásí-li \`revoked\`, trezor nebo účet odebral provozovatel sítě. To vše řeší provozovatel sítě: řekni to Operátorovi a nic neobcházej. Jinou verzi \`bw\` neinstaluj, \`~/.local/bin/bw\`, který není Lazuria, nepřepisuj a heslo účtu, API klíč ani relaci nikam nekopíruj. Důkaz: \`lazurio vault status --json\` hlásí \`connected\`.`, + `Target state: the Bitwarden CLI at the version Lazurio pins (${bitwardenPin.version}, the OSS build of the official releases https://github.com/bitwarden/clients) runs as \`~/.local/bin/bw\`; this Environment's account, whose address the Machine handover names, exists in its network's vault, has the Environment's own vault (an organization with the collection Agenti), and is signed in and unlocked. The command \`lazurio vault setup --json\` does it (the Launchpad does the same at its start): it installs the pinned \`bw\`, creates the account with a password generated here that no person knows, creates the vault, signs the account in with its API key and returns the state. When it reports \`unsupported\` with the reason \`no-vault\`, the handover names no vault yet; \`not-allowed\`, the network has not allowed the account's address yet; \`revoked\`, the network's operator removed the vault or the account. The network's operator resolves each of these: tell the Operator and work around nothing. Install no other version of \`bw\`, never overwrite a \`~/.local/bin/bw\` that is not Lazurio's, and copy the account's password, API key or session nowhere. Proof: \`lazurio vault status --json\` reports \`connected\`.`, ), purpose: { - cs: "Bitwarden CLI (`bw`) přihlášené k vlastnímu účtu tohoto Environmentu v jeho trezoru Vaultwarden. Co v něm je, smějí agenti použít bez ptaní.", - en: "Bitwarden CLI (`bw`) signed in to this Environment's own account in its Vaultwarden vault. What you find there you may use without asking.", + cs: "Bitwarden CLI (`bw`) přihlášené k vlastnímu trezoru tohoto Environmentu v Lazurio Vaultwardenu jeho sítě. Trezor patří Environmentu a jeho agenti ho používají sami. Co v něm je, smějí agenti použít bez ptaní.", + en: "Bitwarden CLI (`bw`) signed in to this Environment's own vault in its network's Lazurio Vaultwarden. The vault belongs to the Environment and its agents use it on their own: what you find in it you may use without asking.", }, usage: writingUsage( - 'Na začátku práce spusť `eval "$(lazurio vault env)"`; dá ti odemčené `bw` k trezoru tohoto Environmentu. Když `bw` hlásí zamčený trezor, spusť `eval "$(lazurio vault env)"` znovu; když `lazurio vault env` hlásí, že trezor není připojený, pošli Operátora do Launchpadu (Nastavení → Nástroje → bitwarden). Nikdy nespouštěj `bw login`, `unlock`, `lock`, `logout` ani `bw config`: odemčení drží Launchpad pro všechny agenty a každé další odemčení ho ostatním zruší. Před čtením spusť `bw sync`, hledej `bw list items --search ` a hodnotu z `bw get password|username|totp ` předávej rovnou do příkazu, nikdy do chatu, Gitu, logu ani PR. Nové heslo nebo token ulož do kolekce Environmentu: v šabloně `bw get template item` vyplň `organizationId` a `collectionIds` z `$LAZURIO_VAULT_ORGANIZATION_ID` a `$LAZURIO_VAULT_COLLECTION_ID`, pak `bw encode` a `bw create item`, a pojmenuj ho podle služby a účelu; do vlastního trezoru účtu nic neukládej. Chybí-li něco, požádej Operátora, ať to do kolekce nasdílí.', - 'At the start of work run `eval "$(lazurio vault env)"`; it gives you an unlocked `bw` for this Environment\'s vault. When `bw` reports a locked vault, run `eval "$(lazurio vault env)"` again; when `lazurio vault env` reports that the vault is not connected, send the Operator to the Launchpad (Settings → Tools → bitwarden). Never run `bw login`, `unlock`, `lock`, `logout` or `bw config`: the Launchpad keeps the unlocked session for all agents and every further unlock ends it for the others. Run `bw sync` before reading, search with `bw list items --search ` and pass a value of `bw get password|username|totp ` straight into a command, never into chat, Git, a log or a PR. Store a new password or token in the Environment\'s collection: fill `organizationId` and `collectionIds` of the `bw get template item` template from `$LAZURIO_VAULT_ORGANIZATION_ID` and `$LAZURIO_VAULT_COLLECTION_ID`, then `bw encode` and `bw create item`, and name it after the service and its purpose; store nothing in the account\'s own vault. When something is missing, ask the Operator to share it into the collection.', + 'Než o trezoru cokoli řekneš, ověř jeho stav příkazem `lazurio vault status`; jen ten platí. Na začátku práce spusť `eval "$(lazurio vault env)"`; dá ti odemčené `bw` k trezoru tohoto Environmentu, a když `bw` hlásí zamčený trezor, spusť ho znovu. Nikdy nespouštěj `bw login`, `unlock`, `lock`, `logout` ani `bw config`: odemčení drží Environment pro všechny agenty a každé další odemčení ho ostatním zruší. Před čtením spusť `bw sync`, hledej `bw list items --search ` a hodnotu z `bw get password|username|totp ` předávej rovnou do příkazu, nikdy do chatu, Gitu, logu ani PR. Nové heslo nebo token ulož do trezoru Environmentu: v šabloně `bw get template item` vyplň `organizationId` a `collectionIds` z `$LAZURIO_VAULT_ORGANIZATION_ID` a `$LAZURIO_VAULT_COLLECTION_ID` (kolekce Agenti), pak `bw encode` a `bw create item`, a pojmenuj ho podle služby a účelu; do vlastního trezoru účtu nic neukládej. O tajemství nikdy nežádej v chatu.', + "Before you say anything about the vault, check its state with `lazurio vault status`; only that counts. At the start of work run `eval \"$(lazurio vault env)\"`; it gives you an unlocked `bw` for this Environment's vault, and when `bw` reports a locked vault, run it again. Never run `bw login`, `unlock`, `lock`, `logout` or `bw config`: the Environment keeps the unlocked session for all agents and every further unlock ends it for the others. Run `bw sync` before reading, search with `bw list items --search ` and pass a value of `bw get password|username|totp ` straight into a command, never into chat, Git, a log or a PR. Store a new password or token in the Environment's vault: fill `organizationId` and `collectionIds` of the `bw get template item` template from `$LAZURIO_VAULT_ORGANIZATION_ID` and `$LAZURIO_VAULT_COLLECTION_ID` (the collection Agenti), then `bw encode` and `bw create item`, and name it after the service and its purpose; store nothing in the account's own vault. Never ask for a secret in chat.", { cs: "Navenek viditelný zápis do služby, ke které přístup z trezoru patří,", en: "An externally visible write to the service a credential of the vault belongs to", @@ -462,8 +465,8 @@ export const toolCatalog: readonly ToolEntry[] = Object.freeze([ }), ]); -/** The Environment vault's catalog tool (decision F43): set up by `lazurio - * vault connect` and Settings → Tools → bitwarden, not by the curated +/** The Environment's vault's catalog tool (decisions F43, F52): set up by + * the Launchpad at its start and `lazurio vault setup`, not by the curated * install and sign-in of F19. */ export const vaultToolName = "bitwarden"; diff --git a/src/tools/cli.ts b/src/tools/cli.ts index 227f2c79a..868a781a2 100644 --- a/src/tools/cli.ts +++ b/src/tools/cli.ts @@ -139,8 +139,8 @@ tools composio-org [list | switch ] [--json] marked, and switching the current one. Apps connected in Composio belong to the account and organization of this Environment. Tools set up by an agent (gogcli, neon) have no curated flow: use - lazurio tools prompt . The Environment vault (bitwarden) is - connected with lazurio vault connect or in the Launchpad.`; + lazurio tools prompt . The Environment's own vault (bitwarden) is + set up by the Launchpad at its start or with lazurio vault setup.`; export class ToolsUsageError extends Error {} diff --git a/src/tools/curated-cli.ts b/src/tools/curated-cli.ts index d9671eb84..ccd1ce6c2 100644 --- a/src/tools/curated-cli.ts +++ b/src/tools/curated-cli.ts @@ -131,21 +131,21 @@ export function refuseTool( : `Unknown tool ${name}; the catalog offers: ${known.join(", ")}`, }; } - // The Environment vault has its own flow (decision F43): no sign-in of a - // person, an account of the Environment. + // The Environment's vault has its own flow (decisions F43, F52): no + // sign-in of a person, the Environment's own account and vault. if (name === vaultToolName) { const result = { kind: "blocked", reason: "setup-vault", tool: name, - command: "lazurio vault connect", + command: "lazurio vault setup", }; return { code: 2, result, text: json ? JSON.stringify(result) - : `${name} is the Environment vault: connect it in the Launchpad (Settings → Tools → bitwarden) or with lazurio vault connect.`, + : `${name} is the Environment's own vault: the Launchpad sets it up at its start, and lazurio vault setup does the same; lazurio vault status says how it is.`, }; } // Executor is set up by Lazurio itself (decision F44). diff --git a/src/update/cli.ts b/src/update/cli.ts index 01cf5eb24..db3beca5c 100644 --- a/src/update/cli.ts +++ b/src/update/cli.ts @@ -272,6 +272,12 @@ export const executorAtStart = hosted: hostedOperator(context), })) === "hosted"; +/** Whether the Launchpad of this base sets the Environment's own vault up + * after it starts (decision F52): exactly where it sets Executor up + * (`executorAtStart`), a supervised base for the hosted operator; the vault + * itself then decides whether it needs a setup. */ +export const vaultAtStart = executorAtStart; + export async function updateEnvironment( context: CliContext, base: string, diff --git a/src/vault/bw.ts b/src/vault/bw.ts index 4fa5a544e..cff4be22c 100644 --- a/src/vault/bw.ts +++ b/src/vault/bw.ts @@ -3,9 +3,9 @@ import { open, rm } from "node:fs/promises"; import { join } from "node:path"; import { parseUniqueJson } from "../providers/unique-json"; import type { ToolProcessResult, ToolRunner } from "../tools/status"; -import { isFingerprint, isSession, isVaultId } from "./store"; +import { isSession, isVaultId } from "./store"; -// The Bitwarden CLI of one Environment vault account (decision F43), driven +// The Bitwarden CLI of one Environment vault account (decisions F43, F52), driven // by the core and never by a person: always the pinned binary, always with // the account's own BITWARDENCLI_APPDATA_DIR (bw rewrites its data file on // every start, so no run may reach another profile), never interactive. A @@ -191,10 +191,10 @@ export function parseCollections(stdout: string): BwCollection[] | null { return collections; } -/** One item of the Environment's collection that is a candidate for a - * declared name: only what the selection of decision F46 reads. Every other - * field of the item (its notes, fields, username, TOTP, URIs) is dropped - * here and never leaves this module. */ +/** One item of the Environment's vault that is a candidate for a declared + * name: only what the selection of decision F46 reads. Every other field of + * the item (its notes, fields, username, TOTP, URIs) is dropped here and + * never leaves this module. */ export type BwSecretItem = Readonly<{ name: string; organizationId: string | null; @@ -365,11 +365,21 @@ export function bwCli(environment: BwEnvironment) { session(value), ); }, - /** How many items the account sees. bw has no count: the list is read - * in memory for its length only and dropped. */ - itemCount(value: string): Promise> { + /** How many items the account sees, or of one organization. bw has no + * count: the list is read in memory for its length only and dropped. */ + itemCount( + value: string, + organizationId?: string, + ): Promise> { return step( - ["list", "items", "--nointeraction"], + [ + "list", + "items", + ...(organizationId === undefined + ? [] + : ["--organizationid", organizationId]), + "--nointeraction", + ], (stdout) => { const items = jsonOf(stdout); return Array.isArray(items) ? items.length : null; @@ -379,12 +389,13 @@ export function bwCli(environment: BwEnvironment) { itemsMaxBytes, ); }, - /** The items of one collection of one organization whose name is one of - * `names` (decision F46). The ids are not secret and go on argv; bw - * filters by them, and the caller selects again by every field. */ + /** The items of one organization, or of one collection of it (a 0197 + * pilot), whose name is one of `names` (decision F46). The ids are not + * secret and go on argv; bw filters by them, and the caller selects + * again by every field. */ secretItems( value: string, - scope: Readonly<{ organizationId: string; collectionId: string }>, + scope: Readonly<{ organizationId: string; collectionId?: string }>, names: ReadonlySet, ): Promise> { return step( @@ -393,8 +404,9 @@ export function bwCli(environment: BwEnvironment) { "items", "--organizationid", scope.organizationId, - "--collectionid", - scope.collectionId, + ...(scope.collectionId === undefined + ? [] + : ["--collectionid", scope.collectionId]), "--nointeraction", ], (stdout) => parseSecretItems(stdout, names), @@ -403,13 +415,6 @@ export function bwCli(environment: BwEnvironment) { itemsMaxBytes, ); }, - fingerprint(value: string): Promise> { - return step( - ["get", "fingerprint", "me", "--nointeraction"], - (stdout) => (isFingerprint(stdout.trim()) ? stdout.trim() : null), - session(value), - ); - }, logout(value: string | null): Promise> { return step( ["logout", "--nointeraction"], diff --git a/src/vault/cli.ts b/src/vault/cli.ts index 11a969a83..40bc5552c 100644 --- a/src/vault/cli.ts +++ b/src/vault/cli.ts @@ -4,88 +4,86 @@ import type { CliContext, CommandOutput } from "../update/cli"; import { exitFailure, exitOk, exitUsage } from "../update/errors"; import type { VaultUnsupportedReason } from "./context"; import { + type VaultEnvRefusal, type VaultEnvResult, type VaultHost, type VaultPhase, type VaultStatus, - vaultConnect, vaultEnv, vaultRefresh, + vaultSetup, vaultStatus, } from "./flow"; import { processVaultHost } from "./host"; -/** `lazurio vault`: the Environment vault for agents (decision F43). The same - * core as the Launchpad's Settings → Tools → bitwarden. */ +/** `lazurio vault`: the Environment's own vault for agents (decisions F43, + * F52). The same core as the Launchpad's Settings → Tools → bitwarden and its + * start. */ export const vaultHelp = `vault env [--json] - The Environment vault for this shell: prints shell exports of - BITWARDENCLI_APPDATA_DIR, BW_SESSION, LAZURIO_VAULT_ORGANIZATION_ID and - LAZURIO_VAULT_COLLECTION_ID. Run it as eval "$(lazurio vault env)", then - plain bw. The Launchpad keeps one unlocked session for the whole - Environment; when that session is no longer the unlocked one, this command - unlocks it again (each unlock ends the earlier session, so run it again - when bw says the vault is locked). Never run bw login, unlock, lock, logout - or config. Not connected: one line on stderr, nothing on stdout. --json - prints {kind: "vault-env", env} with the same four values. The session is - printed by design, for the agent's shell only: never paste it into chat, - Git, a log or a pull request. + This Environment's vault for this shell: prints shell exports of + BITWARDENCLI_APPDATA_DIR, BW_SESSION, LAZURIO_VAULT_ORGANIZATION_ID (the + Environment's own vault) and LAZURIO_VAULT_COLLECTION_ID (its collection + Agenti). Run it as eval "$(lazurio vault env)", then plain bw. The + Environment keeps one unlocked session for all its agents; when that + session is no longer the unlocked one, this command unlocks it again (each + unlock ends the earlier session, so run it again when bw says the vault is + locked). Never run bw login, unlock, lock, logout or config. Not set up: + one line on stderr, nothing on stdout. --json prints {kind: "vault-env", + env} with the same four values. The session is printed by design, for the + agent's shell only: never paste it into chat, Git, a log or a pull + request. vault status [--json] - This Environment's vault account as the Launchpad shows it, from bw's local - copy (no network): connected (organization, collections, items), waiting - for the Admin's confirmation (with the fingerprint phrase), not connected, - or why this Environment has no vault account here. + This Environment's vault as the Launchpad shows it, from bw's local copy + (no network): connected (its organization and how many items it holds), + not set up yet (and the next step), or why this Environment has no vault + here. The one source of truth: read it before saying anything about the + vault. vault refresh [--json] Syncs with the vault, unlocks the session again when needed, then the - status: also revoked (access removed in the vault) or unreachable. -vault connect [--json] - What Settings → Tools → bitwarden does, for an agent: installs the pinned - Bitwarden CLI, creates the account vaultwarden@ with a - password generated here (an Admin or Owner of the vault's organization must - have invited the address into the collection Environmenty/ · - first), signs it in with its API key, unlocks the one session and - syncs. Then an Admin confirms the member by the fingerprint phrase printed - here. Remote Environments on Linux only; this computer is the second wave. - Exit status: 0 connected or waiting for confirmation, 2 waiting for a - person (not invited, revoked, not available here), 1 failure.`; + status: also revoked (the vault is gone or its account refused) or + unreachable. +vault setup [--json] + What the Launchpad does at its start: installs the pinned Bitwarden CLI, + registers this Environment's account (the address its Machine handover + names, which the network pre-allowed) with a password generated here, + creates the Environment's own vault, an organization named as the handover + says with the first collection Agenti (or finds it by its ID and renames it + when the name changed), signs bw in with the account's API key, unlocks the + one session and syncs. Safe to run again. Remote Environments on Linux + only; this computer is the second wave. Exit status: 0 connected, 2 + waiting for a person (no vault named, not allowed by the network, revoked, + not available here), 1 failure.`; export type VaultCliContext = CliContext & Readonly<{ /** Test seam: the vault host instead of this process's. */ host?: VaultHost | undefined; - /** Where `connect` reports its phases (default: nothing). */ + /** Where `setup` reports its phases (default: nothing). */ progress?: ((line: string) => void) | undefined; }>; const reasons: Readonly> = { workstation: - "this Environment has no vault account: only a Remote Environment on Linux has one now (this computer is the second wave)", + "this Environment has no vault: only a Remote Environment on Linux has one now (this computer is the second wave)", "folder-unreadable": "this Environment's Folder cannot be read", "handover-missing": - "this Environment has no vault account: there is no Machine handover", + "this Environment has no vault: there is no Machine handover", "handover-unreadable": "the Machine handover cannot be read", "not-operator": "this account is not the Environment's declared operator", - "no-address": - "the Machine handover records no hosted entry, so the Environment's address is not known", - "no-network": - "the Machine handover names no tailnet, so the Environment's vault is not known", - "vault-unknown": - "the tailnet's control server is not headscale., so the Environment's vault is not known", + "no-vault": + "this Environment has no vault yet: its Machine handover names none", }; -const envRefusals: Readonly< - Record< - Extract["reason"], - string - > -> = { +const notSetUp = + "this Environment's vault is not set up yet (lazurio vault status says why; the Launchpad sets it up at its start, lazurio vault setup does the same)"; + +const envRefusals: Readonly> = { ...reasons, - "not-installed": - "the vault is not connected in this Environment: ask the Operator to connect it in the Launchpad (Settings → Tools → bitwarden)", - "not-connected": - "the vault is not connected in this Environment: ask the Operator to connect it in the Launchpad (Settings → Tools → bitwarden)", + "not-installed": notSetUp, + "not-connected": notSetUp, busy: "the vault is busy with another operation; run it again in a moment", "unlock-failed": - "the vault session could not be unlocked; tell the Operator (Settings → Tools → bitwarden shows the state)", + "the vault session could not be unlocked; lazurio vault status shows the state", }; /** One shell word: single quotes, a quote inside closed and escaped. */ @@ -107,38 +105,49 @@ export function exportsOf( .join("\n"); } +/** Where people open the Environment's vault: the web vault of the network, + * filtered to the vault's organization. */ +export const vaultLinkOf = (vault: string, organizationId: string): string => + `${vault.replace(/\/+$/, "")}/#/vault?organizationId=${encodeURIComponent(organizationId)}`; + const plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`; +const stepText: Readonly> = { + install: "installing the pinned Bitwarden CLI", + account: "registering the account", + vault: "creating the Environment's vault", + "sign-in": "signing bw in", +}; + /** The status in one or two plain lines; never a secret. */ export function statusText(status: VaultStatus): string { if (status.state === "unsupported") return `Not available: ${reasons[status.reason]}.`; const where = `${status.account} in ${status.vault}`; + const pilot = status.origin === "pilot-0197"; switch (status.state) { - case "not-installed": - case "none": - return status.registered - ? `Not connected: the account ${where} exists; lazurio vault connect signs it in again.` - : `Not connected. An Admin or Owner of the vault's organization invites ${status.account} with edit rights into the collection "${status.collection}" in ${status.vault}; then run lazurio vault connect (or Settings → Tools → bitwarden).`; - case "awaiting-invite": - return `Not invited yet: the vault refused to create ${status.account}. An Admin or Owner of the vault's organization invites it with edit rights into the collection "${status.collection}" in ${status.vault}, then run lazurio vault connect again.`; - case "confirming": - return `Waiting for the confirmation: an Admin or Owner confirms the member ${status.account} in ${status.vault}; the fingerprint phrase must be ${status.fingerprint}.${ - status.organization === null - ? "" - : ` Confirmed in ${status.organization}, but the collection "${status.collection}" is not visible yet.` - }`; - case "connected": - return `Connected: ${where}, collection "${status.collection}"${ - status.organization === null ? "" : ` of ${status.organization}` - }${ - status.collections === null || status.items === null + case "not-set-up": + return `Not set up yet: ${where}; the next step is ${stepText[status.next]}. The Launchpad sets it up at its start; lazurio vault setup does the same.`; + case "not-allowed": + return `Not allowed yet: the vault refused to register ${where}. The network has not pre-allowed this address, or removed an unused pre-allowance; the network's operator allows it again at the next apply of its host, then run lazurio vault setup.`; + case "connected": { + const seen = + status.items === null || status.organization === null ? " (locked: lazurio vault refresh unlocks it)" - : `; it sees ${plural(status.collections, "collection", "collections")} and ${plural(status.items, "item", "items")}` - }. Fingerprint: ${status.fingerprint}.`; + : `; it holds ${plural(status.items, "item", "items")}`; + return pilot + ? `Connected the 0197 way (read only until this Environment's own vault replaces it): ${where}, collection ${status.collectionId}${ + status.organization === null ? "" : ` of ${status.organization}` + }${seen}.` + : `Connected: this Environment's own vault${ + status.organization === null ? "" : ` "${status.organization}"` + }, ${where}${seen}. Open it at ${vaultLinkOf(status.vault, status.organizationId)}.`; + } case "revoked": - return `Access removed in the vault: ${status.account} no longer sees its collection. An Admin or Owner invites it again; then lazurio vault connect.`; + return pilot + ? `Access removed in the vault: ${status.account} no longer sees its collection.` + : `Revoked: ${where} no longer has this Environment's vault (its organization is gone or its API key refused). The network's operator decides what happens next.`; case "unreachable": return `The vault does not answer (${status.reason}): ${status.vault}.`; case "failed": @@ -148,17 +157,20 @@ export function statusText(status: VaultStatus): string { const phaseText: Readonly> = { install: "Installing the pinned Bitwarden CLI…", - account: "Creating the account…", + account: "Registering the account…", + vault: "Setting up the Environment's vault…", "sign-in": "Signing in…", }; +const commands = ["env", "status", "refresh", "setup"] as const; + export async function runVaultCommand( args: readonly string[], context: VaultCliContext, ): Promise { const usage = Object.freeze({ code: exitUsage, - stderr: `Usage: vault env|status|refresh|connect [--json]\n${vaultHelp}`, + stderr: `Usage: vault ${commands.join("|")} [--json]\n${vaultHelp}`, }); let json = false; let command: string; @@ -180,7 +192,7 @@ export async function runVaultCommand( } catch { return usage; } - if (!["env", "status", "refresh", "connect"].includes(command)) return usage; + if (!(commands as readonly string[]).includes(command)) return usage; const host = context.host ?? processVaultHost({ @@ -210,15 +222,15 @@ export async function runVaultCommand( ? await vaultStatus(host) : command === "refresh" ? await vaultRefresh(host) - : await vaultConnect(host, (phase) => { + : await vaultSetup(host, (phase: VaultPhase) => { if (!json) context.progress?.(phaseText[phase]); }); const code = status.state === "failed" || status.state === "unreachable" ? exitFailure - : command === "connect" && + : command === "setup" && (status.state === "unsupported" || - status.state === "awaiting-invite" || + status.state === "not-allowed" || status.state === "revoked") ? exitUsage : exitOk; diff --git a/src/vault/context.ts b/src/vault/context.ts index 0648aefdf..dbb8903c2 100644 --- a/src/vault/context.ts +++ b/src/vault/context.ts @@ -1,51 +1,42 @@ import { isAbsolute, join } from "node:path"; import type { MachineContext } from "../machine/context"; -import { environmentIdOf } from "../shell/contract"; -import { shellMessages } from "../shell/messages"; -// The Environment vault (decision F43, root decision 0193): which vault this -// Environment's own account lives in, what the account is called and which -// collection is the Environment's. Pure: the handover, the kind of -// Environment and its name go in; the facts come out, or why this -// Environment has no vault account here. Nothing here reads a file. +// The Environment's own vault (root decision 0198, decision F52): which +// network vault this Environment's technical account lives in, what the +// account is called and what its vault is named, all as the root-issued +// handover's `vault` member says (DEV-6631 contract C2). Nothing is derived +// or guessed: without the member the Environment has no vault yet. Pure: the +// handover and the kind of Environment go in, the facts come out, or why +// this Environment has no vault here. Nothing here reads a file. -/** The kinds of Remote Environment that get a vault account now. A - * workstation (this computer) is the second wave. */ +/** The kinds of Remote Environment. A workstation (this computer) is the + * second wave of root decision 0193. */ export type VaultEnvironmentKind = "personal" | "work" | "team" | "automated"; export type VaultContext = Readonly<{ - /** The vault of the Environment's network: `https://vaultwarden.` - * where the handover's tailnet control server is `https://headscale.`. */ + kind: "own"; + /** The network's Lazurio Vaultwarden: `vault.server_url`. */ vault: string; - /** Its host; with the address it names the account's state directory. */ + /** Its host; with the account it names the account's state directory. */ host: string; - /** The Environment's own address: `..lazurio.io` for an - * Organization's Environment, `.lazurio.io` for a personal one. */ - address: string; - /** The account: `vaultwarden@
`. */ + /** The Environment's technical account: `vault.account`. */ account: string; - /** The machine part of the address: the work VM's name or the personal - * slug. It identifies the Environment's collection. */ - machine: string; - kind: VaultEnvironmentKind; - /** The Environment's name as the shell gives it (decision 0185): its own - * label (a Team's, a persona's) or its kind's, in the vault's language. */ + /** The vault's name, the name of the Environment's own organization in + * Vaultwarden: `vault.name`. Its identity is its ID, never this name. */ name: string; - /** The Environment's own collection: `Environmenty/ · `. */ - collection: string; - /** The Organization that owns the Environment, as the handover names it - * (`owner.organization`, a lowercase slug); null for a personal - * Environment, which a person owns. Its collection belongs to this - * Organization's vault, so only its own applications read runtime - * secrets from it (decision F46). */ + environment: VaultEnvironmentKind; + /** The Organization that owns a work Environment (`owner.organization`, a + * lowercase slug); null for a personal Environment, which a person owns. + * It decides which applications read runtime secrets (decision F46 as F52 + * amends it). */ organization: string | null; }>; -/** Why an Environment has no vault account here; every reason refuses - * before anything is installed, written or sent. */ +/** Why an Environment has no vault here; every reason refuses before + * anything is installed, written or sent. */ export type VaultUnsupportedReason = /** Not a Remote Environment (this computer, or not Linux): the second - * wave of decision 0193. */ + * wave of root decision 0193. */ | "workstation" /** The Environment's Folder (its preset) cannot be read. */ | "folder-unreadable" @@ -55,150 +46,58 @@ export type VaultUnsupportedReason = | "handover-unreadable" /** This process is not the handover's declared operator. */ | "not-operator" - /** The handover records no hosted entry, or its Launchpad origin gives no - * Environment address. */ - | "no-address" - /** The handover names no tailnet control server. */ - | "no-network" - /** The control server is not `headscale.`, so the vault's address - * is not known. */ - | "vault-unknown"; + /** The handover names no vault for this Environment (yet): Machines + * writes the member only where the network pre-allowed its account. */ + | "no-vault"; export type VaultUnsupported = Readonly<{ kind: "unsupported"; reason: VaultUnsupportedReason; }>; -const hostedDomain = "lazurio.io"; -const dnsLabel = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; - -/** The collection prefix of decision 0193, in the vault's language. */ -export const collectionPrefix = "Environmenty/"; - -/** The vault of a network from its tailnet control server: only - * `https://headscale.` (an optional trailing slash, nothing else) gives - * `https://vaultwarden.`; anything else is unknown (fail closed). */ -export function vaultOriginOf(controlServer: string): string | null { - let url: URL; - try { - url = new URL(controlServer); - } catch { - return null; - } - const written = controlServer.toLowerCase(); - if ( - url.protocol !== "https:" || - url.username !== "" || - url.password !== "" || - url.port !== "" || - (written !== url.origin && written !== `${url.origin}/`) - ) - return null; - const labels = url.hostname.split("."); - if ( - labels.length < 3 || - labels[0] !== "headscale" || - !labels.every((label) => dnsLabel.test(label)) - ) - return null; - return `https://${["vaultwarden", ...labels.slice(1)].join(".")}`; -} - -/** The Environment's name as the collection carries it: its own label when - * it is plain one-line text without a slash (a slash nests collections in - * the vault), otherwise its kind's name. */ -export function environmentNameOf( - kind: VaultEnvironmentKind, - label: string | null, -): string { - const clean = label?.trim() ?? ""; - return clean.length > 0 && - clean.length <= 64 && - !/[\p{Cc}/\u2028\u2029\u202a-\u202e\u2066-\u2069\ufeff]/u.test(clean) - ? clean - : shellMessages("cs").names[kind]; -} - -export const collectionNameOf = (name: string, machine: string): string => - `${collectionPrefix}${name} · ${machine}`; - -/** Whether a collection the account sees is this Environment's: named - * `Environmenty/ · ` for this machine. The name part may - * differ from the one shown (a Team's display name can change); the - * machine part identifies the Environment. */ -export function isEnvironmentCollection( - name: string, - context: Pick, -): boolean { - const suffix = ` · ${context.machine}`; - return ( - name.startsWith(collectionPrefix) && - name.endsWith(suffix) && - name.length > collectionPrefix.length + suffix.length - ); -} - -/** The vault facts of one Remote Environment: from the live handover (the - * vault from its tailnet control server, the address from its Launchpad - * entry, the one derivation of an Environment's id), the kind of - * Environment its Folder records and the name the shell gives it. */ +/** The vault facts of one Remote Environment from its live handover and the + * kind of Environment its Folder records. */ export function vaultContextOf( input: Readonly<{ handover: MachineContext; - kind: VaultEnvironmentKind; - /** The Environment's own label, when it has one (a Team's, a - * persona's); null names it by its kind. */ - label: string | null; + environment: VaultEnvironmentKind; }>, ): VaultContext | VaultUnsupported { - const unsupported = (reason: VaultUnsupportedReason): VaultUnsupported => - Object.freeze({ kind: "unsupported", reason }); - const { handover } = input; - const origin = handover.entry?.launchpad.external_origin; - const id = origin === undefined ? null : environmentIdOf(origin); - if (id === null) return unsupported("no-address"); - const labels = id.split("."); - // A personal Environment is one label, an Organization's two. - if (labels.length !== (handover.machine.kind === "personal-vm" ? 1 : 2)) - return unsupported("no-address"); - const controlServer = handover.network?.headscale_server_url; - if (controlServer === undefined) return unsupported("no-network"); - const vault = vaultOriginOf(controlServer); - if (vault === null) return unsupported("vault-unknown"); - const machine = labels[0] as string; - const address = `${id}.${hostedDomain}`; - const name = environmentNameOf(input.kind, input.label); + const vault = input.handover.vault; + if (vault === undefined) + return Object.freeze({ kind: "unsupported", reason: "no-vault" }); + const { owner } = input.handover; return Object.freeze({ - vault, - host: new URL(vault).hostname, - address, - account: `vaultwarden@${address}`, - machine, - kind: input.kind, - name, - collection: collectionNameOf(name, machine), - organization: - handover.owner.kind === "organization" - ? handover.owner.organization - : null, + kind: "own", + vault: vault.server_url, + host: new URL(vault.server_url).hostname, + account: vault.account, + name: vault.name, + environment: input.environment, + organization: owner.kind === "organization" ? owner.organization : null, }); } -/** Where one Environment's account keeps its files: `${XDG_STATE_HOME:-~/ - * .local/state}/lazurio/vault//`, keyed by - * the account's whole identity, so an Environment whose address changes - * never reads the files of the account it had before (a relative - * XDG_STATE_HOME is invalid and ignored, as for the install base). Both - * parts are DNS names checked label by label above. */ +/** Where one account keeps its files: `${XDG_STATE_HOME:-~/.local/state}/ + * lazurio/vault//`. The key of an Environment's own account + * is the account itself, so an account the handover replaces never reads + * the files of the one before, and the address-keyed directory of a 0197 + * pilot (`legacy-0197/`) stays beside it untouched. A relative + * XDG_STATE_HOME is invalid and ignored, as for the install base. Both parts + * come from the schema-checked handover (a DNS name, an e-mail address of + * DNS labels): neither holds a slash. */ export function vaultStateDirectory( - identity: Pick, + host: string, + key: string, home: string, env: Readonly>, ): string { + if ([host, key].some((part) => part === "" || /[/\\]|^\.\.?$/.test(part))) + throw new Error("Invalid vault state directory"); const xdg = env.XDG_STATE_HOME; const state = xdg !== undefined && xdg !== "" && isAbsolute(xdg) ? xdg : join(home, ".local", "state"); - return join(state, "lazurio", "vault", identity.host, identity.address); + return join(state, "lazurio", "vault", host, key); } diff --git a/src/vault/flow.ts b/src/vault/flow.ts index 87813e56e..b42d0bf8a 100644 --- a/src/vault/flow.ts +++ b/src/vault/flow.ts @@ -1,26 +1,26 @@ import { randomUUID } from "node:crypto"; -import type { FileLock } from "../platform/flock"; -import { FileLockError } from "../platform/flock"; import type { InstallFetch } from "../tools/install"; import type { ToolRunner } from "../tools/status"; -import { - type BwCli, - type BwCollection, - type BwFailure, - type BwOrganization, - type BwStatus, - bwCli, -} from "./bw"; -import { - isEnvironmentCollection, - type VaultContext, - type VaultUnsupported, - type VaultUnsupportedReason, +import type { BwCli, BwFailure } from "./bw"; +import type { + VaultContext, + VaultUnsupported, + VaultUnsupportedReason, } from "./context"; -import { installPinnedBw, pinnedBinary, pinnedInstalled } from "./install"; +import { installPinnedBw, pinnedInstalled } from "./install"; +import type { PilotContext } from "./legacy-0197/context"; +import { + pilotEnv, + pilotRefresh, + pilotSecrets, + pilotSecretsAdmission, + pilotStatus, +} from "./legacy-0197/pilot"; +import { ensureOwnVault } from "./organization"; import type { BitwardenPin } from "./pin"; import { DEVICE_TYPE_SDK, + type Device, fetchApiKey, generateMasterPassword, passwordLogin, @@ -28,41 +28,81 @@ import { type VaultFetch, VaultwardenError, } from "./register"; +import { + cliOf, + lockMs, + readSecrets, + sharedSession, + signedInAs, + usableSession, + withLock, +} from "./session"; +import { + accountOf, + failedStatus, + type SecretApplication, + unsupportedStatus, + type VaultEnvResult, + type VaultFacts, + type VaultFailureStage, + type VaultPhase, + type VaultSecretsRefusal, + type VaultSecretsResult, + type VaultStatus, +} from "./status"; import { completeAccount, createAccount, ensureVaultDirectories, - forgetSignIn, forgetUnregisteredAccount, isReady, - lockVault, type ReadyAccount, - readAccount, readRecord, readSession, + type VaultAccount, type VaultPaths, type VaultRecord, vaultPaths, writeRecord, - writeSession, } from "./store"; -// The Environment vault (decision F43, root decision 0193): one core for the -// CLI (`lazurio vault`) and the Launchpad (Settings → Tools → bitwarden). -// Status-driven and idempotent: every operation reads what is there and -// moves it on, so an interrupted one is completed by the next. Each mutation -// holds the account's kernel lock. Nothing secret is returned but by `env`, -// which hands the session to an agent's shell by design; the journal carries -// the operation, the outcome and a fixed reason, never a value. +export type { + SecretApplication, + VaultEnvironment, + VaultEnvRefusal, + VaultEnvResult, + VaultFacts, + VaultFailureStage, + VaultPhase, + VaultSecret, + VaultSecretAbsence, + VaultSecretsRefusal, + VaultSecretsResult, + VaultStatus, +} from "./status"; + +// The Environment's own vault (root decision 0198, decision F52): one core +// for the CLI (`lazurio vault`) and the Launchpad (Settings → Tools → +// bitwarden, and its start). Each Environment's technical account, which the +// network pre-allowed and the handover names, registers itself, creates the +// Environment's own organization in the network's Lazurio Vaultwarden with +// the first collection Agenti, and keeps one unlocked session its agents +// share. Status-driven and idempotent: every operation reads what is there +// and moves it on, so an interrupted one is completed by the next. Each +// mutation holds the account's kernel lock. Nothing secret is returned but +// by `env`, which hands the session to an agent's shell by design; the +// journal carries the operation, the outcome and a fixed reason, never a +// value. An Environment connected the 0197 way, whose handover names no +// vault yet, is read by the frozen subset in `legacy-0197/` instead. /** Where the vault runs: trusted composition, never HTTP input. */ export type VaultHost = Readonly<{ - /** The Environment's vault, or why it has none here; read at the start - * of every operation. */ - context: () => Promise; - /** The account's state directory: its vault host and the Environment's - * address, the account's whole identity. */ - directory: (identity: Pick) => string; + /** The Environment's vault, a 0197 pilot's, or why it has none here; read + * at the start of every operation. */ + context: () => Promise; + /** The state directory of one account: the vault's host and the key (the + * own account itself; a 0197 pilot's Environment address). */ + directory: (host: string, key: string) => string; /** The product's install base, where the pinned CLI lives. */ base: string; /** `~/.local/bin`, the standard entry of `bw`. */ @@ -78,576 +118,230 @@ export type VaultHost = Readonly<{ pin?: BitwardenPin | undefined; journal?: ((entry: VaultJournalEntry) => void) | undefined; now?: (() => Date) | undefined; - /** How long a mutation waits for another one (default 10 s; connect, - * which may download the CLI, waits longer). */ + /** How long a mutation waits for another one (default 10 s; setup, which + * may download the CLI, waits longer). */ lockMs?: number | undefined; }>; export type VaultJournalEntry = Readonly<{ - operation: "connect" | "refresh" | "disconnect" | "unlock" | "secrets"; + operation: "setup" | "refresh" | "unlock" | "secrets" | "vault"; outcome: string; reason?: string; + /** The Launchpad's own setup after its start. */ + trigger?: "start"; }>; -/** What the row and the dialog show, in every state. */ -export type VaultFacts = Readonly<{ - /** `https://vaultwarden.` */ - vault: string; - /** `vaultwarden@` */ - account: string; - /** The Environment's collection: the one it is connected to, otherwise - * the name the operator gives it. */ - collection: string; - /** The Environment's name in the collection. */ - name: string; - /** A Team's Environment: the whole Team sees the collection. */ - team: boolean; -}>; - -export type VaultFailureStage = - | "install" - | "account" - | "sign-in" - | "sync" - | "status"; - -export type VaultStatus = - | Readonly<{ - kind: "vault-status"; - state: "unsupported"; - reason: VaultUnsupportedReason; - }> - | (VaultFacts & - Readonly<{ - kind: "vault-status"; - /** `not-installed`: the pinned CLI is not here; `none`: no account - * signed in. `registered`: the account exists in the vault - * (connecting again only signs it in). */ - state: "not-installed" | "none"; - registered: boolean; - }>) - | (VaultFacts & - Readonly<{ - kind: "vault-status"; - /** The vault refused the registration: the address is not invited - * (yet). Nothing was left behind. */ - state: "awaiting-invite"; - }>) - | (VaultFacts & - Readonly<{ - kind: "vault-status"; - /** Signed in; the organization or the collection is not visible - * yet: an Admin confirms the member by its fingerprint. */ - state: "confirming"; - fingerprint: string; - /** A confirmed organization without the collection, when there is - * one. */ - organization: string | null; - /** The session is not the unlocked one; refresh unlocks it. */ - locked?: true; - }>) - | (VaultFacts & - Readonly<{ - kind: "vault-status"; - state: "connected"; - fingerprint: string; - organization: string | null; - /** How many collections and items the account sees; null when the - * session was not unlocked (refresh unlocks it). */ - collections: number | null; - items: number | null; - locked?: true; - }>) - | (VaultFacts & - Readonly<{ - kind: "vault-status"; - /** It was connected; the organization or the collection is gone. */ - state: "revoked"; - fingerprint: string | null; - }>) - | (VaultFacts & - Readonly<{ - kind: "vault-status"; - state: "unreachable"; - fingerprint: string | null; - reason: string; - }>) - | (VaultFacts & - Readonly<{ - kind: "vault-status"; - state: "failed"; - stage: VaultFailureStage; - reason: string; - /** The prepared prompt of an agent who completes it. */ - fallback: "agent"; - }>); - -export type VaultPhase = "install" | "account" | "sign-in"; - -/** What `lazurio vault env` hands an agent's shell. */ -export type VaultEnvironment = Readonly<{ - BITWARDENCLI_APPDATA_DIR: string; - BW_SESSION: string; - LAZURIO_VAULT_ORGANIZATION_ID: string; - LAZURIO_VAULT_COLLECTION_ID: string; -}>; - -export type VaultEnvResult = - | Readonly<{ kind: "vault-env"; env: VaultEnvironment }> - | Readonly<{ - kind: "vault-env-refused"; - reason: - | VaultUnsupportedReason - | "not-installed" - | "not-connected" - | "busy" - | "unlock-failed"; - }>; - -const lockMs = 10_000; -const connectLockMs = 15 * 60_000; +const setupLockMs = 15 * 60_000; -const factsOf = (context: VaultContext): VaultFacts => ({ +const ownFacts = (context: VaultContext): VaultFacts => ({ vault: context.vault, account: context.account, - collection: context.collection, name: context.name, - team: context.kind === "team", + team: context.environment === "team", + origin: "own", }); -function cliOf(host: VaultHost, paths: VaultPaths): BwCli { - return bwCli({ - binary: pinnedBinary(host.base, host.pin), - data: paths.data, - home: host.home, - path: host.path, - run: host.run, - }); -} +const ownPaths = (host: VaultHost, context: VaultContext): VaultPaths => + vaultPaths(host.directory(context.host, context.account)); -/** Whether bw's profile is signed in to exactly this account at exactly this - * vault. Anything else (no sign-in, another account or vault, as after an - * agent's `bw login` in this data directory) is not the Environment's - * sign-in: it is never used, reported as connected or handed out. */ -function signedInAs( - state: BwStatus, - account: Readonly<{ email: string; server: string }>, -): boolean { - return ( - state.status !== "unauthenticated" && - state.userEmail?.toLowerCase() === account.email && - state.serverUrl?.replace(/\/+$/, "") === account.server - ); -} +const notSetUp = (facts: VaultFacts, next: VaultPhase): VaultStatus => ({ + kind: "vault-status", + state: "not-set-up", + ...facts, + next, +}); -/** The account's own collection among those it sees (root decision 0193, - * addendum 2026-10-11: its name is the operator's). Once connected, only the - * recorded ID counts: a rename changes nothing, and a collection that is gone - * is gone (revoked), whatever else the account sees. At a first connection, - * when nothing is recorded (a disconnect forgets the record, so connecting - * again is a first connection again): the one with the name the dialog - * suggested, else the only one named for this machine, else the only - * collection the account sees, whatever its name. */ -export function environmentCollection( - collections: readonly BwCollection[], - context: VaultContext, - record: VaultRecord, -): BwCollection | undefined { - if (record.collectionId !== null) - return collections.find((entry) => entry.id === record.collectionId); - const exact = collections.find((entry) => entry.name === context.collection); - if (exact !== undefined) return exact; - const named = collections.filter((entry) => - isEnvironmentCollection(entry.name, context), +/** Whether the Launchpad's start moves this vault on (the Executor pattern, + * decision F44's addendum of 2026-10-11): an own vault not set up yet, one + * whose session is not the unlocked one, or one whose name is no longer the + * handover's. Never a 0197 pilot, a vault that is not supported here, or + * one that ended in a failure or a revocation: those wait for a person or an + * agent. */ +export function setUpAtStart(status: VaultStatus): boolean { + if (status.state === "unsupported" || status.origin !== "own") return false; + if (status.state === "not-set-up") return true; + return ( + status.state === "connected" && + (status.locked === true || status.organization !== status.name) ); - if (named.length === 1) return named[0]; - return collections.length === 1 ? collections[0] : undefined; } type Observation = | Readonly<{ kind: "connected"; - organization: BwOrganization | undefined; - collection: BwCollection; - collections: number; + organization: string; items: number | null; }> - | Readonly<{ kind: "confirming"; organization: string | null }> - | Readonly<{ kind: "revoked" }> + | Readonly<{ kind: "gone" }> | Readonly<{ kind: "failed"; reason: BwFailure }>; -/** What the account sees in bw's local copy, as of its last sync. A - * collection counts only in a confirmed organization; an organization - * reported as revoked, or a recorded collection that is gone, is a revoked - * access. */ +/** What bw's local copy, as of its last sync, holds of the recorded + * organization: confirmed (the account holds its key) or gone. */ async function observe( bw: BwCli, session: string, - context: VaultContext, - record: VaultRecord, + organizationId: string, ): Promise { const organizations = await bw.organizations(session); if (!organizations.ok) return { kind: "failed", reason: organizations.reason }; - const collections = await bw.collections(session); - if (!collections.ok) return { kind: "failed", reason: collections.reason }; - const confirmed = organizations.value.filter((entry) => entry.status === 2); - const visible = collections.value.filter((entry) => - confirmed.some((organization) => organization.id === entry.organizationId), + const own = organizations.value.find( + (entry) => entry.id === organizationId && entry.status === 2, ); - const own = environmentCollection(visible, context, record); - if (own !== undefined) { - const items = await bw.itemCount(session); - return { - kind: "connected", - organization: confirmed.find((entry) => entry.id === own.organizationId), - collection: own, - collections: visible.length, - items: items.ok ? items.value : null, - }; - } - if ( - record.collectionId !== null || - organizations.value.some((entry) => entry.status === -1) - ) - return { kind: "revoked" }; - return { kind: "confirming", organization: confirmed[0]?.name ?? null }; + if (own === undefined) return { kind: "gone" }; + const items = await bw.itemCount(session, organizationId); + return { + kind: "connected", + organization: own.name, + items: items.ok ? items.value : null, + }; } -async function fingerprintOf( - bw: BwCli, - session: string, - record: VaultRecord, -): Promise { - if (record.fingerprint !== null) return record.fingerprint; - const read = await bw.fingerprint(session); - return read.ok ? read.value : null; -} +type Recorded = Readonly<{ organizationId: string; collectionId: string }>; -/** The status of an observation with the facts. */ function statusOf( facts: VaultFacts, + record: Recorded, observation: Exclude, - fingerprint: string | null, ): VaultStatus { - if (observation.kind === "revoked") - return { kind: "vault-status", state: "revoked", ...facts, fingerprint }; - if (fingerprint === null) - return failedStatus(facts, "status", "fingerprint-unreadable"); - if (observation.kind === "confirming") - return { - kind: "vault-status", - state: "confirming", - ...facts, - fingerprint, - organization: observation.organization, - }; + if (observation.kind === "gone") + return { kind: "vault-status", state: "revoked", ...facts }; return { kind: "vault-status", state: "connected", ...facts, - collection: observation.collection.name, - fingerprint, - organization: observation.organization?.name ?? null, - collections: observation.collections, + organizationId: record.organizationId, + collectionId: record.collectionId, + organization: observation.organization, items: observation.items, }; } -function failedStatus( - facts: VaultFacts, - stage: VaultFailureStage, - reason: string, -): VaultStatus { - return { - kind: "vault-status", - state: "failed", - ...facts, - stage, - reason, - fallback: "agent", - }; -} +/** The ids the record holds once the vault exists. */ +const recordedVault = (record: VaultRecord): Recorded | null => + record.organizationId !== null && record.collectionId !== null + ? { + organizationId: record.organizationId, + collectionId: record.collectionId, + } + : null; -/** The status of a session that is not the unlocked one, from the record: - * nothing is unlocked by a read. */ -function lockedStatus(facts: VaultFacts, record: VaultRecord): VaultStatus { - if (record.fingerprint === null) - return failedStatus(facts, "status", "locked"); - if (record.collectionId !== null) +/** The account, the record and the CLI of a set-up own vault, or the status + * that says what is missing. Local: nothing runs. */ +async function ownState( + host: VaultHost, + context: VaultContext, + facts: VaultFacts, + paths: VaultPaths, +): Promise< + | Readonly<{ kind: "ready"; account: ReadyAccount; recorded: Recorded }> + | Readonly<{ kind: "status"; status: VaultStatus }> +> { + const account = await accountOf(paths, context); + if (account === "unreadable") return { - kind: "vault-status", - state: "connected", - ...facts, - fingerprint: record.fingerprint, - organization: null, - collections: null, - items: null, - locked: true, + kind: "status", + status: failedStatus(facts, "account", "account-unreadable"), }; - return { - kind: "vault-status", - state: "confirming", - ...facts, - fingerprint: record.fingerprint, - organization: null, - locked: true, - }; -} - -type Prepared = - | Readonly<{ kind: "status"; status: VaultStatus }> - | Readonly<{ - kind: "ready"; - context: VaultContext; - facts: VaultFacts; - paths: VaultPaths; - }>; - -async function prepare(host: VaultHost): Promise { - const context = await host.context(); - if (context.kind === "unsupported") + if (account === "mismatch") return { kind: "status", - status: { - kind: "vault-status", - state: "unsupported", - reason: context.reason, - }, + status: failedStatus(facts, "account", "account-mismatch"), }; - return { - kind: "ready", - context, - facts: factsOf(context), - paths: vaultPaths(host.directory(context)), - }; -} - -const none = ( - facts: VaultFacts, - state: "not-installed" | "none", - registered: boolean, -): VaultStatus => ({ kind: "vault-status", state, ...facts, registered }); - -/** The account file, or a failure when it is there and unreadable or not - * this Environment's account (never replaced: it holds the only copy of the - * account's password). An account serves only the Environment whose address - * and vault it carries; its directory is keyed by them, and this holds even - * when a file is not where it belongs. */ -async function accountOf( - paths: VaultPaths, - context: VaultContext, -): Promise< - Awaited> | "unreadable" | "mismatch" -> { - let account: Awaited>; + if (!(await pinnedInstalled(host.base, host.pin))) + return { kind: "status", status: notSetUp(facts, "install") }; + if (account === null || !isReady(account)) + return { kind: "status", status: notSetUp(facts, "account") }; + let record: VaultRecord; try { - account = await readAccount(paths); + record = await readRecord(paths); } catch { - return "unreadable"; + return { + kind: "status", + status: failedStatus(facts, "vault", "record-unreadable"), + }; } - return account !== null && - (account.email !== context.account || account.server !== context.vault) - ? "mismatch" - : account; + const recorded = recordedVault(record); + if (recorded === null) + return { kind: "status", status: notSetUp(facts, "vault") }; + return { kind: "ready", account, recorded }; } /** `status`: local, no network, no mutation. */ export async function vaultStatus(host: VaultHost): Promise { - const prepared = await prepare(host); - if (prepared.kind === "status") return prepared.status; - const { context, facts, paths } = prepared; - const account = await accountOf(paths, context); - if (account === "unreadable") - return failedStatus(facts, "account", "account-unreadable"); - if (account === "mismatch") - return failedStatus(facts, "account", "account-mismatch"); - const ready = account !== null && isReady(account); - if (!(await pinnedInstalled(host.base, host.pin))) - return none(facts, "not-installed", ready); - if (!ready) return none(facts, "none", false); + const context = await host.context(); + if (context.kind === "unsupported") return unsupportedStatus(context.reason); + if (context.kind === "pilot") return pilotStatus(host, context); + const facts = ownFacts(context); + const paths = ownPaths(host, context); + const state = await ownState(host, context, facts, paths); + if (state.kind === "status") return state.status; + const { account, recorded } = state; const bw = cliOf(host, paths); - const record = await readRecord(paths); const session = await readSession(paths).catch(() => null); - const state = await bw.status(session); - if (state.ok && !signedInAs(state.value, account)) - return none(facts, "none", true); - if (session === null) return lockedStatus(facts, record); - const observation = await observe(bw, session, context, record); + const signedIn = await bw.status(session); + if (signedIn.ok && !signedInAs(signedIn.value, account)) + return notSetUp(facts, "sign-in"); + const locked: VaultStatus = { + kind: "vault-status", + state: "connected", + ...facts, + ...recorded, + organization: null, + items: null, + locked: true, + }; + if (session === null) return locked; + const observation = await observe(bw, session, recorded.organizationId); if (observation.kind === "failed") { if (observation.reason === "unauthenticated") - return none(facts, "none", true); - if (observation.reason === "locked") return lockedStatus(facts, record); + return notSetUp(facts, "sign-in"); + if (observation.reason === "locked") return locked; return failedStatus(facts, "status", observation.reason); } - return statusOf(facts, observation, await fingerprintOf(bw, session, record)); + return statusOf(facts, recorded, observation); } -async function locked( - paths: VaultPaths, - timeoutMs: number, - busy: () => T | Promise, - work: () => Promise, -): Promise { - let lock: FileLock; - try { - lock = await lockVault(paths, timeoutMs); - } catch (error) { - if (error instanceof FileLockError && error.reason === "busy") - return busy(); - throw error; - } - try { - return await work(); - } finally { - await lock.release(); - } -} - -type Session = - | Readonly<{ ok: true; session: string; fresh: boolean }> - | Readonly<{ ok: false; reason: BwFailure }>; - -/** The one session of the Environment: the recorded one while it is the - * unlocked one, otherwise a new unlock, written before it is handed out. - * Only under the account's lock. */ -async function usableSession( - host: VaultHost, - bw: BwCli, - paths: VaultPaths, - account: ReadyAccount, -): Promise { - const current = await readSession(paths).catch(() => null); - const state = await bw.status(current); - if (!state.ok) return { ok: false, reason: state.reason }; - if (!signedInAs(state.value, account)) - return { ok: false, reason: "unauthenticated" }; - if (state.value.status === "unlocked" && current !== null) - return { ok: true, session: current, fresh: false }; - const unlocked = await bw.unlock(account.masterPassword); - host.journal?.({ - operation: "unlock", - outcome: unlocked.ok ? "unlocked" : "failed", - ...(unlocked.ok ? {} : { reason: unlocked.reason }), - }); - if (!unlocked.ok) return unlocked; - await writeSession(paths, unlocked.value); - return { ok: true, session: unlocked.value, fresh: true }; -} +const deviceOf = (account: VaultAccount): Device => ({ + identifier: account.deviceIdentifier, + name: "Lazurio Launchpad", + type: DEVICE_TYPE_SDK, +}); -/** `refresh`: a sync with the vault, a new unlock when the session is no - * longer the unlocked one, and the status after it. */ -export async function vaultRefresh(host: VaultHost): Promise { - const prepared = await prepare(host); - if (prepared.kind === "status") return prepared.status; - const { context, facts, paths } = prepared; - const account = await accountOf(paths, context); - if ( - account === "unreadable" || - account === "mismatch" || - account === null || - !isReady(account) || - !(await pinnedInstalled(host.base, host.pin)) - ) - return vaultStatus(host); - return locked( - paths, - host.lockMs ?? lockMs, - () => vaultStatus(host), - async () => { - const bw = cliOf(host, paths); - const record = await readRecord(paths); - const journal = (status: VaultStatus) => { - host.journal?.({ - operation: "refresh", - outcome: status.state, - ...("reason" in status ? { reason: status.reason } : {}), - }); - return status; - }; - let session = await usableSession(host, bw, paths, account); - if (!session.ok) - return journal( - session.reason === "unauthenticated" - ? none(facts, "none", true) - : failedStatus(facts, "sign-in", session.reason), - ); - let synced = await bw.sync(session.session); - // Unlocked by another bw run since the check: unlock once more. - if (!synced.ok && synced.reason === "locked" && !session.fresh) { - session = await usableSession(host, bw, paths, account); - if (!session.ok) - return journal(failedStatus(facts, "sign-in", session.reason)); - synced = await bw.sync(session.session); - } - const fingerprint = await fingerprintOf(bw, session.session, record); - if (!synced.ok) { - if (synced.reason === "unauthenticated") - return journal(none(facts, "none", true)); - if (synced.reason === "invalid-credentials") - return journal({ - kind: "vault-status", - state: "revoked", - ...facts, - fingerprint, - }); - // The CLI itself did not run: not a question of the vault. - if (synced.reason === "spawn-failed") - return journal(failedStatus(facts, "sync", synced.reason)); - return journal({ - kind: "vault-status", - state: "unreachable", - ...facts, - fingerprint, - reason: synced.reason, - }); - } - const observation = await observe(bw, session.session, context, record); - if (observation.kind === "failed") - return journal(failedStatus(facts, "status", observation.reason)); - await recordObservation(paths, record, observation, fingerprint); - return journal(statusOf(facts, observation, fingerprint)); - }, - ); -} +type Step = + | Readonly<{ kind: "ready"; value: T }> + | Readonly<{ kind: "status"; status: VaultStatus }>; -/** The record follows what was seen: the fingerprint always, the collection - * once connected. A revoked access keeps it, so the row says so until the - * operator connects again. */ -async function recordObservation( - paths: VaultPaths, - record: VaultRecord, - observation: Exclude, - fingerprint: string | null, -): Promise { - await writeRecord(paths, { - fingerprint: fingerprint ?? record.fingerprint, - organizationId: - observation.kind === "connected" - ? observation.collection.organizationId - : record.organizationId, - collectionId: - observation.kind === "connected" - ? observation.collection.id - : record.collectionId, - }).catch(() => undefined); +/** A refusal of the vault in words of the status: unreachable, or failed at + * `stage` with the vault's fixed reason. */ +function refusalOf( + facts: VaultFacts, + stage: VaultFailureStage, + error: unknown, +): Step { + const reason = + error instanceof VaultwardenError ? error.reason : "unexpected"; + return { + kind: "status", + status: + reason === "unreachable" + ? { kind: "vault-status", state: "unreachable", ...facts, reason } + : failedStatus(facts, stage, reason), + }; } -type AccountOutcome = - | Readonly<{ kind: "ready"; account: ReadyAccount }> - | Readonly<{ kind: "status"; status: VaultStatus }>; - /** The account: created once with a password generated here, written before * the registration (the vault refuses a second one, so a lost password - * would need an Admin), registered, logged in with the Environment's one - * device identifier, and its API key added. An unfinished one is resumed: - * logged in when the vault has it, registered when it does not. */ + * would need the network's operator), registered, logged in with the + * Environment's one device identifier, and its API key added. An unfinished + * one is resumed: logged in when the vault has it, registered when it does + * not. */ async function ensureAccount( host: VaultHost, context: VaultContext, facts: VaultFacts, paths: VaultPaths, -): Promise { +): Promise> { const existing = await accountOf(paths, context); if (existing === "unreadable") return { @@ -660,7 +354,7 @@ async function ensureAccount( status: failedStatus(facts, "account", "account-mismatch"), }; if (existing !== null && isReady(existing)) - return { kind: "ready", account: existing }; + return { kind: "ready", value: existing }; const account = existing ?? (await (async () => { @@ -675,35 +369,13 @@ async function ensureAccount( return created; })()); const client = { fetch: host.fetch }; - const device = { - identifier: account.deviceIdentifier, - name: "Lazurio Launchpad", - type: DEVICE_TYPE_SDK, - }; const login = () => passwordLogin(client, { serverUrl: context.vault, email: account.email, password: account.masterPassword, - device, + device: deviceOf(account), }); - const failure = (error: unknown): AccountOutcome => { - const reason = - error instanceof VaultwardenError ? error.reason : "unexpected"; - return { - kind: "status", - status: - reason === "unreachable" - ? { - kind: "vault-status", - state: "unreachable", - ...facts, - fingerprint: null, - reason, - } - : failedStatus(facts, "account", reason), - }; - }; let session: Awaited> | undefined; if (existing !== null) { // Resumed: the registration may have happened before an interruption. @@ -714,7 +386,7 @@ async function ensureAccount( !(error instanceof VaultwardenError) || error.reason !== "invalid-credentials" ) - return failure(error); + return refusalOf(facts, "account", error); } } if (session === undefined) { @@ -723,63 +395,159 @@ async function ensureAccount( serverUrl: context.vault, email: account.email, password: account.masterPassword, - name: `Environment ${context.name} · ${context.machine}`, + name: context.name, }); } catch (error) { if (error instanceof VaultwardenError && error.reason === "not-invited") { // A password generated in this run leaves nothing behind: the vault // has no account with it. A resumed account file stays: the vault's - // refusal does not tell "not invited" from "exists already", so it + // refusal does not tell "not allowed" from "exists already", so it // may hold the only copy of a registered account's password. if (existing === null) await forgetUnregisteredAccount(paths); return { kind: "status", - status: { kind: "vault-status", state: "awaiting-invite", ...facts }, + status: { kind: "vault-status", state: "not-allowed", ...facts }, }; } - return failure(error); + return refusalOf(facts, "account", error); } try { session = await login(); } catch (error) { - return failure(error); + return refusalOf(facts, "account", error); } } try { const key = await fetchApiKey(client, session); return { kind: "ready", - account: await completeAccount(paths, account, key), + value: await completeAccount(paths, account, key), + }; + } catch (error) { + return refusalOf(facts, "account", error); + } +} + +/** The Environment's own organization and its collection Agenti, created, + * recognized by the record or renamed (organization.ts). */ +async function ensureVault( + host: VaultHost, + context: VaultContext, + facts: VaultFacts, + paths: VaultPaths, + account: ReadyAccount, +): Promise> { + let record: VaultRecord; + try { + record = await readRecord(paths); + } catch { + return { + kind: "status", + status: failedStatus(facts, "vault", "record-unreadable"), + }; + } + try { + const own = await ensureOwnVault({ + client: { fetch: host.fetch }, + server: context.vault, + account, + name: context.name, + device: deviceOf(account), + record, + save: (next) => writeRecord(paths, next), + }); + if (own.kind === "gone") + return { + kind: "status", + status: { kind: "vault-status", state: "revoked", ...facts }, + }; + if (own.kind === "collection-unknown") + return { + kind: "status", + status: failedStatus(facts, "vault", "collection-unknown"), + }; + if (own.created) host.journal?.({ operation: "vault", outcome: "created" }); + if (own.renamed) host.journal?.({ operation: "vault", outcome: "renamed" }); + return { + kind: "ready", + value: { + organizationId: own.organizationId, + collectionId: own.collectionId, + }, }; } catch (error) { - return failure(error); + // The API key refused: the network's operator removed or disabled the + // account (or rotated its key); nothing here can sign it in again. + if ( + error instanceof VaultwardenError && + error.reason === "invalid-credentials" + ) + return { + kind: "status", + status: { kind: "vault-status", state: "revoked", ...facts }, + }; + return refusalOf(facts, "vault", error); + } +} + +/** bw signed in to exactly this account at exactly this vault. */ +async function signIn( + bw: BwCli, + account: ReadyAccount, +): Promise< + Readonly<{ ok: true }> | Readonly<{ ok: false; reason: BwFailure }> +> { + const state = await bw.status(null); + if (!state.ok) return state; + if (signedInAs(state.value, account)) return { ok: true }; + // Another sign-in in this account's data directory is signed out first. + if (state.value.status !== "unauthenticated") { + const out = await bw.logout(null); + if (!out.ok) return out; } + const configured = await bw.configServer(account.server); + if (!configured.ok) return configured; + const login = await bw.loginApiKey(account.clientId, account.clientSecret); + return login.ok ? { ok: true } : login; } -/** `connect`: installs the pinned CLI, creates the account when there is - * none, signs it in with its API key, unlocks the one session and syncs. - * The collection it was connected to stays its own, also when connecting - * again after a revoked access: only a disconnect forgets it (root decision - * 0193, addendum 2026-10-11). Never runs twice at once. */ -export async function vaultConnect( +const unreachableOr = ( + facts: VaultFacts, + stage: VaultFailureStage, + reason: BwFailure, +): VaultStatus => + reason === "unreachable" || reason === "timeout" + ? { kind: "vault-status", state: "unreachable", ...facts, reason } + : failedStatus(facts, stage, reason); + +/** `setup`: installs the pinned CLI, registers the account when there is + * none, creates the Environment's own vault (or finds it by its ID, renamed + * when the handover's name changed), signs bw in with the API key, unlocks + * the one session and syncs. Idempotent: a vault that is set up is checked, + * renamed when needed, unlocked and synced again. Never runs twice at once. + * A 0197 pilot is only read: no Environment is connected the old way any + * more. */ +export async function vaultSetup( host: VaultHost, onPhase: (phase: VaultPhase) => void = () => undefined, ): Promise { - const prepared = await prepare(host); - if (prepared.kind === "status") return prepared.status; - const { context, facts, paths } = prepared; + const context = await host.context(); + if (context.kind === "unsupported") return unsupportedStatus(context.reason); + if (context.kind === "pilot") return pilotStatus(host, context); + const facts = ownFacts(context); + const paths = ownPaths(host, context); const journal = (status: VaultStatus) => { host.journal?.({ - operation: "connect", + operation: "setup", outcome: status.state, ...("reason" in status ? { reason: status.reason } : {}), }); return status; }; await ensureVaultDirectories(paths); - return locked( + return withLock( paths, - host.lockMs ?? connectLockMs, + host.lockMs ?? setupLockMs, () => journal(failedStatus(facts, "install", "busy")), async () => { onPhase("install"); @@ -804,295 +572,197 @@ export async function vaultConnect( onPhase("account"); const account = await ensureAccount(host, context, facts, paths); if (account.kind === "status") return journal(account.status); + onPhase("vault"); + const vault = await ensureVault( + host, + context, + facts, + paths, + account.value, + ); + if (vault.kind === "status") return journal(vault.status); onPhase("sign-in"); const bw = cliOf(host, paths); - const signedIn = await signIn(bw, account.account); + const signedIn = await signIn(bw, account.value); if (!signedIn.ok) - return journal( - signedIn.reason === "unreachable" || signedIn.reason === "timeout" - ? { - kind: "vault-status", - state: "unreachable", - ...facts, - fingerprint: null, - reason: signedIn.reason, - } - : failedStatus(facts, "sign-in", signedIn.reason), - ); - const session = await usableSession(host, bw, paths, account.account); + return journal(unreachableOr(facts, "sign-in", signedIn.reason)); + const session = await usableSession(host, bw, paths, account.value); if (!session.ok) return journal(failedStatus(facts, "sign-in", session.reason)); const synced = await bw.sync(session.session); - // The fingerprint is read anew; the collection it was connected to is - // kept, so a connect never takes another one in its place. - const recorded = await readRecord(paths); - const kept: VaultRecord = { - fingerprint: null, - organizationId: recorded.organizationId, - collectionId: recorded.collectionId, - }; - const fingerprint = await fingerprintOf(bw, session.session, kept); if (!synced.ok) - return journal( - synced.reason === "unreachable" || synced.reason === "timeout" - ? { - kind: "vault-status", - state: "unreachable", - ...facts, - fingerprint, - reason: synced.reason, - } - : failedStatus(facts, "sync", synced.reason), - ); - const observation = await observe(bw, session.session, context, kept); + return journal(unreachableOr(facts, "sync", synced.reason)); + const observation = await observe( + bw, + session.session, + vault.value.organizationId, + ); if (observation.kind === "failed") return journal(failedStatus(facts, "status", observation.reason)); - await writeRecord(paths, kept).catch(() => undefined); - await recordObservation(paths, kept, observation, fingerprint); - return journal(statusOf(facts, observation, fingerprint)); + return journal(statusOf(facts, vault.value, observation)); }, ); } -/** bw signed in to exactly this account at exactly this vault. */ -async function signIn( - bw: BwCli, - account: ReadyAccount, -): Promise< - Readonly<{ ok: true }> | Readonly<{ ok: false; reason: BwFailure }> -> { - const state = await bw.status(null); - if (!state.ok) return state; - if (signedInAs(state.value, account)) return { ok: true }; - // Another sign-in in this account's data directory is signed out first. - if (state.value.status !== "unauthenticated") { - const out = await bw.logout(null); - if (!out.ok) return out; - } - const configured = await bw.configServer(account.server); - if (!configured.ok) return configured; - const login = await bw.loginApiKey(account.clientId, account.clientSecret); - return login.ok ? { ok: true } : login; -} - -/** `disconnect`: bw signs out and its store, the session and the record go; - * the account stays in the vault and in its file, so connecting again signs - * the same account in. Access ends completely only when an Admin removes the - * account in the vault. Only for the Environment's own readable account - * file; otherwise nothing changes. */ -export async function vaultDisconnect(host: VaultHost): Promise { - const prepared = await prepare(host); - if (prepared.kind === "status") return prepared.status; - const { context, facts, paths } = prepared; - const result = await locked( +/** `refresh`: a sync with the vault, a new unlock when the session is no + * longer the unlocked one, and the status after it. A vault that is not set + * up yet answers its local status: only a setup moves it on. */ +export async function vaultRefresh(host: VaultHost): Promise { + const context = await host.context(); + if (context.kind === "unsupported") return unsupportedStatus(context.reason); + if (context.kind === "pilot") return pilotRefresh(host, context); + const facts = ownFacts(context); + const paths = ownPaths(host, context); + const state = await ownState(host, context, facts, paths); + if (state.kind === "status") return state.status; + const { account, recorded } = state; + return withLock( paths, host.lockMs ?? lockMs, - () => failedStatus(facts, "sign-in", "busy"), + () => vaultStatus(host), async () => { - // Only the Environment's own account, readable, is signed out. Another - // account's file, an unreadable one (it may hold the only copy of the - // password, and bw's store then the only working sign-in) or none at - // all leaves everything as it is. - const account = await accountOf(paths, context); - if (account === "mismatch") - return failedStatus(facts, "account", "account-mismatch"); - if (account === "unreadable") - return failedStatus(facts, "account", "account-unreadable"); - if (account === null) return vaultStatus(host); - if (await pinnedInstalled(host.base, host.pin)) { - const session = await readSession(paths).catch(() => null); - await cliOf(host, paths).logout(session); + const bw = cliOf(host, paths); + const journal = (status: VaultStatus) => { + host.journal?.({ + operation: "refresh", + outcome: status.state, + ...("reason" in status ? { reason: status.reason } : {}), + }); + return status; + }; + let session = await usableSession(host, bw, paths, account); + if (!session.ok) + return journal( + session.reason === "unauthenticated" + ? notSetUp(facts, "sign-in") + : failedStatus(facts, "sign-in", session.reason), + ); + let synced = await bw.sync(session.session); + // Unlocked by another bw run since the check: unlock once more. + if (!synced.ok && synced.reason === "locked" && !session.fresh) { + session = await usableSession(host, bw, paths, account); + if (!session.ok) + return journal(failedStatus(facts, "sign-in", session.reason)); + synced = await bw.sync(session.session); } - await forgetSignIn(paths); - return null; - }, - ); - const status = result ?? (await vaultStatus(host)); - host.journal?.({ - operation: "disconnect", - outcome: result === null ? "disconnected" : status.state, - ...(status.state === "failed" ? { reason: status.reason } : {}), - }); - return status; -} - -type ConnectedSession = - | Readonly<{ - ok: true; - bw: BwCli; - session: string; - data: string; - organizationId: string; - collectionId: string; - }> - | Readonly<{ - ok: false; - reason: Extract["reason"]; - }>; - -/** The one unlocked session of a connected Environment and the ids of its - * collection. A session that is no longer the unlocked one is replaced under - * the account's lock; another process that replaced it meanwhile is trusted, - * so two readers never unlock twice. */ -async function connectedSession( - host: VaultHost, - context: VaultContext, -): Promise { - const refuse = ( - reason: Extract["reason"], - ): ConnectedSession => ({ ok: false, reason }); - const paths = vaultPaths(host.directory(context)); - if (!(await pinnedInstalled(host.base, host.pin))) - return refuse("not-installed"); - const account = await accountOf(paths, context); - if ( - account === "unreadable" || - account === "mismatch" || - account === null || - !isReady(account) - ) - return refuse("not-connected"); - const record = await readRecord(paths); - if (record.organizationId === null || record.collectionId === null) - return refuse("not-connected"); - const { organizationId, collectionId } = record; - const bw = cliOf(host, paths); - const answer = (session: string): ConnectedSession => ({ - ok: true, - bw, - session, - data: paths.data, - organizationId, - collectionId, - }); - const current = await readSession(paths).catch(() => null); - if (current !== null) { - const state = await bw.status(current); - if (state.ok && !signedInAs(state.value, account)) - return refuse("not-connected"); - if (state.ok && state.value.status === "unlocked") return answer(current); - } - return locked( - paths, - host.lockMs ?? 60_000, - () => refuse("busy"), - async () => { - const session = await usableSession(host, bw, paths, account); - if (session.ok) return answer(session.session); - return refuse( - session.reason === "unauthenticated" - ? "not-connected" - : "unlock-failed", + if (!synced.ok) { + if (synced.reason === "unauthenticated") + return journal(notSetUp(facts, "sign-in")); + if (synced.reason === "invalid-credentials") + return journal({ kind: "vault-status", state: "revoked", ...facts }); + // The CLI itself did not run: not a question of the vault. + if (synced.reason === "spawn-failed") + return journal(failedStatus(facts, "sync", synced.reason)); + return journal({ + kind: "vault-status", + state: "unreachable", + ...facts, + reason: synced.reason, + }); + } + const observation = await observe( + bw, + session.session, + recorded.organizationId, ); + if (observation.kind === "failed") + return journal(failedStatus(facts, "status", observation.reason)); + return journal(statusOf(facts, recorded, observation)); }, ); } -/** `env`: the session for an agent's shell. A session that is no longer the - * unlocked one is replaced under the account's lock; another process that - * replaced it meanwhile is trusted, so two agents never unlock twice. */ +/** `env`: the session for an agent's shell, and the ids of the vault and + * of Agenti. A session that is no longer the unlocked one is replaced under + * the account's lock; another process that replaced it meanwhile is + * trusted, so two agents never unlock twice. */ export async function vaultEnv(host: VaultHost): Promise { const context = await host.context(); if (context.kind === "unsupported") return { kind: "vault-env-refused", reason: context.reason }; - const connected = await connectedSession(host, context); - if (!connected.ok) - return { kind: "vault-env-refused", reason: connected.reason }; + if (context.kind === "pilot") return pilotEnv(host, context); + const paths = ownPaths(host, context); + const ready = await connectedAccount(paths, context); + if (ready === null) + return { kind: "vault-env-refused", reason: "not-connected" }; + const shared = await sharedSession(host, paths, ready.account); + if (!shared.ok) return { kind: "vault-env-refused", reason: shared.reason }; return { kind: "vault-env", env: { - BITWARDENCLI_APPDATA_DIR: connected.data, - BW_SESSION: connected.session, - LAZURIO_VAULT_ORGANIZATION_ID: connected.organizationId, - LAZURIO_VAULT_COLLECTION_ID: connected.collectionId, + BITWARDENCLI_APPDATA_DIR: paths.data, + BW_SESSION: shared.session, + LAZURIO_VAULT_ORGANIZATION_ID: ready.recorded.organizationId, + LAZURIO_VAULT_COLLECTION_ID: ready.recorded.collectionId, }, }; } -/** Why no runtime secret of an application can be read from the - * Environment vault (decision F46): a fixed code, never bw's output. */ -export type VaultSecretsRefusal = - /** This computer: no vault identity yet (the second wave of 0193). */ - | "workstation" - /** A Remote Environment whose vault account cannot be derived (no - * handover, not its operator, no address or network, an unknown vault). */ - | "no-vault-identity" - /** The application belongs to another Organization than the one that - * owns the Environment and its collection. */ - | "other-organization" - /** The vault is not connected here (not installed, no account, no - * collection, signed out or the access revoked). */ - | "not-connected" - /** The session could not be unlocked. */ - | "locked" - /** Another process holds the account's lock. */ - | "busy" - /** The vault cannot be reached for the sync. */ - | "unreachable" - /** bw did not answer in the shape this core reads, or did not run. */ - | "vault-failed"; - -/** Why one declared name has no value (decision F46). */ -export type VaultSecretAbsence = - /** No item of that exact name in the Environment's collection. */ - | "missing" - /** More than one such item: which one is meant is not guessed. */ - | "ambiguous" - /** The one item has no login password, or an empty one. */ - | "empty"; +/** The ready account and the recorded vault, or null: nothing else is the + * Environment's connected vault. */ +async function connectedAccount( + paths: VaultPaths, + context: VaultContext, +): Promise | null> { + const account = await accountOf(paths, context); + if ( + account === "unreadable" || + account === "mismatch" || + account === null || + !isReady(account) + ) + return null; + const record = await readRecord(paths).catch(() => null); + const recorded = record === null ? null : recordedVault(record); + return recorded === null ? null : { account, recorded }; +} -export type VaultSecret = - | Readonly<{ kind: "value"; value: string }> - | Readonly<{ kind: "absent"; reason: VaultSecretAbsence }>; +/** Which applications read the Environment's own vault (root decision 0198 + * point 4: personal and work Environments alike): on a work Environment an + * application of the Organization that owns it (slugs compare as GitHub's, + * case-insensitively), on a personal one the Personalspace's applications. + * Null when it may. */ +function ownAdmission( + context: VaultContext, + application: SecretApplication, +): VaultSecretsRefusal | null { + if (context.organization === null) + return application.personalspace ? null : "personal-environment"; + if (application.personalspace) return "personalspace"; + return context.organization.toLowerCase() === + application.company.toLowerCase() + ? null + : "other-organization"; +} -export type VaultSecretsResult = - | Readonly<{ - kind: "vault-secrets"; - /** Every requested name, with its value or why it has none. */ - secrets: ReadonlyMap; - }> - | Readonly<{ kind: "vault-secrets-refused"; reason: VaultSecretsRefusal }>; +const unsupportedRefusal = ( + reason: VaultUnsupportedReason, +): VaultSecretsRefusal => + reason === "workstation" ? "workstation" : "no-vault-identity"; -/** Whether an application of `company` may read runtime secrets from this - * Environment's vault, as far as is known without running bw: the - * Environment has a vault identity, and the application belongs to the - * Organization that owns the Environment (its collection is that - * Organization's; slugs compare as GitHub's, case-insensitively). Null when - * it may. */ +/** Whether an application may read runtime secrets from this Environment's + * vault, as far as is known without running bw. Null when it may. */ export async function vaultSecretsAdmission( host: VaultHost, - company: string, + application: SecretApplication, ): Promise { const context = await host.context(); - return admissionOf(context, company); + if (context.kind === "unsupported") return unsupportedRefusal(context.reason); + if (context.kind === "pilot") + return pilotSecretsAdmission(host, context, application); + return ownAdmission(context, application); } -function admissionOf( - context: VaultContext | VaultUnsupported, - company: string, -): VaultSecretsRefusal | null { - if (context.kind === "unsupported") - return context.reason === "workstation" - ? "workstation" - : "no-vault-identity"; - return context.organization !== null && - context.organization.toLowerCase() === company.toLowerCase() - ? null - : "other-organization"; -} - -/** The values of the runtime secrets `names` of an application of - * `company` (decision F46, root decision 0177): a sync with the vault first, - * so a value changed there takes effect at the next start, then the items - * of the Environment's collection. A name's value is the login password of - * the one item named exactly so, of the connected organization, in the - * connected collection. Values are returned to the caller only; the +/** The values of the runtime secrets `names` of an application (decision + * F46, root decision 0177): a sync first, then the one item named exactly + * so anywhere in the Environment's own vault (any of its collections), its + * login password the value. Values are returned to the caller only; the * journal gets the outcome and a fixed reason. */ export async function vaultSecrets( host: VaultHost, - input: Readonly<{ company: string; names: readonly string[] }>, + input: SecretApplication & Readonly<{ names: readonly string[] }>, ): Promise { - const result = await readSecrets(host, input); + const result = await readVaultSecrets(host, input); host.journal?.({ operation: "secrets", outcome: result.kind === "vault-secrets" ? "read" : "refused", @@ -1101,73 +771,29 @@ export async function vaultSecrets( return result; } -async function readSecrets( +async function readVaultSecrets( host: VaultHost, - input: Readonly<{ company: string; names: readonly string[] }>, + input: SecretApplication & Readonly<{ names: readonly string[] }>, ): Promise { const refuse = (reason: VaultSecretsRefusal): VaultSecretsResult => ({ kind: "vault-secrets-refused", reason, }); const context = await host.context(); - const admission = admissionOf(context, input.company); - if (admission !== null || context.kind === "unsupported") - return refuse(admission ?? "no-vault-identity"); - const sessionRefusal = ( - reason: Extract["reason"], - ): VaultSecretsRefusal => - reason === "busy" - ? "busy" - : reason === "unlock-failed" - ? "locked" - : "not-connected"; - let connected = await connectedSession(host, context); - if (!connected.ok) return refuse(sessionRefusal(connected.reason)); - let synced = await connected.bw.sync(connected.session); - // Replaced by another bw run since the check: once more. - if (!synced.ok && synced.reason === "locked") { - connected = await connectedSession(host, context); - if (!connected.ok) return refuse(sessionRefusal(connected.reason)); - synced = await connected.bw.sync(connected.session); - } - if (!synced.ok) - return refuse( - synced.reason === "unauthenticated" || - synced.reason === "invalid-credentials" - ? "not-connected" - : synced.reason === "locked" - ? "locked" - : synced.reason === "unreachable" || synced.reason === "timeout" - ? "unreachable" - : "vault-failed", - ); - const { organizationId, collectionId } = connected; - const items = await connected.bw.secretItems( - connected.session, - { organizationId, collectionId }, - new Set(input.names), + if (context.kind === "unsupported") + return refuse(unsupportedRefusal(context.reason)); + if (context.kind === "pilot") return pilotSecrets(host, context, input); + const admission = ownAdmission(context, input); + if (admission !== null) return refuse(admission); + const paths = ownPaths(host, context); + const ready = await connectedAccount(paths, context); + if (ready === null) return refuse("not-connected"); + const read = await readSecrets( + () => sharedSession(host, paths, ready.account), + { organizationId: ready.recorded.organizationId }, + input.names, ); - if (!items.ok) - return refuse(items.reason === "locked" ? "locked" : "vault-failed"); - const secrets = new Map(); - for (const name of input.names) { - const matches = items.value.filter( - (item) => - item.name === name && - item.organizationId === organizationId && - item.collectionIds.includes(collectionId), - ); - const [only] = matches; - secrets.set( - name, - only === undefined - ? { kind: "absent", reason: "missing" } - : matches.length > 1 - ? { kind: "absent", reason: "ambiguous" } - : only.password === null || only.password === "" - ? { kind: "absent", reason: "empty" } - : { kind: "value", value: only.password }, - ); - } - return { kind: "vault-secrets", secrets }; + return read.ok + ? { kind: "vault-secrets", secrets: read.secrets } + : refuse(read.reason); } diff --git a/src/vault/host.ts b/src/vault/host.ts index e09ab2c69..692c5c6be 100644 --- a/src/vault/host.ts +++ b/src/vault/host.ts @@ -2,7 +2,7 @@ import { isAbsolute, join } from "node:path"; import { withFolderReadLock } from "../folder/lock"; import { inspectOwnedDirectory } from "../folder/owned-directory"; import { readFolderState } from "../folder/read-state"; -import { presetKinds, teamLabel } from "../launchpad/shell-document"; +import { presetKinds } from "../launchpad/shell-document"; import { bindMachineOperator, MachineContextError, @@ -13,7 +13,6 @@ import { type HostedOperatorSources, readLinuxOperator, } from "../machine/operator"; -import { readFolderCatalog } from "../organizations/catalog"; import type { ToolRunner } from "../tools/status"; import { resolveInstallBase } from "../update/base"; import { @@ -25,13 +24,15 @@ import { vaultStateDirectory, } from "./context"; import type { VaultHost, VaultJournalEntry } from "./flow"; +import { type PilotContext, pilotContextOf } from "./legacy-0197/context"; -// The production composition of the Environment vault (decision F43): the -// facts of this Remote Environment from its root-issued handover, read anew -// for every operation, and the kind and name of the Environment from its -// Folder. Only the handover's declared operator, in a hosted Folder on Linux, -// has a vault account; everything else is a workstation of the second wave -// or a handover that cannot be trusted, and refuses before anything runs. +// The production composition of the Environment vault (decisions F43, F52): +// the facts of this Remote Environment from its root-issued handover, read +// anew for every operation, and the kind of the Environment from its Folder. +// Only the handover's declared operator, in a hosted Folder on Linux, has a +// vault; everything else is a workstation of the second wave or a handover +// that cannot be trusted, and refuses before anything runs. A handover that +// names no vault yet may still be a 0197 pilot's (legacy-0197/). const unsupported = (reason: VaultUnsupportedReason): VaultUnsupported => Object.freeze({ kind: "unsupported", reason }); @@ -46,24 +47,18 @@ export async function readVaultContext( home: string | undefined; sources?: HostedOperatorSources | undefined; }>, -): Promise { +): Promise { if (input.platform !== "linux" || input.folder === undefined) return unsupported("workstation"); const folder = input.folder; let preset: keyof typeof presetKinds; - let machine: Awaited< - ReturnType - >["preferences"]["machine"]; try { await inspectOwnedDirectory(folder); const state = join(folder, ".lazurio"); - ({ preset, machine } = await withFolderReadLock(state, async () => { + preset = await withFolderReadLock(state, async () => { const { preferences } = await readFolderState(state); - return { - preset: preferences.preset.name, - machine: preferences.machine, - }; - })); + return preferences.preset.name; + }); } catch { return unsupported("folder-unreadable"); } @@ -96,16 +91,12 @@ export async function readVaultContext( : "handover-unreadable", ); } - // The Environment's own label, as the rail names it: a Team's or a - // persona's display name from the Organization's catalog, when the Folder - // holds it; otherwise its kind's name. - const catalog = await readFolderCatalog(folder).catch(() => null); - const label = catalog === null ? null : teamLabel(machine, kind, catalog); - return vaultContextOf({ - handover, - kind: kind as VaultEnvironmentKind, - label, - }); + const environment = kind as VaultEnvironmentKind; + const own = vaultContextOf({ handover, environment }); + if (own.kind !== "unsupported") return own; + // No vault named yet: an Environment connected the 0197 way keeps reading + // its collection until its handover names its own vault. + return pilotContextOf({ handover, environment }) ?? own; } /** The vault of this process: its home, its install base and `~/.local/bin`, @@ -150,8 +141,8 @@ export function processVaultHost( sources: input.sources, }); }, - directory: (identity) => - vaultStateDirectory(identity, home ?? "/nonexistent", input.env), + directory: (host, key) => + vaultStateDirectory(host, key, home ?? "/nonexistent", input.env), base: base ?? "/nonexistent", bin: join(home ?? "/nonexistent", ".local", "bin"), home: home ?? "/nonexistent", diff --git a/src/vault/legacy-0197/README.md b/src/vault/legacy-0197/README.md new file mode 100644 index 000000000..98848695f --- /dev/null +++ b/src/vault/legacy-0197/README.md @@ -0,0 +1,36 @@ +# Frozen: the 0197 pilot vault, read only + +Root decision 0198 gives every Environment its own vault (decision F52 in +`docs/decisions.md`, the core in `../flow.ts`). A few Environments were connected +earlier the 0197 way (decision F43): an account `vaultwarden@` +that a person invited into a collection of their own organization, the collection +recorded by its ID beside the account in +`${XDG_STATE_HOME:-~/.local/state}/lazurio/vault///`. + +This folder keeps exactly those Environments working, read only and as before, while +their Machine handover names no `vault`: + +- `context.ts` says where such an account is, derived as F43 derived it: the vault + from `network.headscale_server_url`, the address from the hosted entry. +- `pilot.ts` reads it: the status (connected, revoked, unreachable or failed), the one + shared session unlocked for agents (`lazurio vault env`), and the runtime secrets of + decision F46 from the recorded collection, under F46's rule of 0197 (only the + owning Organization's applications; never a Personalspace module). + +Nothing here connects an Environment, registers an account, confirms a member, adopts +a collection by its name or disconnects, and nothing of the pilot is written but the +shared session. When the handover gains `vault`, the Environment's own vault is set up +with the new account in a directory of its own, and this pilot's directory stays +untouched for the move of its items (DEV-6631 task 649). + +## Deletion condition + +Delete this folder when both hold: + +1. every Environment's handover carries `vault`, and +2. DEV-6631 task 649 has moved every pilot's items into its Environment's own vault. + +Deleting it means removing this folder, the `pilotContextOf` fallback in `../host.ts`, +the `context.kind === "pilot"` branches and the `PilotContext` member of +`VaultHost.context` in `../flow.ts`, and the pilot tests +(`tests/vault-pilot.test.ts`). Nothing else depends on it. diff --git a/src/vault/legacy-0197/context.ts b/src/vault/legacy-0197/context.ts new file mode 100644 index 000000000..314fb3465 --- /dev/null +++ b/src/vault/legacy-0197/context.ts @@ -0,0 +1,92 @@ +import type { MachineContext } from "../../machine/context"; +import { environmentIdOf } from "../../shell/contract"; +import type { VaultEnvironmentKind } from "../context"; + +// FROZEN (README.md here): where a 0197 pilot's account lives, derived as +// decision F43 derived it, so an Environment connected the 0197 way keeps +// reading its collection until its handover carries `vault` and DEV-6631 +// task 649 has moved its items. Pure; nothing here reads a file. + +export type PilotContext = Readonly<{ + kind: "pilot"; + /** `https://vaultwarden.` of the handover's + * `https://headscale.`. */ + vault: string; + host: string; + /** `..lazurio.io` or `.lazurio.io`: the key of the + * pilot's state directory. */ + address: string; + /** `vaultwarden@
` */ + account: string; + environment: VaultEnvironmentKind; + /** The Organization that owns the Environment, null for a person's. */ + organization: string | null; +}>; + +const hostedDomain = "lazurio.io"; +const dnsLabel = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; + +/** The vault of a network from its tailnet control server: only + * `https://headscale.` (an optional trailing slash, nothing else) gives + * `https://vaultwarden.`; anything else is none. */ +export function pilotVaultOf(controlServer: string): string | null { + let url: URL; + try { + url = new URL(controlServer); + } catch { + return null; + } + const written = controlServer.toLowerCase(); + if ( + url.protocol !== "https:" || + url.username !== "" || + url.password !== "" || + url.port !== "" || + (written !== url.origin && written !== `${url.origin}/`) + ) + return null; + const labels = url.hostname.split("."); + if ( + labels.length < 3 || + labels[0] !== "headscale" || + !labels.every((label) => dnsLabel.test(label)) + ) + return null; + return `https://${["vaultwarden", ...labels.slice(1)].join(".")}`; +} + +/** Where a 0197 pilot account of this Environment would be, or null when + * the handover gives no address or no vault the 0197 way. */ +export function pilotContextOf( + input: Readonly<{ + handover: MachineContext; + environment: VaultEnvironmentKind; + }>, +): PilotContext | null { + const { handover } = input; + const origin = handover.entry?.launchpad.external_origin; + const id = origin === undefined ? null : environmentIdOf(origin); + if (id === null) return null; + // A personal Environment is one label, an Organization's two. + if ( + id.split(".").length !== (handover.machine.kind === "personal-vm" ? 1 : 2) + ) + return null; + const controlServer = handover.network?.headscale_server_url; + const vault = + controlServer === undefined ? null : pilotVaultOf(controlServer); + if (vault === null) return null; + const address = `${id}.${hostedDomain}`; + return Object.freeze({ + kind: "pilot", + vault, + host: new URL(vault).hostname, + address, + account: `vaultwarden@${address}`, + environment: input.environment, + organization: + handover.owner.kind === "organization" + ? handover.owner.organization + : null, + }); +} diff --git a/src/vault/legacy-0197/pilot.ts b/src/vault/legacy-0197/pilot.ts new file mode 100644 index 000000000..949b6254b --- /dev/null +++ b/src/vault/legacy-0197/pilot.ts @@ -0,0 +1,319 @@ +import { parseUniqueJson } from "../../providers/unique-json"; +import type { BwCli } from "../bw"; +import type { VaultHost } from "../flow"; +import { pinnedInstalled } from "../install"; +import { + cliOf, + lockMs, + readSecrets, + sharedSession, + signedInAs, + usableSession, + withLock, +} from "../session"; +import { + accountOf, + failedStatus, + type SecretApplication, + unsupportedStatus, + type VaultEnvResult, + type VaultFacts, + type VaultSecretsRefusal, + type VaultSecretsResult, + type VaultStatus, +} from "../status"; +import { + isReady, + isVaultId, + plainObject, + type ReadyAccount, + readOwned, + readSession, + type VaultPaths, + vaultPaths, +} from "../store"; +import type { PilotContext } from "./context"; + +// FROZEN (README.md here): an Environment connected the 0197 way (decision +// F43) keeps working, read only, exactly as before, until its handover names +// its own vault: its status (connected, revoked, unreachable or failed), the +// one shared session unlocked for its agents, and the runtime secrets of +// decision F46 from the collection it recorded. Nothing here connects, +// registers, confirms, adopts a collection by its name or disconnects, and +// no file of the pilot is written but the shared session. + +type Pilot = Readonly<{ + paths: VaultPaths; + account: ReadyAccount; + organizationId: string; + collectionId: string; +}>; + +/** The record of a 0197 connection, as F43 wrote it; anything else is no + * record. */ +async function pilotRecord( + paths: VaultPaths, +): Promise | null> { + try { + const text = await readOwned(paths.record); + if (text === null) return null; + const value = plainObject(parseUniqueJson(text)); + if ( + value === null || + Object.keys(value).sort().join() !== + "collectionId,fingerprint,organizationId" || + !isVaultId(value.organizationId) || + !isVaultId(value.collectionId) + ) + return null; + return { + organizationId: value.organizationId, + collectionId: value.collectionId, + }; + } catch { + return null; + } +} + +/** The pilot of this Environment: its own readable, ready account file and + * a recorded collection, in the directory F43 keyed by the Environment's + * address. Null when it was never connected (or was disconnected): then the + * Environment has no vault yet. */ +async function pilotOf( + host: VaultHost, + context: PilotContext, +): Promise { + const paths = vaultPaths(host.directory(context.host, context.address)); + const account = await accountOf(paths, context); + if ( + account === "unreadable" || + account === "mismatch" || + account === null || + !isReady(account) + ) + return null; + const record = await pilotRecord(paths); + return record === null ? null : { paths, account, ...record }; +} + +const factsOf = (context: PilotContext): VaultFacts => ({ + vault: context.vault, + account: context.account, + name: null, + team: context.environment === "team", + origin: "pilot-0197", +}); + +/** The recorded collection in bw's copy, in an organization the account is + * a confirmed member of, or gone. */ +async function observe( + bw: BwCli, + session: string, + pilot: Pilot, + facts: VaultFacts, +): Promise { + const organizations = await bw.organizations(session); + if (!organizations.ok) + return organizations.reason === "locked" || + organizations.reason === "unauthenticated" + ? organizations.reason + : failedStatus(facts, "status", organizations.reason); + const collections = await bw.collections(session); + if (!collections.ok) + return collections.reason === "locked" || + collections.reason === "unauthenticated" + ? collections.reason + : failedStatus(facts, "status", collections.reason); + const organization = organizations.value.find( + (entry) => entry.id === pilot.organizationId && entry.status === 2, + ); + const visible = collections.value.some( + (entry) => + entry.id === pilot.collectionId && + entry.organizationId === pilot.organizationId, + ); + if (organization === undefined || !visible) + return { kind: "vault-status", state: "revoked", ...facts }; + const items = await bw.itemCount(session); + return { + kind: "vault-status", + state: "connected", + ...facts, + organizationId: pilot.organizationId, + collectionId: pilot.collectionId, + organization: organization.name, + items: items.ok ? items.value : null, + }; +} + +const lockedStatus = (facts: VaultFacts, pilot: Pilot): VaultStatus => ({ + kind: "vault-status", + state: "connected", + ...facts, + organizationId: pilot.organizationId, + collectionId: pilot.collectionId, + organization: null, + items: null, + locked: true, +}); + +/** The pilot's status from bw's local copy: no network, no mutation. */ +export async function pilotStatus( + host: VaultHost, + context: PilotContext, +): Promise { + const pilot = await pilotOf(host, context); + if (pilot === null) return unsupportedStatus("no-vault"); + const facts = factsOf(context); + if (!(await pinnedInstalled(host.base, host.pin))) + return failedStatus(facts, "install", "not-installed"); + const bw = cliOf(host, pilot.paths); + const session = await readSession(pilot.paths).catch(() => null); + const state = await bw.status(session); + if (state.ok && !signedInAs(state.value, pilot.account)) + return failedStatus(facts, "sign-in", "signed-out"); + if (session === null) return lockedStatus(facts, pilot); + const seen = await observe(bw, session, pilot, facts); + if (seen === "locked") return lockedStatus(facts, pilot); + if (seen === "unauthenticated") + return failedStatus(facts, "sign-in", "signed-out"); + return seen; +} + +/** A sync, a new unlock when the session is no longer the unlocked one, and + * the status after it. */ +export async function pilotRefresh( + host: VaultHost, + context: PilotContext, +): Promise { + const pilot = await pilotOf(host, context); + if (pilot === null) return unsupportedStatus("no-vault"); + if (!(await pinnedInstalled(host.base, host.pin))) + return pilotStatus(host, context); + const facts = factsOf(context); + return withLock( + pilot.paths, + host.lockMs ?? lockMs, + () => pilotStatus(host, context), + async () => { + const journal = (status: VaultStatus) => { + host.journal?.({ + operation: "refresh", + outcome: status.state, + ...("reason" in status ? { reason: status.reason } : {}), + }); + return status; + }; + const bw = cliOf(host, pilot.paths); + let session = await usableSession(host, bw, pilot.paths, pilot.account); + if (!session.ok) + return journal( + failedStatus( + facts, + "sign-in", + session.reason === "unauthenticated" + ? "signed-out" + : session.reason, + ), + ); + let synced = await bw.sync(session.session); + // Unlocked by another bw run since the check: unlock once more. + if (!synced.ok && synced.reason === "locked" && !session.fresh) { + session = await usableSession(host, bw, pilot.paths, pilot.account); + if (!session.ok) + return journal(failedStatus(facts, "sign-in", session.reason)); + synced = await bw.sync(session.session); + } + if (!synced.ok) { + if (synced.reason === "unauthenticated") + return journal(failedStatus(facts, "sign-in", "signed-out")); + if (synced.reason === "invalid-credentials") + return journal({ kind: "vault-status", state: "revoked", ...facts }); + if (synced.reason === "spawn-failed") + return journal(failedStatus(facts, "sync", synced.reason)); + return journal({ + kind: "vault-status", + state: "unreachable", + ...facts, + reason: synced.reason, + }); + } + const seen = await observe(bw, session.session, pilot, facts); + if (seen === "locked" || seen === "unauthenticated") + return journal(failedStatus(facts, "status", seen)); + return journal(seen); + }, + ); +} + +/** The shared session and the pilot's recorded ids, for an agent's shell. */ +export async function pilotEnv( + host: VaultHost, + context: PilotContext, +): Promise { + const pilot = await pilotOf(host, context); + if (pilot === null) return { kind: "vault-env-refused", reason: "no-vault" }; + const shared = await sharedSession(host, pilot.paths, pilot.account); + if (!shared.ok) return { kind: "vault-env-refused", reason: shared.reason }; + return { + kind: "vault-env", + env: { + BITWARDENCLI_APPDATA_DIR: pilot.paths.data, + BW_SESSION: shared.session, + LAZURIO_VAULT_ORGANIZATION_ID: pilot.organizationId, + LAZURIO_VAULT_COLLECTION_ID: pilot.collectionId, + }, + }; +} + +/** F46's rule of 0197, frozen: an application of the Organization that owns + * the Environment (the collection is that Organization's); never a + * Personalspace module, never on a personal Environment. */ +function admission( + context: PilotContext, + application: SecretApplication, +): VaultSecretsRefusal | null { + if (application.personalspace) return "personalspace"; + return context.organization !== null && + context.organization.toLowerCase() === application.company.toLowerCase() + ? null + : "other-organization"; +} + +/** Whether an application may read the pilot's collection, as far as is + * known without running bw: a pilot that is not there is no vault. */ +export async function pilotSecretsAdmission( + host: VaultHost, + context: PilotContext, + application: SecretApplication, +): Promise { + if ((await pilotOf(host, context)) === null) return "no-vault-identity"; + return admission(context, application); +} + +/** The runtime secrets from the recorded collection, as F46 read them. */ +export async function pilotSecrets( + host: VaultHost, + context: PilotContext, + input: SecretApplication & Readonly<{ names: readonly string[] }>, +): Promise { + const refuse = (reason: VaultSecretsRefusal): VaultSecretsResult => ({ + kind: "vault-secrets-refused", + reason, + }); + const pilot = await pilotOf(host, context); + if (pilot === null) return refuse("no-vault-identity"); + const refusal = admission(context, input); + if (refusal !== null) return refuse(refusal); + const read = await readSecrets( + () => sharedSession(host, pilot.paths, pilot.account), + { + organizationId: pilot.organizationId, + collectionId: pilot.collectionId, + }, + input.names, + ); + return read.ok + ? { kind: "vault-secrets", secrets: read.secrets } + : refuse(read.reason); +} diff --git a/src/vault/organization.ts b/src/vault/organization.ts new file mode 100644 index 000000000..f9a678b32 --- /dev/null +++ b/src/vault/organization.ts @@ -0,0 +1,252 @@ +import { + apiKeyLogin, + type Device, + encrypt, + makeKeyPair, + publicKeyOf, + randomBytes, + rsaEncrypt, + symmetricKey, + unlockPrivateKey, + type VaultClient, + VaultwardenError, + vaultRequest, +} from "./register"; +import { + isPublicKey, + isVaultId, + plainObject, + type ReadyAccount, + type VaultRecord, +} from "./store"; + +// The Environment's own vault (root decision 0198 point 1, decision F52): its +// own organization in the network's Lazurio Vaultwarden, created by its +// technical account, which is its only Owner, and remembered by ID; names +// never decide what it is. bw cannot create an organization, so this asks +// the vault's API as the account (its API key), with the requests the web +// vault sends; the DEV-6631 study of 2026-10-12 proved them against +// Vaultwarden 1.37.4-lazurio.1 (its `scripts/org.ts`). Nothing secret is +// returned or kept: the organization key exists in memory during its +// creation, then only in the vault, encrypted to the account's own key. + +/** The first collection of every Environment's vault, where agents keep + * what they create (decision F52). */ +export const agentsCollection = "Agenti"; + +/** A membership the vault reports as confirmed (status 2): the account holds + * the organization's key. */ +const confirmed = 2; + +export type OwnVault = + | Readonly<{ + kind: "ready"; + organizationId: string; + /** The collection Agenti, by its ID. */ + collectionId: string; + /** Created in this run. */ + created: boolean; + /** Renamed to the handover's name in this run. */ + renamed: boolean; + }> + /** The recorded organization is no longer the account's: only the + * network's operator can delete it or remove the account from it (0198 + * point 2), so nothing is created in its place. */ + | Readonly<{ kind: "gone" }> + /** The organization's collections do not say which one is Agenti (an + * organization recognized by its receipt after other collections were + * added): nothing is guessed by a name. */ + | Readonly<{ kind: "collection-unknown" }>; + +type Membership = Readonly<{ id: string; name: string }>; + +const unexpected = () => new VaultwardenError("unexpected"); + +/** The organizations the account is a confirmed member of, from its + * profile; every entry must read, or the whole answer is unexpected. */ +function membershipsOf(profile: unknown): Membership[] { + const value = plainObject(profile); + if (value === null || !Array.isArray(value.organizations)) throw unexpected(); + return value.organizations.flatMap((entry: unknown) => { + const organization = plainObject(entry); + if ( + organization === null || + !isVaultId(organization.id) || + typeof organization.name !== "string" || + organization.name.length > 512 || + typeof organization.status !== "number" + ) + throw unexpected(); + return organization.status === confirmed + ? [{ id: organization.id, name: organization.name }] + : []; + }); +} + +/** + * Makes the account's own vault exist, as the record and the handover say, + * and returns it: + * + * - recorded: the organization of the recorded ID, renamed when its name is + * not the handover's `vault.name`; gone when the account no longer belongs + * to it (never replaced); + * - not recorded: created with `POST /api/organizations`: a new organization + * key (64 random bytes) RSA-OAEP-encrypted to the account's own public key, + * which is derived from its own private key (so the key is one this + * Environment can open, whatever the server says); the organization's RSA + * key pair, its private key wrapped by the organization key; the billing + * e-mail the account; the name `vault.name`; and the first collection, + * Agenti, its name encrypted with the organization key. Its public key is + * recorded first as the creation's receipt, so a creation whose answer was + * lost is recognized by it afterwards and never made twice; + * - Agenti: the one collection of the organization, by its ID. + * + * Every step is saved as soon as it is known; a step the vault refuses + * throws a `VaultwardenError` and the next run goes on from the record. + */ +export async function ensureOwnVault( + input: Readonly<{ + client: VaultClient; + server: string; + account: ReadyAccount; + name: string; + device: Device; + record: VaultRecord; + save: (record: VaultRecord) => Promise; + }>, +): Promise { + const { account, client, server } = input; + const login = await apiKeyLogin(client, { + serverUrl: server, + clientId: account.clientId, + clientSecret: account.clientSecret, + device: input.device, + }); + const ask = ( + path: string, + options: Parameters[3] = {}, + ) => + vaultRequest(client, server, path, { + ...options, + token: login.accessToken, + }); + let record = input.record; + const save = async (next: VaultRecord) => { + record = next; + await input.save(next); + }; + const memberships = membershipsOf(await ask("/api/accounts/profile")); + + // A creation whose answer was lost: its organization carries the public + // key recorded before it was asked for. + if (record.organizationId === null && record.pendingKey !== null) + for (const membership of memberships) { + const answer = plainObject( + await ask(`/api/organizations/${membership.id}/public-key`), + ); + if (answer?.publicKey === record.pendingKey) { + await save({ + organizationId: membership.id, + collectionId: null, + pendingKey: null, + }); + break; + } + } + + let organization: Membership; + let created = false; + if (record.organizationId === null) { + const privateKey = await unlockPrivateKey({ + email: account.email, + password: account.masterPassword, + protectedUserKey: login.protectedUserKey, + encryptedPrivateKey: login.encryptedPrivateKey, + iterations: login.iterations, + }); + const organizationKey = randomBytes(64); + const keys = await makeKeyPair(symmetricKey(organizationKey)); + if (!isPublicKey(keys.publicKey)) throw unexpected(); + await save({ + organizationId: null, + collectionId: null, + pendingKey: keys.publicKey, + }); + const answer = plainObject( + await ask("/api/organizations", { + json: { + name: input.name, + billingEmail: account.email, + key: await rsaEncrypt(await publicKeyOf(privateKey), organizationKey), + keys: { + publicKey: keys.publicKey, + encryptedPrivateKey: keys.encryptedPrivateKey, + }, + collectionName: await encrypt( + agentsCollection, + symmetricKey(organizationKey), + ), + // Ignored by Vaultwarden, which has one plan; the web vault sends it. + planType: 0, + }, + }), + ); + if (!isVaultId(answer?.id)) throw unexpected(); + await save({ + organizationId: answer.id, + collectionId: null, + pendingKey: null, + }); + organization = { id: answer.id, name: input.name }; + created = true; + } else { + const recorded = memberships.find( + (membership) => membership.id === record.organizationId, + ); + if (recorded === undefined) return Object.freeze({ kind: "gone" }); + organization = recorded; + } + + let collectionId = record.collectionId; + if (collectionId === null) { + const answer = plainObject( + await ask(`/api/organizations/${organization.id}/collections`), + ); + if (answer === null || !Array.isArray(answer.data)) throw unexpected(); + const ids = answer.data.map((entry: unknown) => { + const collection = plainObject(entry); + if ( + collection === null || + !isVaultId(collection.id) || + collection.organizationId !== organization.id + ) + throw unexpected(); + return collection.id; + }); + const [only] = ids; + if (only === undefined || ids.length !== 1) + return Object.freeze({ kind: "collection-unknown" }); + collectionId = only; + await save({ + organizationId: organization.id, + collectionId, + pendingKey: null, + }); + } + + let renamed = false; + if (organization.name !== input.name) { + await ask(`/api/organizations/${organization.id}`, { + method: "PUT", + json: { name: input.name, billingEmail: account.email }, + }); + renamed = true; + } + return Object.freeze({ + kind: "ready", + organizationId: organization.id, + collectionId, + created, + renamed, + }); +} diff --git a/src/vault/register.ts b/src/vault/register.ts index c9e3e7690..5670b3c0e 100644 --- a/src/vault/register.ts +++ b/src/vault/register.ts @@ -1,21 +1,20 @@ import { Buffer } from "node:buffer"; import { webcrypto } from "node:crypto"; -// The account of an Environment in its network's vault (decision F43): -// created here and signed in by its API key, so the stock Bitwarden CLI can -// run `bw login --apikey` and `bw unlock --passwordfile`. Verified end to end -// against Vaultwarden 1.37.1 and 1.37.4 with the real bw (DEV-6631, the e2e -// report of 2026-10-09); the tests check the crypto against Bitwarden's own -// vectors and the requests against a fake vault. +// The technical account of an Environment in its network's vault (decisions +// F43 and F52): created here and signed in by its API key, so the stock +// Bitwarden CLI can run `bw login --apikey` and `bw unlock --passwordfile`, +// and the core can ask the vault's API as the account (`apiKeyLogin`, +// organization.ts). Verified end to end against Vaultwarden 1.37.1 and 1.37.4 +// with the real bw (DEV-6631, the e2e report of 2026-10-09; the own vault +// against 1.37.4-lazurio.1 on 2026-10-13); the tests check the crypto against +// Bitwarden's own vectors and the requests against a fake vault. // // Server preconditions (Vaultwarden 1.37.x): -// - an Admin or Owner of the vault's organization invited exactly this -// address; -// - SMTP is off: the server then returns the registration token directly -// and, on registration, accepts the pending invitation (Invited 0 → -// Accepted 1). SIGNUPS_ALLOWED=false is fine: the invitation allows it. -// The Admin still confirms the member in their own client (the organization's -// key is handed over end to end; Accepted 1 → Confirmed 2). +// - the network pre-allowed exactly this address (`/admin/invite`, DEV-6631 +// contract C2; a 0197 pilot: an Admin of an organization invited it); +// - SMTP is off: the server then returns the registration token directly. +// SIGNUPS_ALLOWED=false is fine: the pre-allowance allows it. // // Crypto: Bitwarden "v1" account keys, WebCrypto only, no dependency. // masterKey = PBKDF2-SHA256(password, salt = trimmed lowercased @@ -207,7 +206,8 @@ export async function makeKeyPair(wrapWith: SymmetricKey) { } /** EncString type 4 (Rsa2048_OaepSha1_B64): how an organization's key is - * shared with a member's public key. Used by the tests as the Admin. */ + * shared with a member's public key; the own vault's organization key is + * handed to the account's own public key this way (organization.ts). */ export async function rsaEncrypt( publicKeyB64: string, data: Bytes, @@ -244,6 +244,53 @@ export async function rsaDecrypt( ); } +/** The SPKI public key (base64) of an RSA private key in PKCS#8: the key + * the account's own private key belongs to, so the organization key is + * encrypted to a key this Environment can open, whatever the server says. */ +export async function publicKeyOf(privateKeyPkcs8: Bytes): Promise { + const privateKey = await subtle.importKey( + "pkcs8", + privateKeyPkcs8, + RSA_OAEP_SHA1, + true, + ["decrypt"], + ); + const { n, e } = await subtle.exportKey("jwk", privateKey); + if (n === undefined || e === undefined) + throw new Error("expected an RSA private key"); + const publicKey = await subtle.importKey( + "jwk", + { kty: "RSA", n, e, alg: "RSA-OAEP", ext: true }, + RSA_OAEP_SHA1, + true, + ["encrypt"], + ); + return b64(new Uint8Array(await subtle.exportKey("spki", publicKey))); +} + +/** The account's private key from its master password and what the vault + * keeps of it: the master-key-wrapped user key (`Key`) and the user-key- + * wrapped private key (`PrivateKey`), as a client unlocks. */ +export async function unlockPrivateKey( + input: Readonly<{ + email: string; + password: string; + protectedUserKey: string; + encryptedPrivateKey: string; + iterations: number; + }>, +): Promise { + const masterKey = await deriveMasterKey( + input.password, + input.email, + input.iterations, + ); + const userKey = symmetricKey( + await decrypt(input.protectedUserKey, await stretchMasterKey(masterKey)), + ); + return decrypt(input.encryptedPrivateKey, userKey); +} + /** Everything register/finish needs; nothing here is stored outside the * request. */ export async function makeAccountKeys( @@ -284,6 +331,9 @@ export type VaultwardenFailure = /** HTTP 204 instead of a token: SMTP is on and a verification mail went * out, which an Environment account cannot receive. */ | "smtp-enabled" + /** The vault does not let this account create an organization + * (`ORG_CREATION_USERS`). */ + | "organization-refused" /** The password login was refused. */ | "invalid-credentials" /** A KDF other than PBKDF2-SHA256. */ @@ -304,6 +354,8 @@ export class VaultwardenError extends Error { } type CallOptions = Readonly<{ + /** GET without a body and POST with one, unless named. */ + method?: "GET" | "POST" | "PUT" | "DELETE"; json?: unknown; form?: Readonly>; token?: string; @@ -313,7 +365,9 @@ const requestMs = 30_000; export type VaultClient = Readonly<{ fetch?: VaultFetch | undefined }>; -async function call( +/** One request to the vault: its answer as JSON (or text), or a + * `VaultwardenError` with a fixed reason, never the vault's own words. */ +export async function vaultRequest( client: VaultClient, serverUrl: string, path: string, @@ -340,7 +394,7 @@ async function call( response = await (client.fetch ?? fetch)( serverUrl.replace(/\/+$/, "") + path, { - method: body === undefined ? "GET" : "POST", + method: options.method ?? (body === undefined ? "GET" : "POST"), headers, ...(body === undefined ? {} : { body }), redirect: "error", @@ -370,6 +424,8 @@ async function call( throw new VaultwardenError("not-invited", response.status); if (/too many/i.test(message)) throw new VaultwardenError("rate-limited", response.status); + if (/not allowed to create organizations/i.test(message)) + throw new VaultwardenError("organization-refused", response.status); if ( path === "/identity/connect/token" || /username or password is incorrect|invalid_grant/i.test(message) @@ -410,7 +466,7 @@ export async function registerAccount( }>, ): Promise> { const email = normalizeEmail(options.email); - const token = await call( + const token = await vaultRequest( client, options.serverUrl, "/identity/accounts/register/send-verification-email", @@ -426,27 +482,32 @@ export async function registerAccount( if (typeof token !== "string" || token === "") throw new VaultwardenError("smtp-enabled"); const keys = await makeAccountKeys(email, options.password); - await call(client, options.serverUrl, "/identity/accounts/register/finish", { - json: { - email, - emailVerificationToken: token, - masterPasswordHint: null, - userAsymmetricKeys: { - publicKey: keys.publicKey, - encryptedPrivateKey: keys.encryptedPrivateKey, - }, - masterPasswordAuthentication: { - kdf: keys.kdf, - salt: email, - masterPasswordAuthenticationHash: keys.masterPasswordHash, - }, - masterPasswordUnlock: { - kdf: keys.kdf, - salt: email, - masterKeyWrappedUserKey: keys.protectedUserKey, + await vaultRequest( + client, + options.serverUrl, + "/identity/accounts/register/finish", + { + json: { + email, + emailVerificationToken: token, + masterPasswordHint: null, + userAsymmetricKeys: { + publicKey: keys.publicKey, + encryptedPrivateKey: keys.encryptedPrivateKey, + }, + masterPasswordAuthentication: { + kdf: keys.kdf, + salt: email, + masterPasswordAuthenticationHash: keys.masterPasswordHash, + }, + masterPasswordUnlock: { + kdf: keys.kdf, + salt: email, + masterKeyWrappedUserKey: keys.protectedUserKey, + }, }, }, - }); + ); return { email, publicKey: keys.publicKey }; } @@ -463,7 +524,7 @@ export async function passwordLogin( ): Promise { const { serverUrl, password, device } = options; const email = normalizeEmail(options.email); - const prelogin = (await call( + const prelogin = (await vaultRequest( client, serverUrl, "/identity/accounts/prelogin", @@ -483,20 +544,31 @@ export async function passwordLogin( throw new VaultwardenError("unsupported-kdf"); const masterKey = await deriveMasterKey(password, email, iterations); const masterPasswordHash = await makeMasterPasswordHash(masterKey, password); - const token = (await call(client, serverUrl, "/identity/connect/token", { - form: { - grant_type: "password", - scope: "api offline_access", - client_id: "cli", - username: email, - password: masterPasswordHash, - deviceType: String(device.type), - deviceIdentifier: device.identifier, - deviceName: device.name, + const token = (await vaultRequest( + client, + serverUrl, + "/identity/connect/token", + { + form: { + grant_type: "password", + scope: "api offline_access", + client_id: "cli", + username: email, + password: masterPasswordHash, + deviceType: String(device.type), + deviceIdentifier: device.identifier, + deviceName: device.name, + }, }, - })) as Record | null; + )) as Record | null; const accessToken = token?.access_token; if (typeof accessToken !== "string") throw new VaultwardenError("unexpected"); + const userId = subjectOf(accessToken); + return { serverUrl, email, userId, accessToken, masterPasswordHash }; +} + +/** The account id an access token was issued for (its `sub`). */ +function subjectOf(accessToken: string): string { let userId: unknown; try { userId = JSON.parse( @@ -509,7 +581,7 @@ export async function passwordLogin( } if (typeof userId !== "string" || !/^[0-9a-f-]{36}$/.test(userId)) throw new VaultwardenError("unexpected"); - return { serverUrl, email, userId, accessToken, masterPasswordHash }; + return userId; } /** The personal API key for BW_CLIENTID / BW_CLIENTSECRET: created on the @@ -518,12 +590,89 @@ export async function fetchApiKey( client: VaultClient, login: Login, ): Promise> { - const result = (await call(client, login.serverUrl, "/api/accounts/api-key", { - token: login.accessToken, - json: { masterPasswordHash: login.masterPasswordHash }, - })) as Record | null; + const result = (await vaultRequest( + client, + login.serverUrl, + "/api/accounts/api-key", + { + token: login.accessToken, + json: { masterPasswordHash: login.masterPasswordHash }, + }, + )) as Record | null; const secret = result?.apiKey; if (typeof secret !== "string" || !/^[A-Za-z0-9]{8,128}$/.test(secret)) throw new VaultwardenError("unexpected"); return { clientId: `user.${login.userId}`, clientSecret: secret }; } + +/** A sign-in with the account's personal API key: what an access token for + * the vault's API costs once the account is ready, without its master + * password and also where the vault requires SSO of people + * (`SSO_ONLY_API_KEY` exempts the Environment's address shape, 0197 point 4). + * The answer also carries what unlocking the account's keys needs. */ +export type ApiKeyLogin = Readonly<{ + serverUrl: string; + userId: string; + accessToken: string; + /** `Key`: the user key wrapped by the master key (EncString type 2). */ + protectedUserKey: string; + /** `PrivateKey`: the private key wrapped by the user key. */ + encryptedPrivateKey: string; + /** PBKDF2-SHA256 iterations of the master key. */ + iterations: number; +}>; + +export async function apiKeyLogin( + client: VaultClient, + options: Readonly<{ + serverUrl: string; + clientId: string; + clientSecret: string; + device: Device; + }>, +): Promise { + const { serverUrl, device } = options; + const token = (await vaultRequest( + client, + serverUrl, + "/identity/connect/token", + { + form: { + grant_type: "client_credentials", + scope: "api", + client_id: options.clientId, + client_secret: options.clientSecret, + deviceType: String(device.type), + deviceIdentifier: device.identifier, + deviceName: device.name, + }, + }, + )) as Record | null; + const accessToken = token?.access_token; + if (typeof accessToken !== "string") throw new VaultwardenError("unexpected"); + const userId = subjectOf(accessToken); + if (options.clientId !== `user.${userId}`) + throw new VaultwardenError("unexpected"); + if (token?.Kdf !== KDF_PBKDF2_SHA256) + throw new VaultwardenError("unsupported-kdf"); + const iterations = token.KdfIterations; + if ( + typeof iterations !== "number" || + !Number.isSafeInteger(iterations) || + iterations < 5_000 || + iterations > 10_000_000 + ) + throw new VaultwardenError("unsupported-kdf"); + const wrapped = (value: unknown): value is string => + typeof value === "string" && /^2\.[A-Za-z0-9+/=|]{1,20000}$/.test(value); + if (!wrapped(token.Key) || !wrapped(token.PrivateKey)) + throw new VaultwardenError("unexpected"); + return Object.freeze({ + serverUrl, + userId, + accessToken, + protectedUserKey: token.Key, + encryptedPrivateKey: token.PrivateKey, + iterations, + }); +} diff --git a/src/vault/session.ts b/src/vault/session.ts new file mode 100644 index 000000000..e137b6083 --- /dev/null +++ b/src/vault/session.ts @@ -0,0 +1,233 @@ +import type { FileLock } from "../platform/flock"; +import { FileLockError } from "../platform/flock"; +import { type BwCli, type BwFailure, type BwStatus, bwCli } from "./bw"; +import type { VaultHost } from "./flow"; +import { pinnedBinary, pinnedInstalled } from "./install"; +import type { VaultSecret } from "./status"; +import { + lockVault, + type ReadyAccount, + readSession, + type VaultPaths, + writeSession, +} from "./store"; + +// The one unlocked session of an account (decision F43 point 5, kept by +// F52): every `bw unlock` ends the sessions before it, so the Environment +// keeps one and its agents share it. Used by the Environment's own vault and +// by the frozen 0197 pilot subset alike; nothing here decides which vault an +// Environment has. + +export const lockMs = 10_000; + +export function cliOf(host: VaultHost, paths: VaultPaths): BwCli { + return bwCli({ + binary: pinnedBinary(host.base, host.pin), + data: paths.data, + home: host.home, + path: host.path, + run: host.run, + }); +} + +/** Whether bw's profile is signed in to exactly this account at exactly this + * vault. Anything else (no sign-in, another account or vault, as after an + * agent's `bw login` in this data directory) is not the Environment's + * sign-in: it is never used, reported as connected or handed out. */ +export function signedInAs( + state: BwStatus, + account: Readonly<{ email: string; server: string }>, +): boolean { + return ( + state.status !== "unauthenticated" && + state.userEmail?.toLowerCase() === account.email && + state.serverUrl?.replace(/\/+$/, "") === account.server + ); +} + +/** `work` under the account's kernel lock, or `busy` when another holder + * keeps it past `timeoutMs`. */ +export async function withLock( + paths: VaultPaths, + timeoutMs: number, + busy: () => T | Promise, + work: () => Promise, +): Promise { + let lock: FileLock; + try { + lock = await lockVault(paths, timeoutMs); + } catch (error) { + if (error instanceof FileLockError && error.reason === "busy") + return busy(); + throw error; + } + try { + return await work(); + } finally { + await lock.release(); + } +} + +export type Session = + | Readonly<{ ok: true; session: string; fresh: boolean }> + | Readonly<{ ok: false; reason: BwFailure }>; + +/** The recorded session while it is the unlocked one, otherwise a new + * unlock, written before it is handed out. Only under the account's lock. */ +export async function usableSession( + host: VaultHost, + bw: BwCli, + paths: VaultPaths, + account: ReadyAccount, +): Promise { + const current = await readSession(paths).catch(() => null); + const state = await bw.status(current); + if (!state.ok) return { ok: false, reason: state.reason }; + if (!signedInAs(state.value, account)) + return { ok: false, reason: "unauthenticated" }; + if (state.value.status === "unlocked" && current !== null) + return { ok: true, session: current, fresh: false }; + const unlocked = await bw.unlock(account.masterPassword); + host.journal?.({ + operation: "unlock", + outcome: unlocked.ok ? "unlocked" : "failed", + ...(unlocked.ok ? {} : { reason: unlocked.reason }), + }); + if (!unlocked.ok) return unlocked; + await writeSession(paths, unlocked.value); + return { ok: true, session: unlocked.value, fresh: true }; +} + +export type SharedRefusal = + | "not-installed" + | "not-connected" + | "busy" + | "unlock-failed"; + +export type SharedSession = + | Readonly<{ ok: true; bw: BwCli; session: string }> + | Readonly<{ ok: false; reason: SharedRefusal }>; + +/** The one unlocked session of a connected account, for an agent's shell or + * a start's secrets. A session that is no longer the unlocked one is + * replaced under the account's lock; another process that replaced it + * meanwhile is trusted, so two readers never unlock twice. */ +export async function sharedSession( + host: VaultHost, + paths: VaultPaths, + account: ReadyAccount, +): Promise { + if (!(await pinnedInstalled(host.base, host.pin))) + return { ok: false, reason: "not-installed" }; + const bw = cliOf(host, paths); + const current = await readSession(paths).catch(() => null); + if (current !== null) { + const state = await bw.status(current); + if (state.ok && !signedInAs(state.value, account)) + return { ok: false, reason: "not-connected" }; + if (state.ok && state.value.status === "unlocked") + return { ok: true, bw, session: current }; + } + return withLock( + paths, + host.lockMs ?? 60_000, + (): SharedSession => ({ ok: false, reason: "busy" }), + async () => { + const session = await usableSession(host, bw, paths, account); + if (session.ok) return { ok: true, bw, session: session.session }; + return { + ok: false, + reason: + session.reason === "unauthenticated" + ? "not-connected" + : "unlock-failed", + }; + }, + ); +} + +/** Why the vault gave no values at all (decision F46): of the session, the + * sync or bw's answer. */ +export type ReadRefusal = + | "not-connected" + | "locked" + | "busy" + | "unreachable" + | "vault-failed"; + +/** The values of `names` in one scope of the vault (decision F46): a sync + * first, so a value changed in the vault takes effect at the next start, + * then the one item named exactly so in the scope, its login password the + * value. `connect` gives the shared session (again, when another bw run + * replaced it meanwhile). Values are returned to the caller only. */ +export async function readSecrets( + connect: () => Promise, + scope: Readonly<{ organizationId: string; collectionId?: string }>, + names: readonly string[], +): Promise< + | Readonly<{ ok: true; secrets: ReadonlyMap }> + | Readonly<{ ok: false; reason: ReadRefusal }> +> { + const sessionRefusal = (reason: SharedRefusal): ReadRefusal => + reason === "busy" + ? "busy" + : reason === "unlock-failed" + ? "locked" + : "not-connected"; + let connected = await connect(); + if (!connected.ok) + return { ok: false, reason: sessionRefusal(connected.reason) }; + let synced = await connected.bw.sync(connected.session); + // Replaced by another bw run since the check: once more. + if (!synced.ok && synced.reason === "locked") { + connected = await connect(); + if (!connected.ok) + return { ok: false, reason: sessionRefusal(connected.reason) }; + synced = await connected.bw.sync(connected.session); + } + if (!synced.ok) + return { + ok: false, + reason: + synced.reason === "unauthenticated" || + synced.reason === "invalid-credentials" + ? "not-connected" + : synced.reason === "locked" + ? "locked" + : synced.reason === "unreachable" || synced.reason === "timeout" + ? "unreachable" + : "vault-failed", + }; + const items = await connected.bw.secretItems( + connected.session, + scope, + new Set(names), + ); + if (!items.ok) + return { + ok: false, + reason: items.reason === "locked" ? "locked" : "vault-failed", + }; + const secrets = new Map(); + for (const name of names) { + const matches = items.value.filter( + (item) => + item.name === name && + item.organizationId === scope.organizationId && + (scope.collectionId === undefined || + item.collectionIds.includes(scope.collectionId)), + ); + const [only] = matches; + secrets.set( + name, + only === undefined + ? { kind: "absent", reason: "missing" } + : matches.length > 1 + ? { kind: "absent", reason: "ambiguous" } + : only.password === null || only.password === "" + ? { kind: "absent", reason: "empty" } + : { kind: "value", value: only.password }, + ); + } + return { ok: true, secrets }; +} diff --git a/src/vault/status.ts b/src/vault/status.ts new file mode 100644 index 000000000..bed435e1b --- /dev/null +++ b/src/vault/status.ts @@ -0,0 +1,206 @@ +import type { VaultUnsupportedReason } from "./context"; +import { readAccount, type VaultAccount, type VaultPaths } from "./store"; + +// What the vault core answers (decisions F43, F46 and F52): the status of an +// Environment's vault, what an agent's shell gets and what a start's secrets +// are, for the own vault (flow.ts) and the frozen 0197 pilot subset +// (legacy-0197/) alike. Never a secret but the session `env` hands out and +// the values a start reads. + +/** What every status of an Environment's vault says. */ +export type VaultFacts = Readonly<{ + /** The network's vault: `vault.server_url`. */ + vault: string; + /** The Environment's technical account. */ + account: string; + /** The vault's name (`vault.name`); a 0197 pilot has none. */ + name: string | null; + /** A Team's Environment: the whole Team works with its vault. */ + team: boolean; + /** `own`: the Environment's own vault (root decision 0198). `pilot-0197`: + * the collection a 0197 pilot was given in a person's organization, read + * as before until its handover names a vault and DEV-6631 task 649 moves + * its items. */ + origin: "own" | "pilot-0197"; +}>; + +/** The steps of a setup, in order. */ +export type VaultPhase = "install" | "account" | "vault" | "sign-in"; + +export type VaultFailureStage = VaultPhase | "sync" | "status"; + +export type VaultStatus = + | Readonly<{ + kind: "vault-status"; + state: "unsupported"; + reason: VaultUnsupportedReason; + }> + | (VaultFacts & + Readonly<{ + kind: "vault-status"; + /** Not set up yet; `next` is the step a setup takes first. */ + state: "not-set-up"; + next: VaultPhase; + }>) + | (VaultFacts & + Readonly<{ + kind: "vault-status"; + /** The vault refused to register the account: the network has not + * pre-allowed its address (yet), or removed the unused + * pre-allowance. A person of the network acts; nothing was left + * behind. */ + state: "not-allowed"; + }>) + | (VaultFacts & + Readonly<{ + kind: "vault-status"; + state: "connected"; + organizationId: string; + /** Agenti; a 0197 pilot's collection. */ + collectionId: string; + /** The organization's name as bw's copy holds it; null when the + * session was not unlocked (`locked`). */ + organization: string | null; + /** How many items the vault holds; null when locked. */ + items: number | null; + /** The session is not the unlocked one; refresh unlocks it. */ + locked?: true; + }>) + | (VaultFacts & + Readonly<{ + kind: "vault-status"; + /** The account no longer has the vault: its organization is gone or + * its API key is refused (only the network's operator can do + * either); a 0197 pilot's collection is no longer shared. */ + state: "revoked"; + }>) + | (VaultFacts & + Readonly<{ + kind: "vault-status"; + state: "unreachable"; + reason: string; + }>) + | (VaultFacts & + Readonly<{ + kind: "vault-status"; + state: "failed"; + stage: VaultFailureStage; + reason: string; + /** The prepared prompt of an agent who completes it. */ + fallback: "agent"; + }>); + +/** What `lazurio vault env` hands an agent's shell. */ +export type VaultEnvironment = Readonly<{ + BITWARDENCLI_APPDATA_DIR: string; + BW_SESSION: string; + LAZURIO_VAULT_ORGANIZATION_ID: string; + LAZURIO_VAULT_COLLECTION_ID: string; +}>; + +export type VaultEnvRefusal = + | VaultUnsupportedReason + | "not-installed" + | "not-connected" + | "busy" + | "unlock-failed"; + +export type VaultEnvResult = + | Readonly<{ kind: "vault-env"; env: VaultEnvironment }> + | Readonly<{ kind: "vault-env-refused"; reason: VaultEnvRefusal }>; + +export const unsupportedStatus = ( + reason: VaultUnsupportedReason, +): VaultStatus => ({ kind: "vault-status", state: "unsupported", reason }); + +export function failedStatus( + facts: VaultFacts, + stage: VaultFailureStage, + reason: string, +): VaultStatus { + return { + kind: "vault-status", + state: "failed", + ...facts, + stage, + reason, + fallback: "agent", + }; +} + +/** The account file, or a failure when it is there and unreadable or not + * this Environment's account (never replaced: it holds the only copy of the + * account's password). */ +export async function accountOf( + paths: VaultPaths, + expected: Readonly<{ account: string; vault: string }>, +): Promise { + let account: VaultAccount | null; + try { + account = await readAccount(paths); + } catch { + return "unreadable"; + } + return account !== null && + (account.email !== expected.account || account.server !== expected.vault) + ? "mismatch" + : account; +} + +/** Why no runtime secret of an application can be read from the + * Environment's vault (decision F46 as F52 amends it): a fixed code, never + * bw's output. */ +export type VaultSecretsRefusal = + /** This computer: no vault yet (the second wave of 0193). */ + | "workstation" + /** A Remote Environment without a vault (no handover vault, not its + * operator, an unreadable handover). */ + | "no-vault-identity" + /** A Personalspace application on a work Environment: it reads secrets + * only in its person's own personal Environment. */ + | "personalspace" + /** An Organization's application on a personal Environment, whose vault + * serves the Personalspace's applications only. */ + | "personal-environment" + /** An application of another Organization than the one that owns the + * work Environment. */ + | "other-organization" + /** The vault is not set up here (not installed, no account or vault, + * signed out, the access revoked). */ + | "not-connected" + /** The session could not be unlocked. */ + | "locked" + /** Another process holds the account's lock. */ + | "busy" + /** The vault cannot be reached for the sync. */ + | "unreachable" + /** bw did not answer in the shape this core reads, or did not run. */ + | "vault-failed"; + +/** Why one declared name has no value (decision F46). */ +export type VaultSecretAbsence = + /** No item of that exact name in the vault. */ + | "missing" + /** More than one such item: which one is meant is not guessed. */ + | "ambiguous" + /** The one item has no login password, or an empty one. */ + | "empty"; + +export type VaultSecret = + | Readonly<{ kind: "value"; value: string }> + | Readonly<{ kind: "absent"; reason: VaultSecretAbsence }>; + +export type VaultSecretsResult = + | Readonly<{ + kind: "vault-secrets"; + /** Every requested name, with its value or why it has none. */ + secrets: ReadonlyMap; + }> + | Readonly<{ kind: "vault-secrets-refused"; reason: VaultSecretsRefusal }>; + +/** The application that asks: the Organization it belongs to (its runtime + * `company`) and whether it is a Personalspace module. */ +export type SecretApplication = Readonly<{ + company: string; + personalspace: boolean; +}>; diff --git a/src/vault/store.ts b/src/vault/store.ts index 133aacdbe..516461740 100644 --- a/src/vault/store.ts +++ b/src/vault/store.ts @@ -5,7 +5,6 @@ import { lstat, mkdir, open, - readdir, readFile, rm, } from "node:fs/promises"; @@ -14,22 +13,20 @@ import { acquireFileLock, type FileLock } from "../platform/flock"; import { parseUniqueJson } from "../providers/unique-json"; import { syncDirectory, writeDurableFile } from "../update/durable-file"; -// The custody of one Environment vault account (decision F43): the files the -// account needs on this Environment and nothing else, written by Lazurio -// beside bw's own store in the data directory it gives bw, owner-only, in a -// directory of the account's whole identity (the vault and the Environment's -// address): +// The custody of one Environment vault account (decisions F43 and F52): the +// files the account needs on this Environment and nothing else, written by +// Lazurio beside bw's own store in the data directory it gives bw, owner-only, +// in a directory keyed by the vault and the account (context.ts): // -// /lazurio/vault/// 0700 +// /lazurio/vault/// 0700 // lock 0600, empty: the kernel lock -// of connect, refresh, unlock -// and disconnect +// of setup, refresh and unlock // bw/ 0700, BITWARDENCLI_APPDATA_DIR // data.json bw's own store // lazurio-account.json 0600, the account's secrets // lazurio-session 0600, the one BW_SESSION -// lazurio-vault.json 0600, not secret: fingerprint -// and the connected collection +// lazurio-vault.json 0600, not secret: the ids of +// the Environment's own vault // // No secret is ever written anywhere else: not to the Folder, a log, the // journal, Diagnostics or an error. @@ -74,27 +71,15 @@ export type ReadyAccount = VaultAccount & export const isReady = (account: VaultAccount): account is ReadyAccount => account.clientId !== undefined && account.clientSecret !== undefined; -/** What is not secret and saves a bw call: the account's fingerprint phrase - * and the collection it was last connected to. A recorded collection that is - * no longer seen after a sync is a revoked access. */ -export type VaultRecord = Readonly<{ - fingerprint: string | null; - organizationId: string | null; - collectionId: string | null; -}>; - const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; export const isVaultId = (value: unknown): value is string => typeof value === "string" && uuid.test(value); -/** The fingerprint phrase as `bw get fingerprint me` prints it: five words - * of the EFF list joined by hyphens (a word may hold a hyphen itself). */ -export const isFingerprint = (value: unknown): value is string => - typeof value === "string" && - value.length <= 160 && - /^[a-z]+(?:-[a-z]+){4,9}$/.test(value); /** A BW_SESSION as bw prints it: base64 of a 64-byte key. */ export const isSession = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9+/]{40,200}={0,2}$/.test(value); +/** An RSA public key as Vaultwarden keeps it: SPKI, base64. */ +export const isPublicKey = (value: unknown): value is string => + typeof value === "string" && /^[A-Za-z0-9+/]{100,2000}={0,2}$/.test(value); const accountKeys = [ "clientId", @@ -106,7 +91,7 @@ const accountKeys = [ "server", ] as const; -function plainObject(input: unknown): Record | null { +export function plainObject(input: unknown): Record | null { if (typeof input !== "object" || input === null || Array.isArray(input)) return null; const prototype = Object.getPrototypeOf(input); @@ -116,7 +101,9 @@ function plainObject(input: unknown): Record | null { } /** The account file, only in its exact form; anything else is refused, and - * nothing of it is ever echoed. */ + * nothing of it is ever echoed. Whose account it is, every caller checks + * against its own context (the handover's `vault.account`, or a 0197 + * pilot's `vaultwarden@
`). */ export function parseAccount(input: unknown): VaultAccount { const value = plainObject(input); if (value === null) throw new Error("Invalid vault account"); @@ -130,7 +117,7 @@ export function parseAccount(input: unknown): VaultAccount { return field; }; const account: VaultAccount = { - email: text("email", /^vaultwarden@[a-z0-9.-]{1,240}$/), + email: text("email", /^[a-z0-9](?:[a-z0-9-]{0,62})@[a-z0-9.-]{1,240}$/), server: text("server", /^https:\/\/[a-z0-9.-]{1,240}(?::\d{1,5})?$/), deviceIdentifier: text( "deviceIdentifier", @@ -150,7 +137,7 @@ export function parseAccount(input: unknown): VaultAccount { }); } -function serialize(value: unknown): Uint8Array { +export function serialize(value: unknown): Uint8Array { return Buffer.from(`${JSON.stringify(value, null, 2)}\n`); } @@ -166,7 +153,9 @@ export async function ensureVaultDirectories(paths: VaultPaths): Promise { } } -async function readOwned(path: string): Promise { +/** A file of the account's custody, or null when there is none. A link or + * anything but a regular file throws. */ +export async function readOwned(path: string): Promise { try { const entry = await lstat(path); if (!entry.isFile()) throw new Error("Vault file is not a regular file"); @@ -257,75 +246,63 @@ export async function writeSession( await writeDurableFile(paths.data, "lazurio-session", Buffer.from(session)); } -const emptyRecord: VaultRecord = Object.freeze({ - fingerprint: null, +/** The Environment's own vault (decision F52), not secret: its organization + * and its first collection, Agenti, by ID, which is the vault's whole + * identity (names never are). `pendingKey` is the receipt of a creation + * under way: the new organization's public key, written before it is + * created, so an organization whose answer was lost is recognized as this + * account's own afterwards and never created twice. */ +export type VaultRecord = Readonly<{ + organizationId: string | null; + collectionId: string | null; + pendingKey: string | null; +}>; + +export const emptyRecord: VaultRecord = Object.freeze({ organizationId: null, collectionId: null, + pendingKey: null, }); +/** The record, or the empty one when there is none. A record that is there + * but cannot be read throws: it may be the only memory of the vault's ID, so + * nothing is ever created in its place. */ export async function readRecord(paths: VaultPaths): Promise { - try { - const text = await readOwned(paths.record); - if (text === null) return emptyRecord; - const value = plainObject(parseUniqueJson(text)); - if ( - value === null || - Object.keys(value).sort().join() !== - "collectionId,fingerprint,organizationId" || - !(value.fingerprint === null || isFingerprint(value.fingerprint)) || - !(value.organizationId === null || isVaultId(value.organizationId)) || - !(value.collectionId === null || isVaultId(value.collectionId)) - ) - return emptyRecord; - return Object.freeze({ - fingerprint: value.fingerprint as string | null, - organizationId: value.organizationId as string | null, - collectionId: value.collectionId as string | null, - }); - } catch { - // Not secret and derivable again: an unreadable record is no record. - return emptyRecord; - } + const text = await readOwned(paths.record); + if (text === null) return emptyRecord; + const value = plainObject(parseUniqueJson(text)); + if ( + value === null || + Object.keys(value).sort().join() !== + "collectionId,organizationId,pendingKey" || + !(value.organizationId === null || isVaultId(value.organizationId)) || + !(value.collectionId === null || isVaultId(value.collectionId)) || + !(value.pendingKey === null || isPublicKey(value.pendingKey)) || + (value.collectionId !== null && value.organizationId === null) + ) + throw new Error("Invalid vault record"); + return Object.freeze({ + organizationId: value.organizationId as string | null, + collectionId: value.collectionId as string | null, + pendingKey: value.pendingKey as string | null, + }); } export async function writeRecord( paths: VaultPaths, record: VaultRecord, ): Promise { - const current = await readRecord(paths); - if ( - current.fingerprint === record.fingerprint && - current.organizationId === record.organizationId && - current.collectionId === record.collectionId - ) - return; await writeDurableFile( paths.data, "lazurio-vault.json", serialize({ - fingerprint: record.fingerprint, organizationId: record.organizationId, collectionId: record.collectionId, + pendingKey: record.pendingKey, }), ); } -/** Disconnect: bw's own store, the session and the record go; the account - * file stays, so connecting again signs the same account in. */ -export async function forgetSignIn(paths: VaultPaths): Promise { - let entries: string[]; - try { - entries = await readdir(paths.data); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return; - throw error; - } - for (const entry of entries) - if (entry !== "lazurio-account.json") - await rm(join(paths.data, entry), { recursive: true, force: true }); - await syncDirectory(paths.data); -} - /** The kernel lock of one account's mutations (src/platform/flock.ts): a * crashed holder never blocks the next one, and each holder re-reads the * files, which are always whole. */ From 79da135dec3bf3065b88484f41a54af06dd07073 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Tue, 13 Oct 2026 21:37:58 +0200 Subject: [PATCH 2/9] Vault: tests and docs for the Environment's own vault, and the drafted handover member Tests against the real consumers and the fake Vaultwarden, now with the API-key login, the profile and the organization endpoints: the setup from not allowed to connected, idempotent, renamed, a lost creation answer recognized by its receipt, a gone organization and a refused API key revoked and never replaced; the account opening its own organization key from its master password down to Agenti's name; the frozen 0197 pilot with and without `vault`, its directory untouched by the new account; the CLI; the Launchpad over HTTP and its setup at start; the handover member, an earlier Platform refusing it, and its redaction; F46 on the own vault and the vault's rule for Personalspace modules; no value or token on argv, in the journal or an answer. Docs: decision F52 (superseding F43's collection model, amending F46), environment-tools, launchpad-development, machine-handover, recovery, public-development and module-adoption. The vendored handover schema's `vault` member is aligned with the Machines shared contract and marked pending in schema-provenance.json until the Machines pull request of task 637 publishes it. Template revision base-instructions-48 for the agents' bitwarden text. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 158 +++ docs/environment-tools.md | 199 ++-- docs/launchpad-development.md | 69 +- docs/machine-handover.md | 37 +- docs/module-adoption.md | 13 +- docs/public-development.md | 12 +- docs/recovery.md | 8 +- src/folder/render.ts | 2 +- src/machine/lazurio-machine.v1.schema.json | 6 +- src/machine/schema-provenance.json | 5 +- src/recover/sanitize.ts | 4 +- .../__snapshots__/folder-manual.test.ts.snap | 56 +- .../__snapshots__/folder-render.test.ts.snap | 28 +- tests/fixtures/fake-vault.ts | 503 ++++++++-- tests/folder-template-revision.test.ts | 4 +- tests/folder-tools.test.ts | 4 +- tests/launchpad-vault.test.ts | 258 +++-- tests/module-runtime-secrets.test.ts | 132 ++- tests/recover-sanitize.test.ts | 5 + tests/runtime-secrets.test.ts | 105 +- tests/vault-cli.test.ts | 127 ++- tests/vault-context.test.ts | 264 +++-- tests/vault-flow.test.ts | 915 ++++++++---------- tests/vault-handover.test.ts | 174 ++++ tests/vault-host.test.ts | 108 ++- tests/vault-organization.test.ts | 177 ++++ tests/vault-pilot.test.ts | 453 +++++++++ tests/vault-register.test.ts | 141 +++ tests/vault-secrets.test.ts | 290 +++--- tests/vault-store.test.ts | 76 +- tests/vault-view.test.ts | 477 ++++----- 31 files changed, 3265 insertions(+), 1545 deletions(-) create mode 100644 tests/vault-handover.test.ts create mode 100644 tests/vault-organization.test.ts create mode 100644 tests/vault-pilot.test.ts diff --git a/docs/decisions.md b/docs/decisions.md index 1f116cec6..af5577c25 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -7832,6 +7832,16 @@ Verified by tests: ## F43 — The Environment vault: one Vaultwarden account per Environment, its Bitwarden CLI pinned, one session for its agents +> **Superseded in part by [F52](#f52--every-environment-owns-its-vault-its-own-organization-in-the-networks-vaultwarden-created-by-its-technical-account) +> (root decision 0198, 2026-10-13).** The account and its vault now come from the +> handover's `vault` member, and the Environment owns its vault, its own organization; +> the guessed `vaultwarden@
` account, the vault derived from Headscale, the +> collection in a person's organization recognized by its name, the Admin's invitation +> and fingerprint confirmation, the four-step dialog and the disconnect are gone. The +> pinned CLI (point 3), the custody's form (point 1, now keyed by the account) and the +> one session (point 5) stay. Environments connected the way below keep working read +> only through the frozen `src/vault/legacy-0197/` until their items move. + **Decided by Matěj 2026-10-08 and 2026-10-09 (root decision 0193, plan DEV-6631; the Settings wireframe approved in HumanAndMachine-ai/prototypes-lazurio#24); implemented in this revision for Remote Environments on Linux.** Every @@ -8484,6 +8494,15 @@ Automated Environments (Machines #382) and immediate delivery. ## F46 — Runtime secrets: declared names, read from the Environment vault before every start, fail closed +> **Amended by [F52](#f52--every-environment-owns-its-vault-its-own-organization-in-the-networks-vaultwarden-created-by-its-technical-account) +> (root decision 0198, 2026-10-13).** A value is now the login password of the one +> item named exactly like the secret anywhere in the Environment's own vault (point 2 +> below read one collection of an Organization's vault), and point 3's boundary +> becomes the vault's rule: on a work Environment the applications of the +> Organization that owns it, on a personal one the Personalspace's modules +> (`personal-environment`, `personalspace`); the open question of the Personalspace is +> answered. A 0197 pilot keeps this decision's reading unchanged. + **Proposed with issue #129 (root decision 0177, HumanAndMachines/Lazurio#480; the optional secrets of root decision 0196, the Environment ceiling); implemented in this revision.** The secrets an App of a Module needs at start (an API key of an external @@ -10549,3 +10568,142 @@ of every stack read by the Platform's own readers, every generated personal modu listed by the catalog as `personalspace/` (a Bun app executable, `python-uv` not yet, as the plan warns, `none` without an app), and the embedded templates equal to their directory. + +## F53 — Every Environment owns its vault: its own organization in the network's Vaultwarden, created by its technical account + +**Decided by the Admin on 2026-10-12 and 2026-10-13 (root decision 0198 points 1, 2, +4, 6 and 7, with 0197 points 3 and 7–9; plan DEV-6631 task 638 part A, contract C3; +the wireframe of HumanAndMachine-ai/prototypes-lazurio#33); implemented in this +revision for Remote Environments on Linux. Supersedes F43's collection model and +amends F46.** Each Environment has its own vault: its own organization in its +network's Lazurio Vaultwarden. The Environment's technical account creates it, is its +only Owner, and the Environment remembers it by ID; names never decide what it is. +The Environment sets it up itself; its agents use it freely, through the one unlocked +session of F43. + +1. **The account and the vault come from the handover.** Machines writes the + optional, closed member `vault: {server_url, account, name}` (contract C2) only for + a Platform release that reads it, as it gates `entry.environment_relay`, because a + Platform vendoring an earlier schema refuses the whole handover + ([machine handover](machine-handover.md#the-environments-own-vault-decision-f52)). + `account` is `vaultwarden-<26 lowercase base32>@`, generated + and pre-allowed by the network (`/admin/invite`) for this Environment alone; + `name` is " ", letters, digits and + single spaces, at most 50 characters, unique within the network. Nothing is + derived any more: no `vaultwarden@
`, no vault from the tailnet's control + server, no collection matched by a name, including F43's + `Environmenty/ · `. Without the member the Environment has no vault + yet and says so (`unsupported`, `no-vault`). +2. **Custody keyed by the account.** F43's files, in + `${XDG_STATE_HOME:-~/.local/state}/lazurio/vault///`, so an + account the handover replaces starts afresh and a 0197 pilot's directory, keyed by + its address, stays beside it untouched. `lazurio-vault.json` now holds the vault's + organization id, its collection Agenti's id and, while a creation is under way, + its receipt; a record that cannot be read refuses (`record-unreadable`) and nothing + is ever created over it. +3. **Registration, then the vault** (`src/vault/organization.ts`). The account is + registered by F43's flow; the network pre-allowed the address, so a refusal is + `not-allowed` (not pre-allowed yet, or an unused pre-allowance pruned). Then the + core signs in with the API key (`client_credentials`), reads the account's + confirmed organizations from its profile and, without a record, creates the vault + with `POST /api/organizations`: the organization key (64 random bytes) + RSA-OAEP-SHA1-encrypted to the account's own public key, which it derives from its + own private key unlocked by the master password (so the key is one this + Environment can open whatever the server says); the organization's RSA-2048 key + pair, its private key wrapped by the organization key; the billing e-mail, the + account; the name, `vault.name`; and the first collection, "Agenti", its name + encrypted with the organization key. bw cannot create an organization; these are + the web vault's requests, proven against 1.37.4-lazurio.1 by the DEV-6631 study of + 2026-10-12. The new organization's public key is recorded before the request: an + organization whose answer was lost is recognized by it + (`GET /api/organizations//public-key`) and never created twice. Agenti is the + organization's one collection, by its ID; several without a record of it are + `collection-unknown`, never chosen by a name. A recorded organization the account + no longer belongs to is `revoked` and is never replaced (only the network's + operator can delete it, 0198 point 2); a refused API key is `revoked` too. When + `vault.name` changes, the setup renames the organization + (`PUT /api/organizations/`). `ORG_CREATION_USERS` that leaves the account out + is `organization-refused`. +4. **The flow.** install → account → own vault → sign-in and the one shared session, + in one setup (`vaultSetup`, `src/vault/flow.ts`), idempotent and under the + account's lock. `lazurio vault setup` runs it, and so does the installed Launchpad + in the background after its start, by Executor's pattern (F44's addendum of + 2026-10-11): on a supervised base of the hosted operator (`vaultAtStart`), once, + where `setUpAtStart` says the vault needs it (not set up, its session locked, or + its name no longer the handover's); never a 0197 pilot, a revoked vault or one + whose setup stopped, which wait for the row's action or an agent. The states: + `unsupported` (with `no-vault`), `not-set-up` (with the `next` step), + `not-allowed`, `connected` (`organizationId`, `collectionId`, `organization`, + `items`; `locked`), `revoked`, `unreachable` and `failed` (`stage` now also + `vault`). `lazurio vault status` stays the one source of truth for agents and the + Launchpad. The Admin's approval, the fingerprint confirmation and their states, + the four-step dialog and its copy, the name-based adoption and the disconnect are + removed; `connect` is replaced by `setup`. +5. **The Tools row** (Settings → Tools → bitwarden) shows only the state and "Otevřít + trezor", a link to `/#/vault?organizationId=`, plus one action only + where a setup moves the vault on ("Nastavit", "Zkusit znovu", as the wireframe's + unreachable state does); no disconnect for the Environment's own vault. Czech copy + addresses people formally and says little (root decision 0199). The routes are + `POST /api/tools/bitwarden/status|refresh|setup`; a running setup answers + `202 {kind: "vault-setting-up", job, phase}` from all three. +6. **Pilot safety** (`src/vault/legacy-0197/`, frozen). A few Environments were + connected the 0197 way: an account `vaultwarden@
` in a person's + organization with a recorded collection. While such an Environment's handover + names no vault, it keeps working read only exactly as before: its status + (connected, revoked, unreachable or failed), the shared session unlocked for its + agents, and F46 from the recorded collection under F46's rule of 0197. Nothing + connects the old way any more. When its handover gains `vault`, the own vault is + set up with the new account in a directory of its own, and the pilot's directory + is left untouched for DEV-6631 task 649 to move its items. Its README names the + condition of its deletion: every Environment's handover carries `vault` and task + 649 has moved the items. +7. **Runtime secrets** (F46 as amended). A value is the login password of the one + item named exactly like the secret anywhere in the Environment's own vault (any + of its collections); secure-note fields follow with task 651. On a work + Environment the applications of the Organization that owns it read them; on a + personal Environment the Personalspace's modules do (0198 point 4: personal and + work alike); everything else is refused with its reason (`other-organization`, + `personalspace`, `personal-environment`). The catalog's check without the vault + follows the same rule. +8. **The agents' text** (the catalog entry `bitwarden`, template revision + `base-instructions-49`) says only what is true now: the Environment's own vault, + used freely by its agents; `lazurio vault status` read before anything is said + about the vault; never a secret asked for in chat. How a secret reaches the vault + (0198 point 9, paths a, b and c) follows with task 652. +9. **Recovery evidence** withholds the handover's `vault.account`, `vault.name` and + the vault's host (``, ``). + +**Honest limits.** The pre-allowed address is the one credential of the +registration: before it is registered, anyone in the Environment boundary who reads +the handover could register it, which is the boundary of root decision 0172 anyway. +Agents with full access can read the account's secrets on the Environment (F43 +point 9). Organization creation stays open to every account of the network +(`ORG_CREATION_USERS`), so people can create other organizations outside this model; +the threat model of the network's vault records it. People's access to an +Environment's vault (Správci, task 638b) is not in this revision: until then only the +Environment's account is a member of its vault. The vendored handover schema carries +the drafted `vault` member until the Machines pull request of task 637 publishes it +(`schema-provenance.json`'s `pending`). + +| Alternative | Trade-off / disposition | +| --- | --- | +| Keep a collection per Environment in an Organization's vault (F43) | An Admin's approval for every Environment and an Organization vault that holds every Environment's passwords; rejected by 0198 points 1 and 2 | +| Derive the account from the address and the vault from the tailnet | A guessable account and a convention instead of a finished value; rejected for the handover's member | +| Adopt the organization the account owns, or one named like the vault | A name or a role is not an identity; rejected for the ID and the creation's receipt | +| Encrypt the organization key to the public key the server reports | Trusts the server for the one key the Environment must open; rejected for the key derived from its own private key | +| Recreate a vault that is gone | Would hide a deletion only the network's operator can make; rejected for `revoked` | +| Keep connect, the dialog and disconnect beside the own vault | Two models of one tool; rejected, the pilot subset is read only and has a deletion condition | + +Verified by unit tests against the fake Vaultwarden (`tests/fixtures/fake-vault.ts`, +extended with the API-key login, the profile and the organization endpoints) and the +fake bw: the setup from not allowed to connected, idempotent, renamed, its lost answer +recognized by the receipt, gone and refused (`tests/vault-flow.test.ts`); the account +opening its own organization key from its master password down to Agenti's name and +the organization's private key (`tests/vault-organization.test.ts`); the pilot with +and without `vault` (`tests/vault-pilot.test.ts`); the CLI (`tests/vault-cli.test.ts`) +and the Launchpad over HTTP with its start (`tests/launchpad-vault.test.ts`); the +member, an earlier Platform refusing it and its redaction +(`tests/vault-handover.test.ts`); F46 on the own vault (`tests/vault-secrets.test.ts`, +`tests/runtime-secrets.test.ts`, `tests/module-runtime-secrets.test.ts`); no value or +token on argv, in the journal or in an answer. + diff --git a/docs/environment-tools.md b/docs/environment-tools.md index e62c92495..ad55889eb 100644 --- a/docs/environment-tools.md +++ b/docs/environment-tools.md @@ -4,7 +4,7 @@ Proposed bounded pilot procedure under accepted decision 0144. Apart from the curated installation and login of three catalog tools (decision F19, below), the -Environment vault (decision F43, below), Executor (decision F44, below) and the +Environment's own vault (decisions F43 and F52, below), Executor (decision F44, below) and the pilot of the shared GitHub App sign-in (decision F48, below), this document does not claim an implemented tool installer, authenticated harness or usable Environment. @@ -81,7 +81,7 @@ named in the generated instructions with a **tier** and a **setup mode**: | `gh` | `gh` | required: always on, never stored, cannot be disabled | launchpad | | `executor` | `executor` | required; offered in a Remote Environment on Linux (F44) | launchpad (Lazurio's own setup, below) | | `composio` | `composio` | recommended | launchpad | -| `bitwarden` | `bw` | recommended; offered in a Remote Environment on Linux (F43) | launchpad (its own flow, below) | +| `bitwarden` | `bw` | recommended; offered in a Remote Environment on Linux (F43, F52) | launchpad (its own flow, below) | | `wacli` | `wacli` | optional | launchpad | | `gogcli` | `gog` | optional; offered on a computer and in a personal Remote Environment, not in a work one (F44) | agent | | `neon` | `neon` | optional | agent | @@ -474,39 +474,41 @@ earlier temporary exception that let any account sign in on a Team VM has ended. nothing here provisions the App, its broker or a brokered `gh`. The product refuses the personal sign-in and relies on what the Machine delivers. -### The Environment vault (decision F43) - -Root decision 0193: every Environment has its own account `vaultwarden@` in the Vaultwarden of its network, its own collection with edit rights (named -as the operator likes; at a first connection the only collection the account sees is -its own, among several `Environmenty/ · `, the suggested name, decides; -once connected only its ID counts, a gone one reads as revoked, and a disconnect makes -the next connection a first one again; the 0193 addendum of 2026-10-11), and one -unlocked Bitwarden CLI -session that all its agents share. The catalog tool is `bitwarden` (command `bw`); it -has its own flow instead of F19's install and sign-in, which refuse it as +### The Environment's own vault (decisions F43 and F52) + +Root decision 0198: every Environment owns its vault, its own organization in its +network's Lazurio Vaultwarden, created by its technical account, which is its only +Owner, and remembered by ID (decision F52 supersedes F43's collection model; F43's +pinned CLI, custody and one shared session stay). The account and the vault come from +the handover's member `vault: {server_url, account, name}` (DEV-6631 contract C2), +which Machines writes only for a Platform that reads it; without it the Environment +has no vault yet (`unsupported`, `no-vault`). The catalog tool is `bitwarden` (command +`bw`); it has its own flow instead of F19's install and sign-in, which refuse it as `setup-vault`. Remote Environments on Linux only; on this computer it is the second wave (`unsupported`, `workstation`). - **Facts** (`src/vault/context.ts`, read from the handover for every operation): the - vault `https://vaultwarden.` from `network.headscale_server_url` = - `https://headscale.` (anything else refuses, `vault-unknown`), the address from - the Launchpad entry as the shell derives the Environment's id (no entry: - `no-address`), the name from the Folder's preset and the catalog (a Team's or a - persona's display name, else "Osobní", "Pracovní", "Týmový", "Automatizovaný"). Only - the handover's declared operator has the account (`not-operator`). + vault `vault.server_url`, the account `vault.account` + (`vaultwarden-<26 base32>@`, which the network generated and + pre-allowed for this Environment alone), the vault's name `vault.name` and the + Organization that owns a work Environment (`owner.organization`; none for a personal + one). Nothing is derived from the tailnet or the address any more, and no collection + is matched by a name. Only the handover's declared operator has the account + (`not-operator`). - **Custody** (`src/vault/store.ts`), written by the Platform itself, the one exception of [public development](public-development.md): - `${XDG_STATE_HOME:-~/.local/state}/lazurio/vault///` - (0700, the account's whole identity) with `lock` and `bw/` (0700, - `BITWARDENCLI_APPDATA_DIR`), which holds bw's `data.json`, `lazurio-account.json` - (0600: email, server, device identifier, master password, API key, createdAt), - `lazurio-session` (0600) and `lazurio-vault.json` (0600, not secret: fingerprint - phrase, connected organization and collection ids). An Environment whose address - changes starts with no account; an account file whose address or vault is not the - Environment's is refused by every operation, disconnect included - (`account-mismatch`): nothing of it is used, signed out or removed. Nothing else - anywhere; no secret on argv, in a log, the journal or an error. + `${XDG_STATE_HOME:-~/.local/state}/lazurio/vault///` + (0700, keyed by the account, so an account the handover replaces starts afresh and + a 0197 pilot's directory, keyed by its address, stays beside it) with `lock` and + `bw/` (0700, `BITWARDENCLI_APPDATA_DIR`), which holds bw's `data.json`, + `lazurio-account.json` (0600: email, server, device identifier, master password, API + key, createdAt), `lazurio-session` (0600) and `lazurio-vault.json` (0600, not + secret: the vault's organization id, Agenti's collection id, and a creation's + receipt while one is under way). A record that is there but cannot be read refuses + (`record-unreadable`): nothing is ever created over it. An account file whose + account or vault is not the handover's is refused by every operation + (`account-mismatch`). Nothing else anywhere; no secret on argv, in a log, the + journal or an error. - **The pinned CLI** (`src/vault/pin.ts`, `src/vault/install.ts`): bw-oss 2026.7.0 from `https://github.com/bitwarden/clients/releases/download/cli-v2026.7.0/`, the zip of the platform verified against its SHA-256 in the source, its one entry @@ -516,7 +518,7 @@ wave (`unsupported`, `workstation`). and sets `BITWARDENCLI_APPDATA_DIR` to the Environment's `bw/` and `BW_NOINTERACTION=true` unless the caller set them, so a bare `bw` never reaches a default profile or prompts for a password. An entry there that is not Lazurio's is - left alone and the connect fails as `entry-conflict`. Older pinned versions are + left alone and the setup fails as `entry-conflict`. Older pinned versions are removed afterwards. - **The account** (`src/vault/register.ts`): a password of 32 random bytes and a device identifier are written to `lazurio-account.json` before anything is sent; @@ -524,7 +526,7 @@ wave (`unsupported`, `workstation`). receiveMarketingEmails: false}` with `Accept: application/json` answers the registration token (a JSON string, or `text/plain` from 1.37.4 without that header; 204 means SMTP is on: `smtp-enabled`; "Registration not allowed or user - already exists": `awaiting-invite`, and the account file goes when its password was + already exists": `not-allowed`, and the account file goes when its password was generated in the same run, never a resumed one); `POST /identity/accounts/register/finish` with the v1 account keys (PBKDF2-SHA256 600 000, the salt the trimmed lowercased email, an RSA-2048 key pair, the user key wrapped by @@ -532,62 +534,96 @@ wave (`unsupported`, `workstation`). /identity/connect/token` (password grant with the one device identifier) and `POST /api/accounts/api-key`, whose key joins the account file. HTTP 429 is `rate-limited`; nothing retries a login. +- **The vault** (`src/vault/organization.ts`): `POST /identity/connect/token` with + `grant_type=client_credentials` (the API key, the one device identifier), `GET + /api/accounts/profile` for the organizations the account is a confirmed member of, + then by the record: the recorded organization (renamed with `PUT + /api/organizations/` `{name, billingEmail}` when its name is not `vault.name`; + gone: `revoked`, never replaced), or a new one with `POST /api/organizations` + `{name, billingEmail, key, keys: {publicKey, encryptedPrivateKey}, collectionName, + planType: 0}`: a new organization key of 64 random bytes RSA-OAEP-SHA1-encrypted to + the account's own public key (derived from its own private key, which the master + password unlocks), the organization's RSA-2048 key pair with its private key + wrapped by the organization key, the billing e-mail the account, and the first + collection "Agenti", its name encrypted with the organization key. The new + organization's public key is recorded before the request as its receipt; a creation + whose answer was lost is recognized by it (`GET /api/organizations//public-key`) + and never made twice. Agenti is the organization's one collection by its ID (`GET + /api/organizations//collections`); several, without a record of it, are + `collection-unknown`, never chosen by a name. A vault that does not let the account + create organizations (`ORG_CREATION_USERS`) is `organization-refused`; a refused API + key is `revoked`. - **bw** (`src/vault/bw.ts`): always the pinned binary with the account's `BITWARDENCLI_APPDATA_DIR`, `BW_NOINTERACTION` and `--nointeraction`; `bw config server`, `bw login --apikey` (the key in `BW_CLIENTID`/`BW_CLIENTSECRET`; the session it prints is still locked and is never read), `bw unlock --passwordfile --raw` (the file removed at once), `bw sync`, `bw list - organizations|collections|items` and `bw get fingerprint me`, each with the session - in `BW_SESSION`. bw's output never leaves the module; failures are fixed codes - (`locked`, `unauthenticated`, `unreachable`, `rate-limited`, `invalid-credentials`, - `logout-required`, `timeout`, `spawn-failed`, `unreadable`, `failed`). + file> --raw` (the file removed at once), `bw sync` and `bw list + organizations|collections|items`, each with the session in `BW_SESSION`. bw's output + never leaves the module; failures are fixed codes (`locked`, `unauthenticated`, + `unreachable`, `rate-limited`, `invalid-credentials`, `logout-required`, `timeout`, + `spawn-failed`, `unreadable`, `failed`). - **States** (`src/vault/flow.ts`, `kind: "vault-status"` with `vault`, `account`, - `collection`, `name`, `team`): `unsupported` with a reason, `not-installed`, `none` - (`registered`: the account exists, connecting again signs it in), `awaiting-invite`, - `confirming` (`fingerprint`; `organization` when an organization is confirmed but - the collection is not visible; `locked` when the session must be unlocked again), - `connected` (`fingerprint`, `organization`, `collections`, `items`), `revoked`, - `unreachable` (`reason`) and `failed` (`stage`: `install`, `account`, `sign-in`, - `sync` or `status`; `reason`; `fallback: "agent"`). `status` is local (bw's copy, no - network); `refresh` syncs first and unlocks again when the session is no longer the - unlocked one; `connect` installs, creates or resumes the account, signs bw in, - unlocks and syncs; `disconnect` signs bw out and removes its store, the session and - the record, keeping the account, and only for the Environment's own readable account - file (none, an unreadable or another account's: nothing changes). A bw profile signed - in to anything but the account at its vault is never used (status `none`, env refuses); - connecting signs it out and the account in. Mutations hold the account's kernel lock. + `name`, `team` and `origin`, `own` or `pilot-0197`): `unsupported` with a reason, + `not-set-up` (`next`: `install`, `account`, `vault` or `sign-in`), `not-allowed` + (the network has not pre-allowed the address, or removed an unused pre-allowance), + `connected` (`organizationId`, `collectionId`, `organization`, `items`; `locked` + when the session must be unlocked again), `revoked`, `unreachable` (`reason`) and + `failed` (`stage`: `install`, `account`, `vault`, `sign-in`, `sync` or `status`; + `reason`; `fallback: "agent"`). `status` is local (bw's copy, no network); `refresh` + syncs first and unlocks again when the session is no longer the unlocked one; + `setup` installs, registers or resumes the account, creates, recognizes or renames + the vault, signs bw in, unlocks and syncs, and is safe to run again. A bw profile + signed in to anything but the account at its vault is never used (status + `not-set-up`, `next: "sign-in"`; env refuses); a setup signs it out and the account + in. Mutations hold the account's kernel lock. - **CLI** (`lazurio vault`): `env [--json]` prints `export BITWARDENCLI_APPDATA_DIR=…`, - `BW_SESSION`, `LAZURIO_VAULT_ORGANIZATION_ID` and `LAZURIO_VAULT_COLLECTION_ID`, - single-quoted, for `eval "$(lazurio vault env)"`; not connected, one line on stderr, - nothing on stdout, exit 2 (`busy` and `unlock-failed` exit 1). `status`, `refresh` - and `connect [--json]` print the state (connect: exit 0 connected or confirming, 2 - waiting for a person, 1 failed or unreachable; its steps go to stderr). -- **Launchpad**: `POST /api/tools/bitwarden/status|refresh|disconnect` with `{}`, and - `POST /api/tools/bitwarden/connect` with `{}` (starts or joins the one connect) or - `{job}` (asks about it): `202 {kind: "vault-connecting", job, phase}` while it runs - (`install`, `account`, `sign-in`), then the state. A disconnect while a connect runs - is `409 busy`; an unknown job `404 job-unknown`. The journal of the unit gets - `{"scope":"tools-vault","operation":"connect|refresh|disconnect|unlock","outcome":…,"reason":…}` - only. -- **Runtime secrets** (decision F46, `vaultSecrets` in `src/vault/flow.ts`): the - module operations read the declared secrets of an application of the Organization - that owns the Environment (the vault context's `organization`, the handover's - `owner.organization`; another Organization's application is `other-organization`) - through the same one session as `env`: `bw sync`, then `bw list items - --organizationid --collectionid `, of which `secretItems` keeps only the - items of the declared names, and of those only name, organization, collections and - login password. A value is the password of the one item named exactly so in the - connected organization and collection (otherwise `missing`, `ambiguous` or - `empty`). Values go to the caller only; a refusal is a fixed code (`workstation`, - `no-vault-identity`, `other-organization`, `not-connected`, `locked`, `busy`, + `BW_SESSION`, `LAZURIO_VAULT_ORGANIZATION_ID` (the vault) and + `LAZURIO_VAULT_COLLECTION_ID` (Agenti), single-quoted, for `eval "$(lazurio vault + env)"`; not set up, one line on stderr, nothing on stdout, exit 2 (`busy` and + `unlock-failed` exit 1). `status`, `refresh` and `setup [--json]` print the state + (setup: exit 0 connected, 2 waiting for a person: no vault named, not allowed, + revoked or unsupported; 1 failed or unreachable; its steps go to stderr). `status` + is the one source of truth for agents and the Launchpad. +- **Launchpad**: `POST /api/tools/bitwarden/status|refresh` with `{}`, and `POST + /api/tools/bitwarden/setup` with `{}` (starts or joins the one setup) or `{job}` + (asks about it): `202 {kind: "vault-setting-up", job, phase}` while it runs + (`install`, `account`, `vault`, `sign-in`), then the state; status and refresh + answer a running setup the same way. An unknown job is `404 job-unknown`. The + installed Launchpad of a supervised base of the hosted operator (`vaultAtStart`, the + rule of Executor's) runs the setup in the background after its start where + `setUpAtStart` says the vault needs it: not set up, its session locked, or its name + no longer the handover's; never a 0197 pilot, a revoked or failed vault. The journal + of the unit gets `{"scope":"tools-vault","operation":"setup|refresh|unlock|vault|secrets","outcome":…,"reason":…}` + (with `"trigger":"start"` for the start's setup) only. +- **Runtime secrets** (decision F46 as F52 amends it, `vaultSecrets` in + `src/vault/flow.ts`): on a work Environment the applications of the Organization + that owns it read them, on a personal one the Personalspace's modules (root decision + 0198 point 4); another Organization's application is `other-organization`, a + Personalspace module on a work Environment `personalspace`, an Organization's + application on a personal one `personal-environment`. They are read through the + same one session as `env`: `bw sync`, then `bw list items --organizationid `, + of which `secretItems` keeps only the items of the declared names, and of those + only name, organization, collections and login password. A value is the password + of the one item named exactly so anywhere in the Environment's vault (otherwise + `missing`, `ambiguous` or `empty`). Values go to the caller only; a refusal is a + fixed code (`workstation`, `no-vault-identity`, `personalspace`, + `personal-environment`, `other-organization`, `not-connected`, `locked`, `busy`, `unreachable`, `vault-failed`). +- **0197 pilots** (`src/vault/legacy-0197/`, frozen): an Environment connected the + F43 way whose handover names no vault yet keeps working read only: its status, the + shared session for agents and F46 from the collection it recorded, with F46's rule + of 0197. It is never set up, connected, confirmed or disconnected; its directory is + left untouched once the handover names the own vault, for DEV-6631 task 649 to move + its items. Its README names the condition of its deletion. The agents' texts are the catalog entry's (`purpose` in `AGENTS.md`, `usage` in -`manual/this-machine.md`, template revision `base-instructions-34`): start with -`eval "$(lazurio vault env)"`, never `bw login`, `unlock`, `lock`, `logout` or `bw -config`, `bw sync` before reading, values straight into commands, new secrets into the -Environment's collection, nothing in the account's own vault, a missing one asked of -the Operator, and an externally visible write a Publication. +`manual/this-machine.md`, template revision `base-instructions-49`): read `lazurio +vault status` before saying anything about the vault, start with `eval "$(lazurio +vault env)"`, never `bw login`, `unlock`, `lock`, `logout` or `bw config`, `bw sync` +before reading, values straight into commands, new secrets into the Environment's +vault (Agenti), nothing in the account's own vault, never a secret asked for in chat, +and an externally visible write a Publication. How a secret reaches the vault (root +decision 0198 point 9) follows with DEV-6631 task 652. ### Executor (decision F44) @@ -865,9 +901,10 @@ Platform builds no credential broker, account registry, automatic model login or package-manager matrix (`lazurio tools` runs one tool's official update path under decision 0161 and installs only the curated catalog tools of decision F19 and the pinned Bitwarden CLI of decision F43; it is not a general updater or installer); the team -case consumes the existing upstream broker rather than adding one. The Environment -vault (F43) keeps no secret of its own: the vault is the Organization's, and the -Environment account's credentials stay in the Bitwarden CLI's own data directory. Unknown installation state receives a diagnosis +case consumes the existing upstream broker rather than adding one. The Environment's +own vault (F43, F52) keeps no secret in the Platform: the vault is the network's +Vaultwarden, and the Environment account's credentials stay beside the Bitwarden +CLI's own data directory. Unknown installation state receives a diagnosis and operator repair procedure, not an improvised privileged cleanup. Missing accounts remain an explicit pilot prerequisite, not something Machines or a profile can grant. Real Organization materialization and canonical document adoption have their separate diff --git a/docs/launchpad-development.md b/docs/launchpad-development.md index df410da2f..34c90d2ce 100644 --- a/docs/launchpad-development.md +++ b/docs/launchpad-development.md @@ -1263,8 +1263,8 @@ runtime environment the replaced Launchpad gave it (decision F26, the table in JSON, `NODE_PATH`, `NODE_ENV=development`, the runtime and Organization identity, the loopback origin of each sibling module of its Organization it declares (`LAZURIO_RUNTIME_SIBLING__ORIGIN`, F26 addendum of 2026-10-10), the value of -each runtime secret it declares, read from the Environment vault at this start -(`LAZURIO_RUNTIME_SECRET_`, F46; a required one without a value refuses the +each runtime secret it declares, read from the Environment's own vault at this start +(`LAZURIO_RUNTIME_SECRET_`, F46 as F52 amends it; a required one without a value refuses the start as `runtime-secret-unavailable`, an optional one is reported as `secretsNotProvided`), and on a hosted Machine, for the module's default app, the entrypoint's external origin @@ -1545,7 +1545,7 @@ characters escaped), Czech or English by the Folder's locale. | product | `template-revision` | `observeFolder` facts | `warn folder-newer` (a newer product rendered it), `warn revision-unknown`; an older one is `folder-refresh` | | Folder | `folder-state` | `collectRecovery` Folder state; preset and Machine kind from `observeFolder` | `fail folder-state-pending`, `-absent`, `-unrecognized`, `-unreadable` | | Folder | `machine-binding` | recorded `preferences.machine` vs `machineBinding` of the live handover | `warn machine-identity-changed`, `warn handover-changed` (digest; `machine folder-refresh`), `warn binding-absent`, `warn handover-unreadable`; `skipped not-hosted` | -| tools | `tool` | `toolsOverview` (tiers, enabled), else `toolsStatus` over the catalog | required missing `fail required-missing`; `warn recommended-missing`, `warn enabled-missing`, `warn version-unreadable`; `skipped not-enabled`; `skipped not-offered` for a missing tool Lazurio does not offer in this Environment (`toolOffered`: bitwarden outside a Remote Environment on Linux, decision F43; gogcli in a work Environment, F44); Executor is not a tool row but its own check; `signIn`/`ssh` ids with `--sign-in` | +| tools | `tool` | `toolsOverview` (tiers, enabled), else `toolsStatus` over the catalog | required missing `fail required-missing`; `warn recommended-missing`, `warn enabled-missing`, `warn version-unreadable`; `skipped not-enabled`; `skipped not-offered` for a missing tool Lazurio does not offer in this Environment (`toolOffered`: bitwarden outside a Remote Environment on Linux, decisions F43 and F52; gogcli in a work Environment, F44); Executor is not a tool row but its own check; `signIn`/`ssh` ids with `--sign-in` | | tools | `executor` | `executorStatus` ([F44](decisions.md#f44--executor-in-every-remote-environment-installed-run-and-connected-to-the-agents-by-lazurio)): the entry and its marker, `systemctl --user show` of `sh.executor.daemon.service` and its drop-in, `GET 127.0.0.1:4789/api/health`, `codex mcp get executor --json` and `~/.claude.json`; never `fail`, never in `recover` | `ok` running with the installed agents connected (context `toolVersion`, `executorService`, `codexMcp`, `claudeMcp`); `warn executor-not-installed`, `executor-outdated`, `executor-conflict`, `executor-not-running`, `executor-incomplete` (the next step is `lazurio executor setup`, or Settings → Tools → executor); `skipped not-offered` (a computer, not the operator), `skipped handover-unreadable` | | organizations | `catalog` | `readFolderCatalog` | counts of the Organizations and their modules only: the Personalspace group is never counted or named; `warn catalog-unreadable` | | organizations | `organization` | catalog entry | `warn` with the Organization reason; a template `skipped template-not-runtime` | @@ -2030,47 +2030,28 @@ the tool forgot the sign-in on this Machine only (gh, composio) or unlinked the (wacli). An SSH outcome is taken only in its exact form (known reasons, a `SHA256:` fingerprint, no key content). -**The Environment vault** (decision F43, the wireframe of prototypes-lazurio#24). The -`bitwarden` row (`bw`) reads its own state (`/api/tools/bitwarden/status`, and -`/refresh` when the sign-ins are probed: on load and on "Refresh status") and says it -in the wireframe's words: "Nepřipojeno", "Čeká na potvrzení v trezoru", "Připojeno · -2 kolekce · 14 položek" (Czech plurals; "Connected · 1 collection · 2 items"), -"Přístup odebrán v trezoru", "Trezor neodpovídá", and "Brzy · druhá vlna" on this -computer. Its one next step is "Připojit", "Pokračovat", "Připojit znovu" or "Zkusit -znovu" (which syncs), with "Odpojit" once an account is signed in, beside the agents' -switch; its details add the account, the vault (with "Otevřít Vaultwarden" in a new -tab), the organization, the collection, the fingerprint and "Synchronizovat". The -dialog "Připojit Bitwarden" walks four numbered steps, the current one open: (1) "Pozvi -účet v trezoru": "Založ kolekci, pojmenuj ji, jak chceš (třeba takhle), a pozvi do ní -tuhle adresu s právem úprav." (the collection's name is the operator's; root decision -0193, addendum 2026-10-11), one quiet card with "Kolekce" (the suggested name) and -"Adresa účtu", each label above its -one-line value with a quiet copy button, "Otevřít Vaultwarden" and "Pozváno", the line -that only an Admin or Owner of the vault's organization invites and confirms, and on a -Team Environment "Kolekci uvidí celý Team."; a refused registration comes back here -with "Adresa ještě není v trezoru pozvaná." (2) "Environment se připojí": the connect's -phases "Instaluji Bitwarden", "Zakládám účet", "Přihlašuji" with a spinner, asked again -every second with the connect's job, and "Heslo účtu zná jen tento Environment."; a -failure names its stage and reason with "Dokončit s agentem" and "Zkusit znovu". (3) -"Potvrď účet v trezoru": the fingerprint phrase in a selectable box, "Otevřít -Vaultwarden" and "Čekám na potvrzení…" while `/refresh` is asked every five seconds. -Once the member is confirmed but the account does not recognize its collection (at a -first connection it sees none, or several and none with the suggested name; the only -one it sees is its own, whatever its name), the step is titled "Nasdílej účtu kolekci" and says only that: -"Potvrzeno. Ještě účtu v trezoru nasdílej kolekci tohoto Environmentu s právem úprav.", -the suggested name to copy, "Vidí-li účet víc kolekcí, pozná tu svou podle tohohle -názvu.", and "Čekám na kolekci…"; the row -says "Potvrzeno, čeká na kolekci". (4) "Připojeno": "Vidí N -kolekcí · M položek." and "Hotovo"; the agents' switch turns on after the reading that -follows, as after a curated sign-in. An account that exists starts at step 2, a -revoked one at step 1 with "Pozvi tuhle adresu znovu do kolekce s právem úprav." (a -connect keeps the collection it was connected to; while the account does not see it, -"Účet nevidí kolekci, ke které byl připojený. Pozvi ho do ní znovu, nebo Environment -odpoj a připoj ho k jiné kolekci."), a -waiting one at step 3. Closing the dialog stops only the page's polling; the connect -goes on in the Launchpad. "Odpojit" asks first ("Agenti tu přestanou trezor používat. -Přístup úplně ukončíš odebráním účtu v trezoru."). The state is accepted only in its -exact form (`src/launchpad/vault-view.ts`, `tests/vault-view.test.ts`); the DOM is +**The Environment's own vault** (decision F52, the wireframe of +prototypes-lazurio#33; it replaces F43's dialog). The Environment sets its vault up +itself: the installed Launchpad runs the one setup of `/api/tools/bitwarden/setup` in +the background after its start where the vault needs it (`vaultAtStart`, the rule of +Executor's, and `setUpAtStart`), and the `bitwarden` row (`bw`) only reads its state +(`/api/tools/bitwarden/status`, and `/refresh` when the sign-ins are probed: on load and +on "Refresh status"). A setup that runs is the state both answer, `202 {kind: +"vault-setting-up", job, phase}`, and the row follows it by its job whoever started it, +saying its step: "Instaluje se Bitwarden…", "Připravuje se účet trezoru…", +"Připravuje se trezor…", "Přihlašuje se…". Otherwise it says the state in few words: +"Připojeno", "Zatím nenastaveno", "Síť zatím účet trezoru nepovolila", "Trezor byl +odebrán" (a 0197 pilot's: "Přístup odebrán v trezoru"), "Trezor neodpovídá", "Nastavení +se nedokončilo", "Tento Environment zatím trezor nemá" (the handover names no vault) +and "Brzy · druhá vlna" on this computer ("Connected", "Not set up yet", …). Its +controls are "Otevřít trezor" once connected, a link in a new tab to +`/#/vault?organizationId=`, and one action only where a setup moves the +vault on: "Nastavit" when nothing set it up yet and "Zkusit znovu" after a setup that +stopped or a vault that did not answer. A vault the network has not allowed or has +revoked, and a 0197 pilot, offer none; there is no dialog, no details section and no +disconnect. A setup this page followed that ends connected turns the agents' switch on, +as after a curated sign-in. The state is accepted only in its exact form +(`src/launchpad/vault-view.ts`, `tests/vault-view.test.ts`); the DOM is `src/launchpad/vault-panel.ts`. **Executor** (decision F44). The `executor` row reads its own state diff --git a/docs/machine-handover.md b/docs/machine-handover.md index 1293744fc..0092d3bb7 100644 --- a/docs/machine-handover.md +++ b/docs/machine-handover.md @@ -15,7 +15,12 @@ from the merge of Machines pull request **#449** into `main` (commit `30c2fcf8a77914b5a44c652265e927683b2b413c`, SHA-256 `fbbd159b8e6dfc8580a7b8460ddb4a2b2d3158a1b74ab2a420d8ff68005ae53f`), which adds the optional `entry.environment_relay` ([below](#the-hosted-entry-decision-f16), root -decision 0194, decision F45) and changes nothing else. No Machines release carries it +decision 0194, decision F45) and changes nothing else. **Pending:** the vendored file +also carries the optional top-level member `vault` ([below](#the-environments-own-vault-decision-f52), +DEV-6631 contract C2), drafted here from the contract and the Machines shared contract +until the Machines pull request of DEV-6631 task 637 publishes it; before this +Platform merges, the file is replaced byte for byte by that one and +`schema-provenance.json` by its pin (its `pending` field says so meanwhile). No Machines release carries it yet, so the provenance names no version and no tag; the first release that does may add them with the same digest, and a digest other than this one is a new re-pin. Before it, the pin was the merge of Machines @@ -455,6 +460,36 @@ resident keeps the Launchpad port, and the recorded entry serves the CLI's modul links and `lazurio doctor`. Until a Machines release writes it, no Folder records an entry and the Launchpad stays local. +## The Environment's own vault (decision F52) + +Root decision 0198 point 1, DEV-6631 contract C2: the handover may carry, on both +branches, the optional and closed top-level member + +```json +"vault": { + "server_url": "https://vaultwarden..lazurio.io", + "account": "vaultwarden-<26 lowercase base32>@", + "name": " " +} +``` + +`server_url` is the network's Lazurio Vaultwarden; `account` the Environment's +technical account, which the network generated and pre-allowed for this Environment +alone at its Conglomerate Host's apply (`/admin/invite`), and which until it is +registered is a one-time enrollment capability inside the Environment boundary; `name` +the name of the Environment's own vault: letters, digits and single spaces, at most 50 +characters, unique within the network. The Environment registers the account itself, +creates its own organization with it and remembers it by ID; the name only names it +and a change of it renames it ([environment tools](environment-tools.md#the-environments-own-vault-decisions-f43-and-f52)). +Machines writes the member only for a pinned Platform that reads it, as for +`entry.environment_relay`: a Platform vendoring an earlier schema refuses the whole +handover that carries it (`tests/vault-handover.test.ts` shows it). Absent, the +Environment has no vault yet, or, where it was connected the 0197 way, keeps reading +that collection (`src/vault/legacy-0197/`). The member is not part of the Machine's +identity and is not recorded in the Folder's binding: the vault reads the live +handover at every operation. Recovery evidence withholds the account, the name and +the vault's host (``, ``, ``). + ## Delivery by the Machines role (agreed 2026-09-23, Machines #199, v0.12.70) The Machines resident role installs the Platform from a custody-staged, digest-pinned diff --git a/docs/module-adoption.md b/docs/module-adoption.md index a6ea6bd34..1427b756e 100644 --- a/docs/module-adoption.md +++ b/docs/module-adoption.md @@ -340,15 +340,18 @@ only, never values: "optional_secrets": ["OPTIONAL_SERVICE_TOKEN"] ``` -Before every start the value of each is read from the Environment vault (F43): a -sync, then the login password of the one item named exactly so in the Environment's -collection. Only an application of the Organization that owns the Environment reads -it; another mounted Organization's application and every Personalspace module do not. +Before every start the value of each is read from the Environment's own vault (F43, +F52): a sync, then the login password of the one item named exactly so anywhere in +that vault. On a work Environment only an application of the Organization that owns +it reads it, on a personal Environment only a Personalspace module; another mounted +Organization's application, a Personalspace module on a work Environment and an +Organization's application on a personal one do not. That is a rule about declarations, not isolation: all Modules on one Environment run under its one account and are one trust domain (F46 point 3, root decision 0196). A required name without a value refuses the start with `runtime-secret-unavailable` and each name's reason (`missing`, `ambiguous`, `empty`, `not-connected`, -`unreachable`, `other-organization`, `personalspace`, `workstation`, …); an optional +`unreachable`, `other-organization`, `personalspace`, `personal-environment`, +`workstation`, …); an optional name without an item, or one an unusable vault does not give, is only reported (`secretsNotProvided`) and the application starts without the variable, while an optional name held by more than one item or with an empty password refuses the start diff --git a/docs/public-development.md b/docs/public-development.md index 17a585da5..f37fddda8 100644 --- a/docs/public-development.md +++ b/docs/public-development.md @@ -10,11 +10,13 @@ Publish names, formats and safe examples of configuration, not their secret valu Use obvious placeholders such as ``; avoid realistic example tokens. Credential access remains with existing OS/provider/harness custody. Platform stores neither a new secret database nor copies of session credentials. -The one exception is the Environment vault's own account (decision F43): the -Platform creates that account, so it writes the account's generated master -password, its API key and its one Bitwarden CLI session itself, owner-only, -beside the CLI's store on that Environment and nowhere else. Every other -secret stays in the vault. The shared GitHub App sign-in pilot +The one exception is the Environment vault's own account (decisions F43 and +F52): the Platform registers that account, so it writes the account's generated +master password, its API key and its one Bitwarden CLI session itself, +owner-only, beside the CLI's store on that Environment and nowhere else; the +key of the Environment's own vault exists only in memory while the vault is +created, then only in the vault, encrypted to the account. Every other secret +stays in the vault. The shared GitHub App sign-in pilot (decision F48) is a second exception while switched on: GitHub hands its expiring user/refresh pair to the Environment that signed in, so Platform keeps one owner-only chain in that Environment user's state directory, as gh keeps its own diff --git a/docs/recovery.md b/docs/recovery.md index bb253d719..d70000413 100644 --- a/docs/recovery.md +++ b/docs/recovery.md @@ -164,8 +164,9 @@ Per line, in this order: 3. Known private values of this Machine become stable placeholders, matched as whole names, case-insensitively, longest first, in one pass: the Folder path ``, the install base ``, the home `~`, the account ``, the - host name and its short form ``, and numbered ``, ``, - ``, ``, ``, ``, ``, + host name and its short form ``, the Environment's vault account + `` and its vault's name ``, and numbered ``, + ``, ``, ``, ``, ``, ``, ``, ``, ``. Sources: the process (home, `USER`, `LOGNAME`, the account name, the host name), the names under the Folder's `organizations/` and under each Organization's `workspace/`, @@ -175,7 +176,8 @@ Per line, in this order: declares them (the checkout directory need not be the login, `_GEN3`; nothing else of those files is read), the Machine binding the Folder records and the Machine handover (Machine, Owner, Team, assignment login and id, tailnet node, host, - custody repository, peers and their hosts, the hosted entry's hostnames). + custody repository, peers and their hosts, the hosted entry's hostnames, and the + own vault's account, name and host, decision F52). 4. A long run (32 or more of `[A-Za-z0-9+/_=-]`) withholds the line unless it is exactly a 40- or 64-character lowercase hex digest that is either the running or active executable's commit or directly follows a label the product prints diff --git a/src/folder/render.ts b/src/folder/render.ts index d55ca958f..e25dc7554 100644 --- a/src/folder/render.ts +++ b/src/folder/render.ts @@ -42,7 +42,7 @@ import { type AgentVoice, parseAgentVoice, voiceSection } from "./voice"; // future persisted preference schemas. Every change of the generated bytes // moves it to the next number; tests/folder-template-revision.test.ts pins the // rendered digest of the current one (decision F14, addendum 2026-10-03). -export const instructionTemplateRevision = "base-instructions-48"; +export const instructionTemplateRevision = "base-instructions-49"; // Template revisions are ordered by their number. A Folder rendered by an // older revision is re-rendered by the next change of the generated Folder diff --git a/src/machine/lazurio-machine.v1.schema.json b/src/machine/lazurio-machine.v1.schema.json index 3b31083ca..bd0d4ffe8 100644 --- a/src/machine/lazurio-machine.v1.schema.json +++ b/src/machine/lazurio-machine.v1.schema.json @@ -288,9 +288,9 @@ "additionalProperties": false, "required": ["server_url", "account", "name"], "properties": { - "server_url": { "description": "Origin of the network's Lazurio Vaultwarden.", "$ref": "#/$defs/https_origin" }, - "account": { "description": "The Environment's technical account: vaultwarden-<26 lowercase base32 characters>@.", "type": "string", "maxLength": 254, "pattern": "^vaultwarden-[a-z2-7]{26}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\\.lazurio\\.io$" }, - "name": { "description": "Name of the Environment's vault, : letters, digits and single spaces, unique within the network.", "type": "string", "maxLength": 50, "pattern": "^[\\p{L}\\p{Nd}]+(?: [\\p{L}\\p{Nd}]+)*$" } + "server_url": { "description": "Origin of the network's Lazurio Vaultwarden: https://vaultwarden..lazurio.io.", "type": "string", "pattern": "^https://vaultwarden\\.[a-z0-9]+(?:-[a-z0-9]+)*\\.lazurio\\.io$" }, + "account": { "description": "The Environment's technical account: vaultwarden-<26 lowercase base32 characters>@.", "type": "string", "maxLength": 119, "pattern": "^vaultwarden-[a-z2-7]{26}@[a-z0-9]+(?:-[a-z0-9]+)*(?:\\.[a-z0-9]+(?:-[a-z0-9]+)*)?\\.lazurio\\.io$" }, + "name": { "description": "Name of the Environment's vault, : letters, digits and single spaces, unique within the network.", "type": "string", "maxLength": 50, "pattern": "^[\\p{L}0-9]+(?: [\\p{L}0-9]+)*$" } } }, "account": { diff --git a/src/machine/schema-provenance.json b/src/machine/schema-provenance.json index 12b22e176..6ee25e31b 100644 --- a/src/machine/schema-provenance.json +++ b/src/machine/schema-provenance.json @@ -6,7 +6,8 @@ "source_commit": "30c2fcf8a77914b5a44c652265e927683b2b413c", "source_path": "workloads/workspace-vm/lazurio-machine.v1.schema.json", "source_sha256": "fbbd159b8e6dfc8580a7b8460ddb4a2b2d3158a1b74ab2a420d8ff68005ae53f", - "sha256": "fbbd159b8e6dfc8580a7b8460ddb4a2b2d3158a1b74ab2a420d8ff68005ae53f", + "sha256": "d6a5dce89f5fa0ee6616c929a48cccef28346b6e92c4b1c320b13c1f71040a0e", "publication_authorization": "https://github.com/HumanAndMachine-ai/Machines/pull/124#issuecomment-5688845105", - "pin_update": "https://github.com/HumanAndMachine-ai/Machines/pull/449" + "pin_update": "https://github.com/HumanAndMachine-ai/Machines/pull/449", + "pending": "DEV-6631 contract C2: the optional member `vault` {server_url, account, name} is drafted here from the contract and the Machines shared contract (workloads/shared/environment-vault.ts) until the Machines pull request of DEV-6631 task 637 publishes it; the vendored file is replaced byte for byte by that one, and this provenance by its pin, before merge." } diff --git a/src/recover/sanitize.ts b/src/recover/sanitize.ts index f22aae16a..842a9380b 100644 --- a/src/recover/sanitize.ts +++ b/src/recover/sanitize.ts @@ -39,12 +39,12 @@ export const privateKinds = [ "team", "github-login", "github-id", - "vault-account", - "vault-name", "tailnet-node", "machine-host", "peer", "hostname", + "vault-account", + "vault-name", ] as const; export type PrivateKind = (typeof privateKinds)[number]; export type PrivateValue = Readonly<{ kind: PrivateKind; value: string }>; diff --git a/tests/__snapshots__/folder-manual.test.ts.snap b/tests/__snapshots__/folder-manual.test.ts.snap index bbf88cbaf..81df1eeae 100644 --- a/tests/__snapshots__/folder-manual.test.ts.snap +++ b/tests/__snapshots__/folder-manual.test.ts.snap @@ -2,7 +2,7 @@ exports[`a personal VM names reachable peers neutrally from the record and requires the Operator's confirmation 1`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`example\` (personal-vm). - Owner: the person with GitHub login \`example\` (id 12345). @@ -92,7 +92,7 @@ Peers this Environment may reach over SSH, exactly as the handover records them: exports[`a personal VM names reachable peers neutrally from the record and requires the Operator's confirmation 2`] = ` "# Tenhle Environment - + ## Identita podle zaznamenaného handoveru - Název: \`example\` (personal-vm). - Owner: člověk s GitHub loginem \`example\` (id 12345). @@ -182,7 +182,7 @@ Peers, na které odsud smíš přes SSH, přesně jak je zaznamenal handover: exports[`rendered manual/this-machine.md snapshot: local 1`] = ` "# This Environment - + ## Identity, from the recorded handover - The Operator's own workstation. No handover was recorded; the signed-in user is both Owner and Operator. @@ -220,7 +220,7 @@ The Integrations (connected apps) and custom MCP servers of this Environment are exports[`rendered manual/this-machine.md snapshot: hosted-personal 1`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`example\` (personal-vm). - Owner: the person with GitHub login \`example\` (id 12345). @@ -302,7 +302,7 @@ The handover records no peer this Environment may reach over SSH; do not look fo exports[`rendered manual/this-machine.md snapshot: hosted-organization-personal 1`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`workspace\` (workspace-vm). - Owner: Organization \`example\`. @@ -378,7 +378,7 @@ A registered key gives no network access by itself. The network administrator de exports[`rendered manual/this-machine.md snapshot: hosted-organization-team 1`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`workspace\` (workspace-vm). - Owner: Organization \`example\`, Team \`sample-team\`. @@ -456,7 +456,7 @@ A registered key gives no network access by itself. The network administrator de exports[`rendered manual/this-machine.md snapshot: hosted-organization-steward 1`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`workspace\` (workspace-vm). - Owner: Organization \`example\`. @@ -550,7 +550,7 @@ A registered key gives no network access by itself. The network administrator de exports[`rendered manual/lazurio.md snapshot 1`] = ` "# Lazurio - + ## What Lazurio is Lazurio is the shared framework in which people and machines work together on the work of companies (Organizations, Teams and modules) and on a person's own affairs (Personalspace and the optional Buddy). Lazurio is the product's only current name; earlier names remain only in historical records (decision 0128). @@ -609,7 +609,7 @@ These layers are not copied into each other automatically; a chat is a cache. exports[`rendered manual/lazurio.md snapshot 2`] = ` "# Lazurio - + ## Co je Lazurio Lazurio je sdílený rámec, ve kterém lidé a stroje společně pracují na práci firem (Organizace, Teamy a moduly) i na osobních záležitostech člověka (Personalspace a volitelný Buddy). Lazurio je jediný aktuální název produktu; dřívější názvy zůstávají jen v historických záznamech (decision 0128). @@ -668,7 +668,7 @@ Tyhle vrstvy se do sebe automaticky nekopírují; chat je jen cache. exports[`rendered manual/working-here.md snapshot 1`] = ` "# Working here - + ## First understand what the person means Lazurio brings together a company's knowledge and the tools people use. The person should not need to dictate a module's technical name or its address. When they say forecast, they may mean a view inside a sales application. Your job is to find that meaning in their context. This is not a global translation of names: the same term can mean something else in another Organization. @@ -833,7 +833,7 @@ Do the work so that they have it: understandable, reversible, with room to adjus exports[`rendered manual/working-here.md snapshot 2`] = ` "# Jak se tu pracuje - + ## Nejdřív pochop, o čem je řeč Lazurio propojuje firemní know-how a nástroje, se kterými lidé pracují. Člověk ti proto nemusí diktovat technický název modulu ani jeho adresu. Když řekne forecast, může tím myslet pohled uvnitř obchodní aplikace. Tvoje práce je ten význam dohledat v jeho kontextu. Není to globální překlad názvů: stejný pojem může v jiné Organizaci znamenat něco jiného. @@ -998,7 +998,7 @@ Odveď práci tak, aby ho měl: srozumitelně, vratně, s prostorem k úpravě. exports[`rendered manual/roles.md snapshot 1`] = ` "# Roles - + Names authorize nothing. In every role below, what a person may do is decided by their live rights at the providers, above all on GitHub (decisions 0102/0103). ## Operator (Operátor) @@ -1034,7 +1034,7 @@ The term “AI Kolega”, an AI with its own seat and authority like a person, i exports[`rendered manual/roles.md snapshot 2`] = ` "# Role - + Názvy nic neautorizují. U každé role níže rozhodují o tom, co člověk smí, jeho živá práva u providerů, především na GitHubu (decisions 0102/0103). ## Operátor @@ -1070,7 +1070,7 @@ Pojem „AI Kolega“, tedy AI s vlastním seatem a pravomocemi jako člověk, j exports[`rendered manual/glossary.md snapshot 1`] = ` "# Glossary - + English terms first; the Czech term the product and its people use is in parentheses. | Term | Meaning | @@ -1124,7 +1124,7 @@ English terms first; the Czech term the product and its people use is in parenth exports[`rendered manual/glossary.md snapshot 2`] = ` "# Slovník - + Nejdřív český pojem, v závorce anglický, který používají produkt a technické identifikátory. | Pojem | Význam | @@ -1178,7 +1178,7 @@ Nejdřív český pojem, v závorce anglický, který používají produkt a tec exports[`rendered manual/troubleshooting.md snapshot 1`] = ` "# Installation, updates and troubleshooting - + ## Lazurio in this Environment Lazurio is installed here: the product in \`~/.local/share/lazurio/\` with the command \`lazurio\`, and this Folder with its generated files \`AGENTS.md\`, \`manual/\` and \`.lazurio/\`. It is installed only by its installer and updated with \`lazurio update\`. @@ -1258,7 +1258,7 @@ An open technical problem belongs in a GitHub Issue of the exact owning reposito exports[`rendered manual/troubleshooting.md snapshot 2`] = ` "# Instalace, aktualizace a řešení problémů - + ## Lazurio na tomhle Environmentu Lazurio je tu nainstalované: produkt v \`~/.local/share/lazurio/\` s příkazem \`lazurio\` a tenhle Folder s generovanými soubory \`AGENTS.md\`, \`manual/\` a \`.lazurio/\`. Instaluje se jen svým instalátorem a aktualizuje příkazem \`lazurio update\`. @@ -1338,7 +1338,7 @@ Otevřený technický problém patří do GitHub Issue v přesném owning repozi exports[`rendered manual/troubleshooting.md snapshot: hosted-personal / cs 1`] = ` "# Instalace, aktualizace a řešení problémů - + ## Lazurio na tomhle Environmentu Lazurio je tu nainstalované a spravované: produkt v \`~/.local/share/lazurio/\` s příkazem \`~/.local/bin/lazurio\` a tenhle Folder s generovanými soubory \`AGENTS.md\`, \`manual/\` a \`.lazurio/\`. Když tě Operátor požádá „nainstaluj Lazurio“, ověř stav (\`lazurio doctor\`) a doplň jen to, co chybí, postupy níže. @@ -1411,7 +1411,7 @@ Otevřený technický problém patří do GitHub Issue v přesném owning repozi exports[`rendered manual/troubleshooting.md snapshot: hosted-personal / en 1`] = ` "# Installation, updates and troubleshooting - + ## Lazurio in this Environment Lazurio is installed and managed here: the product in \`~/.local/share/lazurio/\` with the command \`~/.local/bin/lazurio\`, and this Folder with its generated files \`AGENTS.md\`, \`manual/\` and \`.lazurio/\`. When the Operator asks you to “install Lazurio”, check the state (\`lazurio doctor\`) and complete only what is missing, with the procedures below. @@ -1484,7 +1484,7 @@ An open technical problem belongs in a GitHub Issue of the exact owning reposito exports[`rendered manual/troubleshooting.md snapshot: hosted-organization-personal / cs 1`] = ` "# Instalace, aktualizace a řešení problémů - + ## Lazurio na tomhle Environmentu Lazurio je tu nainstalované a spravované: produkt v \`~/.local/share/lazurio/\` s příkazem \`~/.local/bin/lazurio\` a tenhle Folder s generovanými soubory \`AGENTS.md\`, \`manual/\` a \`.lazurio/\`. Když tě Operátor požádá „nainstaluj Lazurio“, ověř stav (\`lazurio doctor\`) a doplň jen to, co chybí, postupy níže. @@ -1573,7 +1573,7 @@ Otevřený technický problém patří do GitHub Issue v přesném owning repozi exports[`rendered manual/troubleshooting.md snapshot: hosted-organization-personal / en 1`] = ` "# Installation, updates and troubleshooting - + ## Lazurio in this Environment Lazurio is installed and managed here: the product in \`~/.local/share/lazurio/\` with the command \`~/.local/bin/lazurio\`, and this Folder with its generated files \`AGENTS.md\`, \`manual/\` and \`.lazurio/\`. When the Operator asks you to “install Lazurio”, check the state (\`lazurio doctor\`) and complete only what is missing, with the procedures below. @@ -1662,7 +1662,7 @@ An open technical problem belongs in a GitHub Issue of the exact owning reposito exports[`rendered manual/troubleshooting.md snapshot: hosted-organization-team / cs 1`] = ` "# Instalace, aktualizace a řešení problémů - + ## Lazurio na tomhle Environmentu Lazurio je tu nainstalované a spravované: produkt v \`~/.local/share/lazurio/\` s příkazem \`~/.local/bin/lazurio\` a tenhle Folder s generovanými soubory \`AGENTS.md\`, \`manual/\` a \`.lazurio/\`. Když tě Operátor požádá „nainstaluj Lazurio“, ověř stav (\`lazurio doctor\`) a doplň jen to, co chybí, postupy níže. @@ -1752,7 +1752,7 @@ Otevřený technický problém patří do GitHub Issue v přesném owning repozi exports[`rendered manual/troubleshooting.md snapshot: hosted-organization-team / en 1`] = ` "# Installation, updates and troubleshooting - + ## Lazurio in this Environment Lazurio is installed and managed here: the product in \`~/.local/share/lazurio/\` with the command \`~/.local/bin/lazurio\`, and this Folder with its generated files \`AGENTS.md\`, \`manual/\` and \`.lazurio/\`. When the Operator asks you to “install Lazurio”, check the state (\`lazurio doctor\`) and complete only what is missing, with the procedures below. @@ -1842,7 +1842,7 @@ An open technical problem belongs in a GitHub Issue of the exact owning reposito exports[`rendered manual/troubleshooting.md snapshot: hosted-organization-steward / cs 1`] = ` "# Instalace, aktualizace a řešení problémů - + ## Lazurio na tomhle Environmentu Lazurio je tu nainstalované a spravované: produkt v \`~/.local/share/lazurio/\` s příkazem \`~/.local/bin/lazurio\` a tenhle Folder s generovanými soubory \`AGENTS.md\`, \`manual/\` a \`.lazurio/\`. Když tě Operátor požádá „nainstaluj Lazurio“, ověř stav (\`lazurio doctor\`) a doplň jen to, co chybí, postupy níže. @@ -1931,7 +1931,7 @@ Otevřený technický problém patří do GitHub Issue v přesném owning repozi exports[`rendered manual/troubleshooting.md snapshot: hosted-organization-steward / en 1`] = ` "# Installation, updates and troubleshooting - + ## Lazurio in this Environment Lazurio is installed and managed here: the product in \`~/.local/share/lazurio/\` with the command \`~/.local/bin/lazurio\`, and this Folder with its generated files \`AGENTS.md\`, \`manual/\` and \`.lazurio/\`. When the Operator asks you to “install Lazurio”, check the state (\`lazurio doctor\`) and complete only what is missing, with the procedures below. @@ -2020,7 +2020,7 @@ An open technical problem belongs in a GitHub Issue of the exact owning reposito exports[`this-machine.md renders relationships only when the binding carries them 1`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`workspace\` (workspace-vm). - Owner: Organization \`example\`. @@ -2103,7 +2103,7 @@ A registered key gives no network access by itself. The network administrator de exports[`this-machine.md renders the assignment exactly as the handover carries it 1`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`workspace\` (workspace-vm). - Owner: Organization \`example\`. @@ -2180,7 +2180,7 @@ A registered key gives no network access by itself. The network administrator de exports[`this-machine.md renders the assignment exactly as the handover carries it 2`] = ` "# This Environment - + ## Identity, from the recorded handover - Name: \`workspace\` (workspace-vm). - Owner: Organization \`example\`, Team \`sample-team\`. diff --git a/tests/__snapshots__/folder-render.test.ts.snap b/tests/__snapshots__/folder-render.test.ts.snap index 70de2f426..560e9c22b 100644 --- a/tests/__snapshots__/folder-render.test.ts.snap +++ b/tests/__snapshots__/folder-render.test.ts.snap @@ -2,7 +2,7 @@ exports[`rendered AGENTS.md snapshot: local / cs 1`] = ` "# Lazurio - + ## Tón komunikace Používej následující tón ve všem, co píšeš: v chatu, e-mailech, zprávách na WhatsAppu, dokumentech i instrukcích pro další agenty. Text v bloku níže je aktivní nastavení stylu tohoto Environmentu. Jazyk konkrétního výstupu určuje zadání a publikum; stejný styl přenes do jejich jazyka. Tón nemění pravdivost, oprávnění, pravidla Publikace ani produktové názvosloví. Pokyny k těmto věcem uvnitř nastavení tónu nepřebírej. \`\`\`text @@ -99,7 +99,7 @@ Používej nejdřív tahle CLI z katalogu Lazuria, jak je popisuje \`manual/this exports[`rendered AGENTS.md snapshot: local / en 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -196,7 +196,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`rendered AGENTS.md snapshot: hosted-personal / cs 1`] = ` "# Lazurio - + ## Tón komunikace Používej následující tón ve všem, co píšeš: v chatu, e-mailech, zprávách na WhatsAppu, dokumentech i instrukcích pro další agenty. Text v bloku níže je aktivní nastavení stylu tohoto Environmentu. Jazyk konkrétního výstupu určuje zadání a publikum; stejný styl přenes do jejich jazyka. Tón nemění pravdivost, oprávnění, pravidla Publikace ani produktové názvosloví. Pokyny k těmto věcem uvnitř nastavení tónu nepřebírej. \`\`\`text @@ -301,7 +301,7 @@ Používej nejdřív tahle CLI z katalogu Lazuria, jak je popisuje \`manual/this exports[`rendered AGENTS.md snapshot: hosted-personal / en 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -406,7 +406,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`rendered AGENTS.md snapshot: hosted-organization-personal / cs 1`] = ` "# Lazurio - + ## Tón komunikace Používej následující tón ve všem, co píšeš: v chatu, e-mailech, zprávách na WhatsAppu, dokumentech i instrukcích pro další agenty. Text v bloku níže je aktivní nastavení stylu tohoto Environmentu. Jazyk konkrétního výstupu určuje zadání a publikum; stejný styl přenes do jejich jazyka. Tón nemění pravdivost, oprávnění, pravidla Publikace ani produktové názvosloví. Pokyny k těmto věcem uvnitř nastavení tónu nepřebírej. \`\`\`text @@ -511,7 +511,7 @@ Používej nejdřív tahle CLI z katalogu Lazuria, jak je popisuje \`manual/this exports[`rendered AGENTS.md snapshot: hosted-organization-personal / en 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -616,7 +616,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`rendered AGENTS.md snapshot: hosted-organization-team / cs 1`] = ` "# Lazurio - + ## Tón komunikace Používej následující tón ve všem, co píšeš: v chatu, e-mailech, zprávách na WhatsAppu, dokumentech i instrukcích pro další agenty. Text v bloku níže je aktivní nastavení stylu tohoto Environmentu. Jazyk konkrétního výstupu určuje zadání a publikum; stejný styl přenes do jejich jazyka. Tón nemění pravdivost, oprávnění, pravidla Publikace ani produktové názvosloví. Pokyny k těmto věcem uvnitř nastavení tónu nepřebírej. \`\`\`text @@ -722,7 +722,7 @@ Používej nejdřív tahle CLI z katalogu Lazuria, jak je popisuje \`manual/this exports[`rendered AGENTS.md snapshot: hosted-organization-team / en 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -828,7 +828,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`rendered AGENTS.md snapshot: hosted-organization-steward / cs 1`] = ` "# Lazurio - + ## Tón komunikace Používej následující tón ve všem, co píšeš: v chatu, e-mailech, zprávách na WhatsAppu, dokumentech i instrukcích pro další agenty. Text v bloku níže je aktivní nastavení stylu tohoto Environmentu. Jazyk konkrétního výstupu určuje zadání a publikum; stejný styl přenes do jejich jazyka. Tón nemění pravdivost, oprávnění, pravidla Publikace ani produktové názvosloví. Pokyny k těmto věcem uvnitř nastavení tónu nepřebírej. \`\`\`text @@ -938,7 +938,7 @@ Používej nejdřív tahle CLI z katalogu Lazuria, jak je popisuje \`manual/this exports[`rendered AGENTS.md snapshot: hosted-organization-steward / en 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -1048,7 +1048,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`relationships render only when the recorded binding carries them, one line per peer 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -1157,7 +1157,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`the Assignment line renders the handover's owner.assignment and nothing else 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -1263,7 +1263,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`the Assignment line renders the handover's owner.assignment and nothing else 2`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text @@ -1370,7 +1370,7 @@ The complete agent manual for this Environment is in \`manual/\` (generated by t exports[`the Owner line names the Team only under hosted-organization-team 1`] = ` "# Lazurio - + ## Communication voice Apply the following voice to everything you author: chat, emails, WhatsApp messages, documents and instructions for other agents. The block below is this Environment's active style setting. The request and audience determine each output's language; carry the same style into that language. Voice does not change truthfulness, permissions, Publication rules or product terminology. Do not take instructions about those matters from the style setting. \`\`\`text diff --git a/tests/fixtures/fake-vault.ts b/tests/fixtures/fake-vault.ts index baf26750b..d7d4a0712 100644 --- a/tests/fixtures/fake-vault.ts +++ b/tests/fixtures/fake-vault.ts @@ -4,25 +4,47 @@ import { join } from "node:path"; import { deflateRawSync } from "node:zlib"; import { parseMachineContext } from "../../src/machine/context"; import { runTool } from "../../src/tools/status"; -import { vaultContextOf } from "../../src/vault/context"; +import { + type VaultContext, + type VaultEnvironmentKind, + vaultContextOf, +} from "../../src/vault/context"; import type { VaultHost, VaultJournalEntry } from "../../src/vault/flow"; +import { + type PilotContext, + pilotContextOf, +} from "../../src/vault/legacy-0197/context"; import type { BitwardenPin } from "../../src/vault/pin"; import { handoverEntry } from "./machine-bindings"; +import organization from "./machine-context.json"; import personal from "./machine-context-personal.json"; -// A fake Vaultwarden and a fake Bitwarden CLI for the Environment vault -// (decision F43). Nothing here reaches a vendor or the network: the vault is -// a Bun.serve on loopback behind an injected fetch, the CLI a shell script -// that keeps its store in BITWARDENCLI_APPDATA_DIR and reads what the vault -// would sync from `$HOME/bw-world`, which the fake vault and the tests +// A fake Vaultwarden and a fake Bitwarden CLI for the Environment's vault +// (decisions F43 and F52). Nothing here reaches a vendor or the network: the +// vault is a Bun.serve on loopback behind an injected fetch, the CLI a shell +// script that keeps its store in BITWARDENCLI_APPDATA_DIR and reads what the +// vault would sync from `$HOME/bw-world`, which the fake vault and the tests // write. Every name, host and value is invented. export const zone = "example.lazurio.io"; export const vaultOrigin = `https://vaultwarden.${zone}`; +/** The technical account the network pre-allowed for the personal + * Environment `example` (contract C2's shape). */ +export const ownAccount = + "vaultwarden-ndbrmzvjpwxtt3q7m2e4fihgsa@example.lazurio.io"; +/** The same for the work Environment `workspace` of the Organization + * `example`. */ +export const workAccount = + "vaultwarden-q2wd5oyrbkmfx3czjh7tapi4ul@workspace.example.lazurio.io"; +export const vaultName = "Example Osobní example"; +/** The decrypted name of every vault's first collection, as bw shows it: + * the fake CLI cannot decrypt (tests/vault-organization.test.ts proves the + * real names decrypt to it). */ +export const agents = "Agenti"; +/** A person's organization, where a 0197 pilot was given a collection. */ export const organizationId = "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b"; export const collectionId = "6a5f4e3d-2c1b-4a9f-8e7d-6c5b4a3f2e1d"; export const otherCollectionId = "1f2e3d4c-5b6a-4f9e-8d7c-6b5a4f3e2d1c"; -export const fingerprint = "steep-flavor-uncut-scouring-unnoticed"; // The fake CLI: the commands and messages of bw 2026.7.0 that the vault core // uses. A session is valid while it is the last one `unlock` printed; every @@ -102,10 +124,6 @@ list) *) echo "Unknown object." >&2; exit 1;; esac exit 0;; -get) - unlocked - if [ "$2" = fingerprint ] && [ "$3" = me ]; then cat "$world/fingerprint"; exit 0; fi - echo "Not found." >&2; exit 1;; esac echo "fake bw: unknown command $1" >&2 exit 64 @@ -191,27 +209,64 @@ export function fakeRelease(pin: BitwardenPin, zip: Uint8Array) { }; } -type FakeUser = { +export type FakeUser = { id: string; email: string; hash: string; publicKey: string; + /** The master-key-wrapped user key and the user-key-wrapped private key + * the registration sent: what a token answer hands back. */ + protectedUserKey: string; + encryptedPrivateKey: string; apiKey: string | null; devices: string[]; }; -/** A fake Vaultwarden: the registration, password login and API key - * endpoints with Vaultwarden's shapes and messages, and the membership the - * tests move (invited, accepted on registration, confirmed, removed). */ +export type FakeOrganization = { + id: string; + name: string; + billingEmail: string; + publicKey: string; + encryptedPrivateKey: string; + /** By user id: the organization key encrypted to the member, its type + * (0 Owner) and status (2 confirmed). */ + members: Map; + /** The collections, their names as the vault keeps them (encrypted). */ + collections: { id: string; name: string }[]; +}; + +export type FakeRequest = { + method: string; + path: string; + body: unknown; + accept: string | null; +}; + +/** A fake Vaultwarden: the registration, password and API-key logins, the + * API key, the account's profile and the organization endpoints the + * Environment's own vault uses, with Vaultwarden's shapes and messages; and + * what a 0197 pilot's person did in their own organization (`confirm`, + * `remove`), which the tests move. */ export async function startFakeVault(home: string) { const world = join(home, "bw-world"); await mkdir(world, { recursive: true }); - await writeFile(join(world, "fingerprint"), `${fingerprint}\n`); const invited = new Set(); const users = new Map(); const tokens = new Map(); - const requests: { path: string; body: unknown; accept: string | null }[] = []; - const flags = { smtp: false, rateLimit: false, plainToken: false }; + const organizations = new Map(); + const requests: FakeRequest[] = []; + const flags = { + smtp: false, + rateLimit: false, + plainToken: false, + /** `ORG_CREATION_USERS` leaves this account out. */ + organizationRefused: false, + }; + /** The person's organization of a 0197 pilot, as a sync brings it. */ + let pilotWorld: { + orgs: unknown[]; + collections: unknown[]; + } = { orgs: [], collections: [] }; const json = (body: unknown, status = 200) => Response.json(body, { status }); const refusal = (message: string, status = 400) => json( @@ -225,6 +280,71 @@ export async function startFakeVault(home: string) { }, status, ); + const write = (name: string, value: unknown) => + writeFile(join(world, name), `${JSON.stringify(value)}\n`); + /** What a sync brings: the person's organization of a pilot, and every + * organization an account of this vault is a confirmed member of, with its + * first collection under the name bw would show. */ + async function syncWorld() { + const own = [...organizations.values()].filter((organization) => + [...organization.members.values()].some((member) => member.status === 2), + ); + await write("orgs.json", [ + ...pilotWorld.orgs, + ...own.map((organization) => ({ + object: "organization", + id: organization.id, + name: organization.name, + status: 2, + type: 0, + enabled: true, + })), + ]); + await write("collections.json", [ + ...pilotWorld.collections, + ...own.flatMap((organization) => + organization.collections.map((collection, index) => ({ + object: "collection", + id: collection.id, + organizationId: organization.id, + name: index === 0 ? agents : `Collection ${index}`, + externalId: null, + })), + ), + ]); + } + const claims = (user: FakeUser) => + Buffer.from(JSON.stringify({ sub: user.id })).toString("base64url"); + const tokenAnswer = (user: FakeUser) => + json({ + access_token: `eyJhbGciOiJub25lIn0.${claims(user)}.signature`, + token_type: "Bearer", + expires_in: 7200, + Key: user.protectedUserKey, + PrivateKey: user.encryptedPrivateKey, + Kdf: 0, + KdfIterations: 600_000, + scope: "api", + }); + const bearer = (request: Request): FakeUser | undefined => { + const header = request.headers.get("authorization") ?? ""; + let sub: unknown; + try { + sub = JSON.parse( + Buffer.from(header.split(".")[1] ?? "", "base64url").toString("utf8"), + ).sub; + } catch { + return undefined; + } + return [...users.values()].find((user) => user.id === sub); + }; + const organizationJson = (organization: FakeOrganization) => ({ + object: "organization", + id: organization.id, + name: organization.name, + billingEmail: organization.billingEmail, + hasPublicAndPrivateKeys: true, + }); const server = Bun.serve({ hostname: "127.0.0.1", port: 0, @@ -240,6 +360,7 @@ export async function startFakeVault(home: string) { ? null : JSON.parse(text); requests.push({ + method: request.method, path: url.pathname, body, accept: request.headers.get("accept"), @@ -302,6 +423,8 @@ export async function startFakeVault(home: string) { email, hash: auth.masterPasswordAuthenticationHash, publicKey: keys.publicKey, + protectedUserKey: unlock.masterKeyWrappedUserKey, + encryptedPrivateKey: keys.encryptedPrivateKey, apiKey: null, devices: [], }); @@ -316,16 +439,11 @@ export async function startFakeVault(home: string) { kdfParallelism: null, }); if (url.pathname === "/identity/connect/token") { - const user = users.get(String(value.username)); for (const field of ["deviceIdentifier", "deviceName", "deviceType"]) if (typeof value[field] !== "string" || value[field] === "") return refusal(`${field} cannot be blank`); - if ( - value.grant_type !== "password" || - user === undefined || - user.hash !== value.password - ) - return json( + const invalid = () => + json( { error: "invalid_grant", error_description: "invalid_username_or_password", @@ -335,47 +453,153 @@ export async function startFakeVault(home: string) { }, 400, ); + let user: FakeUser | undefined; + if (value.grant_type === "password") { + user = users.get(String(value.username)); + if (user === undefined || user.hash !== value.password) + return invalid(); + } else if (value.grant_type === "client_credentials") { + user = [...users.values()].find( + (entry) => `user.${entry.id}` === value.client_id, + ); + if ( + value.scope !== "api" || + user === undefined || + user.apiKey === null || + user.apiKey !== value.client_secret + ) + return refusal("Incorrect client_secret"); + } else return invalid(); if (!user.devices.includes(String(value.deviceIdentifier))) user.devices.push(String(value.deviceIdentifier)); - const claims = Buffer.from(JSON.stringify({ sub: user.id })).toString( - "base64url", - ); - return json({ - access_token: `eyJhbGciOiJub25lIn0.${claims}.signature`, - token_type: "Bearer", - Key: "2.redacted", - PrivateKey: "2.redacted", - }); + return tokenAnswer(user); } if (url.pathname === "/api/accounts/api-key") { - const bearer = request.headers.get("authorization") ?? ""; - const claims = JSON.parse( - Buffer.from(bearer.split(".")[1] ?? "", "base64url").toString( - "utf8", - ) || "{}", - ) as { sub?: string }; - const user = [...users.values()].find( - (entry) => entry.id === claims.sub, - ); + const user = bearer(request); if (user === undefined || value.masterPasswordHash !== user.hash) return refusal("Invalid password"); user.apiKey ??= randomBytes(15).toString("hex"); - await writeFile( - join(world, "apikeys"), - [...users.values()] - .filter((entry) => entry.apiKey !== null) - .map((entry) => `user.${entry.id} ${entry.apiKey} ${entry.email}\n`) - .join(""), - ); + await writeApiKeys(); return json({ apiKey: user.apiKey, object: "apiKey" }); } + if (url.pathname.startsWith("/api/")) { + const user = bearer(request); + if (user === undefined) return new Response(null, { status: 401 }); + if (url.pathname === "/api/accounts/profile") + return json({ + object: "profile", + id: user.id, + email: user.email, + organizations: [...organizations.values()].flatMap( + (organization) => { + const member = organization.members.get(user.id); + return member === undefined || member.status !== 2 + ? [] + : [ + { + object: "profileOrganization", + id: organization.id, + name: organization.name, + type: member.type, + status: member.status, + key: member.key, + enabled: true, + }, + ]; + }, + ), + }); + if ( + url.pathname === "/api/organizations" && + request.method === "POST" + ) { + if (flags.organizationRefused) + return refusal("User not allowed to create organizations"); + const keys = value.keys as Record | undefined; + if ( + typeof value.name !== "string" || + value.name === "" || + value.billingEmail !== user.email || + typeof value.key !== "string" || + !value.key.startsWith("4.") || + typeof keys?.publicKey !== "string" || + typeof keys.encryptedPrivateKey !== "string" || + !keys.encryptedPrivateKey.startsWith("2.") || + typeof value.collectionName !== "string" || + !value.collectionName.startsWith("2.") || + value.planType !== 0 + ) + return refusal("Invalid organization", 422); + const organization: FakeOrganization = { + id: randomUUID(), + name: value.name, + billingEmail: value.billingEmail, + publicKey: keys.publicKey, + encryptedPrivateKey: keys.encryptedPrivateKey, + members: new Map([ + [user.id, { key: value.key, type: 0, status: 2 }], + ]), + collections: [{ id: randomUUID(), name: value.collectionName }], + }; + organizations.set(organization.id, organization); + await syncWorld(); + return json(organizationJson(organization)); + } + const match = + /^\/api\/organizations\/([0-9a-f-]{36})(\/public-key|\/collections)?$/.exec( + url.pathname, + ); + const organization = + match === null ? undefined : organizations.get(match[1] as string); + const member = organization?.members.get(user.id); + if (match !== null) { + if (organization === undefined || member === undefined) + return refusal("Organization not found", 404); + if (match[2] === "/public-key" && request.method === "GET") + return json({ + object: "organizationPublicKey", + publicKey: organization.publicKey, + }); + if (match[2] === "/collections" && request.method === "GET") + return member.type > 1 + ? refusal("Resource not found.", 404) + : json({ + object: "list", + continuationToken: null, + data: organization.collections.map((collection) => ({ + object: "collection", + id: collection.id, + organizationId: organization.id, + name: collection.name, + externalId: null, + type: 0, + })), + }); + if (match[2] === undefined && request.method === "PUT") { + if (member.type !== 0) return refusal("Owner required", 404); + if (typeof value.name !== "string" || value.name === "") + return refusal("Invalid organization", 422); + organization.name = value.name; + organization.billingEmail = String(value.billingEmail); + await syncWorld(); + return json(organizationJson(organization)); + } + } + } return new Response("not found", { status: 404 }); }, }); + async function writeApiKeys() { + await writeFile( + join(world, "apikeys"), + [...users.values()] + .filter((entry) => entry.apiKey !== null) + .map((entry) => `user.${entry.id} ${entry.apiKey} ${entry.email}\n`) + .join(""), + ); + } const origin = `http://127.0.0.1:${server.port}`; - const write = (name: string, value: unknown) => - writeFile(join(world, name), `${JSON.stringify(value)}\n`); - const collection = (id: string, name: string) => ({ + const pilotCollection = (id: string, name: string) => ({ object: "collection", id, organizationId, @@ -387,47 +611,93 @@ export async function startFakeVault(home: string) { requests, flags, users, + organizations, /** The vault as the core asks it: the invented https origin mapped to * the loopback server. */ fetch: (url: string, init: RequestInit) => fetch(url.replace(vaultOrigin, origin), init), - invite: (email: string) => invited.add(email), - /** The Admin confirmed the member: the organization, its collections - * and items are what a sync brings. */ + /** The network pre-allows an address (`/admin/invite`, contract C2); a + * 0197 pilot's person invited it the same way. */ + allow: (email: string) => invited.add(email), + /** The organizations the account of `email` belongs to. */ + organizationsOf(email: string): FakeOrganization[] { + const user = users.get(email); + return [...organizations.values()].filter( + (organization) => + user !== undefined && organization.members.has(user.id), + ); + }, + /** The requests of one path (and method). */ + of(path: string, method?: string): FakeRequest[] { + return requests.filter( + (entry) => + entry.path === path && + (method === undefined || entry.method === method), + ); + }, + /** The network's operator deletes an organization (`/admin`). */ + async deleteOrganization(id: string) { + organizations.delete(id); + await syncWorld(); + }, + /** An Owner or Admin adds a collection. */ + async addCollection(id: string) { + organizations + .get(id) + ?.collections.push({ id: randomUUID(), name: "2.added|x|y" }); + await syncWorld(); + }, + /** The account's API key is rotated (or the account removed): the one + * the Environment keeps is refused from now on. */ + async rotateApiKey(email: string) { + const user = users.get(email); + if (user !== undefined) user.apiKey = randomBytes(15).toString("hex"); + await writeApiKeys(); + }, + /** A 0197 pilot's person confirmed the member: their organization, its + * collections and items are what a sync brings. */ async confirm( collectionName: string, items = 3, extra: readonly string[] = [], ) { - await write("orgs.json", [ - { - object: "organization", - id: organizationId, - name: "Example Organization", - status: 2, - type: 2, - enabled: true, - }, - ]); - await write("collections.json", [ - collection(collectionId, collectionName), - ...extra.map((name) => collection(otherCollectionId, name)), - ]); + pilotWorld = { + orgs: [ + { + object: "organization", + id: organizationId, + name: "Example Organization", + status: 2, + type: 2, + enabled: true, + }, + ], + collections: [ + pilotCollection(collectionId, collectionName), + ...extra.map((name) => pilotCollection(otherCollectionId, name)), + ], + }; + await syncWorld(); await write( "items.json", Array.from({ length: items }, (_, index) => ({ object: "item", id: randomUUID(), name: `example-${index}`, + organizationId, + collectionIds: [collectionId], login: { username: "example", password: "invented-value" }, })), ); }, - /** The Admin removed the member. */ + /** The pilot's person removed the member. */ async remove() { - for (const name of ["orgs.json", "collections.json", "items.json"]) - await rm(join(world, name), { force: true }); + pilotWorld = { orgs: [], collections: [] }; + await syncWorld(); + await rm(join(world, "items.json"), { force: true }); }, + /** The items a sync brings. */ + items: (list: readonly unknown[]) => write("items.json", list), unreachable: (on: boolean) => on ? writeFile(join(world, "unreachable"), "") @@ -440,9 +710,19 @@ export async function startFakeVault(home: string) { } export type FakeVault = Awaited>; -/** The personal Remote Environment at `` on a network whose control - * server is `headscale.example.lazurio.io`. */ -export function personalHandoverAt(host: string) { +/** The handover's `vault` member of an Environment in the fake network. */ +export const vaultMember = (account = ownAccount, name = vaultName) => ({ + server_url: vaultOrigin, + account, + name, +}); + +/** The personal Remote Environment at ``, on a network whose control + * server is `headscale.example.lazurio.io`, with or without its vault. */ +export function personalHandoverAt( + host: string, + vault: ReturnType | null = vaultMember(), +) { return parseMachineContext( Buffer.from( JSON.stringify({ @@ -452,14 +732,63 @@ export function personalHandoverAt(host: string) { headscale_server_url: `https://headscale.${zone}`, }, entry: handoverEntry(host), + ...(vault === null ? {} : { vault }), }), ), ); } -/** The personal Remote Environment of `example`. */ +/** The personal Remote Environment of `example`, with its own vault. */ export const personalHandover = personalHandoverAt("example.lazurio.io"); +/** The work Environment `workspace` of the Organization `example`. */ +export function workHandover( + vault: ReturnType | null = vaultMember( + workAccount, + "Example Pracovní workspace", + ), +) { + const { team: _, ...owner } = organization.owner; + return parseMachineContext( + Buffer.from( + JSON.stringify({ + ...organization, + owner, + network: { + ...organization.network, + headscale_server_url: `https://headscale.${zone}`, + }, + entry: handoverEntry("workspace.example.lazurio.io"), + ...(vault === null ? {} : { vault }), + }), + ), + ); +} + +/** The own vault's context of a handover. */ +export function ownContext( + handover = personalHandover, + environment: VaultEnvironmentKind = "personal", +): VaultContext { + const context = vaultContextOf({ handover, environment }); + if (context.kind !== "own") throw new Error("Expected an own vault"); + return context; +} + +/** The 0197 pilot's context of a handover without a vault. */ +export function pilotContext( + handover = personalHandoverAt("example.lazurio.io", null), + environment: VaultEnvironmentKind = "personal", +): PilotContext { + const context = pilotContextOf({ handover, environment }); + if (context === null) throw new Error("Expected a pilot"); + return context; +} + +/** The state directory of one account under a fake home. */ +export const stateDirectory = (home: string, host: string, key: string) => + join(home, ".local", "state", "lazurio", "vault", host, key); + /** A vault host on a private home with the fake vault and release. */ export function fakeHost( input: Readonly<{ @@ -472,24 +801,8 @@ export function fakeHost( }>, ): VaultHost { return { - context: - input.context ?? - (async () => - vaultContextOf({ - handover: personalHandover, - kind: "personal", - label: null, - })), - directory: (identity) => - join( - input.home, - ".local", - "state", - "lazurio", - "vault", - identity.host, - identity.address, - ), + context: input.context ?? (async () => ownContext()), + directory: (host, key) => stateDirectory(input.home, host, key), base: join(input.home, ".local", "share", "lazurio"), bin: join(input.home, ".local", "bin"), home: input.home, diff --git a/tests/folder-template-revision.test.ts b/tests/folder-template-revision.test.ts index 332b90242..28cb14d46 100644 --- a/tests/folder-template-revision.test.ts +++ b/tests/folder-template-revision.test.ts @@ -21,8 +21,8 @@ import { bindings } from "./fixtures/machine-bindings"; // `bun test -u` does not touch it. The fixtures in `tests/fixtures` feed the // compositions too. const pinned = { - revision: "base-instructions-48", - digest: "85405b0748616e94c6ba4fbc783325d8333b47f19f37d14bfc15d9b114698799", + revision: "base-instructions-49", + digest: "80e1bd55dc409004360600b81699abcf3d6078ec2e99e604a98e843d79868a1e", } as const; const optionalTools = activatableTools() diff --git a/tests/folder-tools.test.ts b/tests/folder-tools.test.ts index e15a3009a..b1862798c 100644 --- a/tests/folder-tools.test.ts +++ b/tests/folder-tools.test.ts @@ -735,7 +735,7 @@ test("a profile change and a handover refresh carry the enabled tools forward", }); test("a Folder rendered by an older template revision is upgraded by a tools change", async () => { - expect(instructionTemplateRevision).toBe("base-instructions-48"); + expect(instructionTemplateRevision).toBe("base-instructions-49"); const { preferences, manifest } = await planned(); const older = { ...manifest, @@ -758,7 +758,7 @@ test("a Folder rendered by an older template revision is upgraded by a tools cha recorded, ); if (upgrade.kind !== "profile-change") throw new Error("Expected upgrade"); - expect(upgrade.manifest.templateRevision).toBe("base-instructions-48"); + expect(upgrade.manifest.templateRevision).toBe("base-instructions-49"); expect(upgrade.previous).toEqual(older.outputs); expect(enabledTools(upgrade.preferences)).toEqual(tools); expect(upgrade.files).toEqual( diff --git a/tests/launchpad-vault.test.ts b/tests/launchpad-vault.test.ts index 11f3ff3d7..70bb74962 100644 --- a/tests/launchpad-vault.test.ts +++ b/tests/launchpad-vault.test.ts @@ -1,37 +1,68 @@ -import { expect, test } from "bun:test"; -import { mkdtemp, realpath, rm } from "node:fs/promises"; +import { expect, spyOn, test } from "bun:test"; +import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { initializeFolder } from "../src/folder/initialize-folder"; import { executionOs } from "../src/folder/platform"; import { startLaunchpad } from "../src/launchpad/server"; import { runTool } from "../src/tools/status"; -import type { VaultJournalEntry } from "../src/vault/flow"; +import type { VaultHost, VaultJournalEntry } from "../src/vault/flow"; +import { readSession, vaultPaths } from "../src/vault/store"; import { fakeBw, fakeHost, fakePin, fakeRelease, - fingerprint, + ownAccount, + pilotContext, startFakeVault, + stateDirectory, + vaultName, + vaultOrigin, zipOf, } from "./fixtures/fake-vault"; -// Settings → Tools → bitwarden over HTTP (decision F43): the four routes -// behind the admission of every route, `{}` only, a connect answered while it -// runs and joined by the next request, and the curated routes of F19 +// Settings → Tools → bitwarden over HTTP (decisions F43, F52): the three +// routes behind the admission of every route, `{}` only, a setup answered +// while it runs and joined by the next request, the Launchpad's own setup +// after its start (the Executor pattern), and the curated routes of F19 // refusing the vault. const posix = process.platform !== "win32"; -const account = "vaultwarden@example.lazurio.io"; type Json = Record; -async function session() { +/** Polls until `read` answers something, for at most `ms`. */ +async function until( + read: () => Promise, + ms = 30_000, +): Promise { + const deadline = Date.now() + ms; + for (;;) { + const value = await read(); + if (value) return value; + if (Date.now() > deadline) throw new Error("Timed out waiting"); + await Bun.sleep(25); + } +} + +async function session( + options: Readonly<{ + /** Present: the Launchpad of an install base, asked at its start + * whether it sets the vault up (`vaultAtStart`). */ + vaultAtStart?: () => Promise; + context?: VaultHost["context"]; + /** The host keeps no journal: the Launchpad journals itself. */ + launchpadJournal?: boolean; + /** The network pre-allowed the account before the Launchpad starts. */ + allowed?: boolean; + }> = {}, +) { const parent = await realpath( await mkdtemp(join(tmpdir(), "launchpad-vault-")), ); const home = join(parent, "home"); const vault = await startFakeVault(home); + if (options.allowed === true) vault.allow(ownAccount); const zip = zipOf("bw", fakeBw); const pin = fakePin(zip); const journal: VaultJournalEntry[] = []; @@ -44,11 +75,24 @@ async function session() { detail: "concise", coordination: "direct", }); + // The health socket of the base: a short path, within a socket's limit. + const base = join(parent, "b"); + await mkdir(join(base, "update"), { recursive: true }); + const host = fakeHost({ + home, + vault, + pin, + download: fakeRelease(pin, zip).fetch, + journal, + ...(options.context === undefined ? {} : { context: options.context }), + }); const app = await startLaunchpad( folder, undefined, undefined, - undefined, + options.vaultAtStart === undefined + ? undefined + : { base, version: "1.0.0", vaultAtStart: options.vaultAtStart }, {}, { path: "/usr/bin:/bin", @@ -64,13 +108,7 @@ async function session() { undefined, undefined, undefined, - fakeHost({ - home, - vault, - pin, - download: fakeRelease(pin, zip).fetch, - journal, - }), + options.launchpadJournal === true ? { ...host, journal: undefined } : host, ); const url = new URL(app.url); const call = (route: string, body: unknown, headers: Json = {}) => @@ -88,28 +126,32 @@ async function session() { const response = await call(route, body); return { status: response.status, body: (await response.json()) as Json }; }; - // A connect: started, then asked again while it runs. - const connect = async () => { + // A setup: started, then asked again while it runs. + const setup = async () => { const seen: string[] = []; let job: unknown; - for (let attempt = 0; attempt < 60; attempt++) { + for (let attempt = 0; attempt < 120; attempt++) { const answer = await json( - "/api/tools/bitwarden/connect", + "/api/tools/bitwarden/setup", job === undefined ? {} : { job }, ); if (answer.status !== 202) return { ...answer, seen }; - expect(answer.body.kind).toBe("vault-connecting"); + expect(answer.body.kind).toBe("vault-setting-up"); job = answer.body.job; seen.push(String(answer.body.phase)); } - throw new Error("The connect did not end"); + throw new Error("The setup did not end"); }; return { + home, vault, journal, call, json, - connect, + setup, + paths: vaultPaths( + stateDirectory(home, "vaultwarden.example.lazurio.io", ownAccount), + ), async close() { await app.close(); await vault.stop(); @@ -119,7 +161,7 @@ async function session() { } test.skipIf(!posix)( - "the vault routes connect, confirm, refresh and disconnect over the one core", + "the vault routes set the Environment's own vault up, refresh it and read it over the one core", async () => { const s = await session(); try { @@ -127,41 +169,43 @@ test.skipIf(!posix)( status: 200, body: { kind: "vault-status", - state: "not-installed", - vault: "https://vaultwarden.example.lazurio.io", - account, - collection: "Environmenty/Osobní · example", - name: "Osobní", + state: "not-set-up", + vault: vaultOrigin, + account: ownAccount, + name: vaultName, team: false, - registered: false, + origin: "own", + next: "install", }, }); - expect(await s.connect()).toMatchObject({ + expect(await s.setup()).toMatchObject({ status: 200, - body: { state: "awaiting-invite" }, + body: { state: "not-allowed" }, }); - s.vault.invite(account); - expect(await s.connect()).toMatchObject({ + s.vault.allow(ownAccount); + const done = await s.setup(); + expect(done).toMatchObject({ status: 200, - body: { state: "confirming", fingerprint }, + body: { state: "connected", organization: vaultName, items: 0 }, }); - await s.vault.confirm("Environmenty/Osobní · example", 4); + const [organization] = s.vault.organizationsOf(ownAccount); + expect(done.body.organizationId).toBe(organization?.id); expect(await s.json("/api/tools/bitwarden/refresh")).toMatchObject({ status: 200, - body: { state: "connected", collections: 1, items: 4 }, + body: { state: "connected", organizationId: organization?.id }, }); - expect(await s.json("/api/tools/bitwarden/disconnect")).toMatchObject({ + expect(await s.json("/api/tools/bitwarden/status")).toMatchObject({ status: 200, - body: { state: "none", registered: true }, + body: { state: "connected" }, }); - // Only codes went to the journal. - expect(s.journal.map((entry) => entry.operation)).toEqual([ - "connect", - "unlock", - "connect", - "refresh", - "disconnect", - ]); + // Only codes went to the journal, and no session to any answer. + const operations = s.journal.map((entry) => entry.operation); + expect(operations).toContain("setup"); + expect(operations).toContain("vault"); + expect(operations).toContain("refresh"); + const secret = (await readSession(s.paths)) ?? "?"; + expect(JSON.stringify(done.body)).not.toContain(secret); + expect(JSON.stringify(s.journal)).not.toContain(secret); } finally { await s.close(); } @@ -170,15 +214,14 @@ test.skipIf(!posix)( ); test.skipIf(!posix)( - "the vault routes take `{}` only, behind the admission, and the curated routes refuse the vault", + "the vault routes take `{}` only, behind the admission; connect and disconnect are gone; the curated routes refuse the vault", async () => { const s = await session(); try { for (const route of [ "/api/tools/bitwarden/status", "/api/tools/bitwarden/refresh", - "/api/tools/bitwarden/connect", - "/api/tools/bitwarden/disconnect", + "/api/tools/bitwarden/setup", ]) { expect( (await s.call(route, {}, { Authorization: "Bearer wrong" })).status, @@ -188,10 +231,15 @@ test.skipIf(!posix)( (await s.call(route, {}, { "Content-Type": "text/plain" })).status, ).toBe(415); } - // A connect is asked about only by the handle of the one that runs or + for (const route of [ + "/api/tools/bitwarden/connect", + "/api/tools/bitwarden/disconnect", + ]) + expect((await s.call(route, {})).status).toBe(404); + // A setup is asked about only by the handle of the one that runs or // ran last. expect( - await s.json("/api/tools/bitwarden/connect", { + await s.json("/api/tools/bitwarden/setup", { job: "0123456789abcdef0123456789abcdef", }), ).toEqual({ @@ -199,7 +247,7 @@ test.skipIf(!posix)( body: { kind: "blocked", reason: "job-unknown", tool: "bitwarden" }, }); expect( - (await s.call("/api/tools/bitwarden/connect", { job: "x" })).status, + (await s.call("/api/tools/bitwarden/setup", { job: "x" })).status, ).toBe(400); expect( ( @@ -223,3 +271,105 @@ test.skipIf(!posix)( }, 60_000, ); + +test.skipIf(!posix)( + "after its start the Launchpad sets the own vault up once in the background: the start does not wait, the row's status shows the job, and the journal names the start", + async () => { + const lines: string[] = []; + const log = spyOn(console, "log").mockImplementation( + (...values: unknown[]) => { + lines.push(values.map(String).join(" ")); + }, + ); + let asked = 0; + const s = await session({ + launchpadJournal: true, + allowed: true, + vaultAtStart: async () => { + asked++; + return true; + }, + }); + try { + // The status follows the setup the start began, then its end. + const ended = await until(async () => { + const answer = await s.json("/api/tools/bitwarden/status"); + return answer.status === 200 && answer.body.state === "connected" + ? answer + : null; + }); + expect(ended.body).toMatchObject({ + origin: "own", + organization: vaultName, + }); + expect(asked).toBe(1); + expect(s.vault.organizationsOf(ownAccount)).toHaveLength(1); + const vaultLines = lines + .filter((line) => line.includes('"tools-vault"')) + .map((line) => JSON.parse(line)); + expect(vaultLines).toContainEqual({ + scope: "tools-vault", + operation: "setup", + outcome: "connected", + trigger: "start", + }); + expect(vaultLines).toContainEqual({ + scope: "tools-vault", + operation: "vault", + outcome: "created", + trigger: "start", + }); + } finally { + log.mockRestore(); + await s.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "a Launchpad that is not a supervised base of the hosted operator, or a vault that needs no setup, sets nothing up at its start", + async () => { + // Not asked to (not a supervised hosted base). + const s = await session({ + allowed: true, + vaultAtStart: async () => false, + }); + try { + await Bun.sleep(300); + expect(await s.json("/api/tools/bitwarden/status")).toMatchObject({ + status: 200, + body: { state: "not-set-up", next: "install" }, + }); + expect(s.vault.requests).toHaveLength(0); + } finally { + await s.close(); + } + // A 0197 pilot (no vault in the handover) is only read. + let asked = false; + const pilot = await session({ + context: async () => pilotContext(), + vaultAtStart: async () => { + asked = true; + return true; + }, + }); + try { + await until(async () => asked); + await Bun.sleep(300); + expect(await pilot.json("/api/tools/bitwarden/status")).toEqual({ + status: 200, + body: { + kind: "vault-status", + state: "unsupported", + reason: "no-vault", + }, + }); + expect(pilot.vault.requests).toHaveLength(0); + expect(pilot.journal).toEqual([]); + } finally { + await pilot.close(); + } + }, + 60_000, +); diff --git a/tests/module-runtime-secrets.test.ts b/tests/module-runtime-secrets.test.ts index 450258307..bba0a361f 100644 --- a/tests/module-runtime-secrets.test.ts +++ b/tests/module-runtime-secrets.test.ts @@ -17,6 +17,7 @@ import { import type { RuntimeSecretSource } from "../src/modules/runtime-secrets"; import { readFolderCatalog } from "../src/organizations/catalog"; import type { CliContext } from "../src/update/cli"; +import type { SecretApplication, VaultSecretsRefusal } from "../src/vault/flow"; import { folderFixture, heldBy, @@ -24,7 +25,10 @@ import { writePersonalspaceModule, } from "./fixtures/catalog-folder"; import { createFakeServiceManager } from "./fixtures/fake-service-manager"; -import { organizationWithEntry } from "./fixtures/machine-bindings"; +import { + organizationWithEntry, + personalWithEntry, +} from "./fixtures/machine-bindings"; import { compilePlatform, linuxHost, @@ -36,8 +40,8 @@ import { } from "./fixtures/owned-files"; // The declared runtime secrets of an application, through the module -// operations the CLI and the Launchpad share (decision F46, root decisions -// 0177 and 0196): read before every start, passed to the application's own +// operations the CLI and the Launchpad share (decision F46 as F52 amends it, +// root decisions 0177, 0196 and 0198): read before every start, passed to the application's own // unit only, never as an argument of a process, never to the preparation's // check, never in an answer; a required one without a value refuses the // start with `runtime-secret-unavailable`, an optional one is a note. The @@ -72,17 +76,36 @@ function cliContext(home: string): CliContext { }; } -/** The vault of the work Environment of `example`: only its own apps read - * it, and it holds what `values` holds now. */ -function fakeVault(values: Record) { - const reads: { company: string; names: readonly string[] }[] = []; +/** Which applications a vault serves, as the vault core decides it. */ +type Rule = (application: SecretApplication) => VaultSecretsRefusal | null; +/** The work Environment of `example`: only its own apps. */ +const workVault: Rule = ({ company, personalspace }) => + personalspace + ? "personalspace" + : company.toLowerCase() === "example" + ? null + : "other-organization"; +/** A personal Environment: only the Personalspace's modules. */ +const personalVault: Rule = ({ personalspace }) => + personalspace ? null : "personal-environment"; +/** This computer: no vault yet. */ +const workstationVault: Rule = () => "workstation"; + +/** A vault that serves what `rule` admits and holds what `values` holds + * now. */ +function fakeVault(values: Record, rule: Rule = workVault) { + const reads: { + company: string; + personalspace: boolean; + names: readonly string[]; + }[] = []; const source: RuntimeSecretSource = { - admit: async (company) => - company.toLowerCase() === "example" ? null : "other-organization", - read: async ({ company, names }) => { - reads.push({ company, names }); - if (company.toLowerCase() !== "example") - return { kind: "vault-secrets-refused", reason: "other-organization" }; + admit: async (application) => rule(application), + read: async ({ company, personalspace, names }) => { + reads.push({ company, personalspace, names }); + const refused = rule({ company, personalspace }); + if (refused !== null) + return { kind: "vault-secrets-refused", reason: refused }; return { kind: "vault-secrets", secrets: new Map( @@ -196,7 +219,11 @@ posixTest( }); expect(JSON.stringify(started)).not.toContain(value); expect(vault.reads).toEqual([ - { company: "example", names: ["EXTERNAL_API_KEY", "OPTIONAL_KEY"] }, + { + company: "example", + personalspace: false, + names: ["EXTERNAL_API_KEY", "OPTIONAL_KEY"], + }, ]); const [unit] = [...manager.units.values()]; const environment = Object.fromEntries( @@ -435,7 +462,77 @@ posixTest( ); posixTest( - "a Personalspace module's required secrets have no vault: the catalog and the start say so, and optional ones are a note", + "a Personalspace module reads its secrets in its person's personal Environment, never on a workstation: the catalog and the start say so, and optional ones are a note there", + async () => { + // Its person's personal Remote Environment: the vault serves it. + const parent = await realpath(await mkdtemp(join(root, "personal-"))); + const folder = join(parent, "Lazurio"); + await mkdir(folder); + await mkdir(join(folder, "organizations"), { mode: 0o755 }); + await mkdir(join(folder, "personalspace"), { mode: 0o700 }); + const preset = "hosted-personal"; + await initializeHandoverFolder(folder, { + preset, + machine: personalWithEntry(), + profile: presetProfile(preset, executionOs(process.platform)), + }); + const home = join(parent, "home"); + await mkdir(home); + const module = await writePersonalspaceModule( + folder, + "privateowner", + "privatelogin", + { id: "notes" }, + ); + const port = await runnableModule(module, home); + const pkgPath = join(module, "app", "package.json"); + const pkg = JSON.parse(await readFile(pkgPath, "utf8")); + pkg.lazurio.runtime.secrets = ["EXTERNAL_API_KEY"]; + await writeFile(pkgPath, JSON.stringify(pkg)); + const vault = fakeVault({ EXTERNAL_API_KEY: value }, personalVault); + const manager = createFakeServiceManager({ + runtimeDirectory: join(parent, "runtime"), + }); + await mkdir(manager.runtimeDirectory); + const host: ModuleHost = { + ...linuxHost(manager, home, port, binary), + runtimeSecrets: () => vault.source, + }; + // The account holds this Personalspace (#186). + const holder = heldBy("privateowner"); + const catalogued = (await readFolderCatalog(folder, holder)).personalspace + ?.modules[0]; + expect(catalogued).toMatchObject({ executable: true }); + expect(catalogued).not.toHaveProperty("secrets"); + const operations = createModuleOperations({ + folder, + owner: "cli", + host, + personalspace: holder, + }); + const started = await operations.start("personalspace/notes"); + expect(started).toMatchObject({ outcome: "started", healthy: true }); + expect(JSON.stringify(started)).not.toContain(value); + expect(vault.reads).toEqual([ + { + company: "privatelogin", + personalspace: true, + names: ["EXTERNAL_API_KEY"], + }, + ]); + const [unit] = [...manager.units.values()]; + expect(unit?.environment).toContain( + `LAZURIO_RUNTIME_SECRET_EXTERNAL_API_KEY=${value}`, + ); + await operations.stop("personalspace/notes"); + await operations.close(); + await rm(parent, { recursive: true, force: true }); + }, + 60_000, +); + +posixTest( + "on a workstation a Personalspace module's required secrets have no vault: the catalog and the start say so, and optional ones are a note", async () => { await folderFixture(async (folder) => { const home = join(folder, "..", "home"); @@ -451,7 +548,7 @@ posixTest( const pkg = JSON.parse(await readFile(pkgPath, "utf8")); pkg.lazurio.runtime.secrets = ["EXTERNAL_API_KEY"]; await writeFile(pkgPath, JSON.stringify(pkg)); - const vault = fakeVault({ EXTERNAL_API_KEY: value }); + const vault = fakeVault({ EXTERNAL_API_KEY: value }, workstationVault); const manager = createFakeServiceManager({ runtimeDirectory: join(folder, "..", "runtime"), }); @@ -460,7 +557,7 @@ posixTest( ...linuxHost(manager, home, port, binary), runtimeSecrets: () => vault.source, }; - const finding = [{ name: "EXTERNAL_API_KEY", reason: "personalspace" }]; + const finding = [{ name: "EXTERNAL_API_KEY", reason: "workstation" }]; // The account holds this Personalspace (#186). const holder = heldBy("privateowner"); expect( @@ -492,7 +589,6 @@ posixTest( outcome: "started", secretsNotProvided: finding, }); - expect(vault.reads).toEqual([]); await operations.stop("personalspace/notes"); await operations.close(); }); diff --git a/tests/recover-sanitize.test.ts b/tests/recover-sanitize.test.ts index 18671e469..1d7f59ed9 100644 --- a/tests/recover-sanitize.test.ts +++ b/tests/recover-sanitize.test.ts @@ -62,6 +62,11 @@ function privateValue(random: Random, kind: PrivateKind): string { : `${random.word(1).toUpperCase()}${random.word(random.int(4, 10))}`; case "github-id": return String(random.int(100_000, 99_999_999)); + // The Environment's own vault (decision F52): its account and its name. + case "vault-account": + return `vaultwarden-${random.word(26, "abcdefghijklmnopqrstuvwxyz234567")}@${slug()}.lazurio.io`; + case "vault-name": + return `${random.word(1).toUpperCase()}${random.word(random.int(2, 5))} ${random.word(random.int(4, 9))} ${slug()}`; case "hostname": return `${slug()}.${random.word(5)}.example`; default: diff --git a/tests/runtime-secrets.test.ts b/tests/runtime-secrets.test.ts index d0a47cf47..5cc6174f6 100644 --- a/tests/runtime-secrets.test.ts +++ b/tests/runtime-secrets.test.ts @@ -7,16 +7,20 @@ import { readRuntimeSecrets, } from "../src/modules/runtime-secrets"; import type { + SecretApplication, VaultSecret, VaultSecretsRefusal, VaultSecretsResult, } from "../src/vault/flow"; // What an application's declared runtime secrets become at its start -// (decision F46, root decisions 0177 and 0196): the values of its required -// and optional names as `LAZURIO_RUNTIME_SECRET_`, a refusal naming -// every required name without a value, and a note for the optional ones it -// starts without. The source is a fake; every name and value is invented. +// (decision F46 as F52 amends it, root decisions 0177 and 0196): the values +// of its required and optional names as `LAZURIO_RUNTIME_SECRET_`, a +// refusal naming every required name without a value, and a note for the +// optional ones it starts without. Which applications the vault serves is +// the vault's to say: it is asked with the application's Organization and +// whether it is a Personalspace module. The source is a fake; every name and +// value is invented. const value = "fake-runtime-secret-value-4d2a"; @@ -32,18 +36,26 @@ function source( refused?: VaultSecretsRefusal, ) { const reads: (readonly string[])[] = []; - const admitted: string[] = []; + const admitted: SecretApplication[] = []; + const asked: SecretApplication[] = []; const fake: RuntimeSecretSource = { - admit: async (company) => { - admitted.push(company); + admit: async (application) => { + admitted.push(application); return refused === "workstation" || refused === "no-vault-identity" || - refused === "other-organization" + refused === "other-organization" || + refused === "personalspace" || + refused === "personal-environment" ? refused : null; }, - read: async ({ names }): Promise => { + read: async ({ + company, + personalspace, + names, + }): Promise => { reads.push(names); + asked.push({ company, personalspace }); if (refused !== undefined) return { kind: "vault-secrets-refused", reason: refused }; return { @@ -57,7 +69,7 @@ function source( }; }, }; - return { fake, reads, admitted }; + return { fake, reads, admitted, asked }; } async function refusal(work: Promise) { @@ -163,6 +175,8 @@ test("a vault the app cannot use refuses every required name, and with only opti "workstation", "no-vault-identity", "other-organization", + "personalspace", + "personal-environment", "not-connected", "locked", "busy", @@ -222,40 +236,53 @@ test("a vault the app cannot use refuses every required name, and with only opti ).toEqual([{ name: "EXTERNAL_API_KEY", reason: "vault-failed" }]); }); -test("a Personalspace module and an Environment without a composed vault read nothing; the admission before the install knows it", async () => { - const { fake, reads, admitted } = source({ - EXTERNAL_API_KEY: { kind: "value", value }, +test("the vault is asked with the application's Organization and kind, and decides; an Environment without a composed vault reads nothing", async () => { + // A personal Environment's vault serves a Personalspace module. + const served = source({ EXTERNAL_API_KEY: { kind: "value", value } }); + const personalspace = runtime(["EXTERNAL_API_KEY"], [], "personalspace"); + await admitRuntimeSecrets({ + runtime: personalspace, + personalspace: true, + source: served.fake, }); expect( - await refusal( - readRuntimeSecrets({ - runtime: runtime(["EXTERNAL_API_KEY"]), - personalspace: true, - source: fake, - }), - ), - ).toEqual([{ name: "EXTERNAL_API_KEY", reason: "personalspace" }]); + await readRuntimeSecrets({ + runtime: personalspace, + personalspace: true, + source: served.fake, + }), + ).toEqual({ + variables: { LAZURIO_RUNTIME_SECRET_EXTERNAL_API_KEY: value }, + notProvided: [], + }); + expect(served.admitted).toEqual([ + { company: "personalspace", personalspace: true }, + ]); + expect(served.asked).toEqual([ + { company: "personalspace", personalspace: true }, + ]); + // A work Environment's vault refuses it, before anything is installed. + const refused = source({}, "personalspace"); expect( await refusal( admitRuntimeSecrets({ - runtime: runtime(["EXTERNAL_API_KEY"]), + runtime: personalspace, personalspace: true, - source: fake, + source: refused.fake, }), ), ).toEqual([{ name: "EXTERNAL_API_KEY", reason: "personalspace" }]); expect( await readRuntimeSecrets({ - runtime: runtime([], ["OPTIONAL_KEY"]), + runtime: runtime([], ["OPTIONAL_KEY"], "personalspace"), personalspace: true, - source: fake, + source: refused.fake, }), ).toEqual({ variables: {}, notProvided: [{ name: "OPTIONAL_KEY", reason: "personalspace" }], }); - expect(reads).toEqual([]); - expect(admitted).toEqual([]); + // No vault composed: nothing is asked. expect( await refusal( readRuntimeSecrets({ @@ -264,7 +291,7 @@ test("a Personalspace module and an Environment without a composed vault read no }), ), ).toEqual([{ name: "EXTERNAL_API_KEY", reason: "no-vault-identity" }]); - // The admission asks the source about the Organization only. + // The admission asks about the application only, never its items. const other = source({}, "other-organization"); expect( await refusal( @@ -275,7 +302,7 @@ test("a Personalspace module and an Environment without a composed vault read no }), ), ).toEqual([{ name: "EXTERNAL_API_KEY", reason: "other-organization" }]); - expect(other.admitted).toEqual(["gamma"]); + expect(other.admitted).toEqual([{ company: "gamma", personalspace: false }]); expect(other.reads).toEqual([]); // Optional names never refuse the admission. await admitRuntimeSecrets({ @@ -284,7 +311,7 @@ test("a Personalspace module and an Environment without a composed vault read no }); }); -test("the catalog's check knows a workstation, a Personalspace module and another Organization's app without the vault", async () => { +test("the catalog's check knows, without the vault, a workstation and the applications a work or a personal Environment does not serve", async () => { type Place = Parameters[2]; const workstation: Place = async () => ({ kind: "workstation" }); const owned: Place = async () => ({ @@ -310,19 +337,29 @@ test("the catalog's check knows a workstation, a Personalspace module and anothe reason: "runtime-secret-unavailable", secrets: [{ name: "EXTERNAL_API_KEY", reason: "other-organization" }], }); + // A personal Environment's vault serves the Personalspace's modules, not + // an Organization's app (root decision 0198 point 4). expect(await declaredSecretsFinding(required, false, personal)).toEqual({ reason: "runtime-secret-unavailable", - secrets: [{ name: "EXTERNAL_API_KEY", reason: "other-organization" }], + secrets: [{ name: "EXTERNAL_API_KEY", reason: "personal-environment" }], }); - expect(await declaredSecretsFinding(required, true, unknown)).toEqual({ + expect(await declaredSecretsFinding(required, true, personal)).toEqual({}); + // A work Environment's vault does not serve a Personalspace module. + expect(await declaredSecretsFinding(required, true, owned)).toEqual({ reason: "runtime-secret-unavailable", secrets: [{ name: "EXTERNAL_API_KEY", reason: "personalspace" }], }); + expect(await declaredSecretsFinding(required, true, workstation)).toEqual({ + reason: "runtime-secret-unavailable", + secrets: [{ name: "EXTERNAL_API_KEY", reason: "workstation" }], + }); + // Unknown: the start decides. + expect(await declaredSecretsFinding(required, true, unknown)).toEqual({}); // Only optional names: a note, never a refusal. expect( - await declaredSecretsFinding(runtime([], ["OPTIONAL_KEY"]), true, unknown), + await declaredSecretsFinding(runtime([], ["OPTIONAL_KEY"]), true, owned), ).toEqual({ secretsNotProvided: [{ name: "OPTIONAL_KEY", reason: "personalspace" }], }); - expect(await declaredSecretsFinding(runtime([]), true, unknown)).toEqual({}); + expect(await declaredSecretsFinding(runtime([]), true, owned)).toEqual({}); }); diff --git a/tests/vault-cli.test.ts b/tests/vault-cli.test.ts index 6d30a5a45..894d8fc14 100644 --- a/tests/vault-cli.test.ts +++ b/tests/vault-cli.test.ts @@ -19,9 +19,10 @@ import { exportsOf, runVaultCommand, shellQuote, + statusText, type VaultCliContext, } from "../src/vault/cli"; -import { readSession, vaultPaths } from "../src/vault/store"; +import { readRecord, readSession, vaultPaths } from "../src/vault/store"; import { collectionId, fakeBw, @@ -29,15 +30,18 @@ import { fakePin, fakeRelease, organizationId, + ownAccount, startFakeVault, + stateDirectory, + vaultName, + vaultOrigin, zipOf, } from "./fixtures/fake-vault"; -// `lazurio vault` (decision F43): what an agent's shell gets, what it reads -// when there is nothing to get, and the commands over the same core. +// `lazurio vault` (decisions F43, F52): what an agent's shell gets, what it +// reads when there is nothing to get, and the commands over the same core. const posix = process.platform !== "win32"; -const account = "vaultwarden@example.lazurio.io"; async function world() { const parent = await realpath(await mkdtemp(join(tmpdir(), "vault-cli-"))); @@ -67,15 +71,7 @@ async function world() { context, progress, paths: vaultPaths( - join( - home, - ".local", - "state", - "lazurio", - "vault", - "vaultwarden.example.lazurio.io", - "example.lazurio.io", - ), + stateDirectory(home, "vaultwarden.example.lazurio.io", ownAccount), ), async close() { await vault.stop(); @@ -115,32 +111,47 @@ test.skipIf(!posix)( async () => { const w = await world(); try { - // Not connected: a refusal an agent can read, exit 2, no stdout. + // Not set up: a refusal an agent can read, exit 2, no stdout. const refused = await runVaultCommand(["env"], w.context); expect(refused.code).toBe(2); expect(refused.stdout).toBeUndefined(); expect(refused.stderr?.split("\n")).toHaveLength(1); - expect(refused.stderr).toContain("Settings → Tools → bitwarden"); + expect(refused.stderr).toContain("not set up yet"); + expect(refused.stderr).toContain("lazurio vault status"); - // An agent connects (the fallback of the Launchpad's flow). - w.vault.invite(account); - const connect = await runVaultCommand(["connect"], w.context); - expect(connect.code).toBe(0); - expect(connect.stdout).toContain("Waiting for the confirmation"); - expect(connect.stdout).toContain("steep-flavor-uncut-scouring-unnoticed"); + // Not allowed by the network yet: exit 2, waiting for a person. + const notAllowed = await runVaultCommand(["setup"], w.context); + expect(notAllowed.code).toBe(2); + expect(notAllowed.stdout).toContain("Not allowed yet"); + + // An agent sets it up (what the Launchpad does at its start). + w.vault.allow(ownAccount); + w.progress.length = 0; + const setup = await runVaultCommand(["setup"], w.context); + expect(setup.code).toBe(0); + const record = await readRecord(w.paths); + expect(setup.stdout).toBe( + `Connected: this Environment's own vault "${vaultName}", ${ownAccount} in ${vaultOrigin}; it holds 0 items. Open it at ${vaultOrigin}/#/vault?organizationId=${record.organizationId}.`, + ); expect(w.progress).toEqual([ "Installing the pinned Bitwarden CLI…", - "Creating the account…", + "Registering the account…", + "Setting up the Environment's vault…", "Signing in…", ]); - await w.vault.confirm("Environmenty/Osobní · example", 2); + const status = await runVaultCommand(["status", "--json"], w.context); + expect(status.code).toBe(0); + expect(JSON.parse(status.stdout ?? "")).toMatchObject({ + kind: "vault-status", + state: "connected", + origin: "own", + organizationId: record.organizationId, + collectionId: record.collectionId, + }); const refreshed = await runVaultCommand(["refresh", "--json"], w.context); expect(refreshed.code).toBe(0); expect(JSON.parse(refreshed.stdout ?? "")).toMatchObject({ - kind: "vault-status", state: "connected", - collections: 1, - items: 2, }); const env = await runVaultCommand(["env"], w.context); @@ -151,8 +162,8 @@ test.skipIf(!posix)( [ `export BITWARDENCLI_APPDATA_DIR='${w.paths.data}'`, `export BW_SESSION='${session}'`, - `export LAZURIO_VAULT_ORGANIZATION_ID='${organizationId}'`, - `export LAZURIO_VAULT_COLLECTION_ID='${collectionId}'`, + `export LAZURIO_VAULT_ORGANIZATION_ID='${record.organizationId}'`, + `export LAZURIO_VAULT_COLLECTION_ID='${record.collectionId}'`, ].join("\n"), ); const json = await runVaultCommand(["env", "--json"], w.context); @@ -161,15 +172,14 @@ test.skipIf(!posix)( env: { BITWARDENCLI_APPDATA_DIR: w.paths.data, BW_SESSION: session, - LAZURIO_VAULT_ORGANIZATION_ID: organizationId, - LAZURIO_VAULT_COLLECTION_ID: collectionId, + LAZURIO_VAULT_ORGANIZATION_ID: record.organizationId, + LAZURIO_VAULT_COLLECTION_ID: record.collectionId, }, }); // The status never carries a secret. - const status = await runVaultCommand(["status", "--json"], w.context); expect(status.stdout).not.toContain(session ?? "?"); - expect(status.code).toBe(0); - // An agent's `bw` after eval: the pinned one, with the session. + // An agent's `bw` after eval: the pinned one, with the session, sees + // the vault's collection Agenti. const shell = spawnSync( "/bin/sh", [ @@ -182,7 +192,11 @@ test.skipIf(!posix)( { encoding: "utf8", env: { HOME: w.home, PATH: "/usr/bin:/bin" } }, ); expect(JSON.parse(shell.stdout)).toEqual([ - expect.objectContaining({ id: collectionId }), + expect.objectContaining({ + id: record.collectionId, + organizationId: record.organizationId, + name: "Agenti", + }), ]); // Without eval the wrapper still uses this Environment's data, which // says locked instead of reaching a default profile. @@ -205,6 +219,47 @@ test.skipIf(!posix)( 60_000, ); +test("the status in words names what is missing and never a secret", () => { + const facts = { + kind: "vault-status", + vault: vaultOrigin, + account: ownAccount, + name: vaultName, + team: false, + origin: "own", + } as const; + expect( + statusText({ + kind: "vault-status", + state: "unsupported", + reason: "no-vault", + }), + ).toBe( + "Not available: this Environment has no vault yet: its Machine handover names none.", + ); + expect(statusText({ ...facts, state: "not-set-up", next: "vault" })).toBe( + `Not set up yet: ${ownAccount} in ${vaultOrigin}; the next step is creating the Environment's vault. The Launchpad sets it up at its start; lazurio vault setup does the same.`, + ); + expect(statusText({ ...facts, state: "revoked" })).toContain( + "The network's operator decides", + ); + expect( + statusText({ + ...facts, + name: null, + origin: "pilot-0197", + account: "vaultwarden@example.lazurio.io", + state: "connected", + organizationId, + collectionId, + organization: "Example Organization", + items: 2, + }), + ).toBe( + `Connected the 0197 way (read only until this Environment's own vault replaces it): vaultwarden@example.lazurio.io in ${vaultOrigin}, collection ${collectionId} of Example Organization; it holds 2 items.`, + ); +}); + test("a wrong invocation is a usage error with the help", async () => { const context: VaultCliContext = { identity: embeddedIdentity(), @@ -230,6 +285,8 @@ test("a wrong invocation is a usage error with the help", async () => { for (const args of [ [], ["login"], + ["connect"], + ["disconnect"], ["env", "extra"], ["env", "--json", "--json"], ["status", "--session", "x"], @@ -290,7 +347,7 @@ test.skipIf(!posix)( kind: "blocked", reason: "setup-vault", tool: "bitwarden", - command: "lazurio vault connect", + command: "lazurio vault setup", }); } } finally { diff --git a/tests/vault-context.test.ts b/tests/vault-context.test.ts index 5a951fc99..d390331d4 100644 --- a/tests/vault-context.test.ts +++ b/tests/vault-context.test.ts @@ -1,20 +1,21 @@ import { expect, test } from "bun:test"; import { parseMachineContext } from "../src/machine/context"; +import { vaultContextOf, vaultStateDirectory } from "../src/vault/context"; +import { pilotContextOf, pilotVaultOf } from "../src/vault/legacy-0197/context"; import { - collectionNameOf, - environmentNameOf, - isEnvironmentCollection, - vaultContextOf, - vaultOriginOf, - vaultStateDirectory, -} from "../src/vault/context"; + ownAccount, + vaultMember, + vaultName, + workAccount, +} from "./fixtures/fake-vault"; import { assignments, handoverEntry } from "./fixtures/machine-bindings"; import organization from "./fixtures/machine-context.json"; import personal from "./fixtures/machine-context-personal.json"; -// The Environment vault's facts (decision F43): the vault from the handover's -// tailnet control server, the account from the Environment's address, the -// collection from its name and machine. Invented hosts only. +// The Environment's vault facts (decision F52): everything from the +// handover's `vault` member, nothing derived or guessed; and the 0197 pilot's +// facts, derived as F43 derived them, only where the handover names no +// vault. Invented hosts only. const network = { headscale_server_url: "https://headscale.example.lazurio.io", @@ -22,30 +23,71 @@ const network = { }; const handover = (document: unknown) => parseMachineContext(Buffer.from(JSON.stringify(document))); -const personalVm = handover({ - ...personal, - network, - entry: handoverEntry("example.lazurio.io"), -}); const { team: _, ...withoutTeam } = organization.owner; -const workVm = handover({ - ...organization, - owner: { ...withoutTeam, assignment: assignments.operator }, - network: { ...network, headscale_hostname: "example-workspace" }, - entry: handoverEntry("workspace.example.lazurio.io"), +const personalVm = (vault: unknown = vaultMember()) => + handover({ + ...personal, + network, + entry: handoverEntry("example.lazurio.io"), + ...(vault === null ? {} : { vault }), + }); +const workVm = (vault: unknown = vaultMember(workAccount, "Example work")) => + handover({ + ...organization, + owner: { ...withoutTeam, assignment: assignments.operator }, + network: { ...network, headscale_hostname: "example-workspace" }, + entry: handoverEntry("workspace.example.lazurio.io"), + ...(vault === null ? {} : { vault }), + }); + +test("a personal Remote Environment's vault is exactly the handover's member", () => { + expect( + vaultContextOf({ handover: personalVm(), environment: "personal" }), + ).toEqual({ + kind: "own", + vault: "https://vaultwarden.example.lazurio.io", + host: "vaultwarden.example.lazurio.io", + account: ownAccount, + name: vaultName, + environment: "personal", + organization: null, + }); }); -const teamVm = handover({ - ...organization, - owner: { ...organization.owner, assignment: assignments.team }, - network: { ...network, headscale_hostname: "example-workspace" }, - entry: handoverEntry("workspace.example.lazurio.io"), + +test("a work, Team or Automated Environment's vault names the Organization that owns it", () => { + for (const environment of ["work", "team", "automated"] as const) + expect(vaultContextOf({ handover: workVm(), environment })).toEqual({ + kind: "own", + vault: "https://vaultwarden.example.lazurio.io", + host: "vaultwarden.example.lazurio.io", + account: workAccount, + name: "Example work", + environment, + organization: "example", + }); +}); + +test("without the member the Environment has no vault yet, whatever else the handover says", () => { + for (const document of [personalVm(null), workVm(null)]) + expect( + vaultContextOf({ handover: document, environment: "personal" }), + ).toEqual({ kind: "unsupported", reason: "no-vault" }); + // Neither the tailnet nor the address derives a vault any more. + const { entry: _entry, ...noEntry } = { + ...personal, + network, + vault: vaultMember(), + } as Record; + expect( + vaultContextOf({ handover: handover(noEntry), environment: "personal" }), + ).toMatchObject({ kind: "own", account: ownAccount }); }); -test("the vault of a network is vaultwarden. of its headscale., nothing else", () => { - expect(vaultOriginOf("https://headscale.example.lazurio.io")).toBe( +test("the pilot's vault is vaultwarden. of its headscale., nothing else", () => { + expect(pilotVaultOf("https://headscale.example.lazurio.io")).toBe( "https://vaultwarden.example.lazurio.io", ); - expect(vaultOriginOf("https://headscale.example.lazurio.io/")).toBe( + expect(pilotVaultOf("https://headscale.example.lazurio.io/")).toBe( "https://vaultwarden.example.lazurio.io", ); for (const refused of [ @@ -59,154 +101,90 @@ test("the vault of a network is vaultwarden. of its headscale., noth "https://xheadscale.example.lazurio.io", "not a url", ]) - expect([refused, vaultOriginOf(refused)]).toEqual([refused, null]); + expect([refused, pilotVaultOf(refused)]).toEqual([refused, null]); }); -test("a personal Remote Environment: its slug, its kind's name, the person's network", () => { +test("the pilot's account is vaultwarden@
, and without an address or a vault there is no pilot", () => { expect( - vaultContextOf({ handover: personalVm, kind: "personal", label: null }), + pilotContextOf({ handover: personalVm(null), environment: "personal" }), ).toEqual({ + kind: "pilot", vault: "https://vaultwarden.example.lazurio.io", host: "vaultwarden.example.lazurio.io", address: "example.lazurio.io", account: "vaultwarden@example.lazurio.io", - machine: "example", - kind: "personal", - name: "Osobní", - collection: "Environmenty/Osobní · example", - // A person owns it: no Organization's application reads its secrets. + environment: "personal", organization: null, }); -}); - -test("a work, Team and Automated Environment: . and the name the rail gives it", () => { expect( - vaultContextOf({ handover: workVm, kind: "work", label: null }), + pilotContextOf({ handover: workVm(null), environment: "work" }), ).toMatchObject({ address: "workspace.example.lazurio.io", account: "vaultwarden@workspace.example.lazurio.io", - machine: "workspace", - name: "Pracovní", - collection: "Environmenty/Pracovní · workspace", - // The handover's owning Organization (decision F46). organization: "example", }); - expect( - vaultContextOf({ handover: teamVm, kind: "team", label: "Team Sales" }), - ).toMatchObject({ - name: "Team Sales", - collection: "Environmenty/Team Sales · workspace", - }); - // Without the catalog's label: the kind's name, as the rail shows it. - expect( - vaultContextOf({ handover: teamVm, kind: "team", label: null }), - ).toMatchObject({ collection: "Environmenty/Týmový · workspace" }); - expect( - vaultContextOf({ handover: workVm, kind: "automated", label: "Steward" }), - ).toMatchObject({ collection: "Environmenty/Steward · workspace" }); -}); - -test("without an entry, a tailnet or a known vault the context fails closed", () => { const { entry: _entry, ...noEntry } = { ...personal, network } as Record< string, unknown >; - for (const [document, reason] of [ - [noEntry, "no-address"], - [ - { - ...personal, - network: { - ...network, - headscale_server_url: "https://network.example.invalid", - }, - entry: handoverEntry("example.lazurio.io"), + for (const document of [ + noEntry, + { + ...personal, + network: { + ...network, + headscale_server_url: "https://network.example.invalid", }, - "vault-unknown", - ], + entry: handoverEntry("example.lazurio.io"), + }, // A personal VM whose entry names an Organization's address. - [ - { - ...personal, - network, - entry: handoverEntry("workspace.example.lazurio.io"), - }, - "no-address", - ], - // An entry outside lazurio.io. - [ - { ...personal, network, entry: handoverEntry("example.example.invalid") }, - "no-address", - ], - ] as const) + { + ...personal, + network, + entry: handoverEntry("workspace.example.lazurio.io"), + }, + { ...personal, network, entry: handoverEntry("example.example.invalid") }, + ]) expect( - vaultContextOf({ + pilotContextOf({ handover: handover(document), - kind: "personal", - label: null, - }), - ).toEqual({ kind: "unsupported", reason }); - const { network: _network, ...noNetwork } = organization; - expect( - vaultContextOf({ - handover: handover({ - ...noNetwork, - entry: handoverEntry("workspace.example.lazurio.io"), + environment: "personal", }), - kind: "work", - label: null, - }), - ).toEqual({ kind: "unsupported", reason: "no-network" }); + ).toBeNull(); }); -test("the collection is the Environment's by its machine; a label that would nest is not used", () => { - expect(collectionNameOf("Osobní", "example")).toBe( - "Environmenty/Osobní · example", - ); - const context = { machine: "workspace" }; - for (const [name, own] of [ - ["Environmenty/Pracovní · workspace", true], - ["Environmenty/Team Sales · workspace", true], - ["Environmenty/ · workspace", false], - ["Environmenty/Pracovní · workspace-2", false], - ["Infrastruktura", false], - ["Pracovní · workspace", false], - ] as const) - expect([name, isEnvironmentCollection(name, context)]).toEqual([name, own]); - expect(environmentNameOf("team", "Sales/EU")).toBe("Týmový"); - expect(environmentNameOf("team", " ")).toBe("Týmový"); - expect(environmentNameOf("team", "Team\u0007")).toBe("Týmový"); - expect(environmentNameOf("automated", "Steward")).toBe("Steward"); -}); - -test("the account's state directory is its whole identity and follows XDG_STATE_HOME when it is absolute", () => { - const identity = { - host: "vaultwarden.example.lazurio.io", - address: "workspace.example.lazurio.io", - }; - expect(vaultStateDirectory(identity, "/home/operator", {})).toBe( - "/home/operator/.local/state/lazurio/vault/vaultwarden.example.lazurio.io/workspace.example.lazurio.io", +test("the account's state directory is keyed by the vault and the account, follows XDG_STATE_HOME when it is absolute, and refuses a path", () => { + const host = "vaultwarden.example.lazurio.io"; + expect(vaultStateDirectory(host, ownAccount, "/home/operator", {})).toBe( + `/home/operator/.local/state/lazurio/vault/${host}/${ownAccount}`, ); expect( - vaultStateDirectory(identity, "/home/operator", { + vaultStateDirectory(host, ownAccount, "/home/operator", { XDG_STATE_HOME: "/var/state/operator", }), - ).toBe( - "/var/state/operator/lazurio/vault/vaultwarden.example.lazurio.io/workspace.example.lazurio.io", - ); + ).toBe(`/var/state/operator/lazurio/vault/${host}/${ownAccount}`); expect( - vaultStateDirectory(identity, "/home/operator", { + vaultStateDirectory(host, ownAccount, "/home/operator", { XDG_STATE_HOME: "relative/state", }), - ).toBe( - "/home/operator/.local/state/lazurio/vault/vaultwarden.example.lazurio.io/workspace.example.lazurio.io", - ); - // Another address in the same vault is another directory. + ).toBe(`/home/operator/.local/state/lazurio/vault/${host}/${ownAccount}`); + // A pilot's directory (its address) is another one beside it. expect( - vaultStateDirectory( - { ...identity, address: "workspace-2.example.lazurio.io" }, - "/home/operator", - {}, - ), - ).not.toBe(vaultStateDirectory(identity, "/home/operator", {})); + vaultStateDirectory(host, "example.lazurio.io", "/home/operator", {}), + ).not.toBe(vaultStateDirectory(host, ownAccount, "/home/operator", {})); + for (const [refusedHost, key] of [ + [host, "../escape"], + [host, ".."], + [host, "a/b"], + ["", ownAccount], + [host, ""], + ]) + expect(() => + vaultStateDirectory( + refusedHost as string, + key as string, + "/home/operator", + {}, + ), + ).toThrow(); }); diff --git a/tests/vault-flow.test.ts b/tests/vault-flow.test.ts index 8dc742ffb..fc5ac1a29 100644 --- a/tests/vault-flow.test.ts +++ b/tests/vault-flow.test.ts @@ -9,15 +9,14 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { vaultContextOf } from "../src/vault/context"; import { + setUpAtStart, type VaultHost, type VaultJournalEntry, type VaultStatus, - vaultConnect, - vaultDisconnect, vaultEnv, vaultRefresh, + vaultSetup, vaultStatus, } from "../src/vault/flow"; import { pinnedBinary } from "../src/vault/install"; @@ -28,24 +27,29 @@ import { vaultPaths, } from "../src/vault/store"; import { - collectionId, fakeBw, fakeHost, fakePin, fakeRelease, - fingerprint, - organizationId, - otherCollectionId, - personalHandover, + ownAccount, + ownContext, personalHandoverAt, startFakeVault, + stateDirectory, + vaultMember, + vaultName, vaultOrigin, zipOf, } from "./fixtures/fake-vault"; +// The Environment's own vault (root decision 0198, decision F52) through its +// one core: the account the handover names registers itself, creates the +// Environment's own organization with the collection Agenti, keeps it by ID +// and one shared session for its agents. Against the fake Vaultwarden and the +// fake bw; every name, id and value is invented. + const posix = process.platform !== "win32"; -const account = "vaultwarden@example.lazurio.io"; -const collection = "Environmenty/Osobní · example"; +const host = "vaultwarden.example.lazurio.io"; async function world() { const parent = await realpath(await mkdtemp(join(tmpdir(), "vault-flow-"))); @@ -55,32 +59,24 @@ async function world() { const pin = fakePin(zip); const release = fakeRelease(pin, zip); const journal: VaultJournalEntry[] = []; - const host = fakeHost({ + const host_ = fakeHost({ home, vault, pin, download: release.fetch, journal, }); - const paths = vaultPaths( - join( - home, - ".local", - "state", - "lazurio", - "vault", - "vaultwarden.example.lazurio.io", - "example.lazurio.io", - ), - ); + const paths = vaultPaths(stateDirectory(home, host, ownAccount)); return { home, vault, pin, release, journal, - host, + host: host_, paths, + /** The own organizations of the account. */ + owned: () => vault.organizationsOf(ownAccount), async close() { await vault.stop(); await rm(parent, { recursive: true, force: true }); @@ -89,144 +85,136 @@ async function world() { } const mode = async (path: string) => (await lstat(path)).mode & 0o777; +const facts = { + vault: vaultOrigin, + account: ownAccount, + name: vaultName, + team: false, + origin: "own", +} as const; test.skipIf(!posix)( - "an Environment connects: not invited, invited and confirming, confirmed and connected, revoked, disconnected and back", + "an Environment sets up its own vault: not allowed, then registered, its organization created with Agenti, connected, and set up again without a change", async () => { const w = await world(); try { - // Nothing yet: the facts the operator needs to invite the account. + // Nothing yet, and nothing is read from the network. expect(await vaultStatus(w.host)).toEqual({ kind: "vault-status", - state: "not-installed", - vault: vaultOrigin, - account, - collection, - name: "Osobní", - team: false, - registered: false, + state: "not-set-up", + ...facts, + next: "install", }); + expect(w.vault.requests).toHaveLength(0); - // Not invited: the vault refuses the registration and nothing of the - // account is left behind (the CLI is installed by then). + // Not pre-allowed: the vault refuses the registration and nothing of + // the account is left behind (the CLI is installed by then). const phases: string[] = []; - expect( - await vaultConnect(w.host, (phase) => phases.push(phase)), - ).toMatchObject({ state: "awaiting-invite", account, collection }); + expect(await vaultSetup(w.host, (phase) => phases.push(phase))).toEqual({ + kind: "vault-status", + state: "not-allowed", + ...facts, + }); expect(phases).toEqual(["install", "account"]); expect(await readAccount(w.paths)).toBeNull(); expect(w.vault.users.size).toBe(0); expect(await vaultStatus(w.host)).toMatchObject({ - state: "none", - registered: false, + state: "not-set-up", + next: "account", }); - // Invited: the account is created, signed in and unlocked; it waits - // for the Admin's confirmation by its fingerprint. - w.vault.invite(account); + // Pre-allowed by the network: registered, its own vault created, bw + // signed in and unlocked. + w.vault.allow(ownAccount); phases.length = 0; - expect(await vaultConnect(w.host, (phase) => phases.push(phase))).toEqual( - { - kind: "vault-status", - state: "confirming", - vault: vaultOrigin, - account, - collection, - name: "Osobní", - team: false, - fingerprint, - organization: null, + const connected = await vaultSetup(w.host, (phase) => phases.push(phase)); + expect(phases).toEqual(["install", "account", "vault", "sign-in"]); + const [organization] = w.owned(); + if (organization === undefined) throw new Error("Expected the vault"); + const agentsId = organization.collections[0]?.id ?? "?"; + expect(connected).toEqual({ + kind: "vault-status", + state: "connected", + ...facts, + organizationId: organization.id, + collectionId: agentsId, + organization: vaultName, + items: 0, + }); + // Exactly one organization, named as the handover says, with the + // account its only member, an Owner, and one collection. + expect(w.owned()).toHaveLength(1); + expect(organization.name).toBe(vaultName); + expect(organization.billingEmail).toBe(ownAccount); + expect([...organization.members.values()]).toEqual([ + expect.objectContaining({ type: 0, status: 2 }), + ]); + expect(organization.collections).toHaveLength(1); + // The request carries keys only in their encrypted forms. + const [created] = w.vault.of("/api/organizations", "POST"); + expect(created?.body).toEqual({ + name: vaultName, + billingEmail: ownAccount, + key: expect.stringMatching(/^4\./), + keys: { + publicKey: expect.stringMatching(/^[A-Za-z0-9+/]+=*$/), + encryptedPrivateKey: expect.stringMatching(/^2\./), }, - ); - expect(phases).toEqual(["install", "account", "sign-in"]); - const stored = await readAccount(w.paths); - expect(stored).toMatchObject({ - email: account, - server: vaultOrigin, + collectionName: expect.stringMatching(/^2\./), + planType: 0, }); + // The vault is remembered by its ID, and so is Agenti. + expect(await readRecord(w.paths)).toEqual({ + organizationId: organization.id, + collectionId: agentsId, + pendingKey: null, + }); + expect(w.journal).toContainEqual({ + operation: "vault", + outcome: "created", + }); + const stored = await readAccount(w.paths); + expect(stored).toMatchObject({ email: ownAccount, server: vaultOrigin }); expect(stored?.clientId).toBe( - `user.${w.vault.users.get(account)?.id ?? "?"}`, + `user.${w.vault.users.get(ownAccount)?.id ?? "?"}`, ); - // The one device of the Environment is the account file's. - expect(w.vault.users.get(account)?.devices).toEqual([ + // The one device of the Environment is the account file's, for the + // password and the API-key logins alike. + expect(w.vault.users.get(ownAccount)?.devices).toEqual([ stored?.deviceIdentifier ?? "?", ]); expect(await mode(w.paths.directory)).toBe(0o700); expect(await mode(w.paths.data)).toBe(0o700); expect(await mode(w.paths.account)).toBe(0o600); expect(await mode(w.paths.session)).toBe(0o600); - expect(await vaultStatus(w.host)).toMatchObject({ - state: "confirming", - fingerprint, - }); - // Not connected yet: agents get nothing. - expect(await vaultEnv(w.host)).toEqual({ - kind: "vault-env-refused", - reason: "not-connected", - }); + expect(await mode(w.paths.record)).toBe(0o600); - // Confirmed by the Admin: the next refresh sees the collection. - await w.vault.confirm(collection, 3, ["Infrastruktura"]); - const connected: VaultStatus = { - kind: "vault-status", - state: "connected", - vault: vaultOrigin, - account, - collection, - name: "Osobní", - team: false, - fingerprint, - organization: "Example Organization", - collections: 2, - items: 3, - }; - expect(await vaultRefresh(w.host)).toEqual(connected); // The local status reads the same from bw's copy. expect(await vaultStatus(w.host)).toEqual(connected); + expect(setUpAtStart(connected)).toBe(false); - // Agents get the one unlocked session and the collection. + // Agents get the one unlocked session, the vault and Agenti. const session = await readSession(w.paths); expect(await vaultEnv(w.host)).toEqual({ kind: "vault-env", env: { BITWARDENCLI_APPDATA_DIR: w.paths.data, BW_SESSION: session ?? "?", - LAZURIO_VAULT_ORGANIZATION_ID: organizationId, - LAZURIO_VAULT_COLLECTION_ID: collectionId, + LAZURIO_VAULT_ORGANIZATION_ID: organization.id, + LAZURIO_VAULT_COLLECTION_ID: agentsId, }, }); - // Revoked in the vault: the sync says so, and so does the local - // status afterwards. - await w.vault.remove(); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "revoked", - fingerprint, - }); - expect(await vaultStatus(w.host)).toMatchObject({ state: "revoked" }); - - // Disconnect: bw's store, the session and the record go; the account - // stays and connecting again signs it in without a registration. - expect(await vaultDisconnect(w.host)).toMatchObject({ - state: "none", - registered: true, - }); - expect(await readSession(w.paths)).toBeNull(); - expect((await readAccount(w.paths))?.clientId).toBe(stored?.clientId); - const registrations = w.vault.requests.filter( - (entry) => entry.path === "/identity/accounts/register/finish", - ).length; - await w.vault.confirm(collection, 1); - expect(await vaultConnect(w.host)).toMatchObject({ - state: "connected", - collections: 1, - items: 1, - }); - expect( - w.vault.requests.filter( - (entry) => entry.path === "/identity/accounts/register/finish", - ).length, - ).toBe(registrations); + // Set up again: the same vault, no registration, creation or rename. + const before = w.vault.requests.length; + expect(await vaultSetup(w.host)).toEqual(connected); + const again = w.vault.requests.slice(before).map((entry) => entry.path); + expect(again).not.toContain("/identity/accounts/register/finish"); + expect(again).not.toContain("/api/organizations"); + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(1); + expect(w.vault.requests.some((entry) => entry.method === "PUT")).toBe( + false, + ); // No secret ever reached argv, and the journal holds codes only. const calls = await w.vault.calls(); @@ -250,7 +238,7 @@ test.skipIf(!posix)( for (const secret of secrets) expect(JSON.stringify(entry)).not.toContain(secret as string); } - // The release was downloaded once; the second connect found it. + // The release was downloaded once; the later setups found it. expect(w.release.requests).toHaveLength(1); } finally { await w.close(); @@ -259,19 +247,202 @@ test.skipIf(!posix)( 60_000, ); +test.skipIf(!posix)( + "a new name in the handover renames the vault, which stays the same by its ID", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + const first = await vaultSetup(w.host); + expect(first).toMatchObject({ state: "connected" }); + const renamed: VaultHost = { + ...w.host, + context: async () => + ownContext( + personalHandoverAt( + "example.lazurio.io", + vaultMember(ownAccount, "Example Osobní renamed"), + ), + ), + }; + // The local status sees the name the handover now gives: the start + // sets it up again. + const before = await vaultStatus(renamed); + expect(before).toMatchObject({ + state: "connected", + name: "Example Osobní renamed", + organization: vaultName, + }); + expect(setUpAtStart(before)).toBe(true); + const after = await vaultSetup(renamed); + expect(after).toMatchObject({ + state: "connected", + organization: "Example Osobní renamed", + }); + expect(setUpAtStart(after)).toBe(false); + expect(w.owned()).toHaveLength(1); + expect(w.owned()[0]?.name).toBe("Example Osobní renamed"); + const [rename] = w.vault.requests.filter( + (entry) => entry.method === "PUT", + ); + expect(rename?.body).toEqual({ + name: "Example Osobní renamed", + billingEmail: ownAccount, + }); + expect(w.journal).toContainEqual({ + operation: "vault", + outcome: "renamed", + }); + // The record is the same: the ID is the vault. + expect((await readRecord(w.paths)).organizationId).toBe( + first.state === "connected" ? first.organizationId : "?", + ); + } finally { + await w.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "a creation whose answer was lost is recognized by its receipt and never made twice", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + // The vault creates the organization, then the answer is lost. + let lose = true; + const host_: VaultHost = { + ...w.host, + fetch: async (url, init) => { + const answer = await w.vault.fetch(url, init); + if (lose && url.endsWith("/api/organizations")) + throw new Error("connection reset"); + return answer; + }, + }; + expect(await vaultSetup(host_)).toMatchObject({ + state: "unreachable", + reason: "unreachable", + }); + expect(w.owned()).toHaveLength(1); + const receipt = await readRecord(w.paths); + expect(receipt).toEqual({ + organizationId: null, + collectionId: null, + pendingKey: w.owned()[0]?.publicKey ?? "?", + }); + expect(await vaultStatus(host_)).toMatchObject({ + state: "not-set-up", + next: "vault", + }); + lose = false; + const connected = await vaultSetup(host_); + expect(connected).toMatchObject({ + state: "connected", + organizationId: w.owned()[0]?.id, + }); + expect(w.owned()).toHaveLength(1); + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(1); + expect(await readRecord(w.paths)).toMatchObject({ pendingKey: null }); + } finally { + await w.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "a vault that is gone or an API key refused is revoked and never replaced; a damaged record is never written over", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + const connected = await vaultSetup(w.host); + if (connected.state !== "connected") throw new Error("Expected it"); + // The network's operator deletes the organization. + await w.vault.deleteOrganization(connected.organizationId); + expect(await vaultRefresh(w.host)).toEqual({ + kind: "vault-status", + state: "revoked", + ...facts, + }); + expect(await vaultStatus(w.host)).toMatchObject({ state: "revoked" }); + expect(setUpAtStart(await vaultStatus(w.host))).toBe(false); + expect(await vaultSetup(w.host)).toMatchObject({ state: "revoked" }); + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(1); + expect((await readRecord(w.paths)).organizationId).toBe( + connected.organizationId, + ); + + // A damaged record: the setup refuses and leaves it as it is. + await writeFile(w.paths.record, "{damaged", { mode: 0o600 }); + const damaged = { + state: "failed", + stage: "vault", + reason: "record-unreadable", + fallback: "agent", + }; + expect(await vaultStatus(w.host)).toMatchObject(damaged); + expect(await vaultSetup(w.host)).toMatchObject(damaged); + expect(await readFile(w.paths.record, "utf8")).toBe("{damaged"); + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(1); + expect(await vaultEnv(w.host)).toEqual({ + kind: "vault-env-refused", + reason: "not-connected", + }); + } finally { + await w.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "a refused API key is revoked, and a vault that does not let the account create organizations says so", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + w.vault.flags.organizationRefused = true; + expect(await vaultSetup(w.host)).toMatchObject({ + state: "failed", + stage: "vault", + reason: "organization-refused", + fallback: "agent", + }); + expect(w.owned()).toHaveLength(0); + w.vault.flags.organizationRefused = false; + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); + await w.vault.rotateApiKey(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ state: "revoked" }); + } finally { + await w.close(); + } + }, + 60_000, +); + test.skipIf(!posix)( "a session ended by another unlock is replaced once, by env or refresh, and the newest one is shared", async () => { const w = await world(); try { - w.vault.invite(account); - await w.vault.confirm(collection); - expect(await vaultConnect(w.host)).toMatchObject({ state: "connected" }); + w.vault.allow(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); const first = await readSession(w.paths); // A rogue `bw lock` (agents never run it): the session is no longer // the unlocked one. const store = join(w.paths.data, "fake", "session"); await rm(store); + const locked = await vaultStatus(w.host); + expect(locked).toMatchObject({ + state: "connected", + locked: true, + organization: null, + items: null, + }); + expect(setUpAtStart(locked)).toBe(true); const env = await vaultEnv(w.host); expect(env.kind).toBe("vault-env"); const second = await readSession(w.paths); @@ -286,13 +457,9 @@ test.skipIf(!posix)( await rm(store); expect(await vaultRefresh(w.host)).toMatchObject({ state: "connected" }); expect(await readSession(w.paths)).not.toBe(second); - expect(w.journal.filter((entry) => entry.operation === "unlock")).toEqual( - [ - { operation: "unlock", outcome: "unlocked" }, - { operation: "unlock", outcome: "unlocked" }, - { operation: "unlock", outcome: "unlocked" }, - ], - ); + expect( + w.journal.filter((entry) => entry.operation === "unlock"), + ).toHaveLength(3); } finally { await w.close(); } @@ -305,9 +472,9 @@ test.skipIf(!posix)( async () => { const w = await world(); try { - w.vault.invite(account); + w.vault.allow(ownAccount); w.vault.flags.rateLimit = true; - expect(await vaultConnect(w.host)).toMatchObject({ + expect(await vaultSetup(w.host)).toMatchObject({ state: "failed", stage: "account", reason: "rate-limited", @@ -315,7 +482,7 @@ test.skipIf(!posix)( }); w.vault.flags.rateLimit = false; w.vault.flags.smtp = true; - expect(await vaultConnect(w.host)).toMatchObject({ + expect(await vaultSetup(w.host)).toMatchObject({ state: "failed", stage: "account", reason: "smtp-enabled", @@ -325,15 +492,13 @@ test.skipIf(!posix)( // registers now. const pending = await readAccount(w.paths); expect(pending?.clientId).toBeUndefined(); - expect(await vaultConnect(w.host)).toMatchObject({ state: "confirming" }); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); expect((await readAccount(w.paths))?.masterPassword).toBe( pending?.masterPassword, ); - await w.vault.confirm(collection); await w.vault.unreachable(true); expect(await vaultRefresh(w.host)).toMatchObject({ state: "unreachable", - fingerprint, }); await w.vault.unreachable(false); expect(await vaultRefresh(w.host)).toMatchObject({ state: "connected" }); @@ -349,11 +514,11 @@ test.skipIf(!posix)( async () => { const w = await world(); try { - w.vault.invite(account); + w.vault.allow(ownAccount); // The vault answers the registration, then the network drops before // the login. let drop = true; - const host: VaultHost = { + const host_: VaultHost = { ...w.host, fetch: async (url, init) => { if (drop && url.endsWith("/identity/accounts/prelogin")) @@ -361,34 +526,28 @@ test.skipIf(!posix)( return w.vault.fetch(url, init); }, }; - expect(await vaultConnect(host)).toMatchObject({ + expect(await vaultSetup(host_)).toMatchObject({ state: "unreachable", reason: "unreachable", }); - expect(w.vault.users.has(account)).toBe(true); + expect(w.vault.users.has(ownAccount)).toBe(true); const pending = await readAccount(w.paths); expect(pending?.clientId).toBeUndefined(); drop = false; // The vault refuses the login of the registered account (here: it no // longer takes the password), so the resumed run asks to register, // and the vault refuses that too, as it refuses an address that is - // not invited. The account file is the only copy of the registered + // not allowed. The account file is the only copy of the registered // account's password: it stays. - const user = w.vault.users.get(account); + const user = w.vault.users.get(ownAccount); if (user === undefined) throw new Error("registered user"); const hash = user.hash; user.hash = "refused"; - expect(await vaultConnect(host)).toMatchObject({ - state: "awaiting-invite", - }); + expect(await vaultSetup(host_)).toMatchObject({ state: "not-allowed" }); expect(await readAccount(w.paths)).toEqual(pending); user.hash = hash; - expect(await vaultConnect(host)).toMatchObject({ state: "confirming" }); - expect( - w.vault.requests.filter( - (entry) => entry.path === "/identity/accounts/register/finish", - ), - ).toHaveLength(1); + expect(await vaultSetup(host_)).toMatchObject({ state: "connected" }); + expect(w.vault.of("/identity/accounts/register/finish")).toHaveLength(1); } finally { await w.close(); } @@ -397,107 +556,79 @@ test.skipIf(!posix)( ); test.skipIf(!posix)( - "an Environment whose address changes in the same network never gets the account it had, and an account file out of place is never used", + "an account the handover replaces starts in a directory of its own, the earlier one is untouched, and an account file out of place is never used", async () => { const w = await world(); try { - w.vault.invite(account); - await w.vault.confirm(collection); - expect(await vaultConnect(w.host)).toMatchObject({ state: "connected" }); + w.vault.allow(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); const before = { account: await readFile(w.paths.account, "utf8"), session: await readSession(w.paths), + record: await readFile(w.paths.record, "utf8"), }; - // The same Remote Environment now answers at another address in the - // same network: the vault is the same, the account is not. - const moved = "vaultwarden@moved.lazurio.io"; - const host: VaultHost = { + // The network hands this Environment another account. + const replaced = + "vaultwarden-aaaabbbbccccddddeeeeffffgg@example.lazurio.io"; + const host_: VaultHost = { ...w.host, context: async () => - vaultContextOf({ - handover: personalHandoverAt("moved.lazurio.io"), - kind: "personal", - label: null, - }), + ownContext( + personalHandoverAt( + "example.lazurio.io", + vaultMember(replaced, "Example Osobní replaced"), + ), + ), }; const unlocks = () => w.journal.filter((entry) => entry.operation === "unlock").length; const unlocked = unlocks(); - expect(await vaultStatus(host)).toEqual({ + expect(await vaultStatus(host_)).toEqual({ kind: "vault-status", - state: "none", + state: "not-set-up", vault: vaultOrigin, - account: moved, - collection: "Environmenty/Osobní · moved", - name: "Osobní", + account: replaced, + name: "Example Osobní replaced", team: false, - registered: false, - }); - expect(await vaultRefresh(host)).toMatchObject({ - state: "none", - account: moved, + origin: "own", + next: "account", }); - expect(await vaultEnv(host)).toEqual({ + expect(await vaultEnv(host_)).toEqual({ kind: "vault-env-refused", reason: "not-connected", }); expect(unlocks()).toBe(unlocked); - // Connecting registers the new address, which waits for its own - // invitation. - expect(await vaultConnect(host)).toMatchObject({ - state: "awaiting-invite", - account: moved, - }); - // The earlier account's files are untouched, and it still serves the - // address it belongs to. + // Not allowed by the network yet: refused, nothing of it left. + expect(await vaultSetup(host_)).toMatchObject({ + state: "not-allowed", + account: replaced, + }); + // The earlier account's files are untouched. expect(await readFile(w.paths.account, "utf8")).toBe(before.account); expect(await readSession(w.paths)).toBe(before.session); - const own = await vaultEnv(w.host); - expect(own.kind === "vault-env" ? own.env.BW_SESSION : null).toBe( - before.session, - ); + expect(await readFile(w.paths.record, "utf8")).toBe(before.record); - // The earlier account's files copied under the new address are not - // the new address's account: everything refuses, nothing runs, and - // the file is never replaced. - const misplaced = vaultPaths( - w.host.directory({ - host: "vaultwarden.example.lazurio.io", - address: "moved.lazurio.io", - }), - ); + // The earlier account's files copied under the new account are not the + // new account's: everything refuses, nothing runs, and the file is + // never replaced. + const misplaced = vaultPaths(stateDirectory(w.home, host, replaced)); await writeFile(misplaced.account, before.account, { mode: 0o600 }); - await writeFile(misplaced.session, before.session ?? "", { - mode: 0o600, - }); const mismatch = { state: "failed", stage: "account", reason: "account-mismatch", }; - const logouts = async () => - (await w.vault.calls()) - .split("\n") - .filter((line) => line.startsWith("logout")).length; - const loggedOut = await logouts(); - const store = await readFile(join(misplaced.data, "data.json"), "utf8"); - expect(await vaultStatus(host)).toMatchObject(mismatch); - expect(await vaultRefresh(host)).toMatchObject(mismatch); - expect(await vaultConnect(host)).toMatchObject(mismatch); - expect(await vaultDisconnect(host)).toMatchObject(mismatch); - expect(await vaultEnv(host)).toEqual({ + expect(await vaultStatus(host_)).toMatchObject(mismatch); + expect(await vaultRefresh(host_)).toMatchObject(mismatch); + expect(await vaultSetup(host_)).toMatchObject(mismatch); + expect(await vaultEnv(host_)).toEqual({ kind: "vault-env-refused", reason: "not-connected", }); expect(unlocks()).toBe(unlocked); - expect(await logouts()).toBe(loggedOut); expect(await readFile(misplaced.account, "utf8")).toBe(before.account); - expect(await readSession(misplaced)).toBe(before.session); - expect(await readFile(join(misplaced.data, "data.json"), "utf8")).toBe( - store, - ); expect(w.journal.at(-1)).toEqual({ - operation: "disconnect", + operation: "setup", outcome: "failed", reason: "account-mismatch", }); @@ -509,13 +640,12 @@ test.skipIf(!posix)( ); test.skipIf(!posix)( - "a damaged or missing account file changes nothing: every operation, disconnect included, leaves the sign-in as it is, and the file restored restores the connection", + "a damaged or missing account file changes nothing, and the file restored restores the vault", async () => { const w = await world(); try { - w.vault.invite(account); - await w.vault.confirm(collection); - expect(await vaultConnect(w.host)).toMatchObject({ state: "connected" }); + w.vault.allow(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); const original = await readFile(w.paths.account, "utf8"); const session = await readSession(w.paths); const files = async () => @@ -529,21 +659,10 @@ test.skipIf(!posix)( ); const before = await files(); expect(before).not.toContain(null); - const logouts = async () => - (await w.vault.calls()) - .split("\n") - .filter((line) => line.startsWith("logout")).length; const unlocks = () => w.journal.filter((entry) => entry.operation === "unlock").length; - const counts = { logouts: await logouts(), unlocks: unlocks() }; - const untouched = async () => { - expect(await files()).toEqual(before); - expect(await logouts()).toBe(counts.logouts); - expect(unlocks()).toBe(counts.unlocks); - }; + const unlocked = unlocks(); - // Damaged: every operation refuses, and nothing is replaced or - // removed. await writeFile(w.paths.account, "{invalid", { mode: 0o600 }); const unreadable = { state: "failed", @@ -552,22 +671,14 @@ test.skipIf(!posix)( }; expect(await vaultStatus(w.host)).toMatchObject(unreadable); expect(await vaultRefresh(w.host)).toMatchObject(unreadable); - expect(await vaultConnect(w.host)).toMatchObject(unreadable); - expect(await vaultDisconnect(w.host)).toMatchObject(unreadable); + expect(await vaultSetup(w.host)).toMatchObject(unreadable); expect(await vaultEnv(w.host)).toEqual({ kind: "vault-env-refused", reason: "not-connected", }); expect(await readFile(w.paths.account, "utf8")).toBe("{invalid"); - await untouched(); - - // Missing: there is no account of this Environment to disconnect. - await rm(w.paths.account); - expect(await vaultDisconnect(w.host)).toMatchObject({ - state: "none", - registered: false, - }); - await untouched(); + expect(await files()).toEqual(before); + expect(unlocks()).toBe(unlocked); // Restored: connected as before, with the same session. await writeFile(w.paths.account, original, { mode: 0o600 }); @@ -584,229 +695,32 @@ test.skipIf(!posix)( ); test.skipIf(!posix)( - "a bw profile signed in to another account in the Environment's data directory is never used, and connecting signs the Environment's own account in again", + "a bw profile signed in to another account in the Environment's data directory is never used, and setup signs the Environment's own account in again", async () => { const w = await world(); try { - w.vault.invite(account); - await w.vault.confirm(collection); - expect(await vaultConnect(w.host)).toMatchObject({ state: "connected" }); - // An agent signed bw in to a person's account in this data directory - // (the wrapper's default); the session file still holds the session - // bw answers to. + w.vault.allow(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); const email = join(w.paths.data, "fake", "email"); await writeFile(email, "person@example.lazurio.io\n"); const unlocks = () => w.journal.filter((entry) => entry.operation === "unlock").length; const unlocked = unlocks(); - expect(await vaultStatus(w.host)).toMatchObject({ - state: "none", - registered: true, - }); + const signedOut = await vaultStatus(w.host); + expect(signedOut).toMatchObject({ state: "not-set-up", next: "sign-in" }); + expect(setUpAtStart(signedOut)).toBe(true); expect(await vaultRefresh(w.host)).toMatchObject({ - state: "none", - registered: true, + state: "not-set-up", + next: "sign-in", }); expect(await vaultEnv(w.host)).toEqual({ kind: "vault-env-refused", reason: "not-connected", }); expect(unlocks()).toBe(unlocked); - // Connecting signs that profile out and the Environment's account in. - expect(await vaultConnect(w.host)).toMatchObject({ state: "connected" }); - expect((await readFile(email, "utf8")).trim()).toBe(account); - const env = await vaultEnv(w.host); - expect(env.kind === "vault-env" ? env.env.BW_SESSION : null).toBe( - await readSession(w.paths), - ); - } finally { - await w.close(); - } - }, - 60_000, -); - -test.skipIf(!posix)( - "the only collection the account sees is the Environment's, whatever its name, and it stays so by its ID", - async () => { - const w = await world(); - try { - w.vault.invite(account); - expect(await vaultConnect(w.host)).toMatchObject({ - state: "confirming", - organization: null, - }); - // The operator named the collection as he likes (root decision 0193, - // addendum 2026-10-11). - await w.vault.confirm("Osobní Environment", 2); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - collection: "Osobní Environment", - collections: 1, - items: 2, - }); - const collectionOf = async () => { - const env = await vaultEnv(w.host); - return env.kind === "vault-env" - ? env.env.LAZURIO_VAULT_COLLECTION_ID - : null; - }; - expect(await collectionOf()).toBe(collectionId); - // Renamed: still its collection, by its ID. - await w.vault.confirm("Osobní Environment Example", 2); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - collection: "Osobní Environment Example", - }); - // Another collection appears, even under the suggested name: the - // recorded one stays the Environment's. - await w.vault.confirm("Osobní Environment Example", 2, [collection]); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - collection: "Osobní Environment Example", - collections: 2, - }); - expect(await collectionOf()).toBe(collectionId); - } finally { - await w.close(); - } - }, - 60_000, -); - -test.skipIf(!posix)( - "with several collections the suggested name decides, and a recorded collection that is gone is revoked, never replaced", - async () => { - const w = await world(); - try { - w.vault.invite(account); - await vaultConnect(w.host); - // Two collections, neither named for this Environment: it waits. - await w.vault.confirm("Infrastruktura", 0, ["Banky"]); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "confirming", - organization: "Example Organization", - }); - // One of them gets the suggested name: that one. - await w.vault.confirm(collection, 3, ["Banky"]); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - collection, - collections: 2, - }); - // The Environment's collection is deleted and another one stays - // visible, under any name, even the suggested one or one named for - // this machine: the access is revoked, nothing else takes its place, - // and the record keeps the original collection. - const only = async (name: string) => - writeFile( - join(w.vault.world, "collections.json"), - `${JSON.stringify([ - { - object: "collection", - id: otherCollectionId, - organizationId, - name, - externalId: null, - }, - ])}\n`, - ); - for (const name of [ - "Banky", - collection, - "Environmenty/Jiný název · example", - ]) { - await only(name); - expect([name, await vaultRefresh(w.host)]).toMatchObject([ - name, - { state: "revoked" }, - ]); - expect([name, (await readRecord(w.paths)).collectionId]).toEqual([ - name, - collectionId, - ]); - } - } finally { - await w.close(); - } - }, - 60_000, -); - -test.skipIf(!posix)( - "connecting again keeps the collection it was connected to, also after a revoked access; only a disconnect forgets it", - async () => { - const w = await world(); - try { - w.vault.invite(account); - await vaultConnect(w.host); - await w.vault.confirm(collection, 1); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - }); - // Its collection is gone; another one is visible under the suggested - // name. - await writeFile( - join(w.vault.world, "collections.json"), - `${JSON.stringify([ - { - object: "collection", - id: otherCollectionId, - organizationId, - name: collection, - externalId: null, - }, - ])}\n`, - ); - expect(await vaultRefresh(w.host)).toMatchObject({ state: "revoked" }); - // "Připojit znovu": still revoked, the record keeps the original. - expect(await vaultConnect(w.host)).toMatchObject({ state: "revoked" }); - expect((await readRecord(w.paths)).collectionId).toBe(collectionId); - // Only a disconnect forgets it: the next connection is a first one. - await vaultDisconnect(w.host); - expect(await vaultConnect(w.host)).toMatchObject({ - state: "connected", - collection, - }); - expect((await readRecord(w.paths)).collectionId).toBe(otherCollectionId); - } finally { - await w.close(); - } - }, - 60_000, -); - -test.skipIf(!posix)( - "a new connection after a disconnect is a first connection again: a collection under its own name only while it is the only one", - async () => { - const w = await world(); - try { - w.vault.invite(account); - await vaultConnect(w.host); - await w.vault.confirm("Osobní Environment Example", 1); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - collection: "Osobní Environment Example", - }); - // Another collection is shared meanwhile: still connected, by its ID. - await w.vault.confirm("Osobní Environment Example", 1, ["Banky"]); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - collections: 2, - }); - // Disconnected and connected again: the record is gone, and among - // several collections only the suggested name decides. - expect(await vaultDisconnect(w.host)).toMatchObject({ state: "none" }); - expect(await vaultConnect(w.host)).toMatchObject({ - state: "confirming", - organization: "Example Organization", - }); - // Under the suggested name it is recognized again. - await w.vault.confirm(collection, 1, ["Banky"]); - expect(await vaultRefresh(w.host)).toMatchObject({ - state: "connected", - collection, - }); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); + expect((await readFile(email, "utf8")).trim()).toBe(ownAccount); + expect(w.owned()).toHaveLength(1); } finally { await w.close(); } @@ -819,8 +733,8 @@ test.skipIf(!posix)( async () => { const w = await world(); try { - w.vault.invite(account); - await vaultConnect(w.host); + w.vault.allow(ownAccount); + await vaultSetup(w.host); const binary = pinnedBinary(w.host.base, w.pin); expect(await mode(binary)).toBe(0o755); const entry = join(w.home, ".local", "bin", "bw"); @@ -829,19 +743,19 @@ test.skipIf(!posix)( expect(wrapper).toContain(`BITWARDENCLI_APPDATA_DIR='${w.paths.data}'`); // A tampered release is refused before anything is read from it. await rm(binary); - const host: VaultHost = { + const host_: VaultHost = { ...w.host, download: async () => new Response(new Uint8Array(zipOf("bw", "#!/bin/sh\nexit 0\n"))), }; - expect(await vaultConnect(host)).toMatchObject({ + expect(await vaultSetup(host_)).toMatchObject({ state: "failed", stage: "install", reason: "checksum-mismatch", }); // A `bw` in ~/.local/bin that is not Lazurio's is never replaced. await writeFile(entry, "#!/bin/sh\necho mine\n", { mode: 0o755 }); - expect(await vaultConnect(w.host)).toMatchObject({ + expect(await vaultSetup(w.host)).toMatchObject({ state: "failed", stage: "install", reason: "entry-conflict", @@ -857,44 +771,63 @@ test.skipIf(!posix)( test("a Remote Environment without a vault refuses everything before anything runs", async () => { const parent = await realpath(await mkdtemp(join(tmpdir(), "vault-none-"))); try { - const host: VaultHost = { - context: async () => ({ kind: "unsupported", reason: "workstation" }), - directory: () => join(parent, "never"), - base: join(parent, "never"), - bin: join(parent, "never"), - home: parent, - path: undefined, - platform: "darwin", - arch: "arm64", - run: async () => { - throw new Error("nothing may run"); - }, - }; - const unsupported: VaultStatus = { - kind: "vault-status", - state: "unsupported", - reason: "workstation", - }; - expect(await vaultStatus(host)).toEqual(unsupported); - expect(await vaultConnect(host)).toEqual(unsupported); - expect(await vaultRefresh(host)).toEqual(unsupported); - expect(await vaultDisconnect(host)).toEqual(unsupported); - expect(await vaultEnv(host)).toEqual({ - kind: "vault-env-refused", - reason: "workstation", - }); + for (const reason of ["workstation", "no-vault"] as const) { + const host_: VaultHost = { + context: async () => ({ kind: "unsupported", reason }), + directory: () => join(parent, "never"), + base: join(parent, "never"), + bin: join(parent, "never"), + home: parent, + path: undefined, + platform: "linux", + arch: "x64", + run: async () => { + throw new Error("nothing may run"); + }, + fetch: async () => { + throw new Error("nothing may be asked"); + }, + }; + const unsupported: VaultStatus = { + kind: "vault-status", + state: "unsupported", + reason, + }; + expect(await vaultStatus(host_)).toEqual(unsupported); + expect(await vaultSetup(host_)).toEqual(unsupported); + expect(await vaultRefresh(host_)).toEqual(unsupported); + expect(setUpAtStart(unsupported)).toBe(false); + expect(await vaultEnv(host_)).toEqual({ + kind: "vault-env-refused", + reason, + }); + } expect(await lstat(join(parent, "never")).catch(() => null)).toBeNull(); } finally { await rm(parent, { recursive: true, force: true }); } }); -test("the context of the fixture is the personal Environment of example", () => { +test("the start sets up only an own vault that needs it", () => { + const status = (value: object) => value as VaultStatus; + expect( + setUpAtStart(status({ state: "not-set-up", origin: "own", next: "vault" })), + ).toBe(true); + for (const state of ["not-allowed", "revoked", "unreachable", "failed"]) + expect([state, setUpAtStart(status({ state, origin: "own" }))]).toEqual([ + state, + false, + ]); + // A 0197 pilot is only read. expect( - vaultContextOf({ - handover: personalHandover, - kind: "personal", - label: null, - }), - ).toMatchObject({ account, collection, vault: vaultOrigin }); + setUpAtStart( + status({ + state: "connected", + origin: "pilot-0197", + locked: true, + organization: null, + name: null, + }), + ), + ).toBe(false); }); diff --git a/tests/vault-handover.test.ts b/tests/vault-handover.test.ts new file mode 100644 index 000000000..678ea618b --- /dev/null +++ b/tests/vault-handover.test.ts @@ -0,0 +1,174 @@ +import { expect, test } from "bun:test"; +import Ajv2020 from "ajv/dist/2020"; +import { machineIdentity } from "../src/folder/machine-binding"; +import { machineBinding } from "../src/machine/binding"; +import { + MachineContextError, + parseMachineContext, +} from "../src/machine/context"; +import schema from "../src/machine/lazurio-machine.v1.schema.json"; +import { contextValues } from "../src/recover/private-values"; +import { createSanitizer } from "../src/recover/sanitize"; +import { ownAccount, vaultMember, workAccount } from "./fixtures/fake-vault"; +import { handoverEntry } from "./fixtures/machine-bindings"; +import organization from "./fixtures/machine-context.json"; +import personal from "./fixtures/machine-context-personal.json"; + +// DEV-6631 contract C2: Machines writes the optional, closed member +// `vault: {server_url, account, name}` into lazurio.machine.json on both +// branches, only for a Platform release that reads it, and the Environment +// takes its own vault from it (decision F52). Invented hosts and names only. + +const bytes = (value: unknown) => Buffer.from(JSON.stringify(value)); +const { team: _, ...withoutTeam } = organization.owner; +const documents = { + personal: { + ...personal, + entry: handoverEntry("example.lazurio.io"), + vault: vaultMember(), + }, + work: { + ...organization, + owner: withoutTeam, + entry: handoverEntry("workspace.example.lazurio.io"), + vault: vaultMember(workAccount, "Example Pracovní workspace"), + }, +}; + +test("the member is read exactly as written on both branches", () => { + for (const document of Object.values(documents)) { + const context = parseMachineContext(bytes(document)); + expect(JSON.stringify(context)).toBe(JSON.stringify(document)); + expect(context.vault).toEqual(document.vault); + expect(Object.isFrozen(context.vault)).toBe(true); + } +}); + +test("the member is closed and every part keeps its shape", () => { + const refused = (vault: unknown) => { + try { + parseMachineContext(bytes({ ...documents.personal, vault })); + } catch (error) { + return ( + error instanceof MachineContextError && + error.code === "machine-context-invalid" + ); + } + return false; + }; + const member = vaultMember(); + for (const [name, vault] of Object.entries({ + "another member": { ...member, collection: "Agenti" }, + "no name": { server_url: member.server_url, account: member.account }, + "a 0197 address": { + ...member, + account: "vaultwarden@example.lazurio.io", + }, + "upper-case base32": { + ...member, + account: "vaultwarden-NDBRMZVJPWXTT3Q7M2E4FIHGSA@example.lazurio.io", + }, + "25 characters": { + ...member, + account: "vaultwarden-ndbrmzvjpwxtt3q7m2e4fihgs@example.lazurio.io", + }, + "not base32": { + ...member, + account: "vaultwarden-ndbrmzvjpwxtt3q7m2e4fihgs1@example.lazurio.io", + }, + "a person's address": { + ...member, + account: "1f2e3d4c@vaultwarden-identity.lazurio.ai", + }, + "plain http": { + ...member, + server_url: "http://vaultwarden.example.lazurio.io", + }, + "a path": { + ...member, + server_url: "https://vaultwarden.example.lazurio.io/", + }, + "another host": { ...member, server_url: "https://vault.example.invalid" }, + "two spaces": { ...member, name: "Example Osobní" }, + "a slash": { ...member, name: "Example/Osobní" }, + "a middle dot": { ...member, name: "Example · Osobní" }, + "a trailing space": { ...member, name: "Example Osobní " }, + empty: { ...member, name: "" }, + "51 characters": { ...member, name: "a".repeat(51) }, + })) + expect([name, refused(vault)]).toEqual([name, true]); + // Letters of any language, digits and single spaces, at most 50. + for (const name of [ + "Example Osobní example", + "Žluťoučký kůň 2", + "a".repeat(50), + ]) + expect( + parseMachineContext( + bytes({ ...documents.personal, vault: { ...member, name } }), + ).vault?.name, + ).toBe(name); +}); + +test("a Platform whose vendored schema predates the member refuses the whole handover that carries it, which is why Machines writes it only for a Platform that reads it", () => { + // The schema of the Platform before this member: the same, without it. + const earlier = structuredClone(schema) as unknown as { + $defs: Record }>; + }; + for (const branch of ["organization_workspace_vm", "personal_vm"]) + delete earlier.$defs[branch]?.properties?.vault; + delete earlier.$defs.vault; + const validate = new Ajv2020({ strict: true }).compile(earlier); + for (const document of Object.values(documents)) { + const { vault: __, ...without } = document; + expect(validate(without)).toBe(true); + // The member is unknown to it: not ignored, the whole document fails, + // and with it the Launchpad entry and everything else the handover + // carries. + expect(validate(document)).toBe(false); + } + // This Platform refuses an unknown member the same way. + expect(() => + parseMachineContext(bytes({ ...documents.personal, vault_v2: {} })), + ).toThrow("machine-context-invalid"); +}); + +test("the member is outside the Machine's identity and its Folder binding", () => { + // The same digest for both: only the projection is compared. + const digest = "0".repeat(64); + for (const document of Object.values(documents)) { + const { vault: __, ...without } = document; + const withVault = machineBinding( + parseMachineContext(bytes(document)), + digest, + ); + const plain = machineBinding(parseMachineContext(bytes(without)), digest); + expect(withVault).toEqual(plain); + expect(machineIdentity(withVault)).toEqual(machineIdentity(plain)); + } +}); + +test("recovery evidence withholds the account, the vault's name and the vault's host", () => { + const context = parseMachineContext(bytes(documents.personal)); + const values = contextValues(context); + expect(values).toEqual( + expect.arrayContaining([ + { kind: "vault-account", value: ownAccount }, + { kind: "vault-name", value: "Example Osobní example" }, + { kind: "hostname", value: "vaultwarden.example.lazurio.io" }, + ]), + ); + const sanitizer = createSanitizer({ values }); + const output = sanitizer.sanitize( + [ + `registering ${ownAccount}`, + "vault Example Osobní example renamed", + "GET https://vaultwarden.example.lazurio.io/api/sync 502", + ].join("\n"), + ); + expect(output).not.toContain(ownAccount); + expect(output).not.toContain("ndbrmzvjpwxtt3q7m2e4fihgsa"); + expect(output).not.toContain("Example Osobní example"); + expect(output).not.toContain("vaultwarden.example.lazurio.io"); + expect(sanitizer.gate(output)).toEqual({ kind: "clean", text: output }); +}); diff --git a/tests/vault-host.test.ts b/tests/vault-host.test.ts index 3670805c8..3aa18b430 100644 --- a/tests/vault-host.test.ts +++ b/tests/vault-host.test.ts @@ -12,6 +12,12 @@ import type { VaultUnsupportedReason, } from "../src/vault/context"; import { readVaultContext } from "../src/vault/host"; +import { + ownAccount, + vaultMember, + vaultName, + workAccount, +} from "./fixtures/fake-vault"; import { assignments, binding, @@ -20,8 +26,8 @@ import { import organization from "./fixtures/machine-context.json"; import personal from "./fixtures/machine-context-personal.json"; -// The production composition of the Environment vault's facts (decision -// F43) on real files: a root-issued handover and a hosted Folder under a +// The production composition of the Environment vault's facts (decisions +// F43, F52) on real files: a root-issued handover and a hosted Folder under a // private root, read as `lazurio vault` and the Launchpad read them. Only the // handover's place and the operator's system record are this test's. @@ -31,22 +37,32 @@ const network = { headscale_server_url: "https://headscale.example.lazurio.io", headscale_hostname: "example", }; +const personalDocument = { + ...personal, + network, + entry: handoverEntry("example.lazurio.io"), +}; +const teamDocument = { + ...organization, + owner: { ...organization.owner, assignment: assignments.team }, + network: { ...network, headscale_hostname: "example-workspace" }, + entry: handoverEntry("workspace.example.lazurio.io"), +}; const documents = { - personal: { - ...personal, - network, - entry: handoverEntry("example.lazurio.io"), - }, + personal: { ...personalDocument, vault: vaultMember() }, team: { - ...organization, - owner: { ...organization.owner, assignment: assignments.team }, - network: { ...network, headscale_hostname: "example-workspace" }, - entry: handoverEntry("workspace.example.lazurio.io"), + ...teamDocument, + vault: vaultMember(workAccount, "Example Týmový workspace"), }, + // Handovers that name no vault yet: a 0197 pilot's derivation. + personalPilot: personalDocument, + teamPilot: teamDocument, } as const; const presets: Record = { personal: "hosted-personal", team: "hosted-organization-team", + personalPilot: "hosted-personal", + teamPilot: "hosted-organization-team", }; async function machine(of: keyof typeof documents, handover = true) { @@ -61,7 +77,7 @@ async function machine(of: keyof typeof documents, handover = true) { const folder = join(root, "home", "operator", "Lazurio"); await mkdir(join(folder, "organizations"), { recursive: true, mode: 0o700 }); // The personal preset's layout holds the Personalspace mount too. - if (of === "personal") + if (presets[of] === "hosted-personal") await mkdir(join(folder, "personalspace"), { mode: 0o700 }); await initializeHandoverFolder(folder, { preset: presets[of], @@ -86,41 +102,55 @@ async function machine(of: keyof typeof documents, handover = true) { } test.skipIf(!posix || uid === 0)( - "the declared operator of a hosted Folder on Linux gets the vault facts of its Environment", + "the declared operator of a hosted Folder on Linux gets its Environment's own vault, or a 0197 pilot's where the handover names none", async () => { - const personalVm = await machine("personal"); - const teamVm = await machine("team"); + const read = (vm: Awaited>) => + readVaultContext({ + folder: vm.folder, + platform: "linux", + home: "/home/operator", + sources: vm.sources(), + }); + const vms = { + personal: await machine("personal"), + team: await machine("team"), + personalPilot: await machine("personalPilot"), + teamPilot: await machine("teamPilot"), + }; try { - expect( - await readVaultContext({ - folder: personalVm.folder, - platform: "linux", - home: "/home/operator", - sources: personalVm.sources(), - }), - ).toMatchObject({ + expect(await read(vms.personal)).toEqual({ + kind: "own", + vault: "https://vaultwarden.example.lazurio.io", + host: "vaultwarden.example.lazurio.io", + account: ownAccount, + name: vaultName, + environment: "personal", + organization: null, + }); + expect(await read(vms.team)).toMatchObject({ + kind: "own", + account: workAccount, + name: "Example Týmový workspace", + environment: "team", + organization: "example", + }); + expect(await read(vms.personalPilot)).toEqual({ + kind: "pilot", vault: "https://vaultwarden.example.lazurio.io", + host: "vaultwarden.example.lazurio.io", + address: "example.lazurio.io", account: "vaultwarden@example.lazurio.io", - kind: "personal", - collection: "Environmenty/Osobní · example", + environment: "personal", + organization: null, }); - // A Team Environment whose Folder does not hold its Organization yet - // is named by its kind, as the rail names it. - expect( - await readVaultContext({ - folder: teamVm.folder, - platform: "linux", - home: "/home/operator", - sources: teamVm.sources(), - }), - ).toMatchObject({ + expect(await read(vms.teamPilot)).toMatchObject({ + kind: "pilot", account: "vaultwarden@workspace.example.lazurio.io", - kind: "team", - collection: "Environmenty/Týmový · workspace", + environment: "team", + organization: "example", }); } finally { - await personalVm.close(); - await teamVm.close(); + for (const vm of Object.values(vms)) await vm.close(); } }, ); diff --git a/tests/vault-organization.test.ts b/tests/vault-organization.test.ts new file mode 100644 index 000000000..f430e15a6 --- /dev/null +++ b/tests/vault-organization.test.ts @@ -0,0 +1,177 @@ +import { expect, test } from "bun:test"; +import { mkdtemp, realpath, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + type VaultHost, + type VaultJournalEntry, + vaultSetup, +} from "../src/vault/flow"; +import { agentsCollection } from "../src/vault/organization"; +import { + decrypt, + deriveMasterKey, + publicKeyOf, + rsaDecrypt, + stretchMasterKey, + symmetricKey, +} from "../src/vault/register"; +import { readAccount, readRecord, vaultPaths } from "../src/vault/store"; +import { + fakeBw, + fakeHost, + fakePin, + fakeRelease, + ownAccount, + startFakeVault, + stateDirectory, + zipOf, +} from "./fixtures/fake-vault"; + +// The Environment's own organization (decision F52, src/vault/organization.ts) +// as the vault keeps it: what the account sent can be opened by the account +// alone, from its own master password down to the collection's name; and the +// organization step never guesses which collection is Agenti. + +const posix = process.platform !== "win32"; + +async function world() { + const parent = await realpath(await mkdtemp(join(tmpdir(), "vault-org-"))); + const home = join(parent, "home"); + const vault = await startFakeVault(home); + const zip = zipOf("bw", fakeBw); + const pin = fakePin(zip); + const journal: VaultJournalEntry[] = []; + const host = fakeHost({ + home, + vault, + pin, + download: fakeRelease(pin, zip).fetch, + journal, + }); + return { + vault, + host, + journal, + paths: vaultPaths( + stateDirectory(home, "vaultwarden.example.lazurio.io", ownAccount), + ), + async close() { + await vault.stop(); + await rm(parent, { recursive: true, force: true }); + }, + }; +} + +const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes); + +test.skipIf(!posix)( + "the account opens its own organization key with its own master password, and the key opens Agenti's name and the organization's private key", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); + const account = await readAccount(w.paths); + const user = w.vault.users.get(ownAccount); + const [organization] = w.vault.organizationsOf(ownAccount); + if (account === null || user === undefined || organization === undefined) + throw new Error("Expected the account and its vault"); + const member = organization.members.get(user.id); + if (member === undefined) throw new Error("Expected the membership"); + + // The account's keys, as any of its clients unlocks them: the master + // key from the password, the user key it wraps, the private key the + // user key wraps. + const masterKey = await deriveMasterKey( + account.masterPassword, + account.email, + ); + const userKey = symmetricKey( + await decrypt(user.protectedUserKey, await stretchMasterKey(masterKey)), + ); + const privateKey = await decrypt(user.encryptedPrivateKey, userKey); + // The key the organization key was encrypted to is the account's own. + expect(await publicKeyOf(privateKey)).toBe(user.publicKey); + + // The organization key, encrypted to the account (EncString type 4). + expect(member.key.startsWith("4.")).toBe(true); + const organizationKey = symmetricKey( + await rsaDecrypt(privateKey, member.key), + ); + // It opens the first collection's name … + const [first] = organization.collections; + expect(text(await decrypt(first?.name ?? "", organizationKey))).toBe( + agentsCollection, + ); + expect(agentsCollection).toBe("Agenti"); + // … and the organization's private key, whose public key is the one the + // vault keeps (and the receipt the setup recorded first). + const organizationPrivateKey = await decrypt( + organization.encryptedPrivateKey, + organizationKey, + ); + expect(await publicKeyOf(organizationPrivateKey)).toBe( + organization.publicKey, + ); + // Nothing of the keys is kept on the Environment but the account file + // the account already had. + expect(await readRecord(w.paths)).toEqual({ + organizationId: organization.id, + collectionId: first?.id ?? "?", + pendingKey: null, + }); + } finally { + await w.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "an organization recognized by its receipt with more than one collection is not given an Agenti by guess", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + let lose = true; + const host: VaultHost = { + ...w.host, + fetch: async (url, init) => { + const answer = await w.vault.fetch(url, init); + if (lose && url.endsWith("/api/organizations")) + throw new Error("connection reset"); + return answer; + }, + }; + expect(await vaultSetup(host)).toMatchObject({ state: "unreachable" }); + const [organization] = w.vault.organizationsOf(ownAccount); + if (organization === undefined) throw new Error("Expected the vault"); + // Before the Environment asks again, the organization has a second + // collection. + await w.vault.addCollection(organization.id); + lose = false; + expect(await vaultSetup(host)).toMatchObject({ + state: "failed", + stage: "vault", + reason: "collection-unknown", + fallback: "agent", + }); + // The organization is recorded, Agenti is not, and no second + // organization was created. + expect(await readRecord(w.paths)).toEqual({ + organizationId: organization.id, + collectionId: null, + pendingKey: null, + }); + expect(w.vault.organizationsOf(ownAccount)).toHaveLength(1); + expect(w.journal).not.toContainEqual({ + operation: "vault", + outcome: "created", + }); + } finally { + await w.close(); + } + }, + 60_000, +); diff --git a/tests/vault-pilot.test.ts b/tests/vault-pilot.test.ts new file mode 100644 index 000000000..017de371c --- /dev/null +++ b/tests/vault-pilot.test.ts @@ -0,0 +1,453 @@ +import { expect, test } from "bun:test"; +import { randomUUID } from "node:crypto"; +import { + mkdir, + mkdtemp, + readdir, + readFile, + realpath, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { bwCli } from "../src/vault/bw"; +import { + setUpAtStart, + type VaultHost, + type VaultJournalEntry, + type VaultStatus, + vaultEnv, + vaultRefresh, + vaultSecrets, + vaultSecretsAdmission, + vaultSetup, + vaultStatus, +} from "../src/vault/flow"; +import { installPinnedBw, pinnedBinary } from "../src/vault/install"; +import type { PilotContext } from "../src/vault/legacy-0197/context"; +import { + DEVICE_TYPE_SDK, + fetchApiKey, + generateMasterPassword, + passwordLogin, + registerAccount, +} from "../src/vault/register"; +import { + completeAccount, + createAccount, + ensureVaultDirectories, + readSession, + vaultPaths, + writeSession, +} from "../src/vault/store"; +import { + collectionId, + fakeBw, + fakeHost, + fakePin, + fakeRelease, + organizationId, + otherCollectionId, + ownAccount, + ownContext, + personalHandover, + pilotContext, + startFakeVault, + stateDirectory, + vaultOrigin, + workHandover, + zipOf, +} from "./fixtures/fake-vault"; + +// Pilot safety (DEV-6631 task 638a): an Environment connected the 0197 way +// (decision F43) keeps working read only, exactly as before, while its +// handover names no vault: connected, the shared session unlocked, F46 from +// the recorded collection. Nothing connects the old way any more, and once +// the handover names its own vault the pilot's directory is left untouched +// for the move of task 649. The pilot is seeded as F43 left it. + +const posix = process.platform !== "win32"; +const host = "vaultwarden.example.lazurio.io"; +const value = "fake-pilot-secret-value-5d1c"; + +async function world(kind: "personal" | "work" = "personal") { + const parent = await realpath(await mkdtemp(join(tmpdir(), "vault-pilot-"))); + const home = join(parent, "home"); + const vault = await startFakeVault(home); + const zip = zipOf("bw", fakeBw); + const pin = fakePin(zip); + const release = fakeRelease(pin, zip); + const journal: VaultJournalEntry[] = []; + const context: PilotContext = + kind === "personal" + ? pilotContext() + : pilotContext(workHandover(null), "work"); + let current: Awaited> = context; + const vaultHost = fakeHost({ + home, + vault, + pin, + download: release.fetch, + journal, + context: async () => current, + }); + const paths = vaultPaths(stateDirectory(home, host, context.address)); + return { + home, + vault, + pin, + release, + journal, + context, + host: vaultHost, + paths, + /** What the host's context is from now on. */ + contextIs(next: Awaited>) { + current = next; + }, + /** The pilot as F43 left it: registered, signed in and unlocked in its + * own data directory, its collection in a person's organization + * recorded beside it. */ + async seed(options: Readonly<{ record?: boolean }> = {}) { + vault.allow(context.account); + const client = { fetch: vault.fetch }; + const account = { + email: context.account, + server: vaultOrigin, + deviceIdentifier: randomUUID(), + masterPassword: generateMasterPassword(), + createdAt: "2026-10-09T10:00:00.000Z", + }; + await ensureVaultDirectories(paths); + await createAccount(paths, account); + await registerAccount(client, { + serverUrl: vaultOrigin, + email: account.email, + password: account.masterPassword, + }); + const login = await passwordLogin(client, { + serverUrl: vaultOrigin, + email: account.email, + password: account.masterPassword, + device: { + identifier: account.deviceIdentifier, + name: "Lazurio Launchpad", + type: DEVICE_TYPE_SDK, + }, + }); + const ready = await completeAccount( + paths, + account, + await fetchApiKey(client, login), + ); + const installed = await installPinnedBw({ + base: vaultHost.base, + bin: vaultHost.bin, + data: paths.data, + home, + path: vaultHost.path, + platform: "linux", + arch: "x64", + run: vaultHost.run, + fetch: release.fetch, + pin, + }); + if (installed.kind !== "installed") throw new Error("Expected bw"); + const bw = bwCli({ + binary: pinnedBinary(vaultHost.base, pin), + data: paths.data, + home, + path: vaultHost.path, + run: vaultHost.run, + }); + expect((await bw.configServer(vaultOrigin)).ok).toBe(true); + expect( + (await bw.loginApiKey(ready.clientId, ready.clientSecret)).ok, + ).toBe(true); + const unlocked = await bw.unlock(ready.masterPassword); + if (!unlocked.ok) throw new Error("Expected an unlock"); + await writeSession(paths, unlocked.value); + if (options.record !== false) + await writeFile( + paths.record, + `${JSON.stringify( + { + fingerprint: "steep-flavor-uncut-scouring-unnoticed", + organizationId, + collectionId, + }, + null, + 2, + )}\n`, + { mode: 0o600 }, + ); + await vault.confirm("Environmenty/Osobní · example", 2); + expect((await bw.sync(unlocked.value)).ok).toBe(true); + return ready; + }, + async close() { + await vault.stop(); + await rm(parent, { recursive: true, force: true }); + }, + }; +} + +/** Every file below a directory with its bytes, for "untouched". */ +async function snapshot(directory: string): Promise> { + const files: Record = {}; + const walk = async (at: string) => { + for (const name of (await readdir(at)).sort()) { + const path = join(at, name); + if ((await stat(path)).isDirectory()) await walk(path); + else files[path] = await readFile(path, "base64"); + } + }; + await walk(directory); + return files; +} + +test.skipIf(!posix)( + "a 0197 pilot without a vault in its handover stays connected, read only: status, refresh and the shared session, and no setup the old way", + async () => { + const w = await world(); + try { + await w.seed(); + const facts = { + vault: vaultOrigin, + account: "vaultwarden@example.lazurio.io", + name: null, + team: false, + origin: "pilot-0197", + } as const; + const connected: VaultStatus = { + kind: "vault-status", + state: "connected", + ...facts, + organizationId, + collectionId, + organization: "Example Organization", + items: 2, + }; + expect(await vaultStatus(w.host)).toEqual(connected); + expect(await vaultRefresh(w.host)).toEqual(connected); + expect(setUpAtStart(await vaultStatus(w.host))).toBe(false); + // Agents get the pilot's session and its recorded ids. + const env = await vaultEnv(w.host); + expect(env).toEqual({ + kind: "vault-env", + env: { + BITWARDENCLI_APPDATA_DIR: w.paths.data, + BW_SESSION: (await readSession(w.paths)) ?? "?", + LAZURIO_VAULT_ORGANIZATION_ID: organizationId, + LAZURIO_VAULT_COLLECTION_ID: collectionId, + }, + }); + // A session ended by another unlock is replaced, as before. + await rm(join(w.paths.data, "fake", "session")); + expect(await vaultStatus(w.host)).toMatchObject({ + state: "connected", + locked: true, + }); + const again = await vaultEnv(w.host); + expect(again.kind).toBe("vault-env"); + expect(again.kind === "vault-env" ? again.env.BW_SESSION : null).toBe( + await readSession(w.paths), + ); + // No connection the old way: a setup only reads, and asks nothing. + const requests = w.vault.requests.length; + const downloads = w.release.requests.length; + expect(await vaultSetup(w.host)).toEqual(connected); + expect(w.vault.requests).toHaveLength(requests); + expect(w.release.requests).toHaveLength(downloads); + // The collection is no longer shared: revoked. + await w.vault.remove(); + expect(await vaultRefresh(w.host)).toEqual({ + kind: "vault-status", + state: "revoked", + ...facts, + }); + } finally { + await w.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "a pilot's runtime secrets come from its recorded collection under the 0197 rule", + async () => { + const w = await world("work"); + try { + await w.seed(); + await w.vault.items( + [ + { name: "EXAMPLE_TOKEN", collectionIds: [collectionId] }, + // The same name in another collection is not the pilot's. + { name: "OTHER_TOKEN", collectionIds: [otherCollectionId] }, + ].map((item) => ({ + object: "item", + id: randomUUID(), + type: 1, + name: item.name, + organizationId, + collectionIds: item.collectionIds, + login: { username: "example", password: value }, + })), + ); + const names = ["EXAMPLE_TOKEN", "OTHER_TOKEN"]; + const result = await vaultSecrets(w.host, { + company: "Example", + personalspace: false, + names, + }); + expect(result.kind).toBe("vault-secrets"); + if (result.kind !== "vault-secrets") return; + expect(result.secrets.get("EXAMPLE_TOKEN")).toEqual({ + kind: "value", + value, + }); + expect(result.secrets.get("OTHER_TOKEN")).toEqual({ + kind: "absent", + reason: "missing", + }); + // F46's rule of 0197: never a Personalspace module, never another + // Organization. + for (const [application, reason] of [ + [{ company: "example", personalspace: true }, "personalspace"], + [{ company: "other", personalspace: false }, "other-organization"], + ] as const) { + expect(await vaultSecretsAdmission(w.host, application)).toBe(reason); + expect(await vaultSecrets(w.host, { ...application, names })).toEqual({ + kind: "vault-secrets-refused", + reason, + }); + } + expect( + await vaultSecretsAdmission(w.host, { + company: "example", + personalspace: false, + }), + ).toBeNull(); + // The value is in the result only. + expect(await w.vault.calls()).not.toContain(value); + expect(JSON.stringify(w.journal)).not.toContain(value); + } finally { + await w.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "an Environment never connected the 0197 way, or disconnected, has no vault yet: nothing is read or created", + async () => { + for (const seeded of [false, true]) { + const w = await world("work"); + try { + if (seeded) await w.seed({ record: false }); + const requests = w.vault.requests.length; + const noVault: VaultStatus = { + kind: "vault-status", + state: "unsupported", + reason: "no-vault", + }; + expect([seeded, await vaultStatus(w.host)]).toEqual([seeded, noVault]); + expect([seeded, await vaultRefresh(w.host)]).toEqual([seeded, noVault]); + expect([seeded, await vaultSetup(w.host)]).toEqual([seeded, noVault]); + expect([seeded, await vaultEnv(w.host)]).toEqual([ + seeded, + { kind: "vault-env-refused", reason: "no-vault" }, + ]); + const application = { company: "example", personalspace: false }; + expect(await vaultSecretsAdmission(w.host, application)).toBe( + "no-vault-identity", + ); + expect( + await vaultSecrets(w.host, { ...application, names: ["TOKEN"] }), + ).toEqual({ + kind: "vault-secrets-refused", + reason: "no-vault-identity", + }); + expect(w.vault.requests).toHaveLength(requests); + } finally { + await w.close(); + } + } + }, + 60_000, +); + +test.skipIf(!posix)( + "once the handover names the Environment's own vault, the new account sets it up in its own directory and the pilot's directory stays untouched", + async () => { + const w = await world(); + try { + await w.seed(); + const before = await snapshot(w.paths.directory); + expect(Object.keys(before).length).toBeGreaterThan(3); + // Machines writes `vault` for this Environment. + w.contextIs(ownContext(personalHandover)); + expect(await vaultStatus(w.host)).toMatchObject({ + state: "not-set-up", + origin: "own", + account: ownAccount, + }); + w.vault.allow(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ + state: "connected", + origin: "own", + }); + const own = vaultPaths(stateDirectory(w.home, host, ownAccount)); + const env = await vaultEnv(w.host); + expect( + env.kind === "vault-env" ? env.env.BITWARDENCLI_APPDATA_DIR : null, + ).toBe(own.data); + // The agents' `bw` now defaults to the own account's data. + expect( + await readFile(join(w.home, ".local", "bin", "bw"), "utf8"), + ).toContain(`BITWARDENCLI_APPDATA_DIR='${own.data}'`); + // The pilot's directory is byte for byte what it was. + expect(await snapshot(w.paths.directory)).toEqual(before); + } finally { + await w.close(); + } + }, + 60_000, +); + +test("the pilot's account is derived as F43 derived it, and only from a handover that names no vault", () => { + expect(pilotContext()).toMatchObject({ + kind: "pilot", + vault: vaultOrigin, + address: "example.lazurio.io", + account: "vaultwarden@example.lazurio.io", + organization: null, + }); + expect(pilotContext(workHandover(null), "work")).toMatchObject({ + address: "workspace.example.lazurio.io", + account: "vaultwarden@workspace.example.lazurio.io", + organization: "example", + }); +}); + +test.skipIf(!posix)( + "the pilot's directory is keyed by its address, beside the own account's", + async () => { + const parent = await realpath(await mkdtemp(join(tmpdir(), "vault-dir-"))); + try { + const pilot = stateDirectory(parent, host, "example.lazurio.io"); + const own = stateDirectory(parent, host, ownAccount); + await mkdir(pilot, { recursive: true }); + await mkdir(own, { recursive: true }); + expect( + ( + await readdir(join(parent, ".local/state/lazurio/vault", host)) + ).sort(), + ).toEqual(["example.lazurio.io", ownAccount].sort()); + } finally { + await rm(parent, { recursive: true, force: true }); + } + }, +); diff --git a/tests/vault-register.test.ts b/tests/vault-register.test.ts index c4ff2a27e..c3b063093 100644 --- a/tests/vault-register.test.ts +++ b/tests/vault-register.test.ts @@ -392,3 +392,144 @@ describe("the requests", () => { ).toBe("unsupported-kdf"); }); }); + +// The Environment's own vault (decision F52): the account signs in with its +// API key, unlocks its own keys and asks the vault's API with any method. +describe("the own vault's requests", () => { + const ownEmail = "vaultwarden-ndbrmzvjpwxtt3q7m2e4fihgsa@example.lazurio.io"; + const userId = "6a5f4e3d-2c1b-4a9f-8e7d-6c5b4a3f2e1d"; + const device = { + identifier: "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b", + name: "Lazurio Launchpad", + type: vr.DEVICE_TYPE_SDK, + }; + + test("the public key of a private key is the one generated with it", async () => { + const wrap = vr.symmetricKey(vr.randomBytes(64)); + const pair = await vr.makeKeyPair(wrap); + const privateKey = await vr.decrypt(pair.encryptedPrivateKey, wrap); + expect(await vr.publicKeyOf(privateKey)).toBe(pair.publicKey); + }); + + test("the account's private key unlocks from its master password and what the vault keeps", async () => { + const keys = await vr.makeAccountKeys( + ownEmail, + "throwaway-unit-test", + 5_000, + ); + const privateKey = await vr.unlockPrivateKey({ + email: ownEmail, + password: "throwaway-unit-test", + protectedUserKey: keys.protectedUserKey, + encryptedPrivateKey: keys.encryptedPrivateKey, + iterations: 5_000, + }); + expect(await vr.publicKeyOf(privateKey)).toBe(keys.publicKey); + await expect( + vr.unlockPrivateKey({ + email: ownEmail, + password: "another-password", + protectedUserKey: keys.protectedUserKey, + encryptedPrivateKey: keys.encryptedPrivateKey, + iterations: 5_000, + }), + ).rejects.toThrow("MAC mismatch"); + }); + + test("the API-key login sends client_credentials with the one device and returns what unlocking needs", async () => { + const answer = { + access_token: jwt({ sub: userId }), + token_type: "Bearer", + Key: "2.a|b|c", + PrivateKey: "2.d|e|f", + Kdf: 0, + KdfIterations: 600_000, + }; + const vault = scripted({ + "/identity/connect/token": (body) => { + expect(body).toEqual({ + grant_type: "client_credentials", + scope: "api", + client_id: `user.${userId}`, + client_secret: "a1b2c3d4e5f6a1b2", + deviceType: "21", + deviceIdentifier: device.identifier, + deviceName: device.name, + }); + return Response.json(answer); + }, + }); + const login = { + serverUrl: server, + clientId: `user.${userId}`, + clientSecret: "a1b2c3d4e5f6a1b2", + device, + }; + expect(await vr.apiKeyLogin({ fetch: vault.fetch }, login)).toEqual({ + serverUrl: server, + userId, + accessToken: answer.access_token, + protectedUserKey: "2.a|b|c", + encryptedPrivateKey: "2.d|e|f", + iterations: 600_000, + }); + // Refusals and answers this core does not read are fixed reasons. + for (const [response, reason] of [ + [refusal("Incorrect client_secret"), "invalid-credentials"], + [Response.json({ ...answer, Kdf: 1 }), "unsupported-kdf"], + [Response.json({ ...answer, KdfIterations: 10 }), "unsupported-kdf"], + [ + Response.json({ + ...answer, + access_token: jwt({ sub: device.identifier }), + }), + "unexpected", + ], + [Response.json({ ...answer, Key: null }), "unexpected"], + [new Response("", { status: 503 }), "unreachable"], + ] as const) { + const refused = scripted({ "/identity/connect/token": () => response }); + const error = await vr + .apiKeyLogin({ fetch: refused.fetch }, login) + .catch((caught: unknown) => caught); + expect([reason, (error as vr.VaultwardenError).reason]).toEqual([ + reason, + reason, + ]); + } + }); + + test("a request names its method, carries the token, and an organization the vault does not allow is a fixed reason", async () => { + const vault = scripted({ + "/api/organizations/x": (_body, init) => + Response.json({ method: init.method }), + "/api/organizations": () => + refusal("User not allowed to create organizations"), + }); + for (const method of ["GET", "PUT", "DELETE"] as const) { + expect( + await vr.vaultRequest( + { fetch: vault.fetch }, + server, + "/api/organizations/x", + { + method, + token: "token", + ...(method === "PUT" ? { json: { name: "x" } } : {}), + }, + ), + ).toEqual({ method }); + } + const headers = vault.seen.at(-1)?.init.headers as + | Record + | undefined; + expect(headers?.Authorization).toBe("Bearer token"); + const error = await vr + .vaultRequest({ fetch: vault.fetch }, server, "/api/organizations", { + json: {}, + token: "token", + }) + .catch((caught: unknown) => caught); + expect((error as vr.VaultwardenError).reason).toBe("organization-refused"); + }); +}); diff --git a/tests/vault-secrets.test.ts b/tests/vault-secrets.test.ts index a312d7b59..3ab01dc1c 100644 --- a/tests/vault-secrets.test.ts +++ b/tests/vault-secrets.test.ts @@ -9,78 +9,59 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { parseMachineContext } from "../src/machine/context"; import { parseSecretItems } from "../src/vault/bw"; -import { - type VaultContext, - type VaultUnsupported, - vaultContextOf, -} from "../src/vault/context"; +import type { VaultContext, VaultUnsupported } from "../src/vault/context"; import { type VaultHost, type VaultJournalEntry, - vaultConnect, - vaultRefresh, vaultSecrets, vaultSecretsAdmission, + vaultSetup, } from "../src/vault/flow"; +import { readRecord, vaultPaths } from "../src/vault/store"; import { - collectionId, fakeBw, fakeHost, fakePin, fakeRelease, - organizationId, - otherCollectionId, + ownContext, personalHandover, startFakeVault, + stateDirectory, + workAccount, + workHandover, zipOf, - zone, } from "./fixtures/fake-vault"; -import { handoverEntry } from "./fixtures/machine-bindings"; -import organization from "./fixtures/machine-context.json"; -// The runtime secrets of an application from the Environment vault -// (decision F46, root decision 0177): a sync, then the one item of each -// declared name in the Environment's collection, its login password the -// value. Against the fake Vaultwarden and the fake bw of the vault's own -// tests; every name, id and value is invented. +// The runtime secrets of an application from the Environment's own vault +// (decision F46 as F52 amends it, root decision 0177): a sync, then the one +// item of each declared name anywhere in the vault, its login password the +// value. A work Environment serves its owning Organization's applications, a +// personal one the Personalspace's (0198 point 4). Against the fake +// Vaultwarden and the fake bw; every name, id and value is invented. const posix = process.platform !== "win32"; const otherOrganizationId = "9c8b7a6f-5e4d-4c3b-8a29-1f0e9d8c7b6a"; +const otherCollectionId = "1f2e3d4c-5b6a-4f9e-8d7c-6b5a4f3e2d1c"; // A value that must never appear anywhere but in the result. const value = "fake-runtime-secret-value-7f3a9c"; const changed = "fake-runtime-secret-value-changed-2b8e4d"; /** The work Environment `workspace` of the Organization `example`. */ -const workHandover = parseMachineContext( - Buffer.from( - JSON.stringify({ - ...organization, - owner: { kind: "organization", organization: "example" }, - network: { - headscale_server_url: `https://headscale.${zone}`, - headscale_hostname: "example-workspace", - }, - entry: handoverEntry("workspace.example.lazurio.io"), - }), - ), -); -const workContext = vaultContextOf({ - handover: workHandover, - kind: "work", - label: null, -}); +const workContext = ownContext(workHandover(), "work"); +const application = { company: "Example", personalspace: false } as const; type Item = Readonly<{ name: string; password?: string | null; - organization?: string | null; - collections?: readonly string[]; + /** Another organization's (`foreign`) or the account's own (`personal`). */ + owner?: "foreign" | "personal"; + /** Agenti by default. */ + collection?: "other"; notes?: string; }>; -/** A connected work Environment: invited, connected, confirmed, refreshed. */ +/** A work Environment whose own vault is set up. */ async function connected() { const parent = await realpath( await mkdtemp(join(tmpdir(), "vault-secrets-")), @@ -89,53 +70,58 @@ async function connected() { const vault = await startFakeVault(home); const zip = zipOf("bw", fakeBw); const pin = fakePin(zip); - const release = fakeRelease(pin, zip); const journal: VaultJournalEntry[] = []; const host = fakeHost({ home, vault, pin, - download: release.fetch, + download: fakeRelease(pin, zip).fetch, journal, context: async () => workContext, }); - if (workContext.kind === "unsupported") throw new Error("unsupported"); - vault.invite(workContext.account); - await vaultConnect(host); - await vault.confirm(workContext.collection, 0); - expect(await vaultRefresh(host)).toMatchObject({ state: "connected" }); + vault.allow(workAccount); + expect(await vaultSetup(host)).toMatchObject({ state: "connected" }); + const paths = vaultPaths( + stateDirectory(home, "vaultwarden.example.lazurio.io", workAccount), + ); + const record = await readRecord(paths); + const organizationId = record.organizationId ?? "?"; + const agents = record.collectionId ?? "?"; /** What the next sync brings: the items of the vault. */ const items = (list: readonly Item[]) => - writeFile( - join(vault.world, "items.json"), - JSON.stringify( - list.map((item) => ({ - object: "item", - id: crypto.randomUUID(), - type: 1, - name: item.name, - organizationId: - item.organization === undefined - ? organizationId - : item.organization, - collectionIds: item.collections ?? [collectionId], - notes: item.notes ?? null, - login: - item.password === undefined - ? { username: "example", password: value } - : item.password === null - ? null - : { username: "example", password: item.password }, - })), - ), + vault.items( + list.map((item) => ({ + object: "item", + id: crypto.randomUUID(), + type: 1, + name: item.name, + organizationId: + item.owner === "foreign" + ? otherOrganizationId + : item.owner === "personal" + ? null + : organizationId, + collectionIds: + item.owner === "personal" + ? [] + : [item.collection === "other" ? otherCollectionId : agents], + notes: item.notes ?? null, + login: + item.password === undefined + ? { username: "example", password: value } + : item.password === null + ? null + : { username: "example", password: item.password }, + })), ); return { - parent, home, vault, host, journal, items, + organizationId, + data: paths.data, async close() { await vault.stop(); await rm(parent, { recursive: true, force: true }); @@ -162,32 +148,41 @@ async function everyFile(directory: string, skip?: string): Promise { } test.skipIf(!posix)( - "a declared name is the login password of the one item of that name in the Environment's collection, read after a sync and never written anywhere", + "a declared name is the login password of the one item of that name anywhere in the Environment's vault, read after a sync and never written anywhere", async () => { const w = await connected(); try { await w.items([ { name: "EXTERNAL_API_KEY", notes: "fake-unrelated-note-5c1e" }, + // Another collection of the same vault holds one as well. + { + name: "SECOND_KEY", + collection: "other", + password: "fake-second-value-4e2a", + }, { name: "UNRELATED_ITEM", password: "fake-unrelated-value-0d4f" }, ]); const result = await vaultSecrets(w.host, { - company: "Example", - names: ["EXTERNAL_API_KEY"], + ...application, + names: ["EXTERNAL_API_KEY", "SECOND_KEY"], }); expect(result).toEqual({ kind: "vault-secrets", - secrets: new Map([["EXTERNAL_API_KEY", { kind: "value", value }]]), + secrets: new Map([ + ["EXTERNAL_API_KEY", { kind: "value", value }], + ["SECOND_KEY", { kind: "value", value: "fake-second-value-4e2a" }], + ]), }); - // A sync came first; the items of exactly the connected collection - // were listed; no value was ever an argument. + // A sync came first; the items of exactly the own vault were listed; + // no value was ever an argument. const calls = await w.vault.calls(); const lines = calls.trim().split("\n"); const sync = lastIndex(lines, "sync "); - const list = lastIndex(lines, "list items"); + const list = lastIndex(lines, "list items --organizationid"); expect(sync).toBeGreaterThan(-1); expect(list).toBeGreaterThan(sync); expect(lines[list]).toBe( - `list items --organizationid ${organizationId} --collectionid ${collectionId} --nointeraction|session=yes`, + `list items --organizationid ${w.organizationId} --nointeraction|session=yes`, ); expect(calls).not.toContain(value); // The journal says what happened, never a value or a name. @@ -201,15 +196,7 @@ test.skipIf(!posix)( // `fake/` of its data directory, where the real bw keeps its // encrypted store; that copy is bw's, not this Platform's. const state = join(w.home, ".local", "state"); - const data = join( - state, - "lazurio", - "vault", - "vaultwarden.example.lazurio.io", - "workspace.example.lazurio.io", - "bw", - ); - expect(await everyFile(state, join(data, "fake"))).not.toContain(value); + expect(await everyFile(state, join(w.data, "fake"))).not.toContain(value); expect(await everyFile(join(w.home, ".local", "share"))).not.toContain( value, ); @@ -220,27 +207,26 @@ test.skipIf(!posix)( ); test.skipIf(!posix)( - "missing, held twice, in another collection or organization, or without a password: no value, and why", + "missing, held twice, in another organization or the account's own vault, or without a password: no value, and why", async () => { const w = await connected(); try { await w.items([ { name: "TWICE" }, - { name: "TWICE", password: "fake-second-value-6a1c" }, - { name: "ELSEWHERE", collections: [otherCollectionId] }, - { name: "FOREIGN", organization: otherOrganizationId }, - { name: "PERSONAL", organization: null, collections: [] }, + // Twice across two collections of the vault is twice too. + { name: "TWICE", collection: "other", password: "fake-second-6a1c" }, + { name: "FOREIGN", owner: "foreign" }, + { name: "PERSONAL", owner: "personal" }, { name: "EMPTY", password: "" }, { name: "NO_LOGIN", password: null }, // Another case of the name is another name. { name: "external_api_key" }, ]); const result = await vaultSecrets(w.host, { - company: "example", + ...application, names: [ "MISSING", "TWICE", - "ELSEWHERE", "FOREIGN", "PERSONAL", "EMPTY", @@ -253,7 +239,6 @@ test.skipIf(!posix)( secrets: new Map([ ["MISSING", { kind: "absent", reason: "missing" }], ["TWICE", { kind: "absent", reason: "ambiguous" }], - ["ELSEWHERE", { kind: "absent", reason: "missing" }], ["FOREIGN", { kind: "absent", reason: "missing" }], ["PERSONAL", { kind: "absent", reason: "missing" }], ["EMPTY", { kind: "absent", reason: "empty" }], @@ -280,7 +265,7 @@ test.skipIf(!posix)( await w.items([{ name: "EXTERNAL_API_KEY" }]); const read = async () => { const result = await vaultSecrets(w.host, { - company: "example", + ...application, names: ["EXTERNAL_API_KEY"], }); return result.kind === "vault-secrets" @@ -297,20 +282,18 @@ test.skipIf(!posix)( ); test.skipIf(!posix)( - "an unreachable vault and a revoked access refuse every name with a fixed reason", + "an unreachable vault and a refused grant refuse every name with a fixed reason", async () => { const w = await connected(); try { await w.items([{ name: "EXTERNAL_API_KEY" }]); await w.vault.unreachable(true); - const unreachable = await vaultSecrets(w.host, { - company: "example", - names: ["EXTERNAL_API_KEY"], - }); - expect(unreachable).toEqual({ - kind: "vault-secrets-refused", - reason: "unreachable", - }); + expect( + await vaultSecrets(w.host, { + ...application, + names: ["EXTERNAL_API_KEY"], + }), + ).toEqual({ kind: "vault-secrets-refused", reason: "unreachable" }); expect(w.journal.at(-1)).toEqual({ operation: "secrets", outcome: "refused", @@ -321,7 +304,7 @@ test.skipIf(!posix)( await writeFile(join(w.vault.world, "invalid-grant"), ""); expect( await vaultSecrets(w.host, { - company: "example", + ...application, names: ["EXTERNAL_API_KEY"], }), ).toEqual({ kind: "vault-secrets-refused", reason: "not-connected" }); @@ -331,7 +314,7 @@ test.skipIf(!posix)( }, ); -test("a workstation, an Environment without a vault account and an application of another Organization never run bw", async () => { +test("which applications read the own vault: the owning Organization's on a work Environment, the Personalspace's on a personal one; everything else is refused before bw runs", async () => { const calls: string[][] = []; const host = (context: VaultContext | VaultUnsupported): VaultHost => ({ ...fakeHost({ @@ -346,46 +329,67 @@ test("a workstation, an Environment without a vault account and an application o return { exitCode: 1, stdout: "", stderr: "" }; }, }); - const read = ( - context: VaultContext | VaultUnsupported, - company = "example", - ) => vaultSecrets(host(context), { company, names: ["EXTERNAL_API_KEY"] }); - expect(await read({ kind: "unsupported", reason: "workstation" })).toEqual({ - kind: "vault-secrets-refused", - reason: "workstation", - }); - expect( - await read({ kind: "unsupported", reason: "handover-missing" }), - ).toEqual({ kind: "vault-secrets-refused", reason: "no-vault-identity" }); - // The work Environment of `example`: an app of `gamma` reads nothing from - // its collection; the slug compares as GitHub's, case-insensitively. - expect(await read(workContext, "gamma")).toEqual({ - kind: "vault-secrets-refused", - reason: "other-organization", - }); - // A person's Environment: no Organization's app reads its secrets. - const personal = vaultContextOf({ - handover: personalHandover, - kind: "personal", - label: null, - }); - expect(await read(personal)).toEqual({ - kind: "vault-secrets-refused", - reason: "other-organization", - }); + const personal = ownContext(personalHandover, "personal"); + const cases = [ + // A work Environment of `example`: its own apps (slugs compare as + // GitHub's, case-insensitively), never another Organization's or a + // Personalspace module. + [workContext, { company: "EXAMPLE", personalspace: false }, null], + [ + workContext, + { company: "gamma", personalspace: false }, + "other-organization", + ], + [workContext, { company: "example", personalspace: true }, "personalspace"], + // A personal Environment: the Personalspace's modules, never an + // Organization's app. + [personal, { company: "personalspace", personalspace: true }, null], + [ + personal, + { company: "example", personalspace: false }, + "personal-environment", + ], + // No vault here: a workstation, or no vault named or readable. + [ + { kind: "unsupported", reason: "workstation" }, + { company: "example", personalspace: false }, + "workstation", + ], + [ + { kind: "unsupported", reason: "no-vault" }, + { company: "example", personalspace: false }, + "no-vault-identity", + ], + [ + { kind: "unsupported", reason: "handover-missing" }, + { company: "example", personalspace: true }, + "no-vault-identity", + ], + ] as const; + for (const [context, app, reason] of cases) { + expect([app, await vaultSecretsAdmission(host(context), app)]).toEqual([ + app, + reason, + ]); + // Admitted, but the vault is not set up here: refused before bw reads + // anything of the vault. + expect([ + app, + await vaultSecrets(host(context), { ...app, names: ["KEY"] }), + ]).toEqual([ + app, + { + kind: "vault-secrets-refused", + reason: reason ?? "not-connected", + }, + ]); + } expect(calls).toEqual([]); - expect(await vaultSecretsAdmission(host(workContext), "EXAMPLE")).toBeNull(); - expect(await vaultSecretsAdmission(host(workContext), "gamma")).toBe( - "other-organization", - ); - // Not connected: refused before bw reads anything of the vault. - expect(await read(workContext)).toEqual({ - kind: "vault-secrets-refused", - reason: "not-connected", - }); }); test("the item reader keeps only the declared names and only what the selection reads", () => { + const organizationId = "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b"; + const collectionId = "6a5f4e3d-2c1b-4a9f-8e7d-6c5b4a3f2e1d"; const names = new Set(["EXTERNAL_API_KEY"]); const stdout = JSON.stringify([ { diff --git a/tests/vault-store.test.ts b/tests/vault-store.test.ts index b788021dd..371a9dc14 100644 --- a/tests/vault-store.test.ts +++ b/tests/vault-store.test.ts @@ -20,7 +20,6 @@ import { completeAccount, createAccount, ensureVaultDirectories, - forgetSignIn, forgetUnregisteredAccount, parseAccount, readAccount, @@ -31,13 +30,14 @@ import { writeRecord, writeSession, } from "../src/vault/store"; +import { ownAccount } from "./fixtures/fake-vault"; -// The custody of one Environment vault account (decision F43) and what is -// read from bw: exact shapes only, the password written once, nothing of an -// account file ever echoed. +// The custody of one Environment vault account (decisions F43, F52) and what +// is read from bw: exact shapes only, the password written once, the own +// vault's record never guessed, nothing of an account file ever echoed. const account: VaultAccount = { - email: "vaultwarden@example.lazurio.io", + email: ownAccount, server: "https://vaultwarden.example.lazurio.io", deviceIdentifier: "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b", masterPassword: "A".repeat(43), @@ -61,13 +61,18 @@ async function temporary() { }; } -test("the account file is taken only in its exact form", () => { +test("the account file is taken only in its exact form, an own account's or a 0197 pilot's", () => { expect(parseAccount({ ...account })).toEqual(account); expect(parseAccount({ ...account, ...key })).toEqual({ ...account, ...key }); + // A 0197 pilot's account file reads the same way; whose it is, each + // caller checks against its own context. + const pilot = { ...account, email: "vaultwarden@example.lazurio.io" }; + expect(parseAccount(pilot)).toEqual(pilot); for (const refused of [ { ...account, extra: true }, { ...account, clientId: key.clientId }, - { ...account, email: "someone@example.invalid" }, + { ...account, email: "Someone@Example.invalid" }, + { ...account, email: "someone" }, { ...account, server: "http://vaultwarden.example.lazurio.io" }, { ...account, masterPassword: "short" }, { ...account, deviceIdentifier: "device" }, @@ -105,7 +110,7 @@ test("the password is written once, before the registration; the API key joins i } }); -test("a refused registration leaves nothing; a disconnect keeps only the account", async () => { +test("a refused registration leaves nothing; the session is written whole", async () => { const t = await temporary(); try { await createAccount(t.paths, account); @@ -119,23 +124,48 @@ test("a refused registration leaves nothing; a disconnect keeps only the account expect(await readSession(t.paths)).toBe(session); expect((await lstat(t.paths.session)).mode & 0o777).toBe(0o600); await expect(writeSession(t.paths, "not a session")).rejects.toThrow(); - await writeRecord(t.paths, { - fingerprint: "steep-flavor-uncut-scouring-unnoticed", - organizationId: "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b", - collectionId: "6a5f4e3d-2c1b-4a9f-8e7d-6c5b4a3f2e1d", - }); - await writeFile(join(t.paths.data, "data.json"), "{}"); - await forgetSignIn(t.paths); - expect(await readdir(t.paths.data)).toEqual(["lazurio-account.json"]); - expect(await readRecord(t.paths)).toEqual({ - fingerprint: null, + expect(await readFile(t.paths.account, "utf8")).toContain(key.clientSecret); + } finally { + await t.close(); + } +}); + +test("the own vault's record is its IDs and a creation's receipt, and a damaged one is never taken for none", async () => { + const t = await temporary(); + try { + const empty = { organizationId: null, collectionId: null, - }); - // An unreadable record is no record; it is not secret. - await writeFile(t.paths.record, "{broken"); - expect((await readRecord(t.paths)).collectionId).toBeNull(); - expect(await readFile(t.paths.account, "utf8")).toContain(key.clientSecret); + pendingKey: null, + }; + expect(await readRecord(t.paths)).toEqual(empty); + const receipt = { ...empty, pendingKey: "A".repeat(392) }; + await writeRecord(t.paths, receipt); + expect(await readRecord(t.paths)).toEqual(receipt); + expect((await lstat(t.paths.record)).mode & 0o777).toBe(0o600); + const vault = { + organizationId: "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b", + collectionId: "6a5f4e3d-2c1b-4a9f-8e7d-6c5b4a3f2e1d", + pendingKey: null, + }; + await writeRecord(t.paths, vault); + expect(await readRecord(t.paths)).toEqual(vault); + // Damaged, of another shape (a 0197 pilot's), or a collection without + // its organization: refused, never read as no record. + for (const damaged of [ + "{broken", + JSON.stringify({ + fingerprint: null, + organizationId: vault.organizationId, + collectionId: vault.collectionId, + }), + JSON.stringify({ ...vault, organizationId: null }), + JSON.stringify({ ...vault, pendingKey: "not a key" }), + JSON.stringify({ ...vault, extra: 1 }), + ]) { + await writeFile(t.paths.record, damaged); + await expect(readRecord(t.paths)).rejects.toThrow(); + } } finally { await t.close(); } diff --git a/tests/vault-view.test.ts b/tests/vault-view.test.ts index 38c1b9d7b..15db514f8 100644 --- a/tests/vault-view.test.ts +++ b/tests/vault-view.test.ts @@ -1,345 +1,268 @@ import { expect, test } from "bun:test"; import { messages } from "../src/launchpad/messages"; import { - parseVaultConnecting, + parseVaultSettingUp, parseVaultStatus, - vaultActions, - vaultAfterConnect, - vaultLink, - vaultPhaseMarks, + vaultAction, + vaultOpenLink, vaultRowLine, - vaultSeen, - vaultStartStep, - vaultStepTitles, } from "../src/launchpad/vault-view"; import type { VaultStatus } from "../src/vault/flow"; -// The Environment vault on the tools screen (decision F43, the wireframe of -// prototypes-lazurio#24): the row's states, its one next step, the dialog's -// steps and the server's answers taken only in their exact form. +// The Environment's own vault on the tools screen (decision F52, the +// wireframe of prototypes-lazurio#33): the row's states, "Otevřít trezor", +// the one action where a setup moves the vault on, and the server's answers +// taken only in their exact form. const cs = messages("cs"); const en = messages("en"); +const organizationId = "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b"; +const collectionId = "6a5f4e3d-2c1b-4a9f-8e7d-6c5b4a3f2e1d"; const facts = { vault: "https://vaultwarden.example.lazurio.io", - account: "vaultwarden@example.lazurio.io", - collection: "Environmenty/Osobní · example", - name: "Osobní", + account: "vaultwarden-ndbrmzvjpwxtt3q7m2e4fihgsa@example.lazurio.io", + name: "Example Osobní example", team: false, + origin: "own", }; -const fingerprint = "steep-flavor-uncut-scouring-unnoticed"; const status = (value: Record): VaultStatus => { const parsed = parseVaultStatus({ kind: "vault-status", ...facts, ...value }); if (parsed === null) throw new Error("Unexpected refusal"); return parsed; }; +const connected = { + state: "connected", + organizationId, + collectionId, + organization: "Example Osobní example", + items: 14, +}; test("every state the server answers is read back exactly; anything else is refused", () => { for (const value of [ - { state: "none", registered: false }, - { state: "not-installed", registered: true }, - { state: "awaiting-invite" }, - { state: "confirming", fingerprint, organization: null }, - { state: "confirming", fingerprint, organization: "Example", locked: true }, - { - state: "connected", - fingerprint, - organization: "Example", - collections: 2, - items: 14, - }, - { - state: "connected", - fingerprint, - organization: null, - collections: null, - items: null, - locked: true, - }, - { state: "revoked", fingerprint: null }, - { state: "unreachable", fingerprint, reason: "unreachable" }, + { state: "not-set-up", next: "install" }, + { state: "not-set-up", next: "vault" }, + { state: "not-allowed" }, + connected, + { ...connected, organization: null, items: null, locked: true }, + { state: "revoked" }, + { state: "unreachable", reason: "unreachable" }, { state: "failed", - stage: "install", - reason: "checksum-mismatch", + stage: "vault", + reason: "organization-refused", fallback: "agent", }, ]) - expect(status(value) as unknown).toEqual({ + expect(status(value)).toEqual({ kind: "vault-status", ...facts, ...value, - }); + } as VaultStatus); + // A 0197 pilot's status carries no vault name. expect( parseVaultStatus({ kind: "vault-status", - state: "unsupported", - reason: "workstation", + ...facts, + name: null, + origin: "pilot-0197", + ...connected, }), - ).toEqual({ - kind: "vault-status", - state: "unsupported", - reason: "workstation", - }); + ).toMatchObject({ origin: "pilot-0197", name: null }); + for (const reason of [ + "workstation", + "folder-unreadable", + "handover-missing", + "handover-unreadable", + "not-operator", + "no-vault", + ] as const) + expect( + parseVaultStatus({ kind: "vault-status", state: "unsupported", reason }), + ).toEqual({ kind: "vault-status", state: "unsupported", reason }); for (const refused of [ - { ...facts, kind: "vault-status", state: "connected", fingerprint }, - { ...facts, kind: "vault-status", state: "none" }, - { ...facts, kind: "vault-status", state: "elsewhere" }, + null, + [], + { kind: "vault-status", state: "unsupported", reason: "vault-unknown" }, + { kind: "vault-status", ...facts, state: "confirming" }, + { kind: "vault-status", ...facts, state: "awaiting-invite" }, + { kind: "vault-status", ...facts, state: "not-set-up", next: "connect" }, + { kind: "vault-status", ...facts, origin: "theirs", ...connected }, { - ...facts, kind: "vault-status", - state: "awaiting-invite", - vault: "https://evil.example.invalid", + ...facts, + vault: "http://vaultwarden.example.lazurio.io", + ...connected, }, { - ...facts, kind: "vault-status", - state: "awaiting-invite", - account: "a\u202eb", + ...facts, + vault: "https://vaultwarden.example.lazurio.io/path", + ...connected, }, + { kind: "vault-status", ...facts, ...connected, organizationId: "x" }, + { kind: "vault-status", ...facts, ...connected, items: -1 }, + { kind: "vault-status", ...facts, ...connected, locked: false }, + { kind: "vault-status", ...facts, account: "a\u202eb", ...connected }, { - ...facts, kind: "vault-status", - state: "confirming", - fingerprint: "two words", - organization: null, + ...facts, + state: "failed", + stage: "confirm", + reason: "x", + fallback: "agent", }, - { kind: "vault-status", state: "unsupported", reason: "maybe" }, - null, - [], - "connected", ]) - expect(parseVaultStatus(refused)).toBeNull(); - const job = "0123456789abcdef0123456789abcdef"; - expect( - parseVaultConnecting({ kind: "vault-connecting", job, phase: "account" }), - ).toEqual({ job, phase: "account" }); - expect( - parseVaultConnecting({ kind: "vault-connecting", job, phase: "x" }), - ).toBeNull(); - expect( - parseVaultConnecting({ - kind: "vault-connecting", - job: "1", - phase: "install", - }), - ).toBeNull(); + expect([refused, parseVaultStatus(refused)]).toEqual([refused, null]); }); -test("the third step asks for the confirmation, and once confirmed only for the collection", () => { - const third = (value: Record, copy = cs) => - vaultStepTitles(status(value), copy).confirm; - const waiting = { state: "confirming", fingerprint, organization: null }; - const confirmed = { - state: "confirming", - fingerprint, - organization: "Example", - }; - expect(third(waiting)).toBe("Potvrďte účet v trezoru"); - expect(third(waiting, en)).toBe("Confirm the account in the vault"); - expect(third(confirmed)).toBe("Nasdílejte účtu kolekci"); - expect(third(confirmed, en)).toBe("Share the collection with the account"); - // Every other step keeps its title. - expect(vaultStepTitles(status(confirmed), cs)).toEqual({ - invite: cs.vaultStepInvite, - connect: cs.vaultStepConnect, - confirm: "Nasdílejte účtu kolekci", - done: cs.vaultStepDone, - }); - expect(vaultStepTitles(null, en).confirm).toBe( - "Confirm the account in the vault", - ); -}); - -test("the row says the wireframe's states, with Czech plurals", () => { - const line = (value: Record, copy = cs) => - vaultRowLine(status(value), copy).text; - expect(line({ state: "none", registered: false })).toBe("Nepřipojeno"); - expect(line({ state: "confirming", fingerprint, organization: null })).toBe( - "Čeká na potvrzení v trezoru", - ); - // Confirmed in an organization, without the Environment's collection. - expect( - line({ state: "confirming", fingerprint, organization: "Example" }), - ).toBe("Potvrzeno, čeká na kolekci"); - expect( - line({ state: "confirming", fingerprint, organization: "Example" }, en), - ).toBe("Confirmed, waiting for the collection"); - const connected = (collections: number, items: number) => - line({ - state: "connected", - fingerprint, - organization: "Example", - collections, - items, - }); - expect(connected(2, 14)).toBe("Připojeno · 2 kolekce · 14 položek"); - expect(connected(1, 1)).toBe("Připojeno · 1 kolekce · 1 položka"); - expect(connected(5, 3)).toBe("Připojeno · 5 kolekcí · 3 položky"); - expect(connected(0, 0)).toBe("Připojeno · 0 kolekcí · 0 položek"); - expect( - line( - { - state: "connected", - fingerprint, - organization: "Example", - collections: 1, - items: 2, - }, - en, - ), - ).toBe("Connected · 1 collection · 2 items"); - expect(line({ state: "revoked", fingerprint })).toBe( - "Přístup odebrán v trezoru", - ); - expect(line({ state: "unreachable", fingerprint, reason: "timeout" })).toBe( - "Trezor neodpovídá", - ); - expect( - vaultRowLine( - { kind: "vault-status", state: "unsupported", reason: "workstation" }, - cs, - ).text, - ).toBe("Brzy · druhá vlna"); - expect(vaultRowLine(null, cs).text).toBe("Zjišťuji stav…"); - expect(vaultSeen(3, 21, cs)).toBe("3 kolekce · 21 položek"); +test("a running setup is read with its job and phase only", () => { + const job = "0123456789abcdef0123456789abcdef"; + for (const phase of ["install", "account", "vault", "sign-in"] as const) + expect( + parseVaultSettingUp({ kind: "vault-setting-up", job, phase }), + ).toEqual({ job, phase }); + for (const refused of [ + { kind: "vault-connecting", job, phase: "install" }, + { kind: "vault-setting-up", job: "x", phase: "install" }, + { kind: "vault-setting-up", job, phase: "confirm" }, + null, + ]) + expect(parseVaultSettingUp(refused)).toBeNull(); }); -test("each state offers one next step, and Odpojit once an account is signed in", () => { - const actions = (value: Record) => { - const { primary, disconnect } = vaultActions(status(value), cs); - return [primary?.action ?? null, primary?.label ?? null, disconnect]; - }; - expect(actions({ state: "none", registered: false })).toEqual([ - "connect", - "Připojit", - false, +test("the row says the state in few words, formally in Czech, and the step of a setup that runs", () => { + const lines = (copy: typeof cs) => + [ + vaultRowLine(null, null, copy), + vaultRowLine(status(connected), null, copy), + vaultRowLine( + status({ state: "not-set-up", next: "install" }), + null, + copy, + ), + vaultRowLine(status({ state: "not-allowed" }), null, copy), + vaultRowLine(status({ state: "revoked" }), null, copy), + vaultRowLine( + status({ state: "revoked", origin: "pilot-0197", name: null }), + null, + copy, + ), + vaultRowLine( + status({ state: "unreachable", reason: "unreachable" }), + null, + copy, + ), + vaultRowLine( + status({ + state: "failed", + stage: "vault", + reason: "x", + fallback: "agent", + }), + null, + copy, + ), + vaultRowLine( + { kind: "vault-status", state: "unsupported", reason: "no-vault" }, + null, + copy, + ), + vaultRowLine( + { kind: "vault-status", state: "unsupported", reason: "workstation" }, + null, + copy, + ), + vaultRowLine(null, "vault", copy), + ].map((line) => `${line.state}: ${line.text}`); + expect(lines(cs)).toEqual([ + "unknown: Zjišťuji stav…", + "signed-in: Připojeno", + "unknown: Zatím nenastaveno", + "signed-out: Síť zatím účet trezoru nepovolila", + "signed-out: Trezor byl odebrán", + "signed-out: Přístup odebrán v trezoru", + "signed-out: Trezor neodpovídá", + "signed-out: Nastavení se nedokončilo", + "unknown: Tento Environment zatím trezor nemá", + "unknown: Brzy · druhá vlna", + "unknown: Připravuje se trezor…", ]); - expect( - actions({ state: "confirming", fingerprint, organization: null }), - ).toEqual(["continue", "Pokračovat", true]); - expect( - actions({ - state: "connected", - fingerprint, - organization: null, - collections: 1, - items: 1, - }), - ).toEqual([null, null, true]); - expect(actions({ state: "revoked", fingerprint })).toEqual([ - "reconnect", - "Připojit znovu", - true, + expect(lines(en)).toEqual([ + "unknown: Checking…", + "signed-in: Connected", + "unknown: Not set up yet", + "signed-out: The network has not allowed its account yet", + "signed-out: The vault was removed", + "signed-out: Access removed in the vault", + "signed-out: The vault does not answer", + "signed-out: The setup did not finish", + "unknown: This Environment has no vault yet", + "unknown: Soon · second wave", + "unknown: Preparing the vault…", ]); - expect( - actions({ state: "unreachable", fingerprint, reason: "timeout" }), - ).toEqual(["retry", "Zkusit znovu", true]); - expect( - vaultActions( - { kind: "vault-status", state: "unsupported", reason: "workstation" }, - cs, - ), - ).toEqual({ primary: null, disconnect: false }); }); -test("the dialog starts where the state is and goes where a connect ends", () => { - expect( - vaultStartStep(status({ state: "none", registered: false }), "connect"), - ).toBe("invite"); - // An account that exists only signs in again. - expect( - vaultStartStep(status({ state: "none", registered: true }), "connect"), - ).toBe("connect"); - expect( - vaultStartStep( - status({ state: "confirming", fingerprint, organization: null }), - "continue", - ), - ).toBe("confirm"); - expect( - vaultStartStep(status({ state: "revoked", fingerprint }), "reconnect"), - ).toBe("invite"); - expect(vaultAfterConnect(status({ state: "awaiting-invite" }), cs)).toEqual({ - step: "invite", - failure: "Adresa ještě není v trezoru pozvaná.", - agent: false, - }); - // A connect keeps the collection it was connected to: another one needs a - // disconnect first, and the dialog says so. +test("the row opens the connected vault and offers one action only where a setup moves it on", () => { + expect(vaultOpenLink(status(connected))).toBe( + `https://vaultwarden.example.lazurio.io/#/vault?organizationId=${organizationId}`, + ); + expect(cs.vaultOpen).toBe("Otevřít trezor"); + for (const value of [ + { state: "not-set-up", next: "vault" }, + { state: "not-allowed" }, + { state: "revoked" }, + ]) + expect(vaultOpenLink(status(value))).toBeNull(); + expect(vaultOpenLink(null)).toBeNull(); + // Set up when nothing did, try again after a setup that stopped; never a + // disconnect, never for a vault the network has to act on, a pilot or a + // setup that runs. expect( - vaultAfterConnect(status({ state: "revoked", fingerprint }), cs), - ).toEqual({ - step: "invite", - failure: - "Účet nevidí kolekci, ke které byl připojený. Pozvěte ho do ní znovu, nebo Environment odpojte a připojte ho k jiné kolekci.", - agent: false, - }); + vaultAction(status({ state: "not-set-up", next: "install" }), null, cs), + ).toBe("Nastavit"); expect( - vaultAfterConnect( - status({ state: "confirming", fingerprint, organization: null }), - cs, - ), - ).toEqual({ step: "confirm", failure: null, agent: false }); + vaultAction(status({ state: "unreachable", reason: "x" }), null, cs), + ).toBe("Zkusit znovu"); expect( - vaultAfterConnect( + vaultAction( status({ - state: "connected", - fingerprint, - organization: null, - collections: 1, - items: 0, + state: "failed", + stage: "install", + reason: "x", + fallback: "agent", }), + null, cs, ), - ).toEqual({ step: "done", failure: null, agent: false }); + ).toBe("Zkusit znovu"); + for (const value of [ + connected, + { state: "not-allowed" }, + { state: "revoked" }, + { + state: "unreachable", + reason: "x", + origin: "pilot-0197", + name: null, + }, + ]) + expect([value, vaultAction(status(value), null, cs)]).toEqual([ + value, + null, + ]); expect( - vaultAfterConnect( - status({ - state: "unreachable", - fingerprint: null, - reason: "unreachable", - }), + vaultAction( + status({ state: "not-set-up", next: "install" }), + "install", cs, ), - ).toEqual({ step: "connect", failure: "Trezor neodpovídá.", agent: false }); + ).toBeNull(); expect( - vaultAfterConnect( - status({ - state: "failed", - stage: "account", - reason: "rate-limited", - fallback: "agent", - }), + vaultAction( + { kind: "vault-status", state: "unsupported", reason: "no-vault" }, + null, cs, ), - ).toEqual({ - step: "connect", - failure: "Připojení se nedokončilo (account: rate-limited).", - agent: true, - }); - expect(vaultPhaseMarks("account", cs)).toEqual([ - { label: "Instaluji Bitwarden", mark: "done" }, - { label: "Zakládám účet", mark: "running" }, - { label: "Přihlašuji", mark: "next" }, - ]); - expect(vaultPhaseMarks("done", cs).map((entry) => entry.mark)).toEqual([ - "done", - "done", - "done", - ]); -}); - -test("only the Environment's own vault becomes a link", () => { - expect(vaultLink("https://vaultwarden.example.lazurio.io")).toBe( - "https://vaultwarden.example.lazurio.io/", - ); - for (const refused of [ - "http://vaultwarden.example.lazurio.io", - "https://vault.example.lazurio.io", - "https://vaultwarden.example.lazurio.io:8443", - "https://vaultwarden.example.lazurio.io/admin", - "javascript:alert(1)", - ]) - expect(vaultLink(refused)).toBeNull(); + ).toBeNull(); }); From db678a29c3e12271363edec3e687e89a83fe2e38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Tue, 13 Oct 2026 22:11:47 +0200 Subject: [PATCH 3/9] Vault: the agents' prompt says Environment, and the F46 texts name the vault The bitwarden tool's prompt a person copies for an agent spoke of the Machine handover; towards people the place is the Environment (decision 0170, the wording guard), so it now says the network pre-allowed the account for this Environment and gave it a vault or not. The module view's F46 expectations follow the texts that now name the Environment's vault, not its collection. Co-Authored-By: Claude Opus 5.5 --- src/tools/catalog.ts | 4 ++-- tests/module-view.test.ts | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/tools/catalog.ts b/src/tools/catalog.ts index 62e7b7b1f..21b0c503f 100644 --- a/src/tools/catalog.ts +++ b/src/tools/catalog.ts @@ -342,8 +342,8 @@ export const toolCatalog: readonly ToolEntry[] = Object.freeze([ en: "Task: finish this Environment's vault, the tool `bitwarden` (command `bw`): the Environment's own vault in its network's Lazurio Vaultwarden, with the Environment's account signed in and unlocked for agents. First read the actual state with `lazurio vault status --json`; change nothing that already works.", }, installation: installation( - `Cílový stav: Bitwarden CLI ve verzi, kterou připíná Lazurio (${bitwardenPin.version}, sestavení OSS z oficiálních vydání https://github.com/bitwarden/clients), spouští \`~/.local/bin/bw\`; účet tohoto Environmentu, jehož adresu jmenuje handover Mašiny, je v trezoru jeho sítě založený, má vlastní trezor Environmentu (organizaci s kolekcí Agenti) a je přihlášený a odemčený. Udělá to příkaz \`lazurio vault setup --json\` (totéž dělá Launchpad při svém startu): nainstaluje připnuté \`bw\`, založí účet s heslem, které vznikne tady a nezná ho žádný člověk, založí trezor, přihlásí účet API klíčem a vrátí stav. Hlásí-li \`unsupported\` s důvodem \`no-vault\`, handover zatím žádný trezor nejmenuje; hlásí-li \`not-allowed\`, síť adresu účtu zatím nepovolila; hlásí-li \`revoked\`, trezor nebo účet odebral provozovatel sítě. To vše řeší provozovatel sítě: řekni to Operátorovi a nic neobcházej. Jinou verzi \`bw\` neinstaluj, \`~/.local/bin/bw\`, který není Lazuria, nepřepisuj a heslo účtu, API klíč ani relaci nikam nekopíruj. Důkaz: \`lazurio vault status --json\` hlásí \`connected\`.`, - `Target state: the Bitwarden CLI at the version Lazurio pins (${bitwardenPin.version}, the OSS build of the official releases https://github.com/bitwarden/clients) runs as \`~/.local/bin/bw\`; this Environment's account, whose address the Machine handover names, exists in its network's vault, has the Environment's own vault (an organization with the collection Agenti), and is signed in and unlocked. The command \`lazurio vault setup --json\` does it (the Launchpad does the same at its start): it installs the pinned \`bw\`, creates the account with a password generated here that no person knows, creates the vault, signs the account in with its API key and returns the state. When it reports \`unsupported\` with the reason \`no-vault\`, the handover names no vault yet; \`not-allowed\`, the network has not allowed the account's address yet; \`revoked\`, the network's operator removed the vault or the account. The network's operator resolves each of these: tell the Operator and work around nothing. Install no other version of \`bw\`, never overwrite a \`~/.local/bin/bw\` that is not Lazurio's, and copy the account's password, API key or session nowhere. Proof: \`lazurio vault status --json\` reports \`connected\`.`, + `Cílový stav: Bitwarden CLI ve verzi, kterou připíná Lazurio (${bitwardenPin.version}, sestavení OSS z oficiálních vydání https://github.com/bitwarden/clients), spouští \`~/.local/bin/bw\`; účet, který síť pro tento Environment předem povolila, je v trezoru jeho sítě založený, má vlastní trezor Environmentu (organizaci s kolekcí Agenti) a je přihlášený a odemčený. Udělá to příkaz \`lazurio vault setup --json\` (totéž dělá Launchpad při svém startu): nainstaluje připnuté \`bw\`, založí účet s heslem, které vznikne tady a nezná ho žádný člověk, založí trezor, přihlásí účet API klíčem a vrátí stav. Hlásí-li \`unsupported\` s důvodem \`no-vault\`, síť tomuto Environmentu zatím žádný trezor nepřidělila; hlásí-li \`not-allowed\`, síť adresu účtu zatím nepovolila; hlásí-li \`revoked\`, trezor nebo účet odebral provozovatel sítě. To vše řeší provozovatel sítě: řekni to Operátorovi a nic neobcházej. Jinou verzi \`bw\` neinstaluj, \`~/.local/bin/bw\`, který není Lazuria, nepřepisuj a heslo účtu, API klíč ani relaci nikam nekopíruj. Důkaz: \`lazurio vault status --json\` hlásí \`connected\`.`, + `Target state: the Bitwarden CLI at the version Lazurio pins (${bitwardenPin.version}, the OSS build of the official releases https://github.com/bitwarden/clients) runs as \`~/.local/bin/bw\`; the account its network pre-allowed for this Environment exists in the network's vault, has the Environment's own vault (an organization with the collection Agenti), and is signed in and unlocked. The command \`lazurio vault setup --json\` does it (the Launchpad does the same at its start): it installs the pinned \`bw\`, creates the account with a password generated here that no person knows, creates the vault, signs the account in with its API key and returns the state. When it reports \`unsupported\` with the reason \`no-vault\`, the network has given this Environment no vault yet; \`not-allowed\`, the network has not allowed the account's address yet; \`revoked\`, the network's operator removed the vault or the account. The network's operator resolves each of these: tell the Operator and work around nothing. Install no other version of \`bw\`, never overwrite a \`~/.local/bin/bw\` that is not Lazurio's, and copy the account's password, API key or session nowhere. Proof: \`lazurio vault status --json\` reports \`connected\`.`, ), purpose: { cs: "Bitwarden CLI (`bw`) přihlášené k vlastnímu trezoru tohoto Environmentu v Lazurio Vaultwardenu jeho sítě. Trezor patří Environmentu a jeho agenti ho používají sami. Co v něm je, smějí agenti použít bez ptaní.", diff --git a/tests/module-view.test.ts b/tests/module-view.test.ts index 81a28d657..8342c32bb 100644 --- a/tests/module-view.test.ts +++ b/tests/module-view.test.ts @@ -284,11 +284,11 @@ test("a start refused for its runtime secrets names each one and why, and a star parseModuleResult({ ...refused, secrets: [{ name: "EXTERNAL_API_KEY" }] }), ).toBeNull(); expect(moduleResultMessage(refused, en)).toBe( - "The app was not started: it needs secrets that this Environment's vault did not give it. EXTERNAL_API_KEY, SECOND_KEY: no item of this name in the Environment's collection; THIRD_KEY: more than one item of this name in the Environment's collection. Values are never shown; add or fix the item named exactly like the secret in the Environment's collection and start again.", + "The app was not started: it needs secrets that this Environment's vault did not give it. EXTERNAL_API_KEY, SECOND_KEY: no item of this name in the Environment's vault; THIRD_KEY: more than one item of this name in the Environment's vault. Values are never shown; add or fix the item named exactly like the secret in the Environment's vault and start again.", ); const czech = moduleResultMessage(refused, cs); - expect(czech).toContain("EXTERNAL_API_KEY, SECOND_KEY: v kolekci"); - expect(czech).toContain("THIRD_KEY: v kolekci Environmentu je víc položek"); + expect(czech).toContain("EXTERNAL_API_KEY, SECOND_KEY: v trezoru"); + expect(czech).toContain("THIRD_KEY: v trezoru Environmentu je víc položek"); expect(moduleStatusView(refused, cs).code).toBe("runtime-secret-unavailable"); for (const copy of [en, cs]) for (const reason of [ @@ -319,7 +319,7 @@ test("a start refused for its runtime secrets names each one and why, and a star }); expect(parseModuleResult(started)).toEqual(started); expect(moduleResultMessage(started, en)).toBe( - `${en.moduleStartedHealthy} Started without these optional secrets, so the capabilities that need them are off: OPTIONAL_KEY: the vault is not connected (Settings → Tools → bitwarden).`, + `${en.moduleStartedHealthy} Started without these optional secrets, so the capabilities that need them are off: OPTIONAL_KEY: the vault is not set up yet (Settings → Tools → bitwarden).`, ); expect(moduleResultMessage(started, cs)).toContain( "Spuštěno bez těchto volitelných tajných údajů", From 4def354f68e7749a4ed1439c31b515c0d00a31a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Tue, 13 Oct 2026 22:13:15 +0200 Subject: [PATCH 4/9] Machine: vendor the handover schema with `vault` from Machines #500 The handover's `vault` member is now the one Machines writes: the head of the open Machines pull request #500 (DEV-6631 task 637, guest side), byte for byte, which adds only the optional top-level member to #449's schema, with a work account of the Environment's . address and a personal one of its address. schema-provenance.json pins that head and says in `pending` that it is re-pinned to the pull request's merge before this one merges. The relay test keeps checking the relay member; the provenance and the two account shapes are checked with the vault's member. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 5 ++- docs/machine-handover.md | 13 +++--- src/machine/lazurio-machine.v1.schema.json | 35 +++++++++++----- src/machine/schema-provenance.json | 12 +++--- tests/environment-relay-handover.test.ts | 8 ++-- tests/vault-handover.test.ts | 47 +++++++++++++++++++++- 6 files changed, 90 insertions(+), 30 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index af5577c25..ddbdf7d0f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10681,8 +10681,9 @@ point 9). Organization creation stays open to every account of the network (`ORG_CREATION_USERS`), so people can create other organizations outside this model; the threat model of the network's vault records it. People's access to an Environment's vault (Správci, task 638b) is not in this revision: until then only the -Environment's account is a member of its vault. The vendored handover schema carries -the drafted `vault` member until the Machines pull request of task 637 publishes it +Environment's account is a member of its vault. The vendored handover schema is the +head of the open Machines pull request #500, which writes the member behind its +Platform gate; it is re-pinned to that pull request's merge before this one merges (`schema-provenance.json`'s `pending`). | Alternative | Trade-off / disposition | diff --git a/docs/machine-handover.md b/docs/machine-handover.md index 0092d3bb7..4abd6eaca 100644 --- a/docs/machine-handover.md +++ b/docs/machine-handover.md @@ -15,12 +15,13 @@ from the merge of Machines pull request **#449** into `main` (commit `30c2fcf8a77914b5a44c652265e927683b2b413c`, SHA-256 `fbbd159b8e6dfc8580a7b8460ddb4a2b2d3158a1b74ab2a420d8ff68005ae53f`), which adds the optional `entry.environment_relay` ([below](#the-hosted-entry-decision-f16), root -decision 0194, decision F45) and changes nothing else. **Pending:** the vendored file -also carries the optional top-level member `vault` ([below](#the-environments-own-vault-decision-f52), -DEV-6631 contract C2), drafted here from the contract and the Machines shared contract -until the Machines pull request of DEV-6631 task 637 publishes it; before this -Platform merges, the file is replaced byte for byte by that one and -`schema-provenance.json` by its pin (its `pending` field says so meanwhile). No Machines release carries it +decision 0194, decision F45) and changes nothing else. **Pending re-pin:** the file is +now vendored byte for byte from the head of the open Machines pull request **#500** +(commit `14d448682be5d0a666b39b4c2b2f2bf6867fc448`, SHA-256 +`76a058045be25b718caed8a04e533d67fa8666945bfa4fa0153d618bc4d78957`), which adds only +the optional top-level member `vault` ([below](#the-environments-own-vault-decision-f52), +DEV-6631 contract C2) to #449's; before this Platform merges, it is re-pinned to that +pull request's merge (`schema-provenance.json`'s `pending` says so meanwhile). No Machines release carries it yet, so the provenance names no version and no tag; the first release that does may add them with the same digest, and a digest other than this one is a new re-pin. Before it, the pin was the merge of Machines diff --git a/src/machine/lazurio-machine.v1.schema.json b/src/machine/lazurio-machine.v1.schema.json index bd0d4ffe8..d54f9d9ca 100644 --- a/src/machine/lazurio-machine.v1.schema.json +++ b/src/machine/lazurio-machine.v1.schema.json @@ -49,7 +49,7 @@ "network": { "$ref": "#/$defs/network" }, "relationships": { "allOf": [{ "$ref": "#/$defs/relationships" }, { "type": "object", "properties": { "zone": { "const": "work" } } }] }, "entry": { "$ref": "#/$defs/entry" }, - "vault": { "$ref": "#/$defs/vault" }, + "vault": { "$ref": "#/$defs/vault_work" }, "installed": { "$ref": "#/$defs/installed" }, "account": { "$ref": "#/$defs/account" } } @@ -96,7 +96,7 @@ "network": { "$ref": "#/$defs/network" }, "relationships": { "allOf": [{ "$ref": "#/$defs/relationships" }, { "type": "object", "properties": { "zone": { "const": "personal" } } }] }, "entry": { "$ref": "#/$defs/entry" }, - "vault": { "$ref": "#/$defs/vault" }, + "vault": { "$ref": "#/$defs/vault_personal" }, "installed": { "$ref": "#/$defs/installed" }, "account": { "$ref": "#/$defs/account" } } @@ -282,20 +282,33 @@ } } }, - "vault": { - "description": "This Environment's own vault (root decision 0198 point 1, DEV-6631 contract C2): its network's Lazurio Vaultwarden, the technical account the network generated and pre-allowed for this Environment alone, and the name of the Environment's vault there. The Environment registers the account itself and creates its own organization with it. The account address is a one-time enrollment capability until it is registered (root decision 0197 point 3). Omitted until the Machine runs a LazurioPlatform release that reads it; a reader vendoring an earlier schema refuses a document carrying it.", + "account": { + "description": "Reserved for the Machine's Lazurio account identity issued by the Dashboard; null until that contract exists.", + "type": "null" + }, + "vault_work": { + "description": "This Environment's technical account in its network's vault (root decisions 0197 point 3 and 0198 point 1; docs/machine-identity.md#vault): the vault of its Conglomerate Host, the account vaultwarden-<26 lowercase base32>@..lazurio.io the network pre-allowed for exactly this Environment, and the name of the vault the Environment creates. Not a secret once registered; before, a one-time enrollment capability inside the Environment boundary. Omitted until the Machine runs a LazurioPlatform release that reads it; a reader vendoring an earlier schema refuses a document carrying it.", "type": "object", "additionalProperties": false, "required": ["server_url", "account", "name"], "properties": { - "server_url": { "description": "Origin of the network's Lazurio Vaultwarden: https://vaultwarden..lazurio.io.", "type": "string", "pattern": "^https://vaultwarden\\.[a-z0-9]+(?:-[a-z0-9]+)*\\.lazurio\\.io$" }, - "account": { "description": "The Environment's technical account: vaultwarden-<26 lowercase base32 characters>@.", "type": "string", "maxLength": 119, "pattern": "^vaultwarden-[a-z2-7]{26}@[a-z0-9]+(?:-[a-z0-9]+)*(?:\\.[a-z0-9]+(?:-[a-z0-9]+)*)?\\.lazurio\\.io$" }, - "name": { "description": "Name of the Environment's vault, : letters, digits and single spaces, unique within the network.", "type": "string", "maxLength": 50, "pattern": "^[\\p{L}0-9]+(?: [\\p{L}0-9]+)*$" } + "server_url": { "$ref": "#/$defs/vault_server_url" }, + "account": { "type": "string", "maxLength": 128, "pattern": "^vaultwarden-[a-z2-7]{26}@[a-z0-9]+(?:-[a-z0-9]+)*\\.[a-z0-9]+(?:-[a-z0-9]+)*\\.lazurio\\.io$" }, + "name": { "$ref": "#/$defs/vault_name" } } }, - "account": { - "description": "Reserved for the Machine's Lazurio account identity issued by the Dashboard; null until that contract exists.", - "type": "null" - } + "vault_personal": { + "description": "The same member of a personal VM: its account is vaultwarden-<26 lowercase base32>@.lazurio.io.", + "type": "object", + "additionalProperties": false, + "required": ["server_url", "account", "name"], + "properties": { + "server_url": { "$ref": "#/$defs/vault_server_url" }, + "account": { "type": "string", "maxLength": 128, "pattern": "^vaultwarden-[a-z2-7]{26}@[a-z0-9]+(?:-[a-z0-9]+)*\\.lazurio\\.io$" }, + "name": { "$ref": "#/$defs/vault_name" } + } + }, + "vault_server_url": { "description": "https://vaultwarden., the vault of the Environment's Conglomerate Host.", "type": "string", "maxLength": 120, "pattern": "^https://vaultwarden\\.[a-z0-9]+(?:-[a-z0-9]+)*\\.lazurio\\.io$" }, + "vault_name": { "description": "The vault's name: letters, digits and single spaces, at most 50 characters, unique within the network.", "type": "string", "minLength": 1, "maxLength": 50, "pattern": "^[\\p{L}0-9]+(?: [\\p{L}0-9]+)*$" } } } diff --git a/src/machine/schema-provenance.json b/src/machine/schema-provenance.json index 6ee25e31b..896152620 100644 --- a/src/machine/schema-provenance.json +++ b/src/machine/schema-provenance.json @@ -2,12 +2,12 @@ "source_repository": "HumanAndMachine-ai/Machines", "source_version": null, "source_tag": null, - "source_pull_request": "https://github.com/HumanAndMachine-ai/Machines/pull/449", - "source_commit": "30c2fcf8a77914b5a44c652265e927683b2b413c", + "source_pull_request": "https://github.com/HumanAndMachine-ai/Machines/pull/500", + "source_commit": "14d448682be5d0a666b39b4c2b2f2bf6867fc448", "source_path": "workloads/workspace-vm/lazurio-machine.v1.schema.json", - "source_sha256": "fbbd159b8e6dfc8580a7b8460ddb4a2b2d3158a1b74ab2a420d8ff68005ae53f", - "sha256": "d6a5dce89f5fa0ee6616c929a48cccef28346b6e92c4b1c320b13c1f71040a0e", + "source_sha256": "76a058045be25b718caed8a04e533d67fa8666945bfa4fa0153d618bc4d78957", + "sha256": "76a058045be25b718caed8a04e533d67fa8666945bfa4fa0153d618bc4d78957", "publication_authorization": "https://github.com/HumanAndMachine-ai/Machines/pull/124#issuecomment-5688845105", - "pin_update": "https://github.com/HumanAndMachine-ai/Machines/pull/449", - "pending": "DEV-6631 contract C2: the optional member `vault` {server_url, account, name} is drafted here from the contract and the Machines shared contract (workloads/shared/environment-vault.ts) until the Machines pull request of DEV-6631 task 637 publishes it; the vendored file is replaced byte for byte by that one, and this provenance by its pin, before merge." + "pin_update": "https://github.com/HumanAndMachine-ai/Machines/pull/500", + "pending": "Vendored byte for byte from the head of the open Machines pull request #500 (DEV-6631 task 637, guest side), which adds only the optional member `vault` to #449's schema. Re-pin to its merge commit (and the release that carries it) before this Platform merges; a digest other than this one is a new re-pin." } diff --git a/tests/environment-relay-handover.test.ts b/tests/environment-relay-handover.test.ts index bf404765b..e25d6bc1f 100644 --- a/tests/environment-relay-handover.test.ts +++ b/tests/environment-relay-handover.test.ts @@ -40,10 +40,10 @@ const bytes = (value: unknown) => Buffer.from(JSON.stringify(value)); const { team: _, ...withoutTeam } = organization.owner; const workVm = { ...organization, owner: withoutTeam }; -test("the vendored schema is Machines #449's, which adds only entry.environment_relay", () => { - expect(provenance.source_pull_request).toBe( - "https://github.com/HumanAndMachine-ai/Machines/pull/449", - ); +test("the vendored schema carries Machines #449's entry.environment_relay exactly", () => { + // Re-pinned since to Machines #500, which adds only the top-level `vault` + // (tests/vault-handover.test.ts). + expect(provenance.source_repository).toBe("HumanAndMachine-ai/Machines"); const relay = ( schema as unknown as { $defs: { diff --git a/tests/vault-handover.test.ts b/tests/vault-handover.test.ts index 678ea618b..462aaa586 100644 --- a/tests/vault-handover.test.ts +++ b/tests/vault-handover.test.ts @@ -7,6 +7,7 @@ import { parseMachineContext, } from "../src/machine/context"; import schema from "../src/machine/lazurio-machine.v1.schema.json"; +import provenance from "../src/machine/schema-provenance.json"; import { contextValues } from "../src/recover/private-values"; import { createSanitizer } from "../src/recover/sanitize"; import { ownAccount, vaultMember, workAccount } from "./fixtures/fake-vault"; @@ -35,6 +36,44 @@ const documents = { }, }; +test("the vendored schema is Machines #500's: the member with a work and a personal account shape", () => { + expect(provenance.source_pull_request).toBe( + "https://github.com/HumanAndMachine-ai/Machines/pull/500", + ); + const defs = ( + schema as unknown as { + $defs: Record< + string, + { properties?: Record } & Record + >; + } + ).$defs; + expect(defs.organization_workspace_vm?.properties?.vault).toEqual({ + $ref: "#/$defs/vault_work", + }); + expect(defs.personal_vm?.properties?.vault).toEqual({ + $ref: "#/$defs/vault_personal", + }); + for (const name of ["vault_work", "vault_personal"]) + expect(defs[name]).toMatchObject({ + type: "object", + additionalProperties: false, + required: ["server_url", "account", "name"], + }); + // A work Environment's account is of its . address, a personal + // one's of its address; neither takes the other's. + expect(() => + parseMachineContext( + bytes({ ...documents.personal, vault: vaultMember(workAccount) }), + ), + ).toThrow("machine-context-invalid"); + expect(() => + parseMachineContext( + bytes({ ...documents.work, vault: vaultMember(ownAccount) }), + ), + ).toThrow("machine-context-invalid"); +}); + test("the member is read exactly as written on both branches", () => { for (const document of Object.values(documents)) { const context = parseMachineContext(bytes(document)); @@ -117,7 +156,13 @@ test("a Platform whose vendored schema predates the member refuses the whole han }; for (const branch of ["organization_workspace_vm", "personal_vm"]) delete earlier.$defs[branch]?.properties?.vault; - delete earlier.$defs.vault; + for (const name of [ + "vault_work", + "vault_personal", + "vault_server_url", + "vault_name", + ]) + delete earlier.$defs[name]; const validate = new Ajv2020({ strict: true }).compile(earlier); for (const document of Object.values(documents)) { const { vault: __, ...without } = document; From b0839490d0395efb8c1eb72baa0feeed00156011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Wed, 14 Oct 2026 01:02:43 +0200 Subject: [PATCH 5/9] Vault: bw never starts without a data directory of its own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bw rewrites its store on every start, so a run without BITWARDENCLI_APPDATA_DIR rewrites a default profile, a person's own bw included. Every bw of the vault runs through bwCli (setup, status, refresh, env's unlock, secrets, the 0197 pilot subset, the installer's version check), which now refuses before anything runs unless the binary and the data directory are absolute paths, and sets the directory last on every run, so no step's variables can replace it. The only other path that starts a bw, the version probe of Settings → Tools, already gives it a fresh temporary directory (the catalog's isolatedData) and removes it afterwards; tests/vault-store.test.ts now pins both. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 10 ++++- docs/environment-tools.md | 7 ++- src/vault/bw.ts | 12 ++++-- tests/vault-store.test.ts | 90 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 112 insertions(+), 7 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index ddbdf7d0f..101757a31 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10600,7 +10600,11 @@ session of F43. its address, stays beside it untouched. `lazurio-vault.json` now holds the vault's organization id, its collection Agenti's id and, while a creation is under way, its receipt; a record that cannot be read refuses (`record-unreadable`) and nothing - is ever created over it. + is ever created over it. No bw this product starts ever runs without a data + directory of its own, because bw rewrites its store on every start: the vault's + `bwCli` refuses to start without an absolute one and sets it last on every run, + and the version probe of Settings → Tools gives a `bw` on PATH a fresh temporary + one (the catalog's `isolatedData`). 3. **Registration, then the vault** (`src/vault/organization.ts`). The account is registered by F43's flow; the network pre-allowed the address, so a refusal is `not-allowed` (not pre-allowed yet, or an unused pre-allowance pruned). Then the @@ -10702,7 +10706,9 @@ recognized by the receipt, gone and refused (`tests/vault-flow.test.ts`); the ac opening its own organization key from its master password down to Agenti's name and the organization's private key (`tests/vault-organization.test.ts`); the pilot with and without `vault` (`tests/vault-pilot.test.ts`); the CLI (`tests/vault-cli.test.ts`) -and the Launchpad over HTTP with its start (`tests/launchpad-vault.test.ts`); the +and the Launchpad over HTTP with its start (`tests/launchpad-vault.test.ts`); bw +refused without its own data directory, and the Tools probe's temporary one +(`tests/vault-store.test.ts`); the member, an earlier Platform refusing it and its redaction (`tests/vault-handover.test.ts`); F46 on the own vault (`tests/vault-secrets.test.ts`, `tests/runtime-secrets.test.ts`, `tests/module-runtime-secrets.test.ts`); no value or diff --git a/docs/environment-tools.md b/docs/environment-tools.md index ad55889eb..00c0b0855 100644 --- a/docs/environment-tools.md +++ b/docs/environment-tools.md @@ -554,7 +554,12 @@ wave (`unsupported`, `workstation`). create organizations (`ORG_CREATION_USERS`) is `organization-refused`; a refused API key is `revoked`. - **bw** (`src/vault/bw.ts`): always the pinned binary with the account's - `BITWARDENCLI_APPDATA_DIR`, `BW_NOINTERACTION` and `--nointeraction`; `bw config + `BITWARDENCLI_APPDATA_DIR`, `BW_NOINTERACTION` and `--nointeraction`. bw rewrites + its store on every start, so `bwCli` refuses to start without an absolute data + directory and a binary by its path, and sets the directory last on every run; the + version probe of Settings → Tools runs a `bw` on PATH with a fresh temporary one + (the catalog's `isolatedData`). No bw of this product reaches a default profile, + a person's own included. `bw config server`, `bw login --apikey` (the key in `BW_CLIENTID`/`BW_CLIENTSECRET`; the session it prints is still locked and is never read), `bw unlock --passwordfile --raw` (the file removed at once), `bw sync` and `bw list diff --git a/src/vault/bw.ts b/src/vault/bw.ts index cff4be22c..6aed9d6a1 100644 --- a/src/vault/bw.ts +++ b/src/vault/bw.ts @@ -1,6 +1,6 @@ import { randomBytes } from "node:crypto"; import { open, rm } from "node:fs/promises"; -import { join } from "node:path"; +import { isAbsolute, join } from "node:path"; import { parseUniqueJson } from "../providers/unique-json"; import type { ToolProcessResult, ToolRunner } from "../tools/status"; import { isSession, isVaultId } from "./store"; @@ -245,10 +245,16 @@ export function parseSecretItems( export type BwCli = ReturnType; export function bwCli(environment: BwEnvironment) { + // Never a bw without a data directory of its own: bw rewrites its store on + // every start, so a run without one would reach a default profile (a + // person's own bw). Refused before anything runs, and set last on every + // run, so nothing a step adds can replace it. + if (!isAbsolute(environment.data) || !isAbsolute(environment.binary)) + throw new Error("bw runs only by its path, with its own data directory"); + const data = environment.data; const base: Record = { PATH: environment.path ?? "/usr/bin:/bin", HOME: environment.home, - BITWARDENCLI_APPDATA_DIR: environment.data, BW_NOINTERACTION: "true", }; async function run( @@ -261,7 +267,7 @@ export function bwCli(environment: BwEnvironment) { return await environment.run( [environment.binary, ...args], timeoutMs, - { ...base, ...extra }, + { ...base, ...extra, BITWARDENCLI_APPDATA_DIR: data }, maxBytes === undefined ? undefined : { maxBytes }, ); } catch { diff --git a/tests/vault-store.test.ts b/tests/vault-store.test.ts index 371a9dc14..906fea01b 100644 --- a/tests/vault-store.test.ts +++ b/tests/vault-store.test.ts @@ -1,16 +1,21 @@ import { expect, test } from "bun:test"; import { lstat, + mkdir, mkdtemp, readdir, readFile, realpath, rm, + stat, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { isAbsolute, join } from "node:path"; +import { findTool } from "../src/tools/catalog"; +import { type ToolRunner, toolsStatus } from "../src/tools/status"; import { + bwCli, bwFailureOf, parseBwStatus, parseCollections, @@ -222,3 +227,86 @@ test("bw's answers are read in their shapes and its failures by its fixed messag expect(failure("something else")).toBe("failed"); expect(bwFailureOf("timeout")).toBe("timeout"); }); + +// bw rewrites its store on every start, so a run without a data directory of +// its own would rewrite a default profile, a person's own bw included. No +// path of this product can start one: the vault's bw refuses before anything +// runs and sets its directory last on every run, and the version probe of +// Settings → Tools gives a bw on PATH a fresh temporary one. +test.skipIf(process.platform === "win32")( + "bw never starts without a data directory of its own", + async () => { + const parent = await realpath( + await mkdtemp(join(tmpdir(), "vault-bw-data-")), + ); + try { + const home = join(parent, "home"); + const runs: { + command: readonly string[]; + data: string | undefined; + existed: boolean; + }[] = []; + const run: ToolRunner = async (command, _timeoutMs, env) => { + const data = env.BITWARDENCLI_APPDATA_DIR; + runs.push({ + command, + data, + existed: + data !== undefined && + (await stat(data).then( + (found) => found.isDirectory(), + () => false, + )), + }); + return { exitCode: 0, stdout: "2026.7.0\n", stderr: "" }; + }; + const data = join(parent, "state", "bw"); + const binary = join(parent, "tools", "bw"); + for (const [path, directory] of [ + [binary, ""], + [binary, "bw"], + [binary, "./state/bw"], + ["bw", data], + ] as const) + expect(() => + bwCli({ binary: path, data: directory, home, path: undefined, run }), + ).toThrow(); + expect(runs).toEqual([]); + const bw = bwCli({ binary, data, home, path: undefined, run }); + expect(await bw.version()).toBe("2026.7.0"); + expect((await bw.loginApiKey("user.example", "example")).ok).toBe(true); + expect(runs.map((entry) => entry.data)).toEqual([data, data]); + + // Settings → Tools: a bw on PATH (a person's own) runs its version + // command with a fresh temporary data directory, gone afterwards. + runs.length = 0; + const bin = join(parent, "bin"); + await mkdir(bin, { recursive: true }); + await writeFile(join(bin, "bw"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + const bitwarden = findTool("bitwarden"); + if (bitwarden === undefined) throw new Error("Expected bitwarden"); + expect(bitwarden.isolatedData).toBe("BITWARDENCLI_APPDATA_DIR"); + await toolsStatus({ + path: bin, + home, + platform: process.platform, + run, + catalog: [bitwarden], + }); + expect(runs).toHaveLength(1); + const probe = runs[0]?.data ?? ""; + expect(runs[0]?.command).toEqual([join(bin, "bw"), "--version"]); + expect(runs[0]?.existed).toBe(true); + expect(isAbsolute(probe)).toBe(true); + expect(probe.startsWith(home)).toBe(false); + expect( + await stat(probe).then( + () => true, + () => false, + ), + ).toBe(false); + } finally { + await rm(parent, { recursive: true, force: true }); + } + }, +); From 42d0d0cf992731c2ba74ea0032929dbcad3ac069 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Wed, 14 Oct 2026 01:02:53 +0200 Subject: [PATCH 6/9] =?UTF-8?q?Vault:=20the=20setup=20in=20which=20the=20v?= =?UTF-8?q?ault=20becomes=20ready=20turns=20"Pou=C5=BE=C3=ADvaj=C3=AD=20ag?= =?UTF-8?q?enti"=20on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root decision 0198 point 1: the agents use the Environment's vault themselves, so a vault they are not told about makes no sense. The setup that records the vault's collection Agenti, which happens once per vault, now turns the agents' switch on for bitwarden in the Environment's Folder, at the Launchpad's start as with `lazurio vault setup`: the change the switch itself makes, at the current revision, refused as the switch is where the tool is not offered or the Organization does not allow it (enableVaultForAgents in src/vault/host.ts, called by the core outside the account's lock). No later setup (a new session after a restart, a rename, a repair) turns it on again, so a person who turns the switch off keeps it off; a failure is journaled (agents-not-enabled) and never fails the setup. The page no longer toggles the switch itself: after a setup it followed ends connected, it reads the Folder again. Tested in the core everywhere (tests/vault-flow.test.ts) and over HTTP in the Launchpad's Folder on Linux, where the Folder offers the vault (tests/launchpad-vault.test.ts). Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 17 ++++-- docs/environment-tools.md | 11 +++- docs/launchpad-development.md | 6 ++- src/launchpad/server.ts | 12 ++++- src/launchpad/tools-panel.ts | 16 +++--- src/launchpad/vault-panel.ts | 5 +- src/vault/flow.ts | 36 +++++++++++-- src/vault/host.ts | 43 ++++++++++++++- tests/launchpad-vault.test.ts | 98 +++++++++++++++++++++++++++++++---- tests/vault-flow.test.ts | 87 ++++++++++++++++++++++++++++--- 10 files changed, 287 insertions(+), 44 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 101757a31..f403ee20c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10649,7 +10649,15 @@ session of F43. unreachable state does); no disconnect for the Environment's own vault. Czech copy addresses people formally and says little (root decision 0199). The routes are `POST /api/tools/bitwarden/status|refresh|setup`; a running setup answers - `202 {kind: "vault-setting-up", job, phase}` from all three. + `202 {kind: "vault-setting-up", job, phase}` from all three. The setup in which + the vault becomes ready (its collection Agenti recorded) turns "Používají agenti" + on for `bitwarden` in the Environment's Folder (0198 point 1: the agents use the + Environment's vault themselves): the change the switch makes, refused as the + switch is where the tool is not offered or the Organization does not allow it. + Once per vault: a person may turn it off and it stays off, because no later setup + (a new session, a rename, a repair) turns it on again; a failure is journaled + (`agents-not-enabled`) and is never the setup's. `lazurio vault setup` does the + same; the page itself no longer turns it on. 6. **Pilot safety** (`src/vault/legacy-0197/`, frozen). A few Environments were connected the 0197 way: an account `vaultwarden@
` in a person's organization with a recorded collection. While such an Environment's handover @@ -10706,9 +10714,10 @@ recognized by the receipt, gone and refused (`tests/vault-flow.test.ts`); the ac opening its own organization key from its master password down to Agenti's name and the organization's private key (`tests/vault-organization.test.ts`); the pilot with and without `vault` (`tests/vault-pilot.test.ts`); the CLI (`tests/vault-cli.test.ts`) -and the Launchpad over HTTP with its start (`tests/launchpad-vault.test.ts`); bw -refused without its own data directory, and the Tools probe's temporary one -(`tests/vault-store.test.ts`); the +and the Launchpad over HTTP with its start (`tests/launchpad-vault.test.ts`); the +agents' switch turned on once per vault, by the core everywhere and in the +Launchpad's Folder on Linux (the same two files); bw refused without its own data +directory, and the Tools probe's temporary one (`tests/vault-store.test.ts`); the member, an earlier Platform refusing it and its redaction (`tests/vault-handover.test.ts`); F46 on the own vault (`tests/vault-secrets.test.ts`, `tests/runtime-secrets.test.ts`, `tests/module-runtime-secrets.test.ts`); no value or diff --git a/docs/environment-tools.md b/docs/environment-tools.md index 00c0b0855..bcc313834 100644 --- a/docs/environment-tools.md +++ b/docs/environment-tools.md @@ -597,8 +597,15 @@ wave (`unsupported`, `workstation`). installed Launchpad of a supervised base of the hosted operator (`vaultAtStart`, the rule of Executor's) runs the setup in the background after its start where `setUpAtStart` says the vault needs it: not set up, its session locked, or its name - no longer the handover's; never a 0197 pilot, a revoked or failed vault. The journal - of the unit gets `{"scope":"tools-vault","operation":"setup|refresh|unlock|vault|secrets","outcome":…,"reason":…}` + no longer the handover's; never a 0197 pilot, a revoked or failed vault. The setup + in which the vault becomes ready (its collection Agenti recorded, `outcome: + "ready"`) turns "Používají agenti" on for `bitwarden` in the Folder + (`enableVaultForAgents`, `src/vault/host.ts`, also for `lazurio vault setup`): the + switch's own change at the current revision, refused as the switch is where the + tool is not offered or the Organization does not allow it. Once per vault, so a + person who turns it off keeps it off; a failure is journaled (`agents-not-enabled`), + never the setup's. The journal of the unit gets + `{"scope":"tools-vault","operation":"setup|refresh|unlock|vault|secrets","outcome":…,"reason":…}` (with `"trigger":"start"` for the start's setup) only. - **Runtime secrets** (decision F46 as F52 amends it, `vaultSecrets` in `src/vault/flow.ts`): on a work Environment the applications of the Organization diff --git a/docs/launchpad-development.md b/docs/launchpad-development.md index 34c90d2ce..f51121f5b 100644 --- a/docs/launchpad-development.md +++ b/docs/launchpad-development.md @@ -2049,8 +2049,10 @@ controls are "Otevřít trezor" once connected, a link in a new tab to vault on: "Nastavit" when nothing set it up yet and "Zkusit znovu" after a setup that stopped or a vault that did not answer. A vault the network has not allowed or has revoked, and a 0197 pilot, offer none; there is no dialog, no details section and no -disconnect. A setup this page followed that ends connected turns the agents' switch on, -as after a curated sign-in. The state is accepted only in its exact form +disconnect. The setup in which the vault becomes ready turns the agents' switch on in the +Folder itself, once per vault (decision F52), so a person who turns it off keeps it off; +the page never turns it on, and after a setup it followed that ends connected it reads +the Folder again to show it. The state is accepted only in its exact form (`src/launchpad/vault-view.ts`, `tests/vault-view.test.ts`); the DOM is `src/launchpad/vault-panel.ts`. diff --git a/src/launchpad/server.ts b/src/launchpad/server.ts index 738c90d74..7c70db344 100644 --- a/src/launchpad/server.ts +++ b/src/launchpad/server.ts @@ -98,7 +98,7 @@ import { toolsUpdate } from "../tools/update"; import { embeddedIdentity } from "../update/identity"; import { runProcess } from "../update/self-check"; import type { VaultHost } from "../vault/flow"; -import { processVaultHost } from "../vault/host"; +import { enableVaultForAgents, processVaultHost } from "../vault/host"; import type { LaunchpadBoot } from "./boot"; import { launchpadBoot, withBoot } from "./boot-document"; import { createChatPromptCheck, issueChatLink, publicEntry } from "./chat"; @@ -572,11 +572,19 @@ export async function startLaunchpad( journal: vaultJournal, }) : undefined; + // The setup in which the vault becomes ready turns the agents' switch on + // in this Launchpad's Folder (decision F52): the default host does so + // already, a given one gets it here. const vault = createVaultRoutes({ host: () => vaultHost === undefined ? (defaultVault as VaultHost) - : { ...vaultHost, journal: vaultHost.journal ?? vaultJournal }, + : { + ...vaultHost, + journal: vaultHost.journal ?? vaultJournal, + enableForAgents: + vaultHost.enableForAgents ?? (() => enableVaultForAgents(folder)), + }, // A closing Launchpad starts no setup (`start` asks it last). closing: () => closing, }); diff --git a/src/launchpad/tools-panel.ts b/src/launchpad/tools-panel.ts index 7cfb910d6..8b62c43a0 100644 --- a/src/launchpad/tools-panel.ts +++ b/src/launchpad/tools-panel.ts @@ -102,9 +102,11 @@ export function createToolsPanel( const loginBody = find("#tools-login-body"); const loginClose = find("#tools-login-close"); // The Environment's own vault (decision F52): its own state, read beside - // the tools; the Environment sets it up itself, and a setup this page - // followed that ends connected turns the agents' switch on, as a completed - // sign-in does. + // the tools; the Environment sets it up itself, and the setup in which the + // vault becomes ready turns the agents' switch on in the Folder, once per + // vault (never this page, so a person's "off" stays). A setup this page + // followed that ends connected may have changed the Folder: the whole page + // reads it again. const vault = createVaultPanel({ post: options.post, copy: options.copy, @@ -112,13 +114,7 @@ export function createToolsPanel( connected: () => { // The setup is the next act on the row: the notice before it ends. endNotice(vaultToolName); - void refresh().then(() => { - const tool = overview?.tools.find( - (entry) => entry.name === vaultToolName, - ); - if (tool !== undefined && tool.tier !== "required" && !tool.enabled) - void toggle(tool, true); - }); + void reloadPage(); }, }); diff --git a/src/launchpad/vault-panel.ts b/src/launchpad/vault-panel.ts index e13141393..e08195c31 100644 --- a/src/launchpad/vault-panel.ts +++ b/src/launchpad/vault-panel.ts @@ -32,8 +32,9 @@ export function createVaultPanel( copy: () => Copy; /** The vault's state changed: the tools section draws again. */ changed: () => void; - /** A setup this page followed ended connected: the agents' switch turns - * on, as after a sign-in completed in this Launchpad session. */ + /** A setup this page followed ended connected: the page reads the + * Folder again (the setup in which the vault became ready turned the + * agents' switch on there, decision F52). */ connected: () => void; }>, ) { diff --git a/src/vault/flow.ts b/src/vault/flow.ts index b42d0bf8a..d1df1a749 100644 --- a/src/vault/flow.ts +++ b/src/vault/flow.ts @@ -117,6 +117,11 @@ export type VaultHost = Readonly<{ download?: InstallFetch | undefined; pin?: BitwardenPin | undefined; journal?: ((entry: VaultJournalEntry) => void) | undefined; + /** "Používají agenti" on for the vault (decision F52): called once per + * vault, after the setup in which it became ready (its collection Agenti + * recorded), and never by a later setup, so a person who turns the switch + * off keeps it off. A failure is journaled and is never the setup's. */ + enableForAgents?: (() => Promise) | undefined; now?: (() => Date) | undefined; /** How long a mutation waits for another one (default 10 s; setup, which * may download the CLI, waits longer). */ @@ -436,7 +441,7 @@ async function ensureVault( facts: VaultFacts, paths: VaultPaths, account: ReadyAccount, -): Promise> { +): Promise>> { let record: VaultRecord; try { record = await readRecord(paths); @@ -468,11 +473,16 @@ async function ensureVault( }; if (own.created) host.journal?.({ operation: "vault", outcome: "created" }); if (own.renamed) host.journal?.({ operation: "vault", outcome: "renamed" }); + // Ready from now on: this run recorded its collection Agenti, which + // happens once per vault. + const becameReady = record.collectionId === null; + if (becameReady) host.journal?.({ operation: "vault", outcome: "ready" }); return { kind: "ready", value: { organizationId: own.organizationId, collectionId: own.collectionId, + becameReady, }, }; } catch (error) { @@ -511,6 +521,19 @@ async function signIn( return login.ok ? { ok: true } : login; } +/** The vault became ready in this setup: "Používají agenti" on for it, by + * the composition (decision F52), after the account's lock is released. Best + * effort: a failure is journaled and is never the setup's, and the switch + * stays where it is for a person to turn. */ +async function turnAgentsOn(host: VaultHost): Promise { + if (host.enableForAgents === undefined) return; + try { + await host.enableForAgents(); + } catch { + host.journal?.({ operation: "vault", outcome: "agents-not-enabled" }); + } +} + const unreachableOr = ( facts: VaultFacts, stage: VaultFailureStage, @@ -525,8 +548,9 @@ const unreachableOr = ( * when the handover's name changed), signs bw in with the API key, unlocks * the one session and syncs. Idempotent: a vault that is set up is checked, * renamed when needed, unlocked and synced again. Never runs twice at once. - * A 0197 pilot is only read: no Environment is connected the old way any - * more. */ + * The setup in which the vault becomes ready turns the agents' switch on + * (`enableForAgents`); no later one does. A 0197 pilot is only read: no + * Environment is connected the old way any more. */ export async function vaultSetup( host: VaultHost, onPhase: (phase: VaultPhase) => void = () => undefined, @@ -545,7 +569,8 @@ export async function vaultSetup( return status; }; await ensureVaultDirectories(paths); - return withLock( + const ready = { became: false }; + const status = await withLock( paths, host.lockMs ?? setupLockMs, () => journal(failedStatus(facts, "install", "busy")), @@ -581,6 +606,7 @@ export async function vaultSetup( account.value, ); if (vault.kind === "status") return journal(vault.status); + ready.became = vault.value.becameReady; onPhase("sign-in"); const bw = cliOf(host, paths); const signedIn = await signIn(bw, account.value); @@ -602,6 +628,8 @@ export async function vaultSetup( return journal(statusOf(facts, vault.value, observation)); }, ); + if (ready.became) await turnAgentsOn(host); + return status; } /** `refresh`: a sync with the vault, a new unlock when the session is no diff --git a/src/vault/host.ts b/src/vault/host.ts index 692c5c6be..1c1c3c162 100644 --- a/src/vault/host.ts +++ b/src/vault/host.ts @@ -1,7 +1,9 @@ import { isAbsolute, join } from "node:path"; -import { withFolderReadLock } from "../folder/lock"; +import { readFolderTools } from "../folder/inspect-tools-change"; +import { FolderOperationBusyError, withFolderReadLock } from "../folder/lock"; import { inspectOwnedDirectory } from "../folder/owned-directory"; import { readFolderState } from "../folder/read-state"; +import { updateTools } from "../folder/update-profile"; import { presetKinds } from "../launchpad/shell-document"; import { bindMachineOperator, @@ -13,6 +15,7 @@ import { type HostedOperatorSources, readLinuxOperator, } from "../machine/operator"; +import { vaultToolName } from "../tools/catalog"; import type { ToolRunner } from "../tools/status"; import { resolveInstallBase } from "../update/base"; import { @@ -99,8 +102,40 @@ export async function readVaultContext( return pilotContextOf({ handover, environment }) ?? own; } +/** "Používají agenti" on for the vault in one Folder, at its current + * revision (decision F52): the change the switch itself makes, refused as + * the switch is where this Environment does not offer the vault or its + * Organization does not allow it. A Folder that another change holds or + * changed meanwhile is read again, as the Organization's settings are + * applied (src/organization-settings/apply.ts); anything else throws. */ +export async function enableVaultForAgents(folder: string): Promise { + const attempts = 4; + for (let attempt = 1; ; attempt += 1) { + try { + const recorded = await readFolderTools(folder); + if (recorded.enabled.includes(vaultToolName)) return; + const result = await updateTools( + folder, + recorded.revision, + [...recorded.enabled, vaultToolName].sort(), + ); + if ( + result.kind !== "blocked" || + result.reason !== "stale-revision" || + attempt >= attempts + ) + return; + } catch (error) { + if (!(error instanceof FolderOperationBusyError) || attempt >= attempts) + throw error; + } + await Bun.sleep(250 * attempt); + } +} + /** The vault of this process: its home, its install base and `~/.local/bin`, - * its PATH for bw, and the Folder the context is read from. */ + * its PATH for bw, and the Folder the context is read from, which is also + * the one whose agents' switch the vault turns on once it is ready. */ export function processVaultHost( input: Readonly<{ folder: () => Promise; @@ -151,5 +186,9 @@ export function processVaultHost( arch: input.arch ?? process.arch, run: input.run, journal: input.journal, + async enableForAgents() { + const folder = await input.folder(); + if (folder !== undefined) await enableVaultForAgents(folder); + }, }); } diff --git a/tests/launchpad-vault.test.ts b/tests/launchpad-vault.test.ts index 70bb74962..cd1d6101c 100644 --- a/tests/launchpad-vault.test.ts +++ b/tests/launchpad-vault.test.ts @@ -2,8 +2,13 @@ import { expect, spyOn, test } from "bun:test"; import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { initializeFolder } from "../src/folder/initialize-folder"; +import { + initializeFolder, + initializeHandoverFolder, +} from "../src/folder/initialize-folder"; +import { readFolderTools } from "../src/folder/inspect-tools-change"; import { executionOs } from "../src/folder/platform"; +import { presetProfile } from "../src/folder/presets"; import { startLaunchpad } from "../src/launchpad/server"; import { runTool } from "../src/tools/status"; import type { VaultHost, VaultJournalEntry } from "../src/vault/flow"; @@ -21,6 +26,7 @@ import { vaultOrigin, zipOf, } from "./fixtures/fake-vault"; +import { bindings } from "./fixtures/machine-bindings"; // Settings → Tools → bitwarden over HTTP (decisions F43, F52): the three // routes behind the admission of every route, `{}` only, a setup answered @@ -55,6 +61,9 @@ async function session( launchpadJournal?: boolean; /** The network pre-allowed the account before the Launchpad starts. */ allowed?: boolean; + /** The Folder of a personal Remote Environment (bitwarden is offered + * there on Linux) instead of this computer's. */ + hosted?: boolean; }> = {}, ) { const parent = await realpath( @@ -67,14 +76,24 @@ async function session( const pin = fakePin(zip); const journal: VaultJournalEntry[] = []; const folder = join(parent, "Lazurio"); - await initializeFolder(folder, { - os: executionOs(process.platform), - access: "local", - purpose: "human", - locale: "cs", - detail: "concise", - coordination: "direct", - }); + if (options.hosted === true) { + await mkdir(folder, { mode: 0o700 }); + await mkdir(join(folder, "organizations"), { mode: 0o700 }); + await mkdir(join(folder, "personalspace"), { mode: 0o700 }); + await initializeHandoverFolder(folder, { + preset: "hosted-personal", + machine: bindings.personal, + profile: presetProfile("hosted-personal", executionOs(process.platform)), + }); + } else + await initializeFolder(folder, { + os: executionOs(process.platform), + access: "local", + purpose: "human", + locale: "cs", + detail: "concise", + coordination: "direct", + }); // The health socket of the base: a short path, within a socket's limit. const base = join(parent, "b"); await mkdir(join(base, "update"), { recursive: true }); @@ -144,6 +163,7 @@ async function session( }; return { home, + folder, vault, journal, call, @@ -319,6 +339,20 @@ test.skipIf(!posix)( outcome: "created", trigger: "start", }); + // The vault became ready, but this computer's Folder does not offer + // it: the switch refuses as it always does, and nothing failed. + expect(vaultLines).toContainEqual({ + scope: "tools-vault", + operation: "vault", + outcome: "ready", + trigger: "start", + }); + expect( + vaultLines.filter((line) => line.outcome === "agents-not-enabled"), + ).toEqual([]); + expect((await readFolderTools(s.folder)).enabled).not.toContain( + "bitwarden", + ); } finally { log.mockRestore(); await s.close(); @@ -327,6 +361,52 @@ test.skipIf(!posix)( 60_000, ); +// Root decision 0198 point 1: the agents use the Environment's vault +// themselves. The Folder offers it on a Remote Environment on Linux only, so +// this runs there (CI); `tests/vault-flow.test.ts` holds the once-per-vault +// rule everywhere. +test.skipIf(process.platform !== "linux")( + 'the setup in which the vault becomes ready turns "Používají agenti" on in the Launchpad\'s Folder; a person who turns it off keeps it off through later setups', + async () => { + const s = await session({ + hosted: true, + allowed: true, + vaultAtStart: async () => true, + }); + try { + // The start's setup ends with the vault connected and switched on. + await until(async () => { + const answer = await s.json("/api/tools/bitwarden/status"); + return answer.status === 200 && answer.body.state === "connected" + ? answer + : null; + }); + const on = await readFolderTools(s.folder); + expect(on.enabled).toContain("bitwarden"); + // The person turns it off. + expect( + await s.json("/api/tools/update", { + expectedRevision: on.revision, + tools: on.enabled.filter((tool) => tool !== "bitwarden"), + }), + ).toMatchObject({ status: 200, body: { kind: "updated" } }); + // A later setup of the same vault, its session lost as after a + // restart: connected again, and the switch stays off. + await rm(join(s.paths.data, "fake", "session")); + expect(await s.setup()).toMatchObject({ + status: 200, + body: { state: "connected" }, + }); + expect((await readFolderTools(s.folder)).enabled).not.toContain( + "bitwarden", + ); + } finally { + await s.close(); + } + }, + 60_000, +); + test.skipIf(!posix)( "a Launchpad that is not a supervised base of the hosted operator, or a vault that needs no setup, sets nothing up at its start", async () => { diff --git a/tests/vault-flow.test.ts b/tests/vault-flow.test.ts index fc5ac1a29..7cc151e38 100644 --- a/tests/vault-flow.test.ts +++ b/tests/vault-flow.test.ts @@ -59,13 +59,20 @@ async function world() { const pin = fakePin(zip); const release = fakeRelease(pin, zip); const journal: VaultJournalEntry[] = []; - const host_ = fakeHost({ - home, - vault, - pin, - download: release.fetch, - journal, - }); + // How often the agents' switch was turned on for the vault. + let enabled = 0; + const host_: VaultHost = { + ...fakeHost({ + home, + vault, + pin, + download: release.fetch, + journal, + }), + enableForAgents: async () => { + enabled += 1; + }, + }; const paths = vaultPaths(stateDirectory(home, host, ownAccount)); return { home, @@ -75,6 +82,7 @@ async function world() { journal, host: host_, paths, + enabled: () => enabled, /** The own organizations of the account. */ owned: () => vault.organizationsOf(ownAccount), async close() { @@ -398,6 +406,71 @@ test.skipIf(!posix)( 60_000, ); +test.skipIf(!posix)( + "the setup in which the own vault becomes ready turns the agents' switch on once: never a refused setup, a later one, one after a lost session or a rename; a switch that fails is journaled, never the setup's", + async () => { + const w = await world(); + try { + // Not allowed yet: no vault, no switch. + expect(await vaultSetup(w.host)).toMatchObject({ state: "not-allowed" }); + expect(w.enabled()).toBe(0); + w.vault.allow(ownAccount); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); + expect(w.enabled()).toBe(1); + expect(w.journal).toContainEqual({ + operation: "vault", + outcome: "ready", + }); + // The same vault set up again, after its session was lost (the start's + // case after a person turned the switch off) and under a new name. + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); + await rm(join(w.paths.data, "fake", "session")); + expect(await vaultStatus(w.host)).toMatchObject({ locked: true }); + expect(await vaultSetup(w.host)).toMatchObject({ state: "connected" }); + const renamed: VaultHost = { + ...w.host, + context: async () => + ownContext( + personalHandoverAt( + "example.lazurio.io", + vaultMember(ownAccount, "Example Osobní renamed"), + ), + ), + }; + expect(await vaultSetup(renamed)).toMatchObject({ + state: "connected", + organization: "Example Osobní renamed", + }); + expect(w.enabled()).toBe(1); + expect( + w.journal.filter((entry) => entry.outcome === "ready"), + ).toHaveLength(1); + } finally { + await w.close(); + } + // A switch that cannot be turned: the setup still connects, and the + // journal says so with a fixed code. + const failing = await world(); + try { + failing.vault.allow(ownAccount); + const host: VaultHost = { + ...failing.host, + enableForAgents: async () => { + throw new Error("The Folder is busy"); + }, + }; + expect(await vaultSetup(host)).toMatchObject({ state: "connected" }); + expect(failing.journal).toContainEqual({ + operation: "vault", + outcome: "agents-not-enabled", + }); + } finally { + await failing.close(); + } + }, + 60_000, +); + test.skipIf(!posix)( "a refused API key is revoked, and a vault that does not let the account create organizations says so", async () => { From 7bcb6b94a45c8b9c631c7e914b954ee17ff0c2d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Wed, 14 Oct 2026 01:43:39 +0200 Subject: [PATCH 7/9] Vault: an unresolved creation is never sent again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The creation's receipt (the new organization's public key, recorded before POST /api/organizations) was only looked for among the confirmed memberships of one profile. A profile that briefly omitted the new organization (an answer that was lost, a listing that came late, a request that arrived late) made the next setup create a second organization and overwrite the receipt, orphaning the first. Now, while a receipt is unresolved, no setup sends another creation. Each one looks for the organization that carries the recorded key among the account's memberships of any status and records it once its membership is confirmed; until then, and while nothing matches, the setup and the local status report the new state `creating`, and the Launchpad's start sets it up again. The receipt carries its time: only a receipt older than 15 minutes (a request times out at 30 s) that still matches nothing is taken for a creation that never happened, discarded (journal receipt-expired, nothing else) and the vault created once. A creation the vault refuses with its answer (4xx but 429) created nothing and discards its receipt at once; no answer or a server error keeps it. The row says "Trezor se zakládá" with "Zkusit znovu"; F52 point 3 states the rule. Tests: the review's reproduction (a lost answer, then one profile without the organization: `creating`, one organization, found by the next setup) and a receipt that matches nothing making exactly one organization after its bound. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 38 ++++--- docs/environment-tools.md | 19 +++- docs/launchpad-development.md | 5 +- src/launchpad/messages.ts | 2 + src/launchpad/vault-view.ts | 16 ++- src/vault/cli.ts | 6 +- src/vault/flow.ts | 32 ++++-- src/vault/organization.ts | 178 ++++++++++++++++++++++++------- src/vault/status.ts | 8 ++ src/vault/store.ts | 19 +++- tests/vault-flow.test.ts | 130 +++++++++++++++++++++- tests/vault-organization.test.ts | 2 + tests/vault-store.test.ts | 25 ++++- tests/vault-view.test.ts | 9 ++ 14 files changed, 407 insertions(+), 82 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index f403ee20c..9129b954d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10598,9 +10598,9 @@ session of F43. `${XDG_STATE_HOME:-~/.local/state}/lazurio/vault///`, so an account the handover replaces starts afresh and a 0197 pilot's directory, keyed by its address, stays beside it untouched. `lazurio-vault.json` now holds the vault's - organization id, its collection Agenti's id and, while a creation is under way, - its receipt; a record that cannot be read refuses (`record-unreadable`) and nothing - is ever created over it. No bw this product starts ever runs without a data + organization id, its collection Agenti's id and, while a creation is unresolved, + its receipt and the receipt's time; a record that cannot be read refuses + (`record-unreadable`) and nothing is ever created over it. No bw this product starts ever runs without a data directory of its own, because bw rewrites its store on every start: the vault's `bwCli` refuses to start without an absolute one and sets it last on every run, and the version probe of Settings → Tools gives a `bw` on PATH a fresh temporary @@ -10618,9 +10618,19 @@ session of F43. account; the name, `vault.name`; and the first collection, "Agenti", its name encrypted with the organization key. bw cannot create an organization; these are the web vault's requests, proven against 1.37.4-lazurio.1 by the DEV-6631 study of - 2026-10-12. The new organization's public key is recorded before the request: an - organization whose answer was lost is recognized by it - (`GET /api/organizations//public-key`) and never created twice. Agenti is the + 2026-10-12. **Idempotent by its receipt:** the new organization's public key is + recorded with the time before the request is sent, and while that receipt is + unresolved no setup sends another creation. Each one looks for the organization + that carries the key among the account's memberships of any status + (`/api/accounts/profile`, then `GET /api/organizations//public-key`) and + records it once its membership is confirmed. While none carries it (an answer that + was lost, a profile that lists the organization late, a request that arrives late) + the setup reports `creating` and the next one looks again; only a receipt older + than 15 minutes, far above any request's 30 s, that still matches nothing is taken + for a creation that never happened: it is discarded, journaled + (`receipt-expired`, nothing else) and the vault created anew, once. A creation the + vault refuses with its answer (a 4xx but a rate limit) created nothing and + discards its receipt at once; no answer or a server error keeps it. Agenti is the organization's one collection, by its ID; several without a record of it are `collection-unknown`, never chosen by a name. A recorded organization the account no longer belongs to is `revoked` and is never replaced (only the network's @@ -10633,10 +10643,11 @@ session of F43. account's lock. `lazurio vault setup` runs it, and so does the installed Launchpad in the background after its start, by Executor's pattern (F44's addendum of 2026-10-11): on a supervised base of the hosted operator (`vaultAtStart`), once, - where `setUpAtStart` says the vault needs it (not set up, its session locked, or - its name no longer the handover's); never a 0197 pilot, a revoked vault or one - whose setup stopped, which wait for the row's action or an agent. The states: - `unsupported` (with `no-vault`), `not-set-up` (with the `next` step), + where `setUpAtStart` says the vault needs it (not set up, its creation not + confirmed yet, its session locked, or its name no longer the handover's); never a + 0197 pilot, a revoked vault or one whose setup stopped, which wait for the row's + action or an agent. The states: `unsupported` (with `no-vault`), `not-set-up` + (with the `next` step), `creating` (a receipt not resolved yet), `not-allowed`, `connected` (`organizationId`, `collectionId`, `organization`, `items`; `locked`), `revoked`, `unreachable` and `failed` (`stage` now also `vault`). `lazurio vault status` stays the one source of truth for agents and the @@ -10646,7 +10657,8 @@ session of F43. 5. **The Tools row** (Settings → Tools → bitwarden) shows only the state and "Otevřít trezor", a link to `/#/vault?organizationId=`, plus one action only where a setup moves the vault on ("Nastavit", "Zkusit znovu", as the wireframe's - unreachable state does); no disconnect for the Environment's own vault. Czech copy + unreachable state does; "Trezor se zakládá" with "Zkusit znovu" while its creation + is not confirmed); no disconnect for the Environment's own vault. Czech copy addresses people formally and says little (root decision 0199). The routes are `POST /api/tools/bitwarden/status|refresh|setup`; a running setup answers `202 {kind: "vault-setting-up", job, phase}` from all three. The setup in which @@ -10710,7 +10722,9 @@ Platform gate; it is re-pinned to that pull request's merge before this one merg Verified by unit tests against the fake Vaultwarden (`tests/fixtures/fake-vault.ts`, extended with the API-key login, the profile and the organization endpoints) and the fake bw: the setup from not allowed to connected, idempotent, renamed, its lost answer -recognized by the receipt, gone and refused (`tests/vault-flow.test.ts`); the account +recognized by the receipt, a profile that omits the new organization leaving it +`creating` with one organization until it is found, a receipt that matches nothing +made once after its bound, gone and refused (`tests/vault-flow.test.ts`); the account opening its own organization key from its master password down to Agenti's name and the organization's private key (`tests/vault-organization.test.ts`); the pilot with and without `vault` (`tests/vault-pilot.test.ts`); the CLI (`tests/vault-cli.test.ts`) diff --git a/docs/environment-tools.md b/docs/environment-tools.md index bcc313834..7c926ea6d 100644 --- a/docs/environment-tools.md +++ b/docs/environment-tools.md @@ -504,7 +504,8 @@ wave (`unsupported`, `workstation`). `lazurio-account.json` (0600: email, server, device identifier, master password, API key, createdAt), `lazurio-session` (0600) and `lazurio-vault.json` (0600, not secret: the vault's organization id, Agenti's collection id, and a creation's - receipt while one is under way). A record that is there but cannot be read refuses + receipt with its time while it is unresolved). A record that is there but cannot + be read refuses (`record-unreadable`): nothing is ever created over it. An account file whose account or vault is not the handover's is refused by every operation (`account-mismatch`). Nothing else anywhere; no secret on argv, in a log, the @@ -546,9 +547,16 @@ wave (`unsupported`, `workstation`). password unlocks), the organization's RSA-2048 key pair with its private key wrapped by the organization key, the billing e-mail the account, and the first collection "Agenti", its name encrypted with the organization key. The new - organization's public key is recorded before the request as its receipt; a creation - whose answer was lost is recognized by it (`GET /api/organizations//public-key`) - and never made twice. Agenti is the organization's one collection by its ID (`GET + organization's public key is recorded with the time before the request as its + receipt, and while it is unresolved no setup sends another creation: each looks for + the organization that carries the key among the account's memberships of any status + (`GET /api/organizations//public-key`) and records it once its membership is + confirmed; found nowhere, the setup is `creating` and the next one looks again (an + answer that was lost, a profile that lists it late, a request that arrives late). + Only a receipt older than 15 minutes (`receiptBoundMs`; a request takes at most + 30 s) that still matches nothing is discarded (journal `receipt-expired`) and the + vault created anew, once. A creation refused by the vault's answer (4xx but 429) + discards its receipt at once. Agenti is the organization's one collection by its ID (`GET /api/organizations//collections`); several, without a record of it, are `collection-unknown`, never chosen by a name. A vault that does not let the account create organizations (`ORG_CREATION_USERS`) is `organization-refused`; a refused API @@ -569,7 +577,8 @@ wave (`unsupported`, `workstation`). `spawn-failed`, `unreadable`, `failed`). - **States** (`src/vault/flow.ts`, `kind: "vault-status"` with `vault`, `account`, `name`, `team` and `origin`, `own` or `pilot-0197`): `unsupported` with a reason, - `not-set-up` (`next`: `install`, `account`, `vault` or `sign-in`), `not-allowed` + `not-set-up` (`next`: `install`, `account`, `vault` or `sign-in`), `creating` (a + creation's receipt not resolved yet; the start sets it up again), `not-allowed` (the network has not pre-allowed the address, or removed an unused pre-allowance), `connected` (`organizationId`, `collectionId`, `organization`, `items`; `locked` when the session must be unlocked again), `revoked`, `unreachable` (`reason`) and diff --git a/docs/launchpad-development.md b/docs/launchpad-development.md index f51121f5b..7e45c2ea9 100644 --- a/docs/launchpad-development.md +++ b/docs/launchpad-development.md @@ -2040,14 +2040,15 @@ on "Refresh status"). A setup that runs is the state both answer, `202 {kind: "vault-setting-up", job, phase}`, and the row follows it by its job whoever started it, saying its step: "Instaluje se Bitwarden…", "Připravuje se účet trezoru…", "Připravuje se trezor…", "Přihlašuje se…". Otherwise it says the state in few words: -"Připojeno", "Zatím nenastaveno", "Síť zatím účet trezoru nepovolila", "Trezor byl +"Připojeno", "Zatím nenastaveno", "Trezor se zakládá" (its creation not confirmed yet), +"Síť zatím účet trezoru nepovolila", "Trezor byl odebrán" (a 0197 pilot's: "Přístup odebrán v trezoru"), "Trezor neodpovídá", "Nastavení se nedokončilo", "Tento Environment zatím trezor nemá" (the handover names no vault) and "Brzy · druhá vlna" on this computer ("Connected", "Not set up yet", …). Its controls are "Otevřít trezor" once connected, a link in a new tab to `/#/vault?organizationId=`, and one action only where a setup moves the vault on: "Nastavit" when nothing set it up yet and "Zkusit znovu" after a setup that -stopped or a vault that did not answer. A vault the network has not allowed or has +stopped, a vault that did not answer or a creation not confirmed yet. A vault the network has not allowed or has revoked, and a 0197 pilot, offer none; there is no dialog, no details section and no disconnect. The setup in which the vault becomes ready turns the agents' switch on in the Folder itself, once per vault (decision F52), so a person who turns it off keeps it off; diff --git a/src/launchpad/messages.ts b/src/launchpad/messages.ts index fa651cfa3..a4314ff66 100644 --- a/src/launchpad/messages.ts +++ b/src/launchpad/messages.ts @@ -986,6 +986,7 @@ const en = { vaultRowChecking: "Checking…", vaultRowConnected: "Connected", vaultRowNotSetUp: "Not set up yet", + vaultRowCreating: "The vault is being created", vaultRowNotAllowed: "The network has not allowed its account yet", vaultRowRemoved: "The vault was removed", vaultRowRevoked: "Access removed in the vault", @@ -2361,6 +2362,7 @@ const cs: Record = { vaultRowChecking: "Zjišťuji stav…", vaultRowConnected: "Připojeno", vaultRowNotSetUp: "Zatím nenastaveno", + vaultRowCreating: "Trezor se zakládá", vaultRowNotAllowed: "Síť zatím účet trezoru nepovolila", vaultRowRemoved: "Trezor byl odebrán", vaultRowRevoked: "Přístup odebrán v trezoru", diff --git a/src/launchpad/vault-view.ts b/src/launchpad/vault-view.ts index 22fb12a9f..1d6fd21ff 100644 --- a/src/launchpad/vault-view.ts +++ b/src/launchpad/vault-view.ts @@ -14,6 +14,7 @@ type Copy = Readonly>; const states = [ "unsupported", "not-set-up", + "creating", "not-allowed", "connected", "revoked", @@ -121,6 +122,8 @@ export function parseVaultStatus(input: unknown): VaultStatus | null { next: value.next as VaultPhase, } : null; + case "creating": + return { kind: "vault-status", state: "creating", ...facts }; case "not-allowed": return { kind: "vault-status", state: "not-allowed", ...facts }; case "connected": @@ -220,6 +223,8 @@ export function vaultRowLine( }; case "not-set-up": return { text: copy.vaultRowNotSetUp, state: "unknown" }; + case "creating": + return { text: copy.vaultRowCreating, state: "unknown" }; case "not-allowed": return { text: copy.vaultRowNotAllowed, state: "signed-out" }; case "connected": @@ -238,9 +243,10 @@ export function vaultRowLine( } /** The row's one action besides "Otevřít trezor": set the own vault up - * when nothing set it up yet, or try again after a setup that stopped. A - * vault the network has not allowed or has revoked waits for a person of the - * network, and a 0197 pilot is only read: neither offers one. */ + * when nothing set it up yet, or try again after a setup that stopped or a + * creation not confirmed yet. A vault the network has not allowed or has + * revoked waits for a person of the network, and a 0197 pilot is only read: + * neither offers one. */ export function vaultAction( status: VaultStatus | null, running: VaultPhase | null, @@ -254,7 +260,9 @@ export function vaultAction( ) return null; if (status.state === "not-set-up") return copy.vaultActionSetUp; - return status.state === "failed" || status.state === "unreachable" + return status.state === "failed" || + status.state === "unreachable" || + status.state === "creating" ? copy.vaultActionRetry : null; } diff --git a/src/vault/cli.ts b/src/vault/cli.ts index 40bc5552c..e15b9e783 100644 --- a/src/vault/cli.ts +++ b/src/vault/cli.ts @@ -129,6 +129,8 @@ export function statusText(status: VaultStatus): string { switch (status.state) { case "not-set-up": return `Not set up yet: ${where}; the next step is ${stepText[status.next]}. The Launchpad sets it up at its start; lazurio vault setup does the same.`; + case "creating": + return `Being created: the creation of this Environment's vault for ${where} is not confirmed yet (its answer was lost, or the vault does not list it yet). The next setup looks for it again and never creates a second one; lazurio vault setup does it now.`; case "not-allowed": return `Not allowed yet: the vault refused to register ${where}. The network has not pre-allowed this address, or removed an unused pre-allowance; the network's operator allows it again at the next apply of its host, then run lazurio vault setup.`; case "connected": { @@ -226,7 +228,9 @@ export async function runVaultCommand( if (!json) context.progress?.(phaseText[phase]); }); const code = - status.state === "failed" || status.state === "unreachable" + status.state === "failed" || + status.state === "unreachable" || + (command === "setup" && status.state === "creating") ? exitFailure : command === "setup" && (status.state === "unsupported" || diff --git a/src/vault/flow.ts b/src/vault/flow.ts index d1df1a749..2ec4b549f 100644 --- a/src/vault/flow.ts +++ b/src/vault/flow.ts @@ -156,15 +156,21 @@ const notSetUp = (facts: VaultFacts, next: VaultPhase): VaultStatus => ({ next, }); +const creating = (facts: VaultFacts): VaultStatus => ({ + kind: "vault-status", + state: "creating", + ...facts, +}); + /** Whether the Launchpad's start moves this vault on (the Executor pattern, - * decision F44's addendum of 2026-10-11): an own vault not set up yet, one - * whose session is not the unlocked one, or one whose name is no longer the - * handover's. Never a 0197 pilot, a vault that is not supported here, or - * one that ended in a failure or a revocation: those wait for a person or an - * agent. */ + * decision F44's addendum of 2026-10-11): an own vault not set up yet or + * whose creation is not confirmed yet, one whose session is not the + * unlocked one, or one whose name is no longer the handover's. Never a 0197 + * pilot, a vault that is not supported here, or one that ended in a failure + * or a revocation: those wait for a person or an agent. */ export function setUpAtStart(status: VaultStatus): boolean { if (status.state === "unsupported" || status.origin !== "own") return false; - if (status.state === "not-set-up") return true; + if (status.state === "not-set-up" || status.state === "creating") return true; return ( status.state === "connected" && (status.locked === true || status.organization !== status.name) @@ -268,7 +274,13 @@ async function ownState( } const recorded = recordedVault(record); if (recorded === null) - return { kind: "status", status: notSetUp(facts, "vault") }; + return { + kind: "status", + status: + record.organizationId === null && record.pendingKey !== null + ? creating(facts) + : notSetUp(facts, "vault"), + }; return { kind: "ready", account, recorded }; } @@ -460,7 +472,13 @@ async function ensureVault( device: deviceOf(account), record, save: (next) => writeRecord(paths, next), + now: () => host.now?.() ?? new Date(), + // Never a key or an id: that a creation never happened, nothing else. + discarded: () => + host.journal?.({ operation: "vault", outcome: "receipt-expired" }), }); + if (own.kind === "creating") + return { kind: "status", status: creating(facts) }; if (own.kind === "gone") return { kind: "status", diff --git a/src/vault/organization.ts b/src/vault/organization.ts index f9a678b32..d4a8d6f71 100644 --- a/src/vault/organization.ts +++ b/src/vault/organization.ts @@ -38,6 +38,13 @@ export const agentsCollection = "Agenti"; * the organization's key. */ const confirmed = 2; +/** How long a creation's receipt keeps every new creation back: far longer + * than any request may take (30 s), so an organization whose answer was + * lost, that the vault lists late or whose request arrived late is found by + * its receipt and never made twice. Only a receipt this old that still + * matches no organization is taken for a creation that never happened. */ +export const receiptBoundMs = 15 * 60_000; + export type OwnVault = | Readonly<{ kind: "ready"; @@ -56,15 +63,26 @@ export type OwnVault = /** The organization's collections do not say which one is Agenti (an * organization recognized by its receipt after other collections were * added): nothing is guessed by a name. */ - | Readonly<{ kind: "collection-unknown" }>; + | Readonly<{ kind: "collection-unknown" }> + /** A creation was asked for and no organization carries its receipt yet + * (its answer was lost, the vault lists it late, or the request is still + * under way), or the one that does is not confirmed for the account yet: + * nothing is created again (unmatched, until the receipt is older than + * `receiptBoundMs`); the next run looks again. */ + | Readonly<{ kind: "creating" }>; -type Membership = Readonly<{ id: string; name: string }>; +type Membership = Readonly<{ id: string; name: string; confirmed: boolean }>; const unexpected = () => new VaultwardenError("unexpected"); -/** The organizations the account is a confirmed member of, from its - * profile; every entry must read, or the whole answer is unexpected. */ -function membershipsOf(profile: unknown): Membership[] { +/** The organizations the account is a member of, from its profile: the + * confirmed ones, or (`any`) those of every status, where a creation's + * receipt is looked for; every entry must read, or the whole answer is + * unexpected. */ +function membershipsOf( + profile: unknown, + status: "confirmed" | "any" = "confirmed", +): Membership[] { const value = plainObject(profile); if (value === null || !Array.isArray(value.organizations)) throw unexpected(); return value.organizations.flatMap((entry: unknown) => { @@ -77,12 +95,22 @@ function membershipsOf(profile: unknown): Membership[] { typeof organization.status !== "number" ) throw unexpected(); - return organization.status === confirmed - ? [{ id: organization.id, name: organization.name }] + const member = organization.status === confirmed; + return status === "any" || member + ? [{ id: organization.id, name: organization.name, confirmed: member }] : []; }); } +/** Whether an answer of the vault refuses the request itself (4xx but a + * rate limit): it was not carried out. */ +const refused = (error: unknown): boolean => + error instanceof VaultwardenError && + error.status !== undefined && + error.status >= 400 && + error.status < 500 && + error.status !== 429; + /** * Makes the account's own vault exist, as the record and the handover say, * and returns it: @@ -97,8 +125,16 @@ function membershipsOf(profile: unknown): Membership[] { * key pair, its private key wrapped by the organization key; the billing * e-mail the account; the name `vault.name`; and the first collection, * Agenti, its name encrypted with the organization key. Its public key is - * recorded first as the creation's receipt, so a creation whose answer was - * lost is recognized by it afterwards and never made twice; + * recorded first, with the time, as the creation's receipt; + * - a receipt not resolved yet: the organization that carries its public + * key, among the account's memberships of any status, recorded once the + * membership is confirmed (until then `creating`). While none carries it, + * nothing is created again (`creating`) until the receipt is older than + * `receiptBoundMs`: an answer that was lost, a profile that lists it late + * or a request that arrives late never makes a second vault. Only then is + * the receipt taken for a creation that never happened, discarded + * (`discarded`) and the vault created anew. A creation the vault refuses + * with its answer discards the receipt at once; * - Agenti: the one collection of the organization, by its ID. * * Every step is saved as soon as it is known; a step the vault refuses @@ -113,6 +149,9 @@ export async function ensureOwnVault( device: Device; record: VaultRecord; save: (record: VaultRecord) => Promise; + now: () => Date; + /** A receipt older than the bound that matched nothing was discarded. */ + discarded?: (() => void) | undefined; }>, ): Promise { const { account, client, server } = input; @@ -135,24 +174,60 @@ export async function ensureOwnVault( record = next; await input.save(next); }; - const memberships = membershipsOf(await ask("/api/accounts/profile")); + const profile = await ask("/api/accounts/profile"); + const memberships = membershipsOf(profile); - // A creation whose answer was lost: its organization carries the public - // key recorded before it was asked for. - if (record.organizationId === null && record.pendingKey !== null) - for (const membership of memberships) { - const answer = plainObject( - await ask(`/api/organizations/${membership.id}/public-key`), - ); + // A creation not resolved yet: its organization carries the public key + // recorded before it was asked for, under a membership of any status. A + // membership whose key the vault refuses to show is not it; any other + // failure throws, and the receipt stays for the next run. + if (record.organizationId === null && record.pendingKey !== null) { + let found: Membership | null = null; + for (const membership of membershipsOf(profile, "any")) { + let answer: Record | null; + try { + answer = plainObject( + await ask(`/api/organizations/${membership.id}/public-key`), + ); + } catch (error) { + if (refused(error)) continue; + throw error; + } if (answer?.publicKey === record.pendingKey) { - await save({ - organizationId: membership.id, - collectionId: null, - pendingKey: null, - }); + found = membership; break; } } + if (found?.confirmed === true) + await save({ + organizationId: found.id, + collectionId: null, + pendingKey: null, + pendingSince: null, + }); + // Created, but the account's membership is not confirmed yet: it is + // this vault, so it is waited for however long it takes. + else if (found !== null) return Object.freeze({ kind: "creating" }); + // Young, or of a time that does not read: wait. + else if ( + !( + input.now().getTime() - Date.parse(record.pendingSince ?? "") >= + receiptBoundMs + ) + ) + return Object.freeze({ kind: "creating" }); + else { + // Older than the bound and found nowhere: that creation never + // happened, so the vault is created anew. + await save({ + organizationId: null, + collectionId: null, + pendingKey: null, + pendingSince: null, + }); + input.discarded?.(); + } + } let organization: Membership; let created = false; @@ -171,33 +246,53 @@ export async function ensureOwnVault( organizationId: null, collectionId: null, pendingKey: keys.publicKey, + pendingSince: input.now().toISOString(), }); - const answer = plainObject( - await ask("/api/organizations", { - json: { - name: input.name, - billingEmail: account.email, - key: await rsaEncrypt(await publicKeyOf(privateKey), organizationKey), - keys: { - publicKey: keys.publicKey, - encryptedPrivateKey: keys.encryptedPrivateKey, + let answer: Record | null; + try { + answer = plainObject( + await ask("/api/organizations", { + json: { + name: input.name, + billingEmail: account.email, + key: await rsaEncrypt( + await publicKeyOf(privateKey), + organizationKey, + ), + keys: { + publicKey: keys.publicKey, + encryptedPrivateKey: keys.encryptedPrivateKey, + }, + collectionName: await encrypt( + agentsCollection, + symmetricKey(organizationKey), + ), + // Ignored by Vaultwarden, which has one plan; the web vault + // sends it. + planType: 0, }, - collectionName: await encrypt( - agentsCollection, - symmetricKey(organizationKey), - ), - // Ignored by Vaultwarden, which has one plan; the web vault sends it. - planType: 0, - }, - }), - ); + }), + ); + } catch (error) { + // Refused by its answer, it created nothing: the receipt goes. No + // answer, or a server error, may have created it: the receipt stays. + if (refused(error)) + await save({ + organizationId: null, + collectionId: null, + pendingKey: null, + pendingSince: null, + }); + throw error; + } if (!isVaultId(answer?.id)) throw unexpected(); await save({ organizationId: answer.id, collectionId: null, pendingKey: null, + pendingSince: null, }); - organization = { id: answer.id, name: input.name }; + organization = { id: answer.id, name: input.name, confirmed: true }; created = true; } else { const recorded = memberships.find( @@ -231,6 +326,7 @@ export async function ensureOwnVault( organizationId: organization.id, collectionId, pendingKey: null, + pendingSince: null, }); } diff --git a/src/vault/status.ts b/src/vault/status.ts index bed435e1b..03c67ecdf 100644 --- a/src/vault/status.ts +++ b/src/vault/status.ts @@ -42,6 +42,14 @@ export type VaultStatus = state: "not-set-up"; next: VaultPhase; }>) + | (VaultFacts & + Readonly<{ + kind: "vault-status"; + /** The vault's creation was asked for and is not confirmed yet (its + * answer was lost, or the vault does not list it yet): the next + * setup looks for it again, and nothing is created twice. */ + state: "creating"; + }>) | (VaultFacts & Readonly<{ kind: "vault-status"; diff --git a/src/vault/store.ts b/src/vault/store.ts index 516461740..802695a45 100644 --- a/src/vault/store.ts +++ b/src/vault/store.ts @@ -250,20 +250,29 @@ export async function writeSession( * and its first collection, Agenti, by ID, which is the vault's whole * identity (names never are). `pendingKey` is the receipt of a creation * under way: the new organization's public key, written before it is - * created, so an organization whose answer was lost is recognized as this - * account's own afterwards and never created twice. */ + * created, so an organization whose answer was lost, or that the vault + * lists late, is recognized as this account's own afterwards and never + * created twice; `pendingSince` is when it was written (ISO 8601, UTC). */ export type VaultRecord = Readonly<{ organizationId: string | null; collectionId: string | null; pendingKey: string | null; + pendingSince: string | null; }>; export const emptyRecord: VaultRecord = Object.freeze({ organizationId: null, collectionId: null, pendingKey: null, + pendingSince: null, }); +/** A time in its one form: `Date#toISOString`'s. */ +const isInstant = (value: unknown): value is string => + typeof value === "string" && + !Number.isNaN(Date.parse(value)) && + new Date(value).toISOString() === value; + /** The record, or the empty one when there is none. A record that is there * but cannot be read throws: it may be the only memory of the vault's ID, so * nothing is ever created in its place. */ @@ -274,10 +283,12 @@ export async function readRecord(paths: VaultPaths): Promise { if ( value === null || Object.keys(value).sort().join() !== - "collectionId,organizationId,pendingKey" || + "collectionId,organizationId,pendingKey,pendingSince" || !(value.organizationId === null || isVaultId(value.organizationId)) || !(value.collectionId === null || isVaultId(value.collectionId)) || !(value.pendingKey === null || isPublicKey(value.pendingKey)) || + !(value.pendingSince === null || isInstant(value.pendingSince)) || + (value.pendingKey === null) !== (value.pendingSince === null) || (value.collectionId !== null && value.organizationId === null) ) throw new Error("Invalid vault record"); @@ -285,6 +296,7 @@ export async function readRecord(paths: VaultPaths): Promise { organizationId: value.organizationId as string | null, collectionId: value.collectionId as string | null, pendingKey: value.pendingKey as string | null, + pendingSince: value.pendingSince as string | null, }); } @@ -299,6 +311,7 @@ export async function writeRecord( organizationId: record.organizationId, collectionId: record.collectionId, pendingKey: record.pendingKey, + pendingSince: record.pendingSince, }), ); } diff --git a/tests/vault-flow.test.ts b/tests/vault-flow.test.ts index 7cc151e38..3121b6da4 100644 --- a/tests/vault-flow.test.ts +++ b/tests/vault-flow.test.ts @@ -176,6 +176,7 @@ test.skipIf(!posix)( organizationId: organization.id, collectionId: agentsId, pendingKey: null, + pendingSince: null, }); expect(w.journal).toContainEqual({ operation: "vault", @@ -339,11 +340,16 @@ test.skipIf(!posix)( organizationId: null, collectionId: null, pendingKey: w.owned()[0]?.publicKey ?? "?", + pendingSince: expect.stringMatching(/^\d{4}-\d\d-\d\dT[\d:.]+Z$/), }); - expect(await vaultStatus(host_)).toMatchObject({ - state: "not-set-up", - next: "vault", + // Not confirmed yet: the start looks for it again. + const pending = await vaultStatus(host_); + expect(pending).toEqual({ + kind: "vault-status", + state: "creating", + ...facts, }); + expect(setUpAtStart(pending)).toBe(true); lose = false; const connected = await vaultSetup(host_); expect(connected).toMatchObject({ @@ -360,6 +366,122 @@ test.skipIf(!posix)( 60_000, ); +test.skipIf(!posix)( + "an unresolved creation is never made again: a profile that omits the new organization leaves the vault creating, and the organization found later is the one vault", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + // The vault creates the organization, then the answer is lost. + let lose = true; + // How many profiles omit every organization (the vault lists the new + // one late, or the request is still under way). + let omit = 0; + const host_: VaultHost = { + ...w.host, + fetch: async (url, init) => { + const answer = await w.vault.fetch(url, init); + if (lose && url.endsWith("/api/organizations")) + throw new Error("connection reset"); + if (omit > 0 && url.endsWith("/api/accounts/profile")) { + omit -= 1; + const profile = (await answer.json()) as Record; + return Response.json({ ...profile, organizations: [] }); + } + return answer; + }, + }; + expect(await vaultSetup(host_)).toMatchObject({ state: "unreachable" }); + expect(w.owned()).toHaveLength(1); + const receipt = await readRecord(w.paths); + lose = false; + omit = 1; + // The profile omits it: nothing is created, the receipt stays. + expect(await vaultSetup(host_)).toEqual({ + kind: "vault-status", + state: "creating", + ...facts, + }); + expect(w.owned()).toHaveLength(1); + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(1); + expect(await readRecord(w.paths)).toEqual(receipt); + expect(await vaultStatus(host_)).toMatchObject({ state: "creating" }); + // Listed again: the organization that carries the receipt is the vault. + expect(await vaultSetup(host_)).toMatchObject({ + state: "connected", + organizationId: w.owned()[0]?.id, + }); + expect(w.owned()).toHaveLength(1); + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(1); + expect(await readRecord(w.paths)).toMatchObject({ + organizationId: w.owned()[0]?.id, + pendingKey: null, + pendingSince: null, + }); + expect(w.journal).not.toContainEqual({ + operation: "vault", + outcome: "receipt-expired", + }); + } finally { + await w.close(); + } + }, + 60_000, +); + +test.skipIf(!posix)( + "a receipt that matches nothing waits out its bound, then the creation that never happened is made once", + async () => { + const w = await world(); + try { + w.vault.allow(ownAccount); + let clock = Date.parse("2026-10-14T01:00:00.000Z"); + // The creation never reaches the vault: no answer, no organization. + let drop = true; + const host_: VaultHost = { + ...w.host, + now: () => new Date(clock), + fetch: async (url, init) => { + if (drop && url.endsWith("/api/organizations")) + throw new Error("connection reset"); + return w.vault.fetch(url, init); + }, + }; + expect(await vaultSetup(host_)).toMatchObject({ state: "unreachable" }); + drop = false; + expect(w.owned()).toHaveLength(0); + expect(await readRecord(w.paths)).toMatchObject({ + organizationId: null, + pendingSince: "2026-10-14T01:00:00.000Z", + }); + // Within the bound nothing is created, however often it is asked. + for (const minutes of [1, 14]) { + clock = Date.parse("2026-10-14T01:00:00.000Z") + minutes * 60_000; + expect(await vaultSetup(host_)).toMatchObject({ state: "creating" }); + } + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(0); + // Past it, still found nowhere: the receipt is discarded, and the + // vault is created once. + clock = Date.parse("2026-10-14T01:15:00.000Z"); + expect(await vaultSetup(host_)).toMatchObject({ state: "connected" }); + expect(w.owned()).toHaveLength(1); + expect(w.vault.of("/api/organizations", "POST")).toHaveLength(1); + expect(w.journal).toContainEqual({ + operation: "vault", + outcome: "receipt-expired", + }); + expect(await readRecord(w.paths)).toMatchObject({ + organizationId: w.owned()[0]?.id, + pendingKey: null, + pendingSince: null, + }); + } finally { + await w.close(); + } + }, + 60_000, +); + test.skipIf(!posix)( "a vault that is gone or an API key refused is revoked and never replaced; a damaged record is never written over", async () => { @@ -886,6 +1008,8 @@ test("the start sets up only an own vault that needs it", () => { expect( setUpAtStart(status({ state: "not-set-up", origin: "own", next: "vault" })), ).toBe(true); + // A creation not confirmed yet is looked for again. + expect(setUpAtStart(status({ state: "creating", origin: "own" }))).toBe(true); for (const state of ["not-allowed", "revoked", "unreachable", "failed"]) expect([state, setUpAtStart(status({ state, origin: "own" }))]).toEqual([ state, diff --git a/tests/vault-organization.test.ts b/tests/vault-organization.test.ts index f430e15a6..9afbbd461 100644 --- a/tests/vault-organization.test.ts +++ b/tests/vault-organization.test.ts @@ -120,6 +120,7 @@ test.skipIf(!posix)( organizationId: organization.id, collectionId: first?.id ?? "?", pendingKey: null, + pendingSince: null, }); } finally { await w.close(); @@ -163,6 +164,7 @@ test.skipIf(!posix)( organizationId: organization.id, collectionId: null, pendingKey: null, + pendingSince: null, }); expect(w.vault.organizationsOf(ownAccount)).toHaveLength(1); expect(w.journal).not.toContainEqual({ diff --git a/tests/vault-store.test.ts b/tests/vault-store.test.ts index 906fea01b..c9ee5ff35 100644 --- a/tests/vault-store.test.ts +++ b/tests/vault-store.test.ts @@ -135,16 +135,21 @@ test("a refused registration leaves nothing; the session is written whole", asyn } }); -test("the own vault's record is its IDs and a creation's receipt, and a damaged one is never taken for none", async () => { +test("the own vault's record is its IDs and a creation's receipt with its time, and a damaged one is never taken for none", async () => { const t = await temporary(); try { const empty = { organizationId: null, collectionId: null, pendingKey: null, + pendingSince: null, }; expect(await readRecord(t.paths)).toEqual(empty); - const receipt = { ...empty, pendingKey: "A".repeat(392) }; + const receipt = { + ...empty, + pendingKey: "A".repeat(392), + pendingSince: "2026-10-13T21:00:00.000Z", + }; await writeRecord(t.paths, receipt); expect(await readRecord(t.paths)).toEqual(receipt); expect((await lstat(t.paths.record)).mode & 0o777).toBe(0o600); @@ -152,11 +157,14 @@ test("the own vault's record is its IDs and a creation's receipt, and a damaged organizationId: "0b9e2f3a-5c1d-4e8f-9a7b-1c2d3e4f5a6b", collectionId: "6a5f4e3d-2c1b-4a9f-8e7d-6c5b4a3f2e1d", pendingKey: null, + pendingSince: null, }; await writeRecord(t.paths, vault); expect(await readRecord(t.paths)).toEqual(vault); - // Damaged, of another shape (a 0197 pilot's), or a collection without - // its organization: refused, never read as no record. + // Damaged, of another shape (a 0197 pilot's, or this one's before the + // receipt had a time), a collection without its organization, or a + // receipt without its time or a time in another form: refused, never + // read as no record. for (const damaged of [ "{broken", JSON.stringify({ @@ -164,8 +172,17 @@ test("the own vault's record is its IDs and a creation's receipt, and a damaged organizationId: vault.organizationId, collectionId: vault.collectionId, }), + JSON.stringify({ + organizationId: null, + collectionId: null, + pendingKey: receipt.pendingKey, + }), JSON.stringify({ ...vault, organizationId: null }), JSON.stringify({ ...vault, pendingKey: "not a key" }), + JSON.stringify({ ...receipt, pendingSince: null }), + JSON.stringify({ ...empty, pendingSince: receipt.pendingSince }), + JSON.stringify({ ...receipt, pendingSince: "2026-10-13T21:00:00Z" }), + JSON.stringify({ ...receipt, pendingSince: "yesterday" }), JSON.stringify({ ...vault, extra: 1 }), ]) { await writeFile(t.paths.record, damaged); diff --git a/tests/vault-view.test.ts b/tests/vault-view.test.ts index 15db514f8..87b8c59c5 100644 --- a/tests/vault-view.test.ts +++ b/tests/vault-view.test.ts @@ -42,6 +42,7 @@ test("every state the server answers is read back exactly; anything else is refu for (const value of [ { state: "not-set-up", next: "install" }, { state: "not-set-up", next: "vault" }, + { state: "creating" }, { state: "not-allowed" }, connected, { ...connected, organization: null, items: null, locked: true }, @@ -141,6 +142,7 @@ test("the row says the state in few words, formally in Czech, and the step of a null, copy, ), + vaultRowLine(status({ state: "creating" }), null, copy), vaultRowLine(status({ state: "not-allowed" }), null, copy), vaultRowLine(status({ state: "revoked" }), null, copy), vaultRowLine( @@ -179,6 +181,7 @@ test("the row says the state in few words, formally in Czech, and the step of a "unknown: Zjišťuji stav…", "signed-in: Připojeno", "unknown: Zatím nenastaveno", + "unknown: Trezor se zakládá", "signed-out: Síť zatím účet trezoru nepovolila", "signed-out: Trezor byl odebrán", "signed-out: Přístup odebrán v trezoru", @@ -192,6 +195,7 @@ test("the row says the state in few words, formally in Czech, and the step of a "unknown: Checking…", "signed-in: Connected", "unknown: Not set up yet", + "unknown: The vault is being created", "signed-out: The network has not allowed its account yet", "signed-out: The vault was removed", "signed-out: Access removed in the vault", @@ -224,6 +228,11 @@ test("the row opens the connected vault and offers one action only where a setup expect( vaultAction(status({ state: "unreachable", reason: "x" }), null, cs), ).toBe("Zkusit znovu"); + // A creation not confirmed yet: looked for again, never made twice. + expect(vaultAction(status({ state: "creating" }), null, cs)).toBe( + "Zkusit znovu", + ); + expect(vaultOpenLink(status({ state: "creating" }))).toBeNull(); expect( vaultAction( status({ From 3545aa4a756b7477ca45192ea9b47317f4539e3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Wed, 14 Oct 2026 15:02:03 +0200 Subject: [PATCH 8/9] Machine: pin the handover schema to Machines v0.12.159 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Machines #500, which adds only the optional top-level member `vault` (DEV-6631 contract C2), is merged as 8b66889b and released as v0.12.159, whose tag targets that merge. The vendored schema was taken from #500's head and is byte-identical to the merge and to Machines main (SHA-256 76a05804…), so only its provenance changes: the version and tag v0.12.159, the merge commit, and the release as the pin's update. The pending note is gone; docs/machine-handover.md and the decision name the release. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 7 +++---- docs/machine-handover.md | 20 ++++++++------------ src/machine/schema-provenance.json | 9 ++++----- 3 files changed, 15 insertions(+), 21 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 9129b954d..680364bde 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10705,10 +10705,9 @@ point 9). Organization creation stays open to every account of the network (`ORG_CREATION_USERS`), so people can create other organizations outside this model; the threat model of the network's vault records it. People's access to an Environment's vault (Správci, task 638b) is not in this revision: until then only the -Environment's account is a member of its vault. The vendored handover schema is the -head of the open Machines pull request #500, which writes the member behind its -Platform gate; it is re-pinned to that pull request's merge before this one merges -(`schema-provenance.json`'s `pending`). +Environment's account is a member of its vault. The vendored handover schema is Machines +v0.12.159's (the merge of pull request #500, which writes the member behind its +Platform gate). | Alternative | Trade-off / disposition | | --- | --- | diff --git a/docs/machine-handover.md b/docs/machine-handover.md index 4abd6eaca..8ba919870 100644 --- a/docs/machine-handover.md +++ b/docs/machine-handover.md @@ -11,20 +11,16 @@ does not authorize deployment, restart, access changes or resident removal. Machines writes `/etc/lazurio/lazurio.machine.json`, root-owned and non-shared, after successful managed handover. Platform only reads it. The exact upstream JSON Schema is vendored in `src/machine/lazurio-machine.v1.schema.json` -from the merge of Machines pull request **#449** into `main` (commit -`30c2fcf8a77914b5a44c652265e927683b2b413c`, SHA-256 -`fbbd159b8e6dfc8580a7b8460ddb4a2b2d3158a1b74ab2a420d8ff68005ae53f`), which adds the -optional `entry.environment_relay` ([below](#the-hosted-entry-decision-f16), root -decision 0194, decision F45) and changes nothing else. **Pending re-pin:** the file is -now vendored byte for byte from the head of the open Machines pull request **#500** -(commit `14d448682be5d0a666b39b4c2b2f2bf6867fc448`, SHA-256 +from Machines **v0.12.159** (tag commit `8b66889bf4e00b111027f9b280423f4b9cdfcf4e`, the +merge of pull request **#500**; SHA-256 `76a058045be25b718caed8a04e533d67fa8666945bfa4fa0153d618bc4d78957`), which adds only the optional top-level member `vault` ([below](#the-environments-own-vault-decision-f52), -DEV-6631 contract C2) to #449's; before this Platform merges, it is re-pinned to that -pull request's merge (`schema-provenance.json`'s `pending` says so meanwhile). No Machines release carries it -yet, so the provenance names no version and no tag; the first release that does may -add them with the same digest, and a digest other than this one is a new re-pin. -Before it, the pin was the merge of Machines +DEV-6631 contract C2) and changes nothing else. Before it, the pin was the merge of +Machines pull request **#449** into `main` (commit +`30c2fcf8a77914b5a44c652265e927683b2b413c`, SHA-256 +`fbbd159b8e6dfc8580a7b8460ddb4a2b2d3158a1b74ab2a420d8ff68005ae53f`), which added the +optional `entry.environment_relay` ([below](#the-hosted-entry-decision-f16), root +decision 0194, decision F45); before that, the merge of Machines pull request **#398** into `main` (commit `b831308f153519747ebcb4d2d9690c1b9a865a9b`, SHA-256 `475c5197b7c2d812dda960aa30f23a709837dca0560579e5c1c5d4f822d1506e`), which added the optional `entry.browser` (decision F38); before that, the merge of diff --git a/src/machine/schema-provenance.json b/src/machine/schema-provenance.json index 896152620..db992f7d0 100644 --- a/src/machine/schema-provenance.json +++ b/src/machine/schema-provenance.json @@ -1,13 +1,12 @@ { "source_repository": "HumanAndMachine-ai/Machines", - "source_version": null, - "source_tag": null, + "source_version": "0.12.159", + "source_tag": "v0.12.159", "source_pull_request": "https://github.com/HumanAndMachine-ai/Machines/pull/500", - "source_commit": "14d448682be5d0a666b39b4c2b2f2bf6867fc448", + "source_commit": "8b66889bf4e00b111027f9b280423f4b9cdfcf4e", "source_path": "workloads/workspace-vm/lazurio-machine.v1.schema.json", "source_sha256": "76a058045be25b718caed8a04e533d67fa8666945bfa4fa0153d618bc4d78957", "sha256": "76a058045be25b718caed8a04e533d67fa8666945bfa4fa0153d618bc4d78957", "publication_authorization": "https://github.com/HumanAndMachine-ai/Machines/pull/124#issuecomment-5688845105", - "pin_update": "https://github.com/HumanAndMachine-ai/Machines/pull/500", - "pending": "Vendored byte for byte from the head of the open Machines pull request #500 (DEV-6631 task 637, guest side), which adds only the optional member `vault` to #449's schema. Re-pin to its merge commit (and the release that carries it) before this Platform merges; a digest other than this one is a new re-pin." + "pin_update": "https://github.com/HumanAndMachine-ai/Machines/releases/tag/v0.12.159" } From 7eab1559823f520a841edad92db545f851f4e906 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= Date: Wed, 14 Oct 2026 15:02:33 +0200 Subject: [PATCH 9/9] Docs: the Environment's own vault is decision F53 Main took F52 for the module generator (#394), so the vault decision of this branch, written as F52 before that merged, is F53: its heading, the notes on F43 and F46 that point to it, the section and anchor in docs/machine-handover.md, and every comment, doc and test that names it. The module generator's own references to F52 are unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/decisions.md | 6 +++--- docs/environment-tools.md | 12 ++++++------ docs/launchpad-development.md | 8 ++++---- docs/machine-handover.md | 4 ++-- docs/module-adoption.md | 2 +- docs/public-development.md | 2 +- docs/recovery.md | 2 +- src/cli.ts | 4 ++-- src/launchpad/server.ts | 12 ++++++------ src/launchpad/tools-panel.ts | 4 ++-- src/launchpad/vault-panel.ts | 4 ++-- src/launchpad/vault-routes.ts | 2 +- src/launchpad/vault-view.ts | 2 +- src/modules/runtime-secrets.ts | 6 +++--- src/organizations/catalog.ts | 4 ++-- src/recover/private-values.ts | 2 +- src/tools/catalog.ts | 4 ++-- src/tools/curated-cli.ts | 2 +- src/update/cli.ts | 2 +- src/vault/bw.ts | 2 +- src/vault/cli.ts | 2 +- src/vault/context.ts | 4 ++-- src/vault/flow.ts | 6 +++--- src/vault/host.ts | 4 ++-- src/vault/legacy-0197/README.md | 2 +- src/vault/organization.ts | 4 ++-- src/vault/register.ts | 2 +- src/vault/session.ts | 2 +- src/vault/status.ts | 4 ++-- src/vault/store.ts | 4 ++-- tests/fixtures/fake-vault.ts | 2 +- tests/launchpad-vault.test.ts | 2 +- tests/module-runtime-secrets.test.ts | 2 +- tests/recover-sanitize.test.ts | 2 +- tests/runtime-secrets.test.ts | 2 +- tests/vault-cli.test.ts | 2 +- tests/vault-context.test.ts | 2 +- tests/vault-flow.test.ts | 2 +- tests/vault-handover.test.ts | 2 +- tests/vault-host.test.ts | 2 +- tests/vault-organization.test.ts | 2 +- tests/vault-register.test.ts | 2 +- tests/vault-secrets.test.ts | 2 +- tests/vault-store.test.ts | 2 +- tests/vault-view.test.ts | 2 +- 45 files changed, 75 insertions(+), 75 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 680364bde..9aaf2cd10 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -7832,7 +7832,7 @@ Verified by tests: ## F43 — The Environment vault: one Vaultwarden account per Environment, its Bitwarden CLI pinned, one session for its agents -> **Superseded in part by [F52](#f52--every-environment-owns-its-vault-its-own-organization-in-the-networks-vaultwarden-created-by-its-technical-account) +> **Superseded in part by [F53](#f53--every-environment-owns-its-vault-its-own-organization-in-the-networks-vaultwarden-created-by-its-technical-account) > (root decision 0198, 2026-10-13).** The account and its vault now come from the > handover's `vault` member, and the Environment owns its vault, its own organization; > the guessed `vaultwarden@
` account, the vault derived from Headscale, the @@ -8494,7 +8494,7 @@ Automated Environments (Machines #382) and immediate delivery. ## F46 — Runtime secrets: declared names, read from the Environment vault before every start, fail closed -> **Amended by [F52](#f52--every-environment-owns-its-vault-its-own-organization-in-the-networks-vaultwarden-created-by-its-technical-account) +> **Amended by [F53](#f53--every-environment-owns-its-vault-its-own-organization-in-the-networks-vaultwarden-created-by-its-technical-account) > (root decision 0198, 2026-10-13).** A value is now the login password of the one > item named exactly like the secret anywhere in the Environment's own vault (point 2 > below read one collection of an Organization's vault), and point 3's boundary @@ -10585,7 +10585,7 @@ session of F43. optional, closed member `vault: {server_url, account, name}` (contract C2) only for a Platform release that reads it, as it gates `entry.environment_relay`, because a Platform vendoring an earlier schema refuses the whole handover - ([machine handover](machine-handover.md#the-environments-own-vault-decision-f52)). + ([machine handover](machine-handover.md#the-environments-own-vault-decision-f53)). `account` is `vaultwarden-<26 lowercase base32>@`, generated and pre-allowed by the network (`/admin/invite`) for this Environment alone; `name` is " ", letters, digits and diff --git a/docs/environment-tools.md b/docs/environment-tools.md index 7c926ea6d..416ada1d0 100644 --- a/docs/environment-tools.md +++ b/docs/environment-tools.md @@ -4,7 +4,7 @@ Proposed bounded pilot procedure under accepted decision 0144. Apart from the curated installation and login of three catalog tools (decision F19, below), the -Environment's own vault (decisions F43 and F52, below), Executor (decision F44, below) and the +Environment's own vault (decisions F43 and F53, below), Executor (decision F44, below) and the pilot of the shared GitHub App sign-in (decision F48, below), this document does not claim an implemented tool installer, authenticated harness or usable Environment. @@ -81,7 +81,7 @@ named in the generated instructions with a **tier** and a **setup mode**: | `gh` | `gh` | required: always on, never stored, cannot be disabled | launchpad | | `executor` | `executor` | required; offered in a Remote Environment on Linux (F44) | launchpad (Lazurio's own setup, below) | | `composio` | `composio` | recommended | launchpad | -| `bitwarden` | `bw` | recommended; offered in a Remote Environment on Linux (F43, F52) | launchpad (its own flow, below) | +| `bitwarden` | `bw` | recommended; offered in a Remote Environment on Linux (F43, F53) | launchpad (its own flow, below) | | `wacli` | `wacli` | optional | launchpad | | `gogcli` | `gog` | optional; offered on a computer and in a personal Remote Environment, not in a work one (F44) | agent | | `neon` | `neon` | optional | agent | @@ -474,11 +474,11 @@ earlier temporary exception that let any account sign in on a Team VM has ended. nothing here provisions the App, its broker or a brokered `gh`. The product refuses the personal sign-in and relies on what the Machine delivers. -### The Environment's own vault (decisions F43 and F52) +### The Environment's own vault (decisions F43 and F53) Root decision 0198: every Environment owns its vault, its own organization in its network's Lazurio Vaultwarden, created by its technical account, which is its only -Owner, and remembered by ID (decision F52 supersedes F43's collection model; F43's +Owner, and remembered by ID (decision F53 supersedes F43's collection model; F43's pinned CLI, custody and one shared session stay). The account and the vault come from the handover's member `vault: {server_url, account, name}` (DEV-6631 contract C2), which Machines writes only for a Platform that reads it; without it the Environment @@ -616,7 +616,7 @@ wave (`unsupported`, `workstation`). never the setup's. The journal of the unit gets `{"scope":"tools-vault","operation":"setup|refresh|unlock|vault|secrets","outcome":…,"reason":…}` (with `"trigger":"start"` for the start's setup) only. -- **Runtime secrets** (decision F46 as F52 amends it, `vaultSecrets` in +- **Runtime secrets** (decision F46 as F53 amends it, `vaultSecrets` in `src/vault/flow.ts`): on a work Environment the applications of the Organization that owns it read them, on a personal one the Personalspace's modules (root decision 0198 point 4); another Organization's application is `other-organization`, a @@ -923,7 +923,7 @@ package-manager matrix (`lazurio tools` runs one tool's official update path und 0161 and installs only the curated catalog tools of decision F19 and the pinned Bitwarden CLI of decision F43; it is not a general updater or installer); the team case consumes the existing upstream broker rather than adding one. The Environment's -own vault (F43, F52) keeps no secret in the Platform: the vault is the network's +own vault (F43, F53) keeps no secret in the Platform: the vault is the network's Vaultwarden, and the Environment account's credentials stay beside the Bitwarden CLI's own data directory. Unknown installation state receives a diagnosis and operator repair procedure, not an improvised privileged cleanup. Missing accounts diff --git a/docs/launchpad-development.md b/docs/launchpad-development.md index 7e45c2ea9..56d59d24f 100644 --- a/docs/launchpad-development.md +++ b/docs/launchpad-development.md @@ -1264,7 +1264,7 @@ JSON, `NODE_PATH`, `NODE_ENV=development`, the runtime and Organization identity loopback origin of each sibling module of its Organization it declares (`LAZURIO_RUNTIME_SIBLING__ORIGIN`, F26 addendum of 2026-10-10), the value of each runtime secret it declares, read from the Environment's own vault at this start -(`LAZURIO_RUNTIME_SECRET_`, F46 as F52 amends it; a required one without a value refuses the +(`LAZURIO_RUNTIME_SECRET_`, F46 as F53 amends it; a required one without a value refuses the start as `runtime-secret-unavailable`, an optional one is reported as `secretsNotProvided`), and on a hosted Machine, for the module's default app, the entrypoint's external origin @@ -1545,7 +1545,7 @@ characters escaped), Czech or English by the Folder's locale. | product | `template-revision` | `observeFolder` facts | `warn folder-newer` (a newer product rendered it), `warn revision-unknown`; an older one is `folder-refresh` | | Folder | `folder-state` | `collectRecovery` Folder state; preset and Machine kind from `observeFolder` | `fail folder-state-pending`, `-absent`, `-unrecognized`, `-unreadable` | | Folder | `machine-binding` | recorded `preferences.machine` vs `machineBinding` of the live handover | `warn machine-identity-changed`, `warn handover-changed` (digest; `machine folder-refresh`), `warn binding-absent`, `warn handover-unreadable`; `skipped not-hosted` | -| tools | `tool` | `toolsOverview` (tiers, enabled), else `toolsStatus` over the catalog | required missing `fail required-missing`; `warn recommended-missing`, `warn enabled-missing`, `warn version-unreadable`; `skipped not-enabled`; `skipped not-offered` for a missing tool Lazurio does not offer in this Environment (`toolOffered`: bitwarden outside a Remote Environment on Linux, decisions F43 and F52; gogcli in a work Environment, F44); Executor is not a tool row but its own check; `signIn`/`ssh` ids with `--sign-in` | +| tools | `tool` | `toolsOverview` (tiers, enabled), else `toolsStatus` over the catalog | required missing `fail required-missing`; `warn recommended-missing`, `warn enabled-missing`, `warn version-unreadable`; `skipped not-enabled`; `skipped not-offered` for a missing tool Lazurio does not offer in this Environment (`toolOffered`: bitwarden outside a Remote Environment on Linux, decisions F43 and F53; gogcli in a work Environment, F44); Executor is not a tool row but its own check; `signIn`/`ssh` ids with `--sign-in` | | tools | `executor` | `executorStatus` ([F44](decisions.md#f44--executor-in-every-remote-environment-installed-run-and-connected-to-the-agents-by-lazurio)): the entry and its marker, `systemctl --user show` of `sh.executor.daemon.service` and its drop-in, `GET 127.0.0.1:4789/api/health`, `codex mcp get executor --json` and `~/.claude.json`; never `fail`, never in `recover` | `ok` running with the installed agents connected (context `toolVersion`, `executorService`, `codexMcp`, `claudeMcp`); `warn executor-not-installed`, `executor-outdated`, `executor-conflict`, `executor-not-running`, `executor-incomplete` (the next step is `lazurio executor setup`, or Settings → Tools → executor); `skipped not-offered` (a computer, not the operator), `skipped handover-unreadable` | | organizations | `catalog` | `readFolderCatalog` | counts of the Organizations and their modules only: the Personalspace group is never counted or named; `warn catalog-unreadable` | | organizations | `organization` | catalog entry | `warn` with the Organization reason; a template `skipped template-not-runtime` | @@ -2030,7 +2030,7 @@ the tool forgot the sign-in on this Machine only (gh, composio) or unlinked the (wacli). An SSH outcome is taken only in its exact form (known reasons, a `SHA256:` fingerprint, no key content). -**The Environment's own vault** (decision F52, the wireframe of +**The Environment's own vault** (decision F53, the wireframe of prototypes-lazurio#33; it replaces F43's dialog). The Environment sets its vault up itself: the installed Launchpad runs the one setup of `/api/tools/bitwarden/setup` in the background after its start where the vault needs it (`vaultAtStart`, the rule of @@ -2051,7 +2051,7 @@ vault on: "Nastavit" when nothing set it up yet and "Zkusit znovu" after a setup stopped, a vault that did not answer or a creation not confirmed yet. A vault the network has not allowed or has revoked, and a 0197 pilot, offer none; there is no dialog, no details section and no disconnect. The setup in which the vault becomes ready turns the agents' switch on in the -Folder itself, once per vault (decision F52), so a person who turns it off keeps it off; +Folder itself, once per vault (decision F53), so a person who turns it off keeps it off; the page never turns it on, and after a setup it followed that ends connected it reads the Folder again to show it. The state is accepted only in its exact form (`src/launchpad/vault-view.ts`, `tests/vault-view.test.ts`); the DOM is diff --git a/docs/machine-handover.md b/docs/machine-handover.md index 8ba919870..caf5a5fae 100644 --- a/docs/machine-handover.md +++ b/docs/machine-handover.md @@ -14,7 +14,7 @@ JSON Schema is vendored in `src/machine/lazurio-machine.v1.schema.json` from Machines **v0.12.159** (tag commit `8b66889bf4e00b111027f9b280423f4b9cdfcf4e`, the merge of pull request **#500**; SHA-256 `76a058045be25b718caed8a04e533d67fa8666945bfa4fa0153d618bc4d78957`), which adds only -the optional top-level member `vault` ([below](#the-environments-own-vault-decision-f52), +the optional top-level member `vault` ([below](#the-environments-own-vault-decision-f53), DEV-6631 contract C2) and changes nothing else. Before it, the pin was the merge of Machines pull request **#449** into `main` (commit `30c2fcf8a77914b5a44c652265e927683b2b413c`, SHA-256 @@ -457,7 +457,7 @@ resident keeps the Launchpad port, and the recorded entry serves the CLI's modul links and `lazurio doctor`. Until a Machines release writes it, no Folder records an entry and the Launchpad stays local. -## The Environment's own vault (decision F52) +## The Environment's own vault (decision F53) Root decision 0198 point 1, DEV-6631 contract C2: the handover may carry, on both branches, the optional and closed top-level member diff --git a/docs/module-adoption.md b/docs/module-adoption.md index 1427b756e..419d41269 100644 --- a/docs/module-adoption.md +++ b/docs/module-adoption.md @@ -341,7 +341,7 @@ only, never values: ``` Before every start the value of each is read from the Environment's own vault (F43, -F52): a sync, then the login password of the one item named exactly so anywhere in +F53): a sync, then the login password of the one item named exactly so anywhere in that vault. On a work Environment only an application of the Organization that owns it reads it, on a personal Environment only a Personalspace module; another mounted Organization's application, a Personalspace module on a work Environment and an diff --git a/docs/public-development.md b/docs/public-development.md index f37fddda8..9cef433ef 100644 --- a/docs/public-development.md +++ b/docs/public-development.md @@ -11,7 +11,7 @@ Use obvious placeholders such as ``; avoid realistic example tokens. Credential access remains with existing OS/provider/harness custody. Platform stores neither a new secret database nor copies of session credentials. The one exception is the Environment vault's own account (decisions F43 and -F52): the Platform registers that account, so it writes the account's generated +F53): the Platform registers that account, so it writes the account's generated master password, its API key and its one Bitwarden CLI session itself, owner-only, beside the CLI's store on that Environment and nowhere else; the key of the Environment's own vault exists only in memory while the vault is diff --git a/docs/recovery.md b/docs/recovery.md index d70000413..8d03fb007 100644 --- a/docs/recovery.md +++ b/docs/recovery.md @@ -177,7 +177,7 @@ Per line, in this order: nothing else of those files is read), the Machine binding the Folder records and the Machine handover (Machine, Owner, Team, assignment login and id, tailnet node, host, custody repository, peers and their hosts, the hosted entry's hostnames, and the - own vault's account, name and host, decision F52). + own vault's account, name and host, decision F53). 4. A long run (32 or more of `[A-Za-z0-9+/_=-]`) withholds the line unless it is exactly a 40- or 64-character lowercase hex digest that is either the running or active executable's commit or directly follows a label the product prints diff --git a/src/cli.ts b/src/cli.ts index df8750c4e..2e46ac9d5 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -119,7 +119,7 @@ function emit(output: CommandOutput): number { // and serves the update pill on the same update core and service the CLI uses. // Where install and update only report Executor, it sets Executor up after // it starts (decision F44, addendum of 2026-10-11), and the Environment's own -// vault where it needs it (decision F52). +// vault where it needs it (decision F53). async function installedLaunchpad(explicitBase: string, folder: string) { const context = processContext(); const base = installBase(context, explicitBase); @@ -317,7 +317,7 @@ async function runOtherCommand(args: string[]): Promise { // its view. if (args[0] === "browser") return emit(await runBrowserCommand(args.slice(1), processContext())); - // The Environment's vault (decisions F43, F52): `vault env` prints the + // The Environment's vault (decisions F43, F53): `vault env` prints the // shell exports alone on stdout, for `eval "$(lazurio vault env)"`; // setup's steps and every refusal go to stderr. if (args[0] === "vault") diff --git a/src/launchpad/server.ts b/src/launchpad/server.ts index 7c70db344..23dc73095 100644 --- a/src/launchpad/server.ts +++ b/src/launchpad/server.ts @@ -403,7 +403,7 @@ export async function startLaunchpad( * Absent: it never does. */ executorAtStart?: (() => Promise) | undefined; /** Whether this Launchpad sets the Environment's own vault up after it - * starts (decision F52): the same rule as Executor's + * starts (decision F53): the same rule as Executor's * (`vaultAtStart`). Absent: it never does. */ vaultAtStart?: (() => Promise) | undefined; }>, @@ -450,7 +450,7 @@ export async function startLaunchpad( openWindow: (session: string) => ensureThreadWindow(session, undefined, cdpSeams(process.env, runProcess)), }), - // Where the Environment's vault runs (decisions F43, F52): this process's + // Where the Environment's vault runs (decisions F43, F53): this process's // home and the handover, for the Folder this Launchpad serves. Trusted // composition, never HTTP input; tests supply a fake vault and a fake bw. vaultHost?: VaultHost | undefined, @@ -558,7 +558,7 @@ export async function startLaunchpad( }; // The Files page (decision F35): the Operator's Documents folder. const files = createFilesRoutes({ host: documentsHost, headers }); - // The Environment's vault (decisions F43, F52): its routes journal the + // The Environment's vault (decisions F43, F53): its routes journal the // operation, the outcome and a fixed reason, never a value. const vaultJournal = (entry: object) => console.log(JSON.stringify({ scope: "tools-vault", ...entry })); @@ -573,7 +573,7 @@ export async function startLaunchpad( }) : undefined; // The setup in which the vault becomes ready turns the agents' switch on - // in this Launchpad's Folder (decision F52): the default host does so + // in this Launchpad's Folder (decision F53): the default host does so // already, a given one gets it here. const vault = createVaultRoutes({ host: () => @@ -1520,7 +1520,7 @@ export async function startLaunchpad( ); } if (vault.handles(url.pathname)) { - // The Environment's vault (decisions F43, F52): `{}`, or a setup's + // The Environment's vault (decisions F43, F53): `{}`, or a setup's // `{job}`; a setup answers within a second and goes on // (vault-routes.ts). const withJob = @@ -1896,7 +1896,7 @@ export async function startLaunchpad( void (async () => { if ((await executorAtStart()) && !closing) await executor.atStart(); })().catch(() => undefined); - // The Environment's own vault (decision F52), by the same pattern: where + // The Environment's own vault (decision F53), by the same pattern: where // the vault needs it, the one setup of Settings → Tools runs in the // background once the Launchpad listens; never awaited, never a reason for // the start to fail, one attempt per start. diff --git a/src/launchpad/tools-panel.ts b/src/launchpad/tools-panel.ts index 8b62c43a0..ad8580e3f 100644 --- a/src/launchpad/tools-panel.ts +++ b/src/launchpad/tools-panel.ts @@ -101,7 +101,7 @@ export function createToolsPanel( const loginStatus = find("#tools-login-status"); const loginBody = find("#tools-login-body"); const loginClose = find("#tools-login-close"); - // The Environment's own vault (decision F52): its own state, read beside + // The Environment's own vault (decision F53): its own state, read beside // the tools; the Environment sets it up itself, and the setup in which the // vault becomes ready turns the agents' switch on in the Folder, once per // vault (never this page, so a person's "off" stays). A setup this page @@ -1071,7 +1071,7 @@ export function createToolsPanel( notice !== null && notice.name === tool.name ? notice : null; const said = recorded === null ? null : toolNoticeView(recorded, tool, copy); - // The Environment's vault (decision F52) and Executor (F44) say their + // The Environment's vault (decision F53) and Executor (F44) say their // own state and offer their own steps: an account of the Environment and // a service Lazurio runs, not a person's sign-in. const vaultRow = diff --git a/src/launchpad/vault-panel.ts b/src/launchpad/vault-panel.ts index e08195c31..9a3416502 100644 --- a/src/launchpad/vault-panel.ts +++ b/src/launchpad/vault-panel.ts @@ -17,7 +17,7 @@ type Post = ( body: unknown, ) => Promise<{ value: unknown; ok: boolean }>; -// The Environment's own vault on the tools screen (decision F52, the +// The Environment's own vault on the tools screen (decision F53, the // wireframe of prototypes-lazurio#33): the row says the state, opens the // vault ("Otevřít trezor") once it is connected, and offers one action only // where a setup can move it on. The Environment sets the vault up itself, at @@ -34,7 +34,7 @@ export function createVaultPanel( changed: () => void; /** A setup this page followed ended connected: the page reads the * Folder again (the setup in which the vault became ready turned the - * agents' switch on there, decision F52). */ + * agents' switch on there, decision F53). */ connected: () => void; }>, ) { diff --git a/src/launchpad/vault-routes.ts b/src/launchpad/vault-routes.ts index 24da5fdfd..8bbfa7a4d 100644 --- a/src/launchpad/vault-routes.ts +++ b/src/launchpad/vault-routes.ts @@ -9,7 +9,7 @@ import { vaultStatus, } from "../vault/flow"; -// The Environment's own vault in the Launchpad (decisions F43, F52): Settings +// The Environment's own vault in the Launchpad (decisions F43, F53): Settings // → Tools → bitwarden over the same core as `lazurio vault`. Three routes // behind the admission of every route: // diff --git a/src/launchpad/vault-view.ts b/src/launchpad/vault-view.ts index 1d6fd21ff..1326c6ba4 100644 --- a/src/launchpad/vault-view.ts +++ b/src/launchpad/vault-view.ts @@ -2,7 +2,7 @@ import type { VaultUnsupportedReason } from "../vault/context"; import type { VaultPhase, VaultStatus } from "../vault/flow"; import type { MessageKey } from "./messages"; -// The Environment's own vault on the tools screen (decision F52, the +// The Environment's own vault on the tools screen (decision F53, the // wireframe of prototypes-lazurio#33): the row says the state and opens the // vault; the Environment sets the vault up itself. Pure, so it is testable // without a DOM. The server's answers are accepted only in their exact form; diff --git a/src/modules/runtime-secrets.ts b/src/modules/runtime-secrets.ts index 162933529..964a39a94 100644 --- a/src/modules/runtime-secrets.ts +++ b/src/modules/runtime-secrets.ts @@ -11,7 +11,7 @@ import { // The secrets an application declares in `lazurio.runtime` (root decision // 0177, decision F46): its required `secrets` and its `optional_secrets` // (root decision 0196, the Environment ceiling), names only. Before every -// start their values are read from the Environment's own vault (decision F52) +// start their values are read from the Environment's own vault (decision F53) // and passed to the application's own process as // `LAZURIO_RUNTIME_SECRET_`, and to no other process. Which // applications may read it is the vault's rule (flow.ts): on a work @@ -94,7 +94,7 @@ type Declaration = Readonly<{ type Input = Readonly<{ runtime: Declaration; /** A Personalspace module: the vault decides whether it reads (decision - * F52 point 4: on its person's personal Environment). */ + * F53 point 4: on its person's personal Environment). */ personalspace: boolean; /** None where no vault is composed: as an Environment without one. */ source?: RuntimeSecretSource | undefined; @@ -217,7 +217,7 @@ export type SecretEnvironment = /** The catalog's answer for an app's declared secrets, known without the * vault's items and without running anything, by the vault's rule (decision - * F52 point 4): a work Environment serves the apps of the Organization that + * F53 point 4): a work Environment serves the apps of the Organization that * owns it, a personal one the Personalspace's. A required secret the vault * cannot give this app refuses its start (`runtime-secret-unavailable`, as * a preparation finding: the running app is still read and stopped); an diff --git a/src/organizations/catalog.ts b/src/organizations/catalog.ts index 59de62b4a..9b45d834b 100644 --- a/src/organizations/catalog.ts +++ b/src/organizations/catalog.ts @@ -690,7 +690,7 @@ async function readCatalogPersonalspace( folder: string, holder: PersonalspaceHolderRead, /** What the Folder records of the Environment, for the declared secrets - * (decision F46 as F52 amends it). */ + * (decision F46 as F53 amends it). */ environment: () => Promise, ): Promise { const decided = await holder(folder).catch(() => ({ @@ -747,7 +747,7 @@ async function readCatalogPersonalspace( moduleDirectory, space, // A Personalspace module: the personal Environment's vault serves it - // (decision F52 point 4), no other. + // (decision F53 point 4), no other. (runtime) => declaredSecretsFinding(runtime, true, environment), ); const { reason, file, preparationRefused } = own; diff --git a/src/recover/private-values.ts b/src/recover/private-values.ts index 048837b7e..b9a60310a 100644 --- a/src/recover/private-values.ts +++ b/src/recover/private-values.ts @@ -226,7 +226,7 @@ export function contextValues(context: MachineContext | null): PrivateValue[] { ...value("tailnet-node", network?.headscale_hostname), ...peerValues(context.relationships?.peers), ...repositoryValues(installed.machines_release.repository), - // The Environment's own vault (decision F52): its technical account (a + // The Environment's own vault (decision F53): its technical account (a // one-time enrollment capability before it registers, contract C2), the // vault's name and the network vault's host. ...value("vault-account", vault?.account), diff --git a/src/tools/catalog.ts b/src/tools/catalog.ts index 21b0c503f..445dede92 100644 --- a/src/tools/catalog.ts +++ b/src/tools/catalog.ts @@ -318,7 +318,7 @@ export const toolCatalog: readonly ToolEntry[] = Object.freeze([ ), }, }), - // The Environment's own vault (decisions F43 and F52; root decisions 0193, + // The Environment's own vault (decisions F43 and F53; root decisions 0193, // 0197 and 0198): the Bitwarden CLI signed in to the Environment's // technical account, which owns the Environment's vault in its network's // Lazurio Vaultwarden; pinned per Platform release and set up by the @@ -465,7 +465,7 @@ export const toolCatalog: readonly ToolEntry[] = Object.freeze([ }), ]); -/** The Environment's vault's catalog tool (decisions F43, F52): set up by +/** The Environment's vault's catalog tool (decisions F43, F53): set up by * the Launchpad at its start and `lazurio vault setup`, not by the curated * install and sign-in of F19. */ export const vaultToolName = "bitwarden"; diff --git a/src/tools/curated-cli.ts b/src/tools/curated-cli.ts index ccd1ce6c2..7b27355e2 100644 --- a/src/tools/curated-cli.ts +++ b/src/tools/curated-cli.ts @@ -131,7 +131,7 @@ export function refuseTool( : `Unknown tool ${name}; the catalog offers: ${known.join(", ")}`, }; } - // The Environment's vault has its own flow (decisions F43, F52): no + // The Environment's vault has its own flow (decisions F43, F53): no // sign-in of a person, the Environment's own account and vault. if (name === vaultToolName) { const result = { diff --git a/src/update/cli.ts b/src/update/cli.ts index db3beca5c..851fcc9de 100644 --- a/src/update/cli.ts +++ b/src/update/cli.ts @@ -273,7 +273,7 @@ export const executorAtStart = })) === "hosted"; /** Whether the Launchpad of this base sets the Environment's own vault up - * after it starts (decision F52): exactly where it sets Executor up + * after it starts (decision F53): exactly where it sets Executor up * (`executorAtStart`), a supervised base for the hosted operator; the vault * itself then decides whether it needs a setup. */ export const vaultAtStart = executorAtStart; diff --git a/src/vault/bw.ts b/src/vault/bw.ts index 6aed9d6a1..34c7a1ca3 100644 --- a/src/vault/bw.ts +++ b/src/vault/bw.ts @@ -5,7 +5,7 @@ import { parseUniqueJson } from "../providers/unique-json"; import type { ToolProcessResult, ToolRunner } from "../tools/status"; import { isSession, isVaultId } from "./store"; -// The Bitwarden CLI of one Environment vault account (decisions F43, F52), driven +// The Bitwarden CLI of one Environment vault account (decisions F43, F53), driven // by the core and never by a person: always the pinned binary, always with // the account's own BITWARDENCLI_APPDATA_DIR (bw rewrites its data file on // every start, so no run may reach another profile), never interactive. A diff --git a/src/vault/cli.ts b/src/vault/cli.ts index e15b9e783..9bdd240b0 100644 --- a/src/vault/cli.ts +++ b/src/vault/cli.ts @@ -17,7 +17,7 @@ import { import { processVaultHost } from "./host"; /** `lazurio vault`: the Environment's own vault for agents (decisions F43, - * F52). The same core as the Launchpad's Settings → Tools → bitwarden and its + * F53). The same core as the Launchpad's Settings → Tools → bitwarden and its * start. */ export const vaultHelp = `vault env [--json] This Environment's vault for this shell: prints shell exports of diff --git a/src/vault/context.ts b/src/vault/context.ts index dbb8903c2..b4cbf77af 100644 --- a/src/vault/context.ts +++ b/src/vault/context.ts @@ -1,7 +1,7 @@ import { isAbsolute, join } from "node:path"; import type { MachineContext } from "../machine/context"; -// The Environment's own vault (root decision 0198, decision F52): which +// The Environment's own vault (root decision 0198, decision F53): which // network vault this Environment's technical account lives in, what the // account is called and what its vault is named, all as the root-issued // handover's `vault` member says (DEV-6631 contract C2). Nothing is derived @@ -27,7 +27,7 @@ export type VaultContext = Readonly<{ environment: VaultEnvironmentKind; /** The Organization that owns a work Environment (`owner.organization`, a * lowercase slug); null for a personal Environment, which a person owns. - * It decides which applications read runtime secrets (decision F46 as F52 + * It decides which applications read runtime secrets (decision F46 as F53 * amends it). */ organization: string | null; }>; diff --git a/src/vault/flow.ts b/src/vault/flow.ts index 2ec4b549f..62cc50a37 100644 --- a/src/vault/flow.ts +++ b/src/vault/flow.ts @@ -81,7 +81,7 @@ export type { VaultStatus, } from "./status"; -// The Environment's own vault (root decision 0198, decision F52): one core +// The Environment's own vault (root decision 0198, decision F53): one core // for the CLI (`lazurio vault`) and the Launchpad (Settings → Tools → // bitwarden, and its start). Each Environment's technical account, which the // network pre-allowed and the handover names, registers itself, creates the @@ -117,7 +117,7 @@ export type VaultHost = Readonly<{ download?: InstallFetch | undefined; pin?: BitwardenPin | undefined; journal?: ((entry: VaultJournalEntry) => void) | undefined; - /** "Používají agenti" on for the vault (decision F52): called once per + /** "Používají agenti" on for the vault (decision F53): called once per * vault, after the setup in which it became ready (its collection Agenti * recorded), and never by a later setup, so a person who turns the switch * off keeps it off. A failure is journaled and is never the setup's. */ @@ -540,7 +540,7 @@ async function signIn( } /** The vault became ready in this setup: "Používají agenti" on for it, by - * the composition (decision F52), after the account's lock is released. Best + * the composition (decision F53), after the account's lock is released. Best * effort: a failure is journaled and is never the setup's, and the switch * stays where it is for a person to turn. */ async function turnAgentsOn(host: VaultHost): Promise { diff --git a/src/vault/host.ts b/src/vault/host.ts index 1c1c3c162..82be30a26 100644 --- a/src/vault/host.ts +++ b/src/vault/host.ts @@ -29,7 +29,7 @@ import { import type { VaultHost, VaultJournalEntry } from "./flow"; import { type PilotContext, pilotContextOf } from "./legacy-0197/context"; -// The production composition of the Environment vault (decisions F43, F52): +// The production composition of the Environment vault (decisions F43, F53): // the facts of this Remote Environment from its root-issued handover, read // anew for every operation, and the kind of the Environment from its Folder. // Only the handover's declared operator, in a hosted Folder on Linux, has a @@ -103,7 +103,7 @@ export async function readVaultContext( } /** "Používají agenti" on for the vault in one Folder, at its current - * revision (decision F52): the change the switch itself makes, refused as + * revision (decision F53): the change the switch itself makes, refused as * the switch is where this Environment does not offer the vault or its * Organization does not allow it. A Folder that another change holds or * changed meanwhile is read again, as the Organization's settings are diff --git a/src/vault/legacy-0197/README.md b/src/vault/legacy-0197/README.md index 98848695f..55c85dcd9 100644 --- a/src/vault/legacy-0197/README.md +++ b/src/vault/legacy-0197/README.md @@ -1,6 +1,6 @@ # Frozen: the 0197 pilot vault, read only -Root decision 0198 gives every Environment its own vault (decision F52 in +Root decision 0198 gives every Environment its own vault (decision F53 in `docs/decisions.md`, the core in `../flow.ts`). A few Environments were connected earlier the 0197 way (decision F43): an account `vaultwarden@` that a person invited into a collection of their own organization, the collection diff --git a/src/vault/organization.ts b/src/vault/organization.ts index d4a8d6f71..d18139195 100644 --- a/src/vault/organization.ts +++ b/src/vault/organization.ts @@ -20,7 +20,7 @@ import { type VaultRecord, } from "./store"; -// The Environment's own vault (root decision 0198 point 1, decision F52): its +// The Environment's own vault (root decision 0198 point 1, decision F53): its // own organization in the network's Lazurio Vaultwarden, created by its // technical account, which is its only Owner, and remembered by ID; names // never decide what it is. bw cannot create an organization, so this asks @@ -31,7 +31,7 @@ import { // creation, then only in the vault, encrypted to the account's own key. /** The first collection of every Environment's vault, where agents keep - * what they create (decision F52). */ + * what they create (decision F53). */ export const agentsCollection = "Agenti"; /** A membership the vault reports as confirmed (status 2): the account holds diff --git a/src/vault/register.ts b/src/vault/register.ts index 5670b3c0e..8b46afed0 100644 --- a/src/vault/register.ts +++ b/src/vault/register.ts @@ -2,7 +2,7 @@ import { Buffer } from "node:buffer"; import { webcrypto } from "node:crypto"; // The technical account of an Environment in its network's vault (decisions -// F43 and F52): created here and signed in by its API key, so the stock +// F43 and F53): created here and signed in by its API key, so the stock // Bitwarden CLI can run `bw login --apikey` and `bw unlock --passwordfile`, // and the core can ask the vault's API as the account (`apiKeyLogin`, // organization.ts). Verified end to end against Vaultwarden 1.37.1 and 1.37.4 diff --git a/src/vault/session.ts b/src/vault/session.ts index e137b6083..3912bab4b 100644 --- a/src/vault/session.ts +++ b/src/vault/session.ts @@ -13,7 +13,7 @@ import { } from "./store"; // The one unlocked session of an account (decision F43 point 5, kept by -// F52): every `bw unlock` ends the sessions before it, so the Environment +// F53): every `bw unlock` ends the sessions before it, so the Environment // keeps one and its agents share it. Used by the Environment's own vault and // by the frozen 0197 pilot subset alike; nothing here decides which vault an // Environment has. diff --git a/src/vault/status.ts b/src/vault/status.ts index 03c67ecdf..e5e273d2c 100644 --- a/src/vault/status.ts +++ b/src/vault/status.ts @@ -1,7 +1,7 @@ import type { VaultUnsupportedReason } from "./context"; import { readAccount, type VaultAccount, type VaultPaths } from "./store"; -// What the vault core answers (decisions F43, F46 and F52): the status of an +// What the vault core answers (decisions F43, F46 and F53): the status of an // Environment's vault, what an agent's shell gets and what a start's secrets // are, for the own vault (flow.ts) and the frozen 0197 pilot subset // (legacy-0197/) alike. Never a secret but the session `env` hands out and @@ -156,7 +156,7 @@ export async function accountOf( } /** Why no runtime secret of an application can be read from the - * Environment's vault (decision F46 as F52 amends it): a fixed code, never + * Environment's vault (decision F46 as F53 amends it): a fixed code, never * bw's output. */ export type VaultSecretsRefusal = /** This computer: no vault yet (the second wave of 0193). */ diff --git a/src/vault/store.ts b/src/vault/store.ts index 802695a45..b2d4ea537 100644 --- a/src/vault/store.ts +++ b/src/vault/store.ts @@ -13,7 +13,7 @@ import { acquireFileLock, type FileLock } from "../platform/flock"; import { parseUniqueJson } from "../providers/unique-json"; import { syncDirectory, writeDurableFile } from "../update/durable-file"; -// The custody of one Environment vault account (decisions F43 and F52): the +// The custody of one Environment vault account (decisions F43 and F53): the // files the account needs on this Environment and nothing else, written by // Lazurio beside bw's own store in the data directory it gives bw, owner-only, // in a directory keyed by the vault and the account (context.ts): @@ -246,7 +246,7 @@ export async function writeSession( await writeDurableFile(paths.data, "lazurio-session", Buffer.from(session)); } -/** The Environment's own vault (decision F52), not secret: its organization +/** The Environment's own vault (decision F53), not secret: its organization * and its first collection, Agenti, by ID, which is the vault's whole * identity (names never are). `pendingKey` is the receipt of a creation * under way: the new organization's public key, written before it is diff --git a/tests/fixtures/fake-vault.ts b/tests/fixtures/fake-vault.ts index d7d4a0712..93b994a91 100644 --- a/tests/fixtures/fake-vault.ts +++ b/tests/fixtures/fake-vault.ts @@ -20,7 +20,7 @@ import organization from "./machine-context.json"; import personal from "./machine-context-personal.json"; // A fake Vaultwarden and a fake Bitwarden CLI for the Environment's vault -// (decisions F43 and F52). Nothing here reaches a vendor or the network: the +// (decisions F43 and F53). Nothing here reaches a vendor or the network: the // vault is a Bun.serve on loopback behind an injected fetch, the CLI a shell // script that keeps its store in BITWARDENCLI_APPDATA_DIR and reads what the // vault would sync from `$HOME/bw-world`, which the fake vault and the tests diff --git a/tests/launchpad-vault.test.ts b/tests/launchpad-vault.test.ts index cd1d6101c..b12adee72 100644 --- a/tests/launchpad-vault.test.ts +++ b/tests/launchpad-vault.test.ts @@ -28,7 +28,7 @@ import { } from "./fixtures/fake-vault"; import { bindings } from "./fixtures/machine-bindings"; -// Settings → Tools → bitwarden over HTTP (decisions F43, F52): the three +// Settings → Tools → bitwarden over HTTP (decisions F43, F53): the three // routes behind the admission of every route, `{}` only, a setup answered // while it runs and joined by the next request, the Launchpad's own setup // after its start (the Executor pattern), and the curated routes of F19 diff --git a/tests/module-runtime-secrets.test.ts b/tests/module-runtime-secrets.test.ts index bba0a361f..e3c57eb35 100644 --- a/tests/module-runtime-secrets.test.ts +++ b/tests/module-runtime-secrets.test.ts @@ -40,7 +40,7 @@ import { } from "./fixtures/owned-files"; // The declared runtime secrets of an application, through the module -// operations the CLI and the Launchpad share (decision F46 as F52 amends it, +// operations the CLI and the Launchpad share (decision F46 as F53 amends it, // root decisions 0177, 0196 and 0198): read before every start, passed to the application's own // unit only, never as an argument of a process, never to the preparation's // check, never in an answer; a required one without a value refuses the diff --git a/tests/recover-sanitize.test.ts b/tests/recover-sanitize.test.ts index 1d7f59ed9..8432f0e39 100644 --- a/tests/recover-sanitize.test.ts +++ b/tests/recover-sanitize.test.ts @@ -62,7 +62,7 @@ function privateValue(random: Random, kind: PrivateKind): string { : `${random.word(1).toUpperCase()}${random.word(random.int(4, 10))}`; case "github-id": return String(random.int(100_000, 99_999_999)); - // The Environment's own vault (decision F52): its account and its name. + // The Environment's own vault (decision F53): its account and its name. case "vault-account": return `vaultwarden-${random.word(26, "abcdefghijklmnopqrstuvwxyz234567")}@${slug()}.lazurio.io`; case "vault-name": diff --git a/tests/runtime-secrets.test.ts b/tests/runtime-secrets.test.ts index 5cc6174f6..d6af430b5 100644 --- a/tests/runtime-secrets.test.ts +++ b/tests/runtime-secrets.test.ts @@ -14,7 +14,7 @@ import type { } from "../src/vault/flow"; // What an application's declared runtime secrets become at its start -// (decision F46 as F52 amends it, root decisions 0177 and 0196): the values +// (decision F46 as F53 amends it, root decisions 0177 and 0196): the values // of its required and optional names as `LAZURIO_RUNTIME_SECRET_`, a // refusal naming every required name without a value, and a note for the // optional ones it starts without. Which applications the vault serves is diff --git a/tests/vault-cli.test.ts b/tests/vault-cli.test.ts index 894d8fc14..ef1b18b50 100644 --- a/tests/vault-cli.test.ts +++ b/tests/vault-cli.test.ts @@ -38,7 +38,7 @@ import { zipOf, } from "./fixtures/fake-vault"; -// `lazurio vault` (decisions F43, F52): what an agent's shell gets, what it +// `lazurio vault` (decisions F43, F53): what an agent's shell gets, what it // reads when there is nothing to get, and the commands over the same core. const posix = process.platform !== "win32"; diff --git a/tests/vault-context.test.ts b/tests/vault-context.test.ts index d390331d4..695168a11 100644 --- a/tests/vault-context.test.ts +++ b/tests/vault-context.test.ts @@ -12,7 +12,7 @@ import { assignments, handoverEntry } from "./fixtures/machine-bindings"; import organization from "./fixtures/machine-context.json"; import personal from "./fixtures/machine-context-personal.json"; -// The Environment's vault facts (decision F52): everything from the +// The Environment's vault facts (decision F53): everything from the // handover's `vault` member, nothing derived or guessed; and the 0197 pilot's // facts, derived as F43 derived them, only where the handover names no // vault. Invented hosts only. diff --git a/tests/vault-flow.test.ts b/tests/vault-flow.test.ts index 3121b6da4..cb0b46d1b 100644 --- a/tests/vault-flow.test.ts +++ b/tests/vault-flow.test.ts @@ -42,7 +42,7 @@ import { zipOf, } from "./fixtures/fake-vault"; -// The Environment's own vault (root decision 0198, decision F52) through its +// The Environment's own vault (root decision 0198, decision F53) through its // one core: the account the handover names registers itself, creates the // Environment's own organization with the collection Agenti, keeps it by ID // and one shared session for its agents. Against the fake Vaultwarden and the diff --git a/tests/vault-handover.test.ts b/tests/vault-handover.test.ts index 462aaa586..e0b5b8283 100644 --- a/tests/vault-handover.test.ts +++ b/tests/vault-handover.test.ts @@ -18,7 +18,7 @@ import personal from "./fixtures/machine-context-personal.json"; // DEV-6631 contract C2: Machines writes the optional, closed member // `vault: {server_url, account, name}` into lazurio.machine.json on both // branches, only for a Platform release that reads it, and the Environment -// takes its own vault from it (decision F52). Invented hosts and names only. +// takes its own vault from it (decision F53). Invented hosts and names only. const bytes = (value: unknown) => Buffer.from(JSON.stringify(value)); const { team: _, ...withoutTeam } = organization.owner; diff --git a/tests/vault-host.test.ts b/tests/vault-host.test.ts index 3aa18b430..66002cf22 100644 --- a/tests/vault-host.test.ts +++ b/tests/vault-host.test.ts @@ -27,7 +27,7 @@ import organization from "./fixtures/machine-context.json"; import personal from "./fixtures/machine-context-personal.json"; // The production composition of the Environment vault's facts (decisions -// F43, F52) on real files: a root-issued handover and a hosted Folder under a +// F43, F53) on real files: a root-issued handover and a hosted Folder under a // private root, read as `lazurio vault` and the Launchpad read them. Only the // handover's place and the operator's system record are this test's. diff --git a/tests/vault-organization.test.ts b/tests/vault-organization.test.ts index 9afbbd461..49f37d342 100644 --- a/tests/vault-organization.test.ts +++ b/tests/vault-organization.test.ts @@ -28,7 +28,7 @@ import { zipOf, } from "./fixtures/fake-vault"; -// The Environment's own organization (decision F52, src/vault/organization.ts) +// The Environment's own organization (decision F53, src/vault/organization.ts) // as the vault keeps it: what the account sent can be opened by the account // alone, from its own master password down to the collection's name; and the // organization step never guesses which collection is Agenti. diff --git a/tests/vault-register.test.ts b/tests/vault-register.test.ts index c3b063093..139fe03fb 100644 --- a/tests/vault-register.test.ts +++ b/tests/vault-register.test.ts @@ -393,7 +393,7 @@ describe("the requests", () => { }); }); -// The Environment's own vault (decision F52): the account signs in with its +// The Environment's own vault (decision F53): the account signs in with its // API key, unlocks its own keys and asks the vault's API with any method. describe("the own vault's requests", () => { const ownEmail = "vaultwarden-ndbrmzvjpwxtt3q7m2e4fihgsa@example.lazurio.io"; diff --git a/tests/vault-secrets.test.ts b/tests/vault-secrets.test.ts index 3ab01dc1c..e60dc8f40 100644 --- a/tests/vault-secrets.test.ts +++ b/tests/vault-secrets.test.ts @@ -34,7 +34,7 @@ import { } from "./fixtures/fake-vault"; // The runtime secrets of an application from the Environment's own vault -// (decision F46 as F52 amends it, root decision 0177): a sync, then the one +// (decision F46 as F53 amends it, root decision 0177): a sync, then the one // item of each declared name anywhere in the vault, its login password the // value. A work Environment serves its owning Organization's applications, a // personal one the Personalspace's (0198 point 4). Against the fake diff --git a/tests/vault-store.test.ts b/tests/vault-store.test.ts index c9ee5ff35..f8ba7c746 100644 --- a/tests/vault-store.test.ts +++ b/tests/vault-store.test.ts @@ -37,7 +37,7 @@ import { } from "../src/vault/store"; import { ownAccount } from "./fixtures/fake-vault"; -// The custody of one Environment vault account (decisions F43, F52) and what +// The custody of one Environment vault account (decisions F43, F53) and what // is read from bw: exact shapes only, the password written once, the own // vault's record never guessed, nothing of an account file ever echoed. diff --git a/tests/vault-view.test.ts b/tests/vault-view.test.ts index 87b8c59c5..48d08ae0a 100644 --- a/tests/vault-view.test.ts +++ b/tests/vault-view.test.ts @@ -9,7 +9,7 @@ import { } from "../src/launchpad/vault-view"; import type { VaultStatus } from "../src/vault/flow"; -// The Environment's own vault on the tools screen (decision F52, the +// The Environment's own vault on the tools screen (decision F53, the // wireframe of prototypes-lazurio#33): the row's states, "Otevřít trezor", // the one action where a setup moves the vault on, and the server's answers // taken only in their exact form.