From a05163d7eb8ae7d6be0fd702022db9920b0ee172 Mon Sep 17 00:00:00 2001 From: Robert Lemke Date: Sun, 22 Nov 2026 15:20:22 +0100 Subject: [PATCH] Sign in with named profiles, one account each The CLI now keeps profiles instead of hosts: a profile has a name of its own and bundles a host, a token and the account it acted as. A command picks one with --profile or $MINKA_PROFILE, or by host with --host or $MINKA_HOST, else it uses the default profile. "profiles list", "rename", "remove" and "default" manage them, and "auth status" and "doctor" name the active profile and where the choice came from. Previously, the configuration held one token per host. Switching between organizations meant typing the full address, and two accounts on one host could not exist side by side. A host still works as a way to choose: it stands for its one profile, or for the default among several, and refuses to guess otherwise. A sign-out by host follows the same rule, so it never removes or revokes one of two accounts by chance. $MINKA_TOKEN keeps going only to $MINKA_HOST and never to a named profile, which may be another account on the same host; a notice says when it was passed over. An existing file is taken over on load: every host becomes a profile named after it, and the default host the default profile. A plain read never rewrites it. When this version saves, it writes the hosts and the default host beside the profiles, so an older minka still signs in. An older minka that writes the file drops the profiles, though. The next read then takes its hosts over again, so no sign-in is lost, but the profile names and any second account on a host are. The cards of "work start" are kept per account now, so two accounts on one host do not report each other's cards. A store kept per host goes to the profile its host stands for, and the store keeps per host the lists of that profile beside the accounts, for an older minka. Removing a profile drops its lists, so that a later profile of the same name on another host never reports them with its token. Lists that a failed move or drop leaves under a name no profile has are passed over, and a new profile clears its name in the store before it is saved. Nothing deletes them merely because the configuration lacks the name, since a command may read the configuration in the middle of a rename. The heartbeat runs from the mod with the environment Claude Code was started with, so it reports every account that holds a list of its session, each with its own token, rather than only the default one. The read marks of comments and the positions of notifications were already kept per token and stay as they are. Resolves: https://minka.flownative.com/go/card/MNK-TP --- docs/README.md | 5 + docs/decisions.md | 117 +++- docs/stable/at-work.md | 8 +- docs/stable/first-steps.md | 21 +- docs/stable/profiles.md | 166 +++++ docs/stable/security.md | 94 +-- docs/work-in-progress/status.md | 21 +- internal/cli/archive_test.go | 2 +- internal/cli/auth.go | 477 ++++++++----- internal/cli/cards.go | 6 +- internal/cli/cli_test.go | 118 +--- internal/cli/defaulthost_test.go | 49 +- internal/cli/doctor.go | 42 +- internal/cli/logout_test.go | 27 +- internal/cli/output.go | 11 + internal/cli/profiles.go | 459 ++++++++++++ internal/cli/profiles_test.go | 655 ++++++++++++++++++ internal/cli/root.go | 192 ++--- internal/cli/settings.go | 36 +- internal/cli/setup.go | 60 +- internal/cli/work.go | 225 +++--- internal/cli/work_sessions_test.go | 2 +- internal/cli/work_store_test.go | 12 +- internal/cli/work_test.go | 6 +- internal/cli/workaccounts.go | 124 ++++ internal/config/config.go | 54 +- internal/config/config_test.go | 38 +- internal/config/profiles.go | 316 +++++++++ internal/config/profiles_test.go | 221 ++++++ internal/work/accounts_test.go | 50 ++ internal/work/store.go | 170 ++++- internal/work/store_test.go | 16 +- internal/work/store_unix_test.go | 4 +- skills/minka/SKILL.md | 62 +- skills/minka/references/work-and-heartbeat.md | 7 + 35 files changed, 3095 insertions(+), 778 deletions(-) create mode 100644 docs/stable/profiles.md create mode 100644 internal/cli/profiles.go create mode 100644 internal/cli/profiles_test.go create mode 100644 internal/cli/workaccounts.go create mode 100644 internal/config/profiles.go create mode 100644 internal/config/profiles_test.go create mode 100644 internal/work/accounts_test.go diff --git a/docs/README.md b/docs/README.md index e6a5b19..a5d0129 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,11 @@ the documentation says what holds; how it came about is in git. sent and revoked on signing out, how a host name is read whoever wrote it, what is fixed about the HTTP client, which check happens before a request — before any work on sign-in, client or IDs. +- [Profiles](stable/profiles.md): What a profile is and how it is named, which + one a command uses and why, `$MINKA_TOKEN` beside a profile, the default, + the file that older versions still read and what becomes of one they wrote, + the cards of `work start` per account and the heartbeat over all of them — + before any work on sign-in, `profiles`, the configuration file or the store. - [Rich text in both directions](stable/rich-text.md): Markdown to HTML and back, the allowlist of the server, the shapes of a document, sources, files, mentions and references to other records — before any diff --git a/docs/decisions.md b/docs/decisions.md index 2a0c25e..37bbfd6 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -594,10 +594,11 @@ keep a card alight for a working day with nobody left to stop it. *Applies to: `--host`, `$MINKA_HOST`, the default host of the configuration* -A value that names no machine is refused, and a default host the CLI cannot read -is refused where it is read, so that no session comes about under it. Signing out -is the one command that takes an entry as the file writes it, so that one written -by hand can be taken out again. +A value that names no machine is refused, and the host of a profile the CLI cannot +read is refused where it is read, so that no session comes about under it. +Signing out is the one command that takes a profile without reading its host, +so that one written by hand can be taken out again; a `--host` that can be read +chooses as C-192 says. **Why:** Such a value would become a key of the configuration and of the list of cards, and a session under it would carry it into everything that prints a @@ -2746,32 +2747,34 @@ beforehand it refuses beforehand. **Implemented as:** `cli.labelsForNewDecisions *Applies to: `auth login`, `setup`* -`auth login` sets the default host only where there is none or none that can -be read; `--make-default` or `config set host` move it, and `setup` makes its -host the default. **Why:** every session on the machine shares the default, so -one agent's sign-in to a local instance must not send the others there. -**Implemented as:** `cli.signIn`, see [Token, hosts and -requests](stable/security.md#the-default-host). +`auth login` sets the default profile only where there is none or none that +can be used; `--make-default`, `profiles default` or `config set host` move it, +and `setup` makes its profile the default. **Why:** every session on the +machine shares the default, so one agent's sign-in to a local instance must not +send the others there. +**Implemented as:** `cli.signIn`, see [Profiles](stable/profiles.md#the-default). -## C-180 — `config set host` takes only a host signed in to +## C-180 — `config set host` takes only a host with one profile *Applies to: `config set host`, `config get host`* -The value is read like a sign-in's host; one without a token is exit 1 -(`usage`) naming `auth login`, and there is no `config unset`. **Why:** a -default without a token would fail every later command, far from its cause. +The value is read like a sign-in's host and makes the one profile on it the +default; none is exit 1 (`usage`) naming `auth login`, several are exit 8 +naming `profiles default`, and there is no `config unset`. **Why:** a default +without a token would fail every later command, far from its cause, and of two +accounts on one host none is to be guessed. **Implemented as:** `cli.setDefaultHost`. -## C-181 — Signing out of the default host leaves no default +## C-181 — Removing the default profile leaves no default -*Applies to: `auth logout`, every command without a host* +*Applies to: `auth logout`, `profiles remove`, every command without a profile* -No remaining host takes its place; a `notice` says so, and a command without a -host exits 3 with `no default host is set`. **Why:** a host left over is -nobody's choice, and picking one would move the default silently. -**Implemented as:** `config.File.RemoveHost`, `cli.noHostError`. +No remaining profile takes its place; a `notice` says so, and a command without +a profile exits 3 with `no default profile is set`. **Why:** a profile left over +is nobody's choice, and picking one would move the default silently. +**Implemented as:** `config.File.RemoveProfile`, `cli.noAccountError`. ## C-182 — A step is a text, a card or a to-do, decided before any request @@ -2877,3 +2880,77 @@ with it names, per command, what may not be there. **Why:** a hint that the project is missing would tell a member they are none, as for `projects edit` (C-093). **Implemented as:** `cli.setupRefusal`, see [Projects](stable/projects.md#refusals). + + +## C-191 — A profile is one account, under a name of its own + +*Applies to: the configuration file, `--profile`, `profiles …`* + +A profile bundles a host, a token and the account it acted as; several may +share a host. Names are lower case letters, digits, `-` and `.`, start with a +letter or a digit, at most 64 characters; one made without a name is named +after its host. **Why:** switching organizations by a short word, and a name +that never reads as a host can share a key with one. +**Implemented as:** `config.Profile`, `config.CheckProfileName`, see +[Profiles](stable/profiles.md). + + +## C-192 — `--profile`, `--host`, `$MINKA_PROFILE`, `$MINKA_HOST`, the default + +*Applies to: every command that signs in* + +Strongest first, a flag before any variable; both flags together are exit 1. A +host stands for its one profile, or for the default among several; otherwise +exit 8 naming them. An unknown profile is exit 1 listing the profiles. +**Why:** which account writes in an organization is never to be guessed. +**Implemented as:** `cli.chooseAccount`, `cli.chooseIn`, see +[Profiles](stable/profiles.md#which-profile-a-command-uses). + + +## C-193 — `$MINKA_TOKEN` goes to `$MINKA_HOST`, never to a profile + +*Applies to: `$MINKA_TOKEN` beside `--profile` or `$MINKA_PROFILE`* + +The token of the environment signs in a command whose host comes from `--host` +or `$MINKA_HOST` and is that host; a profile named signs in with its own token, +even on that host, and a `notice` says the token was not used. **Why:** the token was given for a host, and a profile names +an account that may be another one there. +**Implemented as:** `cli.chooseAccount`, see +[Profiles](stable/profiles.md#which-profile-a-command-uses). + + +## C-194 — The file keeps the hosts for older versions beside the profiles + +*Applies to: `config.Load`, `config.File.Save`* + +A save writes `hosts` (per host the default profile on it, else the first by +name) and `defaultHost`. `profiles` holds where present, and a token under +`hosts` no profile on that host has is taken over; without `profiles`, every +host becomes a profile. A plain read never writes. **Why:** an older minka on +the same machine keeps working, and what it writes is not lost. +**Implemented as:** `config.onDisk`, see [Profiles](stable/profiles.md#the-configuration-file). + + +## C-195 — A profile keeps its host + +*Applies to: `auth login --profile`, `setup`* + +Signing an existing profile in with another `--host` is exit 1 naming +`profiles remove`; without `--host` it signs in on its own host. **Why:** a +script that names a profile must not find it writing in another organization. +**Implemented as:** `cli.profileOnHost`. + + +## C-196 — The cards at work are kept per account, and every account beats + +*Applies to: `work …`, `heartbeat`, `cards move`, `profiles rename`* + +The store keys a list by profile, or by host for the token of the environment, +and writes per host the lists of the profile the host carries. A rename moves +the lists and drops leftovers under the new name; a removal drops them. Lists +under a name no profile has are passed over, never deleted for it; a new +profile clears its name first or is refused. The heartbeat reports every +account with a list of its session, each with its own token. **Why:** no +account may report another's cards, and the mod knows nothing of profiles. +**Implemented as:** `work.File.Accounts`, `cli.beatEveryAccount`, see +[Profiles](stable/profiles.md#state-per-account). diff --git a/docs/stable/at-work.md b/docs/stable/at-work.md index f13ce86..c40b4e7 100644 --- a/docs/stable/at-work.md +++ b/docs/stable/at-work.md @@ -23,9 +23,11 @@ Only an agent may say so. A person's token is refused with `agentsOnly`. ## Every session has a list of its own The cards lie in `work.json` beside the configuration file, never in a project -and never in the directory a command was started in: one list per host and -session. A signal carries the list of one session and nothing else, under a -client of that session's own (C-103). The server keeps a card alight for as +and never in the directory a command was started in: one list per account and +session, an account being a profile, or a host signed in to through +`$MINKA_TOKEN` ([Profiles](profiles.md#state-per-account)). A signal carries +the list of one session and nothing else, under a client of that session's own +(C-103). The server keeps a card alight for as long as any client names it, so a session that reported the cards of another would keep them glowing after that one died — for hours, as long as anything else on the machine was at work. diff --git a/docs/stable/first-steps.md b/docs/stable/first-steps.md index 4f25d1d..50625d7 100644 --- a/docs/stable/first-steps.md +++ b/docs/stable/first-steps.md @@ -15,14 +15,17 @@ In this order: 1. The config file: one that cannot be read, or that others can read, ends setup before the first question. A token is shown once, and one that cannot be saved is lost. -2. The host: `--host` or `$MINKA_HOST` when given, else it asks. An empty - answer takes the default host; a host that cannot be used is asked for - again. -3. The sign-in: a saved token of this host that it still accepts is kept, and - the host becomes the default, whichever was before: unlike `auth login`, - setup is a person choosing the host of this machine ([Token, hosts and - requests](security.md#the-default-host)). Where that moves the default, - setup says so and `data.previousDefaultHost` names the one before. Only a +2. The profile and its host: a profile `--profile` or `$MINKA_PROFILE` names + that exists brings its host. Otherwise the host is `--host` or `$MINKA_HOST` + when given, else it asks; an empty answer takes the host of the default + profile, and a host that cannot be used is asked for again. The profile on + that host is found as `auth login` finds it ([Profiles](profiles.md#commands)). +3. The sign-in: a saved token of this profile that it still accepts is kept, + and the profile becomes the default, whichever was before: unlike `auth + login`, setup is a person choosing the host of this machine + ([Profiles](profiles.md#the-default)). Where that moves the default, setup + says so, and `data.previousDefaultHost` and `data.previousDefaultProfile` + name the one before. Only a host that refuses the saved token is a reason to ask for a new one; a host that does not answer ends setup with that error. Asking means pointing to the account page of the host, where a token for an agent is created, and taking the token without echo. The token @@ -50,7 +53,7 @@ is the setup, not the command; `data.healthy` is false when a check failed |---|---| | `version` | never; says which minka this is | | `config` | the config file cannot be read, or others can read it | -| `sign-in` | no host or token can be found: nobody is signed in, `$MINKA_TOKEN` stands without `$MINKA_HOST`, `--host` is no host. The hint names the step that needs no terminal first, then `setup`. Skipped when the config check failed. Its detail names the default host beside the host checked where the two differ, and `data.host` and `data.defaultHost` carry both | +| `sign-in` | no host or token can be found: nobody is signed in, `$MINKA_TOKEN` stands without `$MINKA_HOST`, `--host` is no host. The hint names the step that needs no terminal first, then `setup`. Skipped when the config check failed. Its detail names the profile and where the choice came from, and the default profile where it is another one; `data.profile`, `data.host`, `data.defaultProfile` and `data.defaultHost` carry them | | `host` | the host does not answer or refuses the token; carries the hint of that error | | `skill` | warns when none is installed or the installed one differs; a skill behind a symbolic link is fine | | `update` | warns when this minka is older than the minimum Minka named; a newer latest version is `ok` with the hint `brew upgrade minka`. Says that nothing is known yet, or that a build is no release and not compared (C-129) | diff --git a/docs/stable/profiles.md b/docs/stable/profiles.md new file mode 100644 index 0000000..4656a1d --- /dev/null +++ b/docs/stable/profiles.md @@ -0,0 +1,166 @@ +# Profiles + +A profile is one account in one organization: who (a human, an agent or a bot) +and where (the host). It has a name of its own choosing, and the configuration +file keeps per profile the host, the token and the account the token acted as +at sign-in (C-191). Several profiles may sign in to the same host: two +accounts in one organization. + +## Names + +Lower case letters, digits, `-` and `.`, starting with a letter or a digit, at +most 64 characters. Anything else is exit 1 (`usage`) with a hint. A name +never holds `:` or `/`, so it never reads as a host; the list of cards relies +on that (C-196). + +A profile made without a name, by `auth login --host ` on a host with no +profile yet or from a file of hosts (below), is named after its host: the host +without the scheme, a port joined with `-` (`127.0.0.1-8081`), and `-2`, `-3` +behind it where the name is taken. The name is made of the host as far as it +may be printed, so a password written into an address never becomes part of +it. + +## Which profile a command uses + +Strongest first (C-192): + +1. `--profile `, then `--host `; +2. `$MINKA_PROFILE`, then `$MINKA_HOST`; +3. the default profile. + +A flag outweighs every variable of the environment. `--profile` and `--host` +together are exit 1. A host stands for the one profile on it; where several +are, for the default profile if it is among them, and otherwise the command +exits 8 (`ambiguous`) and names them. A host without a profile is a host not +signed in to (exit 3). An unknown profile is exit 1, with the profiles in the +hint. A default profile that is not in the file, or whose host cannot be read, +is exit 1 (`config`), never "no default". + +`$MINKA_HOST` and `$MINKA_TOKEN` sign in without a configuration file. The +token belongs to `$MINKA_HOST`: it is used where the host of a command comes +from `--host` or `$MINKA_HOST` and is that host, and never where a profile is +named, even one on that very host (C-193); a `notice` then says that it was +not used. A profile is an account of its own, and the token of the environment +may be another one. + +`auth status` names the profile and where the choice came from: +`data.profile` (null for the token of the environment), `data.profileSource` +(`--profile`, `--host`, `$MINKA_PROFILE`, `$MINKA_HOST`, `default`) and +`data.defaultProfile`, beside the fields it had before: `data.host`, +`data.hostSource` (`flag`, `environment`, `profile`, `default`) and +`data.defaultHost`, the host of the default profile. `doctor` carries +`data.profile` and `data.defaultProfile` beside `data.host` and +`data.defaultHost`, and its sign-in check says the same in words. + +## Commands + +- `auth login [--profile ] [--host ]`: a new name makes a profile + and needs a host. An existing name signs that profile in again on its own + host; another `--host` is exit 1 naming `profiles remove`, because a profile + keeps its host (C-195). Here, and in `setup`, `--profile` and `--host` go + together. Without `--profile` a host with one profile signs that one in + again, a host with none gets a profile named after the host, and a host with + several is exit 8. `data` adds `profile` and `defaultProfile` to `host`, + `defaultHost` and `isDefault`, which now says whether the profile is the + default. +- `profiles list`: name, host, account, `isDefault`, `isActive`, and `active` + with the profile a command run here now uses and its source; null with the + token of the environment, with `activeProblem` where the choice fails. It + asks nothing of the network and prints no token. +- `profiles rename `: the default and the cards of `work start` go + along. Cards left in the list under the new name belong to no profile and are + dropped, never mixed in. +- `profiles remove [--revoke]`: as `auth logout`, for the profile named. + The cards it holds in the list of `work start` go with it. +- `profiles default `. +- `auth logout [--revoke]`: removes the profile a command uses, chosen as for + every command, so a host with several profiles and the default elsewhere is + exit 8 and removes and revokes nothing. Its host is not read first, and a + `--host` that cannot be read finds the one profile whose host is written + letter for letter like it, so that one written by hand in a form nothing can + read can be taken out again; see [Token, hosts and + requests](security.md#host-names). +- `config set host ` makes the one profile on that host the default; no + profile is exit 1, several are exit 8 naming `profiles default` (C-180). + `config get host` is the host of the default profile. + +## The default + +Every session on the machine shares the default profile, so it moves only when +somebody means it to (C-179): + +- `auth login` makes a profile the default only where there is none yet, or one + no command can use; otherwise it stays, and the answer says so: + `data.isDefault` false, `data.defaultProfile` the default, a summary and a + text line naming it, and breadcrumbs to `--profile` and `profiles default`. + `--make-default` moves it. +- `setup` makes the profile it signs in with the default: it asks a person at + the terminal which host this machine works with. `data.previousDefaultProfile` + names the one before where it moved. +- Removing the default profile leaves no default, with a `notice`, and no + profile that happens to be left takes its place (C-181). A command without a + profile then exits 3 with `no default profile is set` and names `--profile` + and `profiles default`; the next sign-in sets the default again. + +## The configuration file + +The file keeps `profiles` and `defaultProfile`, beside `clientId` and +`comments`. Next to them it writes `hosts` and `defaultHost` in the form of the +versions before profiles, so that such a version still reads the file (C-194): + +- every host carries the token and the account of the default profile where + that one is on it, else of the first profile on it by name; +- `defaultHost` is the host of the default profile. + +Where `profiles` is in the file, it is what holds. A token under `hosts` that no +profile on that host holds was put there by hand and is taken over into a +profile named after the host. A file without `profiles` is one of a version +before profiles, or one such a version wrote last: it drops what it does not +know. Every host with a token in it becomes a profile named after the host, a +host as a sign-in writes it where it can be read and as it stands otherwise, +and the default host becomes the default profile. So an older version's sign-in +or sign-out is never lost; what is lost are the names of the profiles and every +account of a host beyond the one written under it. + +A plain read never writes the file. It is written in the new form when a +command writes it anyway: a sign-in, a sign-out, a rename, `config set`, the +first `clientId`. + +## State per account + +The cards of `work start` are kept per account (C-196): under the name of the +profile, or under the host where the token of the environment signs a command +in. The store keeps them in `accounts`, and beside them, as the configuration +file does, in `hosts` for the versions before profiles: per host the lists of +the profile that host carries in the file, or of the host itself where no +profile signs in to it. + +Where the store has `accounts`, they are what holds, and a host is taken over +only where no account on it holds anything: the copy is of the profile the host +carried when it was written, which after `profiles default` or a new profile +need not be the one it carries now. A rename writes the configuration first, +so the copy goes under the new name. A store with `hosts` alone is one such a +version wrote last, and its lists go to the profile each host carries, or stay +under the host. An older version reporting from the store reports the lists of +that one profile per host; the cards of a second profile on a host it does not +see. + +Removing a profile drops its lists, before the profile leaves the file: under a +name a later profile may take on another host, they would be reported there +with its token. Where a move or a drop could not reach the store, lists stay +under a name no profile has. The heartbeat passes over them, and nothing +deletes them for that: a rename writes the configuration before the store, and +a command in between would otherwise delete the lists it is moving. A sign-in +that makes a new profile clears the store under its name first, and is refused +where it cannot, so no new profile inherits them. + +The heartbeat reports the list of its session in every account that holds one, +each with the token of its own profile. The mod runs it with the environment +Claude Code was started with, which need not be that of the command that took +a card up. `--profile` and `--host` narrow it to the one account. `data.profile` +names the profile where there is one account, and `data.accounts` has one entry +per account with `profile`, `sent`, `reason` and `cardIds`. + +The marks of the comments read and the positions of `notifications wait` are +kept per host and per reader, a reader being the token, so two accounts on one +host never mix there, and a rename changes nothing about them. diff --git a/docs/stable/security.md b/docs/stable/security.md index cb1b346..89e7fc5 100644 --- a/docs/stable/security.md +++ b/docs/stable/security.md @@ -23,7 +23,9 @@ line. - File 0600 in a directory 0700, written atomically with `fsync` and `rename`; a symlink stays a symlink. - A file that others can read is refused instead of silently used. -- It holds several hosts with one token each, and a default host. +- It holds the profiles, each a host and a token, and a default profile, and + beside them the hosts in the form older versions read; see + [Profiles](profiles.md#the-configuration-file). Beside it, `cli-update.json` (0600, written the same way) remembers the versions of minka Minka named last and when the notice of a newer one was @@ -35,39 +37,16 @@ fails a command. A version is taken from a header only where it is a plain ## A token goes to its own host only `MINKA_TOKEN` counts only together with `MINKA_HOST` and only for that host. -Whoever addresses another host with `--host` gets that host's token from the -configuration file, or a refusal — never the token of the first host (C-004). - -## The default host - -The host of a command is `--host`, else `$MINKA_HOST`, else the default host -of the configuration file. Every session on the machine shares that default, -so it moves only when somebody means it to (C-179): - -- `auth login` sets it only where there is none yet, or one that cannot be - read; otherwise it stays, and the answer says so: `data.isDefault` false, - `data.defaultHost` the default, a summary and a text line naming it, and - breadcrumbs to `--host` and `config set host`. `--make-default` moves it. -- `minka config set host ` moves it to a host the file holds a token for, - read the way a sign-in reads it; any other host is exit 1 (`usage`) with - the sign-in as hint, and nothing is written (C-180). `config get host` names - it, `null` where there is none. There is no `config unset`: a default goes - with the sign-out of its host. -- `setup` makes the host it is answered the default: it asks a - person at the terminal which host this machine works with. -- Signing out of the default host leaves no default, with a `notice`, and no - host that happens to be left takes its place (C-181). A command without a - host then exits 3 with `no default host is set` and names `--host` and - `config set host`; the next sign-in sets the default again. - -`auth status` and `doctor` name the default host beside the host of the -command, in `data.defaultHost` and in the text, where the two differ; where -they are the same, the host is named once. A default host or a configuration -file that cannot be read is said as such, with the reason, never as no -default: a command with `--host` gets past it, every command without fails on -it. `auth status` adds `data.hostSource` (`flag`, `environment`, `default`), -`doctor` `data.host`, the host of the command even where no session came -about. +Whoever addresses another host with `--host` gets the token of the profile on +that host, or a refusal — never the token of the first host (C-004). A profile +named with `--profile` or `$MINKA_PROFILE` signs in with its own token, even on +the host of `MINKA_HOST` (C-193). + +## The default profile + +Which profile a command uses, how the default moves and what `auth status` and +`doctor` say about it is in [Profiles](profiles.md#which-profile-a-command-uses) +(C-179…C-181, C-192). ## The Basecamp token of an import @@ -104,29 +83,30 @@ sub-delimiters of a URL by the letter of the standard, so answers at it while it would become a key of the configuration and of the list of cards. -This holds for the default host of the configuration as well, whoever wrote it -there, and a value that cannot be read at all is no host: it is refused where -it is read, and no session comes about under it (C-044). The host is a key of -the list of cards, so every process has to make the same string of it, and a -value no process can make a host of is nothing to carry further: carried -further, it stands in a status, in a report and in the hint of a 401. The -refusal names the file to repair and the way out. Where the configuration keeps -the same host in another form, the refusal says which entry that is: the token -is there, it is only written where nothing looks for it. - -Signing out is the one command that takes the entry as the file writes it, the -host it was told as much as the default one. It has to reach the entry that is -there: one written in another form would be left standing with its token by a -host that was read straight, and one that cannot be read at all is matched -letter for letter. Without `--revoke` nothing goes anywhere from here, and no -command lists the hosts, so an entry that could not be signed out of would be -invisible and unremovable with its token valid on the server. +This holds for the host of a profile as well, whoever wrote it there, and a +value that cannot be read at all is no host: it is refused where it is read, +and no session comes about under it (C-044). A profile is found on a host by +its host read the way a sign-in writes it, so one written by hand in another +form is found all the same, and a host taken over from a file of hosts is +written in that form where it can be read. A value no process can make a host +of is nothing to carry further: carried further, it stands in a status, in a +report and in the hint of a 401. The refusal names the profile and the way +out, `profiles remove`. + +Signing out is the one command that takes a profile without reading its host +first. A `--host` that can be read chooses as everywhere else: the one profile +on it, the default among several, and exit 8 otherwise, so that no token is +taken away or revoked by chance. Only a `--host` that cannot be read finds the +profile whose host is written letter for letter like it, and of several such +none. It has to reach the profile that is there: one whose host cannot be read +would otherwise have no way out of the file. Without `--revoke` nothing goes +anywhere from here. ## Revoking the token on signing out -`auth logout --revoke` sends one request before it touches the file: -`DELETE /me/token` with the token of the entry, which Minka answers by revoking -that token and no other (E-238). The entry is taken out only after the +`auth logout --revoke` and `profiles remove --revoke` send one request before +they touch the file: `DELETE /me/token` with the token of the profile, which +Minka answers by revoking that token and no other (E-238). The entry is taken out only after the revocation went through, because the entry is the one copy of the token this machine has: taken out first, a revocation that then failed would leave a valid token nothing here can reach any more (C-119). @@ -167,9 +147,9 @@ A host that a session carries has been through this reading, so printing it needs nothing further: `auth status`, the report of `doctor` and the hint of a 401 name it as it stands, and there is nothing in it to render away. Rendered is what has not been read where it is printed, and those are five places: the -refusal of a host that was given, the refusal of the default host, the entry a -sign-out takes away, the entry a refusal names as the same host written another -way, and the hint after a request that could not be made, where the host +refusal of a host that was given, the refusal of the host of a profile, the +profile a sign-out takes away, the host `profiles list` names, and the hint +after a request that could not be made, where the host arrives as a bare argument from wherever the caller had it. Whoever prints a value that has not been read adds a sixth. diff --git a/docs/work-in-progress/status.md b/docs/work-in-progress/status.md index 1fb5484..b1acbeb 100644 --- a/docs/work-in-progress/status.md +++ b/docs/work-in-progress/status.md @@ -390,10 +390,10 @@ against a local Minka on its `main`, in a Decisions tool of a test project whose prefix is a single letter; the labels are checked against the fake only, since that project has none. -The default host moves only when somebody means it to: `auth login` keeps it -and says so, `--make-default` and `config set host` move it, signing out of it -leaves none, and `auth status` and `doctor` name it beside the host of the -command ([Token, hosts and requests](../stable/security.md#the-default-host), +The default profile moves only when somebody means it to: `auth login` keeps it +and says so, `--make-default`, `profiles default` and `config set host` move +it, removing it leaves none, and `auth status` and `doctor` name it beside the +profile of the command ([Profiles](../stable/profiles.md#the-default), C-179…C-181). This touches no API; it is tested against temporary configuration files only. @@ -856,6 +856,19 @@ Dogfooding waits for the internal alpha. The smoke token `minka-cli-smoke` ## Checked against the fake only +- Profiles (MNK-TP): `--profile`, `$MINKA_PROFILE`, `profiles list|rename| + remove|default`, the file written with the hosts for older versions beside + the profiles, the store per account and the heartbeat over every account. + Built and tested against temporary files and the fake only; no live check + yet. **The release that carries it needs a line in its notes:** the first + command of this version that writes the configuration writes it with + profiles. An older minka still reads it and signs in with the profile its + host carries, but once it writes the file itself the profile names are gone + and only one account per host is left; this version then takes every host + over as a profile named after it. The store of `work start` is the same: an + older minka sees the cards of the profile each host carries, and one that + writes the store leaves only those. + - A move into another Docs & Files tool (`move --tool`): the fake mirrors the order of the refusals, the ID kept, everything below a folder going along, the place on top of its kind or at the end of an order by hand, the folders diff --git a/internal/cli/archive_test.go b/internal/cli/archive_test.go index 6104b83..505decb 100644 --- a/internal/cli/archive_test.go +++ b/internal/cli/archive_test.go @@ -253,7 +253,7 @@ func everyWrite(e *testEnv) map[string][]string { // archived project is not found at all. An upload is tested by itself, because // it needs a file. var notAWriteIntoAProject = []string{ - "auth login", "auth logout", "auth status", "setup", "doctor", "me", "version", "commands", + "auth login", "auth logout", "auth status", "profiles list", "profiles rename", "profiles remove", "profiles default", "setup", "doctor", "me", "version", "commands", "skill show", "skill install", "skill status", "projects list", "projects create", "tools list", "labels list", "boards list", "boards show", "boards archive", "people list", "trash list", "config get", "config set", diff --git a/internal/cli/auth.go b/internal/cli/auth.go index 34f21cb..38c3e29 100644 --- a/internal/cli/auth.go +++ b/internal/cli/auth.go @@ -26,15 +26,22 @@ func (a *app) newAuthLoginCmd() *cobra.Command { cmd := &cobra.Command{ Use: "login", - Short: "Sign in to a Minka host with an access token", - Long: `Signs in to a Minka host with a personal access token. The token is checked -against the host and then saved in the config file, which only your user can -read. - -The default host, which a command without --host and $MINKA_HOST goes to, -does not move: the first host signed in to becomes it, and later sign-ins -leave it where it is. --make-default makes this host the default, as does -minka config set host for a host signed in to already. + Short: "Sign in to a Minka host with an access token, as a profile", + Long: `Signs in with a personal access token and keeps it as a profile: one account in +one organization. The token is checked against the host and then saved in the +config file, which only your user can read. + +--profile names the profile. A new name makes a new profile and needs +--host; a name that exists signs that profile in again, on its own host, and +--host may only repeat that host. Without --profile, a host with one profile +signs that one in again, a host with none gets a profile named after the host, +and a host with several needs --profile. Here, unlike everywhere else, --profile +and --host go together. + +The default profile, which a command without --profile and --host uses, does +not move: the first profile becomes it, and later sign-ins leave it where it +is. --make-default makes this profile the default, as does +minka profiles default . Without --with-token the token is asked for on the terminal, without echo. With --with-token it is read from stdin. No flag takes the token itself, so it @@ -42,16 +49,17 @@ does not end up in the shell history or the process list. The config file is ~/.config/minka/config.json, or $MINKA_CONFIG.`, Example: ` minka auth login --host https://minka.localbeach.net - minka auth login --host https://minka.localbeach.net --with-token < token.txt - minka auth login --host https://minka.example.com --make-default`, + minka auth login --profile flownative --host https://minka.flownative.com --with-token < token.txt + minka auth login --profile familie --host https://minka.example.com --make-default`, Args: requireArgs(), RunE: func(cmd *cobra.Command, _ []string) error { - host, err := a.explicitHost() + _, file, err := a.loadConfig() if err != nil { return err } - if host == "" { - return usageErrorf(cmd, "--host is required") + name, host, err := a.profileToSignIn(cmd, file) + if err != nil { + return err } token, err := a.readToken(cmd, host, withToken) @@ -59,56 +67,126 @@ The config file is ~/.config/minka/config.json, or $MINKA_CONFIG.`, return err } - path, me, defaultHost, err := a.signIn(host, token, makeDefault) + path, me, file, err := a.signIn(name, host, token, makeDefault) if err != nil { return err } + defaultProfile := file.DefaultProfile + defaultHost := "" + if profile, ok := file.Profiles[defaultProfile]; ok { + defaultHost = config.HostForOutput(profile.Host) + } - summary := fmt.Sprintf("Signed in to %s as %s; it is the default host", host, me.Value.Name) - defaultLine := host + " is the default host." + summary := fmt.Sprintf("Signed in to %s as %s with the profile %s; it is the default profile", host, me.Value.Name, name) + defaultLine := name + " is the default profile." breadcrumbs := []Breadcrumb{ {Action: "projects", Cmd: "minka projects list", Description: "List your projects"}, } - if defaultHost != host { - shown := config.HostForOutput(defaultHost) - summary = fmt.Sprintf("Signed in to %s as %s; the default host stays %s", host, me.Value.Name, shown) - defaultLine = "The default host stays " + shown + ". Give --host " + host + " to a command to reach this host,\nor make it the default: minka config set host " + host + if defaultProfile != name { + summary = fmt.Sprintf("Signed in to %s as %s with the profile %s; the default profile stays %s", host, me.Value.Name, name, defaultProfile) + defaultLine = "The default profile stays " + defaultProfile + ". Give --profile " + name + " to a command to use this one,\nor make it the default: minka profiles default " + name breadcrumbs = []Breadcrumb{ - {Action: "projects", Cmd: "minka projects list --host " + host, Description: "List your projects on " + host}, - {Action: "make-default", Cmd: "minka config set host " + host, Description: "Make " + host + " the default host"}, + {Action: "projects", Cmd: "minka projects list --profile " + name, Description: "List your projects with the profile " + name}, + {Action: "make-default", Cmd: "minka profiles default " + name, Description: "Make " + name + " the default profile"}, } } return a.ok(success{ data: map[string]any{ "host": host, "configPath": path, "person": me.Raw, - "defaultHost": config.HostForOutput(defaultHost), "isDefault": defaultHost == host, + "defaultHost": nullable(defaultHost), "isDefault": defaultProfile == name, + "profile": name, "defaultProfile": nullable(defaultProfile), }, summary: summary, breadcrumbs: breadcrumbs, text: func(w io.Writer) { - fmt.Fprintf(w, "Signed in to %s as %s <%s>.\nThe token is saved in %s.\n%s\n", host, me.Value.Name, me.Value.EmailAddress, path, defaultLine) + fmt.Fprintf(w, "Signed in to %s as %s <%s>, as the profile %s.\nThe token is saved in %s.\n%s\n", host, me.Value.Name, me.Value.EmailAddress, name, path, defaultLine) }, }) }, } cmd.Flags().BoolVar(&withToken, "with-token", false, "Read the token from stdin") - cmd.Flags().BoolVar(&makeDefault, "make-default", false, "Make this host the default host, even when another one is") + cmd.Flags().BoolVar(&makeDefault, "make-default", false, "Make this profile the default, even when another one is") return cmd } -// signIn checks a token against its host and saves it as the token of that -// host. A token the host does not accept is not saved, so the config file never -// holds one that does not work. It returns the default host as it stands after -// the sign-in. +// profileToSignIn is the profile a sign-in is for, and its host. +// +// A profile keeps its host. Signing an existing name in to another host would +// change under every script that names the profile which organization it +// writes in, so that takes removing the profile first. +func (a *app) profileToSignIn(cmd *cobra.Command, file *config.File) (string, string, error) { + host, err := a.explicitHost() + if err != nil { + return "", "", err + } + return a.profileOnHost(cmd, file, host, a.hostFlag != "") +} + +// profileOnHost is profileToSignIn for a host found already, which is empty +// where none was given. hostNamed says whether somebody named the host for this +// command, rather than it coming from $MINKA_HOST. +func (a *app) profileOnHost(cmd *cobra.Command, file *config.File, host string, hostNamed bool) (string, string, error) { + name := a.profileFlag + source := chosenByProfileFlag + if name == "" && a.hostFlag == "" { + name, source = a.getenv("MINKA_PROFILE"), chosenByProfileEnv + } + + if name != "" { + if err := config.CheckProfileName(name); err != nil { + return "", "", profileNameError(source, err) + } + existing, ok := file.Profiles[name] + if !ok { + if host == "" { + return "", "", usageErrorf(cmd, "--host is required for the new profile %s", name) + } + return name, host, nil + } + own, err := config.NormalizeHost(existing.Host) + if err != nil { + return "", "", &Error{Code: CodeConfig, Message: "the host of the profile " + name + " cannot be read: " + err.Error(), Hint: "Take the profile out and sign in again: minka profiles remove " + name} + } + if hostNamed && host != own { + return "", "", &Error{ + Code: CodeUsage, + Message: "the profile " + name + " signs in to " + own + ", not to " + host, + Hint: "A profile keeps its host. Sign in under another name with --profile , or take this one out first: minka profiles remove " + name, + } + } + return name, own, nil + } + + if host == "" { + return "", "", usageErrorf(cmd, "--host or --profile is required") + } + names := file.ProfilesOnHost(host) + switch len(names) { + case 0: + return file.ProfileNameForHost(host), host, nil + case 1: + return names[0], host, nil + } + return "", "", &Error{ + Code: CodeAmbiguous, + Message: fmt.Sprintf("%d profiles sign in to %s: %s", len(names), host, strings.Join(names, ", ")), + Hint: "Name the profile to sign in with --profile .", + } +} + +// signIn checks a token against its host and saves it as the token of a +// profile. A token the host does not accept is not saved, so the config file +// never holds one that does not work. It returns the configuration as it stands +// after the sign-in. // -// The default host is where every command without --host goes, those of other -// sessions on this machine included, so signing in to another host does not -// move it unless that is asked for. Where there is none yet, or one no command -// can read, the host signed in to takes its place: there is nothing a command -// could reach that it would take away. -func (a *app) signIn(host, token string, makeDefault bool) (string, api.Result[api.Me], string, error) { +// The default profile is what every command without --profile and --host uses, +// those of other sessions on this machine included, so signing in with another +// profile does not move it unless that is asked for. Where there is none yet, +// or one no command can use, the profile signed in takes its place: there is +// nothing a command could reach that it would take away. +func (a *app) signIn(name, host, token string, makeDefault bool) (string, api.Result[api.Me], *config.File, error) { me, err := a.newClient(host, token).Me(a.ctx) if err != nil { e := apiError(err, host) @@ -116,24 +194,33 @@ func (a *app) signIn(host, token string, makeDefault bool) (string, api.Result[a e.Message = fmt.Sprintf("%s did not accept the token, nothing was saved", host) e.Hint = "Check that the token is complete and not revoked or expired." } - return "", api.Result[api.Me]{}, "", e + return "", api.Result[api.Me]{}, nil, e } path, file, err := a.loadConfig() if err != nil { - return "", api.Result[api.Me]{}, "", err + return "", api.Result[api.Me]{}, nil, err + } + // A new profile starts with no cards: lists a failed move or drop left + // under its name belong to another account, on whatever host. + if _, exists := file.Profiles[name]; !exists { + if err := a.dropFromTheStore(name); err != nil { + e := &Error{Code: CodeConfig, Message: "nothing was saved: the list of cards on this machine may hold cards under the name " + name + " and could not be cleared: " + err.Error()} + var cause *Error + if errors.As(err, &cause) { + e.Hint = cause.Hint + } + return "", api.Result[api.Me]{}, nil, e + } } - file.Hosts[host] = config.HostEntry{Token: token, PersonName: me.Value.Name, EmailAddress: me.Value.EmailAddress} - // An empty default host fails to normalise like an unreadable one, so both - // count as no default here. - defaultHost, unreadable := config.NormalizeHost(file.DefaultHost) - if makeDefault || unreadable != nil { - file.DefaultHost, defaultHost = host, host + file.Profiles[name] = config.Profile{Host: host, Token: token, PersonName: me.Value.Name, EmailAddress: me.Value.EmailAddress} + if _, err := chooseIn(file, path, chosenByDefault, ""); makeDefault || file.DefaultProfile == "" || err != nil { + file.DefaultProfile = name } if err := file.Save(path); err != nil { - return "", api.Result[api.Me]{}, "", &Error{Code: CodeConfig, Message: err.Error()} + return "", api.Result[api.Me]{}, nil, &Error{Code: CodeConfig, Message: err.Error()} } - return path, me, defaultHost, nil + return path, me, file, nil } func (a *app) readToken(cmd *cobra.Command, host string, fromStdin bool) (string, error) { @@ -184,13 +271,21 @@ func (a *app) readToken(cmd *cobra.Command, host string, fromStdin bool) (string func (a *app) newAuthStatusCmd() *cobra.Command { return &cobra.Command{ Use: "status", - Short: "Show the host and the person you are signed in as", - Long: `Checks the token against the host and shows who it acts as, and names the -default host where the host comes from --host or $MINKA_HOST and is another -one. Exits with 3 when there is no token or the host does not accept it.`, + Short: "Show the profile, the host and the person you are signed in as", + Long: `Checks the token against the host and shows who it acts as, which profile that +is and where the choice came from: --profile, --host, $MINKA_PROFILE, +$MINKA_HOST or the default profile, which it names where it is another one. +Exits with 3 when there is no token or the host does not accept it. + +data.profile is null where the token comes from $MINKA_TOKEN; data.profileSource +is --profile, --host, $MINKA_PROFILE, $MINKA_HOST or default.`, Args: requireArgs(), RunE: func(*cobra.Command, []string) error { - s, err := a.session() + c, path, file, err := a.chooseAccount(true) + if err != nil { + return err + } + s, err := a.sessionOf(c, path, file) if err != nil { return err } @@ -203,22 +298,22 @@ one. Exits with 3 when there is no token or the host does not accept it.`, if s.tokenSource == tokenFromEnvironment { tokenSource = "$MINKA_TOKEN" } - source := a.hostSource() - defaultHost, problem := a.defaultHostToReport() - hosts := hostsInWords(s.host, source, defaultHost, problem) + defaultProfile, defaultHost, problem := a.defaultToReport() + account := accountInWords(c, defaultProfile, problem) return a.ok(success{ data: map[string]any{ - "host": s.host, "hostSource": source, "defaultHost": nullable(defaultHost), + "host": s.host, "hostSource": hostSource(c.source), "defaultHost": nullable(defaultHost), + "profile": nullable(s.profile), "profileSource": c.source, "defaultProfile": nullable(defaultProfile), "tokenSource": s.tokenSource, "person": me.Raw, }, - summary: fmt.Sprintf("Signed in to %s as %s; %s", s.host, me.Value.Name, hosts), + summary: fmt.Sprintf("Signed in to %s as %s; %s", s.host, me.Value.Name, account), text: func(w io.Writer) { fmt.Fprintf(w, "Signed in to %s as %s <%s>.\n", s.host, me.Value.Name, me.Value.EmailAddress) if me.Value.Principal != nil { fmt.Fprintf(w, "Acting for %s.\n", me.Value.Principal.Name) } - fmt.Fprintf(w, "%s.\n", strings.ToUpper(hosts[:1])+hosts[1:]) + fmt.Fprintf(w, "%s.\n", strings.ToUpper(account[:1])+account[1:]) fmt.Fprintf(w, "The token comes from %s.\n", tokenSource) }, }) @@ -226,157 +321,181 @@ one. Exits with 3 when there is no token or the host does not accept it.`, } } -// hostToSignOutOf is the entry a sign-out takes away: the host it was told, else -// the default host of the configuration, and either of them as the file writes -// it. -// -// Taking a token away has to reach the entry that is there, so a value that -// matches one letter for letter is that entry, before anything is read of it: a -// host read the way a sign-in writes it would look past an entry written in -// another form and leave its token where it stands, and one written in a form -// nothing can read at all — refused everywhere else, because a session under it -// would carry the value into everything that prints a host — would have no way -// out of the file at all. Nothing goes anywhere from here, so strictness would -// buy nothing and cost the only way to be rid of such an entry: no command lists -// the hosts, and its token stays valid on the server. A canonical entry is -// untouched by this, because a canonical value matches it letter for letter. -func (a *app) hostToSignOutOf(file *config.File) (string, error) { - given := a.hostFlag - if given == "" { - given = a.getenv("MINKA_HOST") - } - if given == "" { - return file.DefaultHost, nil - } - if _, written := file.Hosts[given]; written { - return given, nil - } - - return a.explicitHost() -} - func (a *app) newAuthLogoutCmd() *cobra.Command { var revoke bool cmd := &cobra.Command{ Use: "logout", - Short: "Remove the token of a host from the config file, and revoke it with --revoke", - Long: `Removes the token of the host from the config file. Without --revoke the token -itself stays valid on the server until it is revoked there. + Short: "Remove the profile a command uses, and revoke its token with --revoke", + Long: `Removes the profile a command uses, the one --profile, --host, $MINKA_PROFILE, +$MINKA_HOST or the default names, and its token from the config file, as +minka profiles remove does. Without --revoke the token itself stays +valid on the server until it is revoked there. --revoke revokes the token on the server first, and only then removes the -entry: the entry is the one copy of the token this machine has, so it is kept +profile: it holds the one copy of the token this machine has, so it is kept when the revocation fails, and the command exits with the code of that failure. Revoking is safe to repeat: a token the server no longer accepts counts as -revoked, the entry is removed, and a notice says so. Only the token of the -entry is revoked; a token in $MINKA_TOKEN is never touched. - -Without --host it is the default host. Signing out of the default host leaves -no default: the next sign-in sets one, or minka config set host names one -of the hosts still signed in to. The entry is reached as the -file writes it, so an address written in by hand can be taken out again; with ---revoke the token goes to that address read like every host, and an entry no -host can be read from keeps its token and exits 1.`, +revoked, the profile is removed, and a notice says so. Only the token of the +profile is revoked; a token in $MINKA_TOKEN is never touched. + +Signing out of the default profile leaves no default: the next sign-in sets +one, or minka profiles default names one of the profiles left.`, Example: ` minka auth logout - minka auth logout --host https://minka.example.com --revoke`, + minka auth logout --profile familie --revoke`, Args: requireArgs(), RunE: func(*cobra.Command, []string) error { path, file, err := a.loadConfig() if err != nil { return err } - host, err := a.hostToSignOutOf(file) + c, err := a.profileToSignOutOf(path, file) if err != nil { return err } - if host == "" { + if c.profile == "" { + var host any + summary := "Not signed in to any host" + if c.host != "" { + host, summary = c.host, "Not signed in to "+c.host + } + var notices []string + if revoke && a.getenv("MINKA_TOKEN") != "" { + notices = append(notices, envTokenNotRevoked) + } return a.ok(success{ - data: map[string]any{"host": nil, "removed": false, "revoked": false}, - summary: "Not signed in to any host", - text: func(w io.Writer) { fmt.Fprintln(w, "Not signed in to any host.") }, + data: map[string]any{"host": host, "profile": nil, "removed": false, "revoked": false}, + summary: summary, + notices: notices, + text: func(w io.Writer) { fmt.Fprintf(w, "%s.\n", summary) }, }) } + return a.removeProfile(path, file, c.profile, revoke) + }, + } + cmd.Flags().BoolVar(&revoke, "revoke", false, "Revoke the token on the server before removing it") - // The entry is reached by the value the file holds; what is printed - // of it is the address alone, which is not where a password belongs. - shown := config.HostForOutput(host) - var notices []string - revoked := false - if entry, standing := file.Hosts[host]; revoke && standing && entry.Token != "" { - alreadyGone, err := a.revokeToken(host, entry.Token) - if err != nil { - return err - } - revoked = true - if alreadyGone { - notices = append(notices, shown+" no longer accepted the token: it was revoked, had expired or belonged to an agent that stepped down, so there was nothing left to revoke") - } - } - // A sign-out reaches the file alone, so a token given in the - // environment is still valid, and whoever asked to revoke has to - // hear that. - if revoke && a.getenv("MINKA_TOKEN") != "" { - notices = append(notices, "the token in $MINKA_TOKEN was not revoked: a sign-out revokes only the token of the config file. Revoke it in Minka's account area, or sign it in with minka auth login --with-token and sign out again with --revoke") - } + return cmd +} - wasDefault := file.DefaultHost == host - removed := file.RemoveHost(host) - // The hosts left keep their tokens, and none of them becomes the - // default by being left over; whoever relied on the default has to - // hear that there is none now. - if removed && wasDefault && len(file.Hosts) > 0 { - notices = append(notices, shown+" was the default host, and no host is the default now: give --host to a command, or make a host signed in to the default with: minka config set host ") +// profileToSignOutOf is the profile a sign-out takes away, chosen the way every +// command chooses it, with one difference: its host is not read first. +// +// Taking a token away has to reach the profile that is there. A profile whose +// host was written into the file in a form nothing can read is refused +// everywhere else, because a session under it would carry the value into +// everything that prints a host. Nothing goes anywhere from here, so strictness +// would buy nothing and cost the way out of the file. For the same reason a +// host given that cannot be read finds the profile whose host is written +// letter for letter like it. A host that can be read is chosen as everywhere +// else, so that of several profiles on it none is taken by chance. +func (a *app) profileToSignOutOf(path string, file *config.File) (choice, error) { + source, value, err := a.requestedChoice() + if err != nil { + return choice{}, err + } + switch source { + case chosenByProfileFlag, chosenByProfileEnv: + if err := config.CheckProfileName(value); err != nil { + return choice{}, profileNameError(source, err) + } + if _, ok := file.Profiles[value]; !ok { + return choice{}, unknownProfileError(file, value) + } + return choice{profile: value, source: source}, nil + case chosenByHostFlag, chosenByHostEnv: + if _, err := config.NormalizeHost(value); err == nil { + break + } + var written []string + for _, name := range file.ProfileNames() { + if file.Profiles[name].Host == value { + written = append(written, name) } - if removed { - if err := file.Save(path); err != nil { - e := &Error{Code: CodeConfig, Message: err.Error()} - if revoked { - e.Message = "the token is revoked, but its entry could not be taken out of the config file: " + err.Error() - e.Data = map[string]any{"host": shown, "removed": false, "revoked": true} - } - return e - } + } + switch len(written) { + case 0: + case 1: + return choice{profile: written[0], source: source}, nil + default: + return choice{}, &Error{ + Code: CodeAmbiguous, + Message: fmt.Sprintf("%d profiles sign in to the host given: %s", len(written), strings.Join(written, ", ")), + Hint: "Name the profile to remove: minka profiles remove ", } + } + default: + if _, ok := file.Profiles[file.DefaultProfile]; ok { + return choice{profile: file.DefaultProfile, source: source}, nil + } + } + return chooseIn(file, path, source, value) +} - summary := "Not signed in to " + shown - if removed { - summary = "Signed out of " + shown - } - answer := success{ - data: map[string]any{"host": shown, "removed": removed, "revoked": revoked}, - summary: summary, - notices: notices, - text: func(w io.Writer) { - switch { - case !removed: - fmt.Fprintf(w, "%s.\n", summary) - case revoked: - fmt.Fprintf(w, "%s. The token is revoked on the server.\n", summary) - default: - fmt.Fprintf(w, "%s. The token stays valid on the server until it is revoked.\n", summary) - } - }, - } - // Saying that there is nothing here would be the whole answer only if - // no token stood under the same host written another way. It does, and - // nothing looks for it there, so the answer says where it is. - if !removed { - if written := hostWrittenAnotherWay(file, host); written != "" { - elsewhere := config.HostForOutput(written) - command := "minka auth logout --host " + elsewhere - if revoke { - command += " --revoke" - } - answer.notices = append(answer.notices, "the configuration keeps a token under "+elsewhere+ - ", the same host written another way; take that entry out with: "+command) - } - } - return a.ok(answer) - }, +// envTokenNotRevoked is what a sign-out with --revoke says where a token is +// given in the environment: a sign-out reaches the file alone, so that token is +// still valid, and whoever asked to revoke has to hear that. +const envTokenNotRevoked = "the token in $MINKA_TOKEN was not revoked: a sign-out revokes only the token of a profile. Revoke it in Minka's account area, or sign it in with minka auth login --with-token and sign out again with --revoke" + +// removeProfile takes a profile and its token out of the configuration, and +// revokes the token first where that is asked for. +func (a *app) removeProfile(path string, file *config.File, name string, revoke bool) error { + profile := file.Profiles[name] + // The profile is reached by its name; what is printed of its host is the + // address alone, which is not where a password belongs. + shown := config.HostForOutput(profile.Host) + var notices []string + revoked := false + if revoke && profile.Token != "" { + alreadyGone, err := a.revokeToken(profile.Host, profile.Token) + if err != nil { + return err + } + revoked = true + if alreadyGone { + notices = append(notices, shown+" no longer accepted the token: it was revoked, had expired or belonged to an agent that stepped down, so there was nothing left to revoke") + } + } + if revoke && a.getenv("MINKA_TOKEN") != "" { + notices = append(notices, envTokenNotRevoked) } - cmd.Flags().BoolVar(&revoke, "revoke", false, "Revoke the token on the server before removing it") - return cmd + // The lists go before the profile does: under a name a later profile may + // take on another host, they would be reported there with its token. + if err := a.dropFromTheStore(name); err != nil { + notices = append(notices, "the cards this profile was working on could not be taken out of the list on this machine: "+err.Error()) + } + + wasDefault := file.DefaultProfile == name + file.RemoveProfile(name) + // The profiles left keep their tokens, and none of them becomes the + // default by being left over; whoever relied on the default has to hear + // that there is none now. + if wasDefault && len(file.Profiles) > 0 { + notices = append(notices, name+" was the default profile, and no profile is the default now: give --profile to a command, or make one the default with: minka profiles default ") + } + if err := file.Save(path); err != nil { + e := &Error{Code: CodeConfig, Message: err.Error()} + if revoked { + e.Message = "the token is revoked, but its profile could not be taken out of the config file: " + err.Error() + e.Data = map[string]any{"host": shown, "profile": name, "removed": false, "revoked": true} + } + return e + } + + summary := "Signed out of " + shown + " and removed the profile " + name + return a.ok(success{ + data: map[string]any{"host": shown, "profile": name, "removed": true, "revoked": revoked}, + summary: summary, + notices: notices, + text: func(w io.Writer) { + if revoked { + fmt.Fprintf(w, "%s. The token is revoked on the server.\n", summary) + return + } + fmt.Fprintf(w, "%s. The token stays valid on the server until it is revoked.\n", summary) + }, + }) } // revokeToken revokes a token at the host its entry names, and says whether diff --git a/internal/cli/cards.go b/internal/cli/cards.go index f0a0042..29cc4d9 100644 --- a/internal/cli/cards.go +++ b/internal/cli/cards.go @@ -812,7 +812,7 @@ takes a card up moves it first and says 'minka work start' afterwards. moved.Value.Column.Type == api.ColumnDone var notices []string if letGo { - if letGo, told := a.letGoOfTheCard(s.host, moved.Value.ID); letGo { + if letGo, told := a.letGoOfTheCard(s, moved.Value.ID); letGo { notices = append(notices, noLongerInHand(told)) } } @@ -866,7 +866,7 @@ that does not get through, with the next signal of the session that held it.`, if card.Value.Column.Type == api.ColumnDone { var notices []string - if letGo, told := a.letGoOfTheCard(s.host, card.Value.ID); letGo { + if letGo, told := a.letGoOfTheCard(s, card.Value.ID); letGo { notices = append(notices, noLongerInHand(told)) } return a.ok(success{ @@ -900,7 +900,7 @@ that does not get through, with the next signal of the session that held it.`, } var notices []string - if letGo, told := a.letGoOfTheCard(s.host, moved.Value.ID); letGo { + if letGo, told := a.letGoOfTheCard(s, moved.Value.ID); letGo { notices = append(notices, noLongerInHand(told)) } return a.ok(success{ diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 2379745..251230a 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -187,7 +187,7 @@ func TestLoginSavesTheTokenInAFileOnlyTheUserCanRead(t *testing.T) { if err != nil { t.Fatal(err) } - if file.DefaultHost != e.server.URL || file.Hosts[e.server.URL].Token != e.fixture.Token { + if name := profileNamedAfter(e.server.URL); file.DefaultProfile != name || file.Profiles[name].Token != e.fixture.Token || file.Profiles[name].Host != e.server.URL { t.Errorf("config %+v", file) } @@ -258,32 +258,17 @@ func TestAConfigFileOthersCanReadIsNotUsed(t *testing.T) { } // A configuration written by hand can keep a host in a form no sign-in writes. -// The token under such an entry is never found, and a refusal that named only the -// host it looked for would name one that stands nowhere in the file and send -// somebody looking at the wrong end. -func TestAHostTheConfigurationWritesAnotherWayIsSaidSo(t *testing.T) { +// Its profile signs in to the host as a sign-in writes it, so the token is +// found under either spelling. +func TestAHostTheConfigurationWritesAnotherWayIsFound(t *testing.T) { e := newTestEnv(t) delete(e.vars, "MINKA_TOKEN") delete(e.vars, "MINKA_HOST") written := e.server.URL + "/" e.writeConfig(`{"defaultHost": "` + written + `", "hosts": {"` + written + `": {"token": "` + e.fixture.Token + `"}}}`) - env, r := e.runJSON("", "me") - expectCode(t, r, ExitAuth) - if env.Code != CodeAuth { - t.Errorf("code %q", env.Code) - } - if !strings.Contains(env.Hint, written) || !strings.Contains(env.Hint, "another way") { - t.Errorf("the hint %q does not say that the configuration keeps the host in another form", env.Hint) - } - if !strings.Contains(env.Hint, "minka auth login --host "+e.server.URL) { - t.Errorf("the hint %q does not say what puts it right", env.Hint) - } - // It names an entry of the file the token lies in, and an agent puts what it - // reads into a log. - if strings.Contains(env.Hint, e.fixture.Token) || strings.Contains(env.Error, e.fixture.Token) { - t.Errorf("the refusal carries the token: %q %q", env.Error, env.Hint) - } + expectCode(t, e.run("", "me", "--json"), ExitOK) + expectCode(t, e.run("", "me", "--host", e.server.URL, "--json"), ExitOK) } func TestLogoutRemovesTheToken(t *testing.T) { @@ -1635,7 +1620,7 @@ func TestTheEnvironmentTokenIsOnlySentToItsHost(t *testing.T) { t.Fatalf("%d requests reached the other host", n) } - file := &config.File{Hosts: map[string]config.HostEntry{other.URL: {Token: otherFixture.StrangerToken}}} + file := &config.File{Profiles: map[string]config.Profile{"other": {Host: other.URL, Token: otherFixture.StrangerToken}}} if err := file.Save(e.vars["MINKA_CONFIG"]); err != nil { t.Fatal(err) } @@ -1697,11 +1682,11 @@ func TestARefusedHostKeepsItsPasswordOutOfTheOutput(t *testing.T) { } } -// A default host the configuration cannot read is no host: it is refused where -// it is read, and no command comes to a session under it. That is what keeps the -// value out of everything that prints a host — a status, a report, the hint of a -// refusal. What the refusal says of the value is the address alone, and it names -// the file to repair. +// A default profile whose host the configuration cannot read is no account: it +// is refused where it is read, and no command comes to a session under it. That +// is what keeps the value out of everything that prints a host — a status, a +// report, the hint of a refusal. What the refusal says of the value is the +// address alone, and it names the profile to repair. func TestADefaultHostThatCannotBeReadIsNoHost(t *testing.T) { const password = "s3cr3t-password" const withCredentials = "https://robert:" + password + "@minka.example.com" @@ -1713,23 +1698,24 @@ func TestADefaultHostThatCannotBeReadIsNoHost(t *testing.T) { e.writeConfig(`{"defaultHost":"` + withCredentials + `","hosts":{"` + withCredentials + `":{"token":"minka_pat_written_by_hand"}}}`) // A session, and the store beside it, are the two ways into such an entry. - for _, command := range [][]string{{"me"}, {"auth", "status"}, {"work", "list"}, {"work", "stop"}} { + for _, command := range [][]string{{"me"}, {"auth", "status"}, {"work", "list"}, {"work", "stop"}, {"profiles", "list"}} { what := strings.Join(command, " ") env, r := e.runJSON("", append(command, "--json")...) - expectCode(t, r, ExitUsage) if out := r.stdout + r.stderr; strings.Contains(out, password) { t.Errorf("%s hands the password on: %s", what, out) } + if what == "profiles list" { + expectCode(t, r, ExitOK) + continue + } + expectCode(t, r, ExitUsage) if env.Code != CodeConfig { t.Errorf("%s answers with code %q", what, env.Code) } - if !strings.Contains(env.Error, "the default host in "+e.vars["MINKA_CONFIG"]+" cannot be read") { - t.Errorf("%s does not say that the default host of the configuration cannot be read: %s", what, env.Error) - } - if !strings.Contains(env.Error, "minka.example.com") { - t.Errorf("%s does not say which host it is about: %s", what, env.Error) + if !strings.Contains(env.Error, "the host of the profile minka.example.com in "+e.vars["MINKA_CONFIG"]+" cannot be read") { + t.Errorf("%s does not say that the host of the default profile cannot be read: %s", what, env.Error) } - if !strings.Contains(env.Hint, `"defaultHost"`) || !strings.Contains(env.Hint, "minka auth login --host https://minka.example.com") { + if !strings.Contains(env.Hint, `"host"`) || !strings.Contains(env.Hint, "minka profiles remove minka.example.com") { t.Errorf("%s gives no way out: %s", what, env.Hint) } } @@ -1754,31 +1740,17 @@ func TestADefaultHostThatCannotBeReadIsNoHost(t *testing.T) { t.Errorf("%d requests were sent", n) } - // Of an entry that cannot be read at all, what may be printed is too little - // to sign in with, and a command line with the replacement in it would not - // work. The hint then names an address to fill in. + // A default host without a token under it becomes no profile at all, and + // what is printed then is no part of the value. unreadable := newTestEnv(t) delete(unreadable.vars, "MINKA_HOST") delete(unreadable.vars, "MINKA_TOKEN") unreadable.writeConfig(`{"defaultHost":"https://robert:` + password + `@minka.example.com\u007f","hosts":{}}`) - env, r := unreadable.runJSON("", "me") - expectCode(t, r, ExitUsage) - if out := r.stdout + r.stderr; strings.Contains(out, password) { - t.Errorf("the refusal hands the password on: %s", out) - } - // What is left of such a value may hold anything, and a printed line goes - // through a terminal and a log that read a control character as an order. - if strings.ContainsRune(r.stdout+r.stderr, '\x7f') { - t.Errorf("a control character of the value reached the output: %q", r.stdout+r.stderr) - } - if strings.Contains(env.Hint, "***") || !strings.Contains(env.Hint, "--host YOUR-INSTANCE-ADDRESS") { - t.Errorf("the hint does not say what is to be filled in: %s", env.Hint) - } - // A line that looks ready to run would be run, by a person or by an agent, - // and would reach a host that is not theirs. - if strings.Contains(env.Hint, "--host https://") { - t.Errorf("the hint names an address of its own: %s", env.Hint) + _, r = unreadable.runJSON("", "me") + expectCode(t, r, ExitAuth) + if out := r.stdout + r.stderr; strings.Contains(out, password) || strings.ContainsRune(out, '\x7f') { + t.Errorf("the refusal hands on what the value holds: %q", out) } } @@ -1805,7 +1777,7 @@ func TestSigningOutOfAHandWrittenEntryPrintsNoPassword(t *testing.T) { if err != nil { t.Fatal(err) } - if _, ok := file.Hosts[withCredentials]; ok { + if ok := len(file.ProfilesOnHost(withCredentials)) > 0; ok { t.Error("the entry the file holds was not the one that was removed") } } @@ -1836,10 +1808,10 @@ func TestSigningOutOfAnEntryThatCannotBeRead(t *testing.T) { if err != nil { t.Fatal(err) } - if _, ok := file.Hosts[written]; ok { + if ok := len(file.ProfilesOnHost(written)) > 0; ok { t.Error("the entry that cannot be read is still there") } - if _, ok := file.Hosts[e.server.URL]; !ok { + if ok := len(file.ProfilesOnHost(e.server.URL)) > 0; !ok { t.Error("the entry of another host was taken away with it") } @@ -1848,11 +1820,9 @@ func TestSigningOutOfAnEntryThatCannotBeRead(t *testing.T) { expectCode(t, r, ExitUsage) } -// An entry written in a form a sign-in would not write is reached as it stands as -// well. Read first, a sign-out would look for the canonical spelling, find -// nothing and leave the token where it is — the very case the CLI itself teaches -// about. The other way round, with the canonical host named and the odd one in -// the file, the answer says which entry holds the token. +// A host written in a form a sign-in would not write is the host of its profile +// as a sign-in writes it, so a sign-out reaches it under either spelling and +// leaves the profile of another host where it is. func TestSigningOutOfAnEntryWrittenAnotherWay(t *testing.T) { const written = "https://hand.example.com/" e := newTestEnv(t) @@ -1864,26 +1834,14 @@ func TestSigningOutOfAnEntryWrittenAnotherWay(t *testing.T) { env, r := e.runJSON("", "auth", "logout", "--host", "https://hand.example.com") expectCode(t, r, ExitOK) - if data := decode(t, env.Data); data["removed"] != false { - t.Errorf("data of the sign-out: %v", data) - } - if !strings.Contains(env.Notice, written) { - t.Errorf("the answer does not say which entry holds the token: %q", env.Notice) - } - - env, r = e.runJSON("", "auth", "logout", "--host", written) - expectCode(t, r, ExitOK) - if data := decode(t, env.Data); data["removed"] != true { + if data := decode(t, env.Data); data["removed"] != true || data["profile"] != "hand.example.com" { t.Errorf("data of the sign-out: %v", data) } - file, err := config.Load(e.vars["MINKA_CONFIG"]) - if err != nil { - t.Fatal(err) - } - if _, ok := file.Hosts[written]; ok { + file := e.config() + if standing := len(file.ProfilesOnHost("https://hand.example.com")) > 0; standing { t.Error("the entry written another way is still there") } - if _, ok := file.Hosts[e.server.URL]; !ok { + if standing := len(file.ProfilesOnHost(e.server.URL)) > 0; !standing { t.Error("the entry of another host was taken away with it") } } @@ -2107,7 +2065,7 @@ func TestLoginAsksForTheTokenOnATerminal(t *testing.T) { if strings.Contains(r.stdout+r.stderr, e.fixture.Token) { t.Error("the token appears in the output") } - if file, err := config.Load(e.vars["MINKA_CONFIG"]); err != nil || file.Hosts[e.server.URL].Token != e.fixture.Token { + if file, err := config.Load(e.vars["MINKA_CONFIG"]); err != nil || file.Profiles[profileNamedAfter(e.server.URL)].Token != e.fixture.Token { t.Errorf("token not saved: %+v, %v", file, err) } } diff --git a/internal/cli/defaulthost_test.go b/internal/cli/defaulthost_test.go index c3c05c0..246af35 100644 --- a/internal/cli/defaulthost_test.go +++ b/internal/cli/defaulthost_test.go @@ -30,7 +30,11 @@ func (e *testEnv) defaultHost() string { if err != nil { e.t.Fatal(err) } - return file.DefaultHost + profile, ok := file.Profiles[file.DefaultProfile] + if !ok { + return "" + } + return profile.Host } // On a fresh machine there is no default to keep, and the first host signed in @@ -63,12 +67,12 @@ func TestASecondLoginKeepsTheDefaultHost(t *testing.T) { if data := decode(t, env.Data); data["isDefault"] != false || data["defaultHost"] != e.server.URL || data["host"] != other.URL { t.Errorf("data %s", env.Data) } - if !strings.Contains(env.Summary, "default host stays "+e.server.URL) { + if !strings.Contains(env.Summary, "default profile stays "+profileNamedAfter(e.server.URL)) { t.Errorf("summary %q", env.Summary) } found := false for _, b := range env.Breadcrumbs { - found = found || b.Cmd == "minka config set host "+other.URL + found = found || b.Cmd == "minka profiles default "+profileNamedAfter(other.URL) } if !found { t.Errorf("no breadcrumb that makes %s the default: %+v", other.URL, env.Breadcrumbs) @@ -76,7 +80,7 @@ func TestASecondLoginKeepsTheDefaultHost(t *testing.T) { r = e.run("minka_pat_bruno", "auth", "login", "--host", other.URL, "--with-token", "--styled") expectCode(t, r, ExitOK) - if !strings.Contains(r.stdout, "The default host stays "+e.server.URL) || !strings.Contains(r.stdout, "minka config set host "+other.URL) { + if !strings.Contains(r.stdout, "The default profile stays "+profileNamedAfter(e.server.URL)) || !strings.Contains(r.stdout, "minka profiles default "+profileNamedAfter(other.URL)) { t.Errorf("the text does not say that the default stays:\n%s", r.stdout) } @@ -162,14 +166,14 @@ func TestLogoutOfTheDefaultHostLeavesNoDefault(t *testing.T) { if e.defaultHost() != "" { t.Errorf("default host %q, want none", e.defaultHost()) } - if !strings.Contains(env.Notice, "no host is the default now") || !strings.Contains(env.Notice, "minka config set host") { + if !strings.Contains(env.Notice, "no profile is the default now") || !strings.Contains(env.Notice, "minka profiles default") { t.Errorf("notice %q", env.Notice) } before := len(other.Requests()) env, r = e.runJSON("", "me") expectCode(t, r, ExitAuth) - if env.Error != "no default host is set" || !strings.Contains(env.Hint, "minka config set host") { + if env.Error != "no default profile is set" || !strings.Contains(env.Hint, "minka profiles default") { t.Errorf("error %q, hint %q", env.Error, env.Hint) } if len(other.Requests()) != before { @@ -189,19 +193,19 @@ func TestStatusNamesTheDefaultHostWhereTheHostOfTheCommandDiffers(t *testing.T) env, r := e.runJSON("", "auth", "status", "--host", other.URL) expectCode(t, r, ExitOK) data := decode(t, env.Data) - if data["host"] != other.URL || data["defaultHost"] != e.server.URL || data["hostSource"] != hostFromFlag { + if data["host"] != other.URL || data["defaultHost"] != e.server.URL || data["hostSource"] != "flag" { t.Errorf("data %s", env.Data) } r = e.run("", "auth", "status", "--host", other.URL, "--styled") expectCode(t, r, ExitOK) - if !strings.Contains(r.stdout, "Signed in to "+other.URL+" ") || !strings.Contains(r.stdout, "the default host is "+e.server.URL+".") { + if !strings.Contains(r.stdout, "Signed in to "+other.URL+" ") || !strings.Contains(r.stdout, "the default profile is "+profileNamedAfter(e.server.URL)+".") { t.Errorf("the text does not name both hosts:\n%s", r.stdout) } e.vars["MINKA_HOST"] = other.URL env, r = e.runJSON("", "auth", "status") expectCode(t, r, ExitOK) - if data := decode(t, env.Data); data["hostSource"] != hostFromEnvironment || data["defaultHost"] != e.server.URL { + if data := decode(t, env.Data); data["hostSource"] != "environment" || data["defaultHost"] != e.server.URL { t.Errorf("data %s", env.Data) } if !strings.Contains(env.Summary, "$MINKA_HOST") { @@ -214,12 +218,12 @@ func TestStatusNamesTheHostOnceWhereItIsTheDefault(t *testing.T) { env, r := e.runJSON("", "auth", "status") expectCode(t, r, ExitOK) - if data := decode(t, env.Data); data["host"] != e.server.URL || data["defaultHost"] != e.server.URL || data["hostSource"] != hostFromDefault { + if data := decode(t, env.Data); data["host"] != e.server.URL || data["defaultHost"] != e.server.URL || data["hostSource"] != "default" { t.Errorf("data %s", env.Data) } r = e.run("", "auth", "status", "--styled") expectCode(t, r, ExitOK) - if strings.Count(r.stdout, e.server.URL) != 1 || !strings.Contains(r.stdout, "It is the default host.") { + if strings.Count(r.stdout, e.server.URL) != 1 || !strings.Contains(r.stdout, "The profile "+profileNamedAfter(e.server.URL)+" is the default profile.") { t.Errorf("the text names the host other than once:\n%s", r.stdout) } } @@ -232,7 +236,7 @@ func TestDoctorNamesTheDefaultHostWhereTheHostOfTheCommandDiffers(t *testing.T) if report.Host == nil || *report.Host != other.URL || report.DefaultHost == nil || *report.DefaultHost != e.server.URL { t.Errorf("host %v, default host %v", report.Host, report.DefaultHost) } - if detail := report.check(t, "sign-in").Detail; !strings.Contains(detail, other.URL) || !strings.Contains(detail, "the default host is "+e.server.URL) { + if detail := report.check(t, "sign-in").Detail; !strings.Contains(detail, other.URL) || !strings.Contains(detail, "the default profile is "+profileNamedAfter(e.server.URL)) { t.Errorf("sign-in detail %q", detail) } @@ -241,28 +245,31 @@ func TestDoctorNamesTheDefaultHostWhereTheHostOfTheCommandDiffers(t *testing.T) if report.Host == nil || *report.Host != e.server.URL || report.DefaultHost == nil || *report.DefaultHost != e.server.URL { t.Errorf("host %v, default host %v", report.Host, report.DefaultHost) } - if detail := report.check(t, "sign-in").Detail; strings.Count(detail, e.server.URL) != 1 || !strings.Contains(detail, "it is the default host") { + if detail := report.check(t, "sign-in").Detail; strings.Count(detail, e.server.URL) != 1 || !strings.Contains(detail, "is the default profile") { t.Errorf("sign-in detail %q", detail) } } -// A default host that cannot be read is no missing default: every command -// without --host fails on it, and a report that called it none would hide that. -func TestStatusAndDoctorSayThatTheDefaultHostCannotBeRead(t *testing.T) { +// A default profile whose host cannot be read is no missing default: every +// command without --profile fails on it, and a report that called it none would +// hide that. +func TestStatusAndDoctorSayThatTheDefaultProfileCannotBeRead(t *testing.T) { e := newTestEnv(t) delete(e.vars, "MINKA_TOKEN") delete(e.vars, "MINKA_HOST") - e.writeConfig(`{"defaultHost":"https://minka.example.com;t=x","hosts":{"` + e.server.URL + `":{"token":"` + e.fixture.Token + `"}}}`) + e.writeConfig(`{"defaultProfile":"bad","profiles":{` + + `"bad":{"host":"https://minka.example.com;t=x","token":"minka_pat_written_by_hand"},` + + `"good":{"host":"` + e.server.URL + `","token":"` + e.fixture.Token + `"}}}`) env, r := e.runJSON("", "auth", "status", "--host", e.server.URL) expectCode(t, r, ExitOK) - if !strings.Contains(env.Summary, "the default host cannot be read: ") || strings.Contains(env.Summary, "no default host is set") { + if !strings.Contains(env.Summary, "the default profile cannot be read: ") || strings.Contains(env.Summary, "no default profile is set") { t.Errorf("summary %q", env.Summary) } e.vars["MINKA_HOST"] = e.server.URL report, _ := e.doctor() - if detail := report.check(t, "sign-in").Detail; !strings.Contains(detail, "the default host cannot be read: ") { + if detail := report.check(t, "sign-in").Detail; !strings.Contains(detail, "the default profile cannot be read: ") { t.Errorf("sign-in detail %q", detail) } } @@ -278,7 +285,7 @@ func TestStatusSaysThatTheConfigurationCannotBeRead(t *testing.T) { env, r := e.runJSON("", "auth", "status") expectCode(t, r, ExitOK) - if !strings.Contains(env.Summary, "the default host cannot be read: ") || !strings.Contains(env.Summary, "accessible by other users") { + if !strings.Contains(env.Summary, "the default profile cannot be read: ") || !strings.Contains(env.Summary, "accessible by other users") { t.Errorf("summary %q", env.Summary) } } @@ -291,7 +298,7 @@ func TestStatusNamesTheFlagBeforeTheEnvironment(t *testing.T) { env, r := e.runJSON("", "auth", "status", "--host", other.URL) expectCode(t, r, ExitOK) - if data := decode(t, env.Data); data["hostSource"] != hostFromFlag || data["host"] != other.URL { + if data := decode(t, env.Data); data["hostSource"] != "flag" || data["host"] != other.URL { t.Errorf("data %s", env.Data) } } diff --git a/internal/cli/doctor.go b/internal/cli/doctor.go index 6f21e76..361dff0 100644 --- a/internal/cli/doctor.go +++ b/internal/cli/doctor.go @@ -34,18 +34,20 @@ func (a *app) newDoctorCmd() *cobra.Command { Long: `Checks what a command needs to work: the config file and its permissions, the host and the token, whether the host answers and accepts the token, whether the installed skill is the one this minka carries, and how this minka -stands against the latest and the oldest version Minka names. Where --host or -$MINKA_HOST names another host than the default one, it names both. +stands against the latest and the oldest version Minka names. It names the +profile a command uses and where that choice came from, and the default +profile where it is another one. It is a report and exits 0 whatever it finds. With --json, data.healthy is false when a check failed; every check carries status (ok, warn, fail, or skip where a check before it failed), detail and, where something can be -done, hint. data.host is the host of the command, data.defaultHost the default host -of the config file; either is null where there is none.`, +done, hint. data.host is the host of the command, data.defaultHost the host of +the default profile, data.profile the profile of the command and +data.defaultProfile the default profile; each is null where there is none.`, Args: requireArgs(), RunE: func(*cobra.Command, []string) error { - checks, host := a.doctorChecks() - defaultHost, _ := a.defaultHostToReport() + checks, host, profile := a.doctorChecks() + defaultProfile, defaultHost, _ := a.defaultToReport() healthy := true problems := 0 @@ -67,6 +69,7 @@ of the config file; either is null where there is none.`, data: map[string]any{ "healthy": healthy, "version": version, "checks": checks, "host": nullable(host), "defaultHost": nullable(defaultHost), + "profile": nullable(profile), "defaultProfile": nullable(defaultProfile), }, summary: summary, text: func(w io.Writer) { @@ -82,9 +85,10 @@ of the config file; either is null where there is none.`, } } -// doctorChecks runs the checks and names the host of the command: the one the -// session reached, else the one --host or $MINKA_HOST names, else none. -func (a *app) doctorChecks() ([]doctorCheck, string) { +// doctorChecks runs the checks and names the host and the profile of the +// command: the ones the session reached, else the ones the choice names, else +// none. +func (a *app) doctorChecks() ([]doctorCheck, string, string) { checks := []doctorCheck{{Name: "version", Status: checkOK, Detail: "minka " + version}} configCheck := doctorCheck{Name: "config", Status: checkOK} @@ -99,8 +103,12 @@ func (a *app) doctorChecks() ([]doctorCheck, string) { signIn := doctorCheck{Name: "sign-in", Status: checkOK} host := doctorCheck{Name: "host", Status: checkOK} - s, err := a.session() - sessionHost := "" + c, path, file, err := a.chooseAccount(true) + var s *session + if err == nil { + s, err = a.sessionOf(c, path, file) + } + sessionHost, sessionProfile := "", "" if err != nil { signIn.Status, signIn.Detail, signIn.Hint = checkFail, err.Error(), hintOf(err) var cliErr *Error @@ -112,16 +120,16 @@ func (a *app) doctorChecks() ([]doctorCheck, string) { signIn.Status, signIn.Detail, signIn.Hint = checkSkip, "not checked, see config", "" } host.Status, host.Detail = checkSkip, "not checked without a sign-in" - // The host the command was given is still the one it would reach. - sessionHost, _ = a.explicitHost() + // The account the command was given is still the one it would reach. + sessionHost, sessionProfile = c.host, c.profile } else { - sessionHost = s.host + sessionHost, sessionProfile = s.host, s.profile signIn.Detail = "a token for " + s.host + " from the config file" if s.tokenSource == tokenFromEnvironment { signIn.Detail = "a token for " + s.host + " from $MINKA_TOKEN" } - defaultHost, problem := a.defaultHostToReport() - signIn.Detail += "; " + hostsInWords(s.host, a.hostSource(), defaultHost, problem) + defaultProfile, _, problem := a.defaultToReport() + signIn.Detail += "; " + accountInWords(c, defaultProfile, problem) if me, err := s.client.Me(a.ctx); err != nil { e := s.fail(err) host.Status, host.Detail, host.Hint = checkFail, e.Message, e.Hint @@ -134,7 +142,7 @@ func (a *app) doctorChecks() ([]doctorCheck, string) { } checks = append(checks, signIn, host) - return append(checks, a.doctorSkillCheck(), a.doctorUpdateCheck()), sessionHost + return append(checks, a.doctorSkillCheck(), a.doctorUpdateCheck()), sessionHost, sessionProfile } func hintOf(err error) string { diff --git a/internal/cli/logout_test.go b/internal/cli/logout_test.go index 87659cc..01416c1 100644 --- a/internal/cli/logout_test.go +++ b/internal/cli/logout_test.go @@ -88,10 +88,10 @@ func TestLogoutRevokesTheTokenOfTheHostItIsTold(t *testing.T) { if err != nil { t.Fatal(err) } - if _, standing := file.Hosts[other.URL]; !standing { + if standing := len(file.ProfilesOnHost(other.URL)) > 0; !standing { t.Error("the entry of the default host was taken out") } - if _, standing := file.Hosts[e.server.URL]; standing { + if standing := len(file.ProfilesOnHost(e.server.URL)) > 0; standing { t.Error("the entry of the host told was left") } } @@ -135,7 +135,7 @@ func TestLogoutKeepsTheEntryWhenTheHostDoesNotAnswer(t *testing.T) { if err != nil { t.Fatal(err) } - if _, standing := file.Hosts[gone.URL]; !standing { + if standing := len(file.ProfilesOnHost(gone.URL)) > 0; !standing { t.Error("the entry was taken out") } } @@ -152,7 +152,7 @@ func TestLogoutSaysTheTokenIsRevokedWhenTheEntryCannotBeRemoved(t *testing.T) { env, r := e.runJSON("", "auth", "logout", "--revoke") expectCode(t, r, ExitUsage) - if env.Code != CodeConfig || !strings.Contains(env.Error, "the token is revoked, but its entry could not be taken out") { + if env.Code != CodeConfig || !strings.Contains(env.Error, "the token is revoked, but its profile could not be taken out") { t.Errorf("code %q, error %q", env.Code, env.Error) } if data := decode(t, env.Data); data["revoked"] != true || data["removed"] != false { @@ -160,21 +160,6 @@ func TestLogoutSaysTheTokenIsRevokedWhenTheEntryCannotBeRemoved(t *testing.T) { } } -// The way to the entry written another way keeps --revoke when it was given. -func TestTheEntryWrittenAnotherWayIsNamedWithRevoke(t *testing.T) { - const written = "https://hand.example.com/" - e := newTestEnv(t) - delete(e.vars, "MINKA_HOST") - delete(e.vars, "MINKA_TOKEN") - e.writeConfig(`{"defaultHost":"` + written + `","hosts":{"` + written + `":{"token":"minka_pat_written_by_hand"}}}`) - - env, r := e.runJSON("", "auth", "logout", "--host", "https://hand.example.com", "--revoke") - expectCode(t, r, ExitOK) - if !strings.HasSuffix(env.Notice, " --revoke") { - t.Errorf("notice %q", env.Notice) - } -} - // signedInByFile signs in through the config file alone, so that a sign-out // has an entry to take out and nothing in the environment stands beside it. func signedInByFile(t *testing.T) *testEnv { @@ -191,7 +176,7 @@ func (e *testEnv) entryStands() bool { if err != nil { e.t.Fatal(err) } - _, standing := file.Hosts[e.server.URL] + standing := len(file.ProfilesOnHost(e.server.URL)) > 0 return standing } @@ -327,7 +312,7 @@ func TestLogoutWithRevokeOfAnEntryThatCannotBeReadSendsNothing(t *testing.T) { if err != nil { t.Fatal(err) } - if _, standing := file.Hosts[written]; !standing { + if standing := len(file.ProfilesOnHost(written)) > 0; !standing { t.Error("the entry was taken out although its token was not revoked") } } diff --git a/internal/cli/output.go b/internal/cli/output.go index be4fba4..c2c29e2 100644 --- a/internal/cli/output.go +++ b/internal/cli/output.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io" + "slices" "strings" ) @@ -80,6 +81,7 @@ type success struct { // ok prints a success. Notices go into the envelope for --json and to stderr // otherwise, so that --quiet keeps stdout to the bare data without losing them. func (a *app) ok(s success) error { + s.notices = slices.Concat(a.runNotices, s.notices) if !a.skillIsTheTopic { if notice := a.staleSkillNotice(); notice != "" { s.notices = append(s.notices, notice) @@ -123,6 +125,14 @@ func (a *app) noticeChannel() noticeChannel { return noChannel } +// noteOnce keeps a notice for the answer of this run, once however often it is +// noted. +func (a *app) noteOnce(notice string) { + if !slices.Contains(a.runNotices, notice) { + a.runNotices = append(a.runNotices, notice) + } +} + func (a *app) warn(notices []string) { for _, notice := range notices { fmt.Fprintf(a.stderr, "Warning: %s\n", notice) @@ -130,6 +140,7 @@ func (a *app) warn(notices []string) { } func (a *app) fail(e *Error) { + e.Notices = slices.Concat(a.runNotices, e.Notices) _, update := a.settleCLIUpdate(a.noticeChannel()) if a.format() != formatText { response := ErrorResponse{OK: false, Error: e.Message, Code: e.Code, Retryable: e.Retryable, Hint: e.fullHint(), Data: e.Data, Notice: strings.Join(e.Notices, "; "), CLIUpdate: update} diff --git a/internal/cli/profiles.go b/internal/cli/profiles.go new file mode 100644 index 0000000..5f3bdfc --- /dev/null +++ b/internal/cli/profiles.go @@ -0,0 +1,459 @@ +package cli + +import ( + "fmt" + "io" + "strings" + + "github.com/flownative/minka-cli/internal/config" + "github.com/spf13/cobra" +) + +// Where the account of a command comes from, strongest first. +const ( + chosenByProfileFlag = "--profile" + chosenByHostFlag = "--host" + chosenByProfileEnv = "$MINKA_PROFILE" + chosenByHostEnv = "$MINKA_HOST" + chosenByDefault = "default" + + // chosenByStore is the account a beat reports for because the list of its + // session lies there. + chosenByStore = "the list of the session" +) + +// choice is the account a command works with. +type choice struct { + profile string // empty where no profile stands for the account + host string // as a sign-in writes it; empty where nothing names one + source string + envToken string // $MINKA_TOKEN, where it is the token of the choice +} + +// key is what the state of the account on this machine is kept under: the name +// of its profile, else its host. A profile name never reads as a host, so the +// two cannot meet. +func (c choice) key() string { + if c.profile != "" && c.envToken == "" { + return c.profile + } + return c.host +} + +// requestedChoice says where a command is told its account from, before the +// configuration is read: --profile, then --host, then $MINKA_PROFILE, then +// $MINKA_HOST, else the default profile. A flag outweighs every variable of the +// environment, and the two flags together contradict each other. +func (a *app) requestedChoice() (source, value string, err error) { + if a.profileFlag != "" && a.hostFlag != "" { + return "", "", &Error{Code: CodeUsage, Message: "--profile and --host both name the account of a command", Hint: "Give one of them: a profile names its host itself."} + } + switch { + case a.profileFlag != "": + return chosenByProfileFlag, a.profileFlag, nil + case a.hostFlag != "": + return chosenByHostFlag, a.hostFlag, nil + case a.getenv("MINKA_PROFILE") != "": + return chosenByProfileEnv, a.getenv("MINKA_PROFILE"), nil + case a.getenv("MINKA_HOST") != "": + return chosenByHostEnv, a.getenv("MINKA_HOST"), nil + default: + return chosenByDefault, "", nil + } +} + +// chooseAccount finds the account of a command, and the configuration where it +// was read. The configuration is read only where it is needed: $MINKA_HOST and +// $MINKA_TOKEN sign a command in without one. +// +// $MINKA_TOKEN belongs to $MINKA_HOST. It is the token of a command whose host +// comes from --host or $MINKA_HOST and is that host, and of no other: a profile +// names an account of its own, which may be another one on the same host. +// Without useEnvToken the token is passed over, for a command about the +// configuration itself. +func (a *app) chooseAccount(useEnvToken bool) (choice, string, *config.File, error) { + source, value, err := a.requestedChoice() + if err != nil { + return choice{}, "", nil, err + } + envToken := a.getenv("MINKA_TOKEN") + if useEnvToken && envToken != "" { + envHostValue := a.getenv("MINKA_HOST") + if envHostValue == "" { + return choice{}, "", nil, &Error{Code: CodeUsage, Message: "$MINKA_TOKEN is set without $MINKA_HOST", Hint: "Set $MINKA_HOST to the host the token belongs to."} + } + envHost, err := config.NormalizeHost(envHostValue) + if err != nil { + return choice{}, "", nil, &Error{Code: CodeUsage, Message: "$MINKA_HOST: " + err.Error()} + } + if source == chosenByProfileFlag || source == chosenByProfileEnv { + a.noteOnce("the token in $MINKA_TOKEN was not used: it belongs to $MINKA_HOST, and " + source + " names a profile, which signs in with its own token") + } + if source == chosenByHostFlag || source == chosenByHostEnv { + host, err := config.NormalizeHost(value) + if err != nil { + return choice{}, "", nil, &Error{Code: CodeUsage, Message: err.Error()} + } + if host == envHost { + return choice{host: host, source: source, envToken: envToken}, "", nil, nil + } + } + } + + path, file, err := a.loadConfig() + if err != nil { + return choice{}, "", nil, err + } + c, err := chooseIn(file, path, source, value) + return c, path, file, err +} + +// chooseIn finds the account of a command in the configuration. +// +// A host stands for the one profile on it. Where several are, it stands for the +// default profile if that is among them, and for none otherwise: which account +// writes in an organization is not to be guessed. A host without a profile is a +// host not signed in to. +func chooseIn(file *config.File, path, source, value string) (choice, error) { + switch source { + case chosenByProfileFlag, chosenByProfileEnv: + if err := config.CheckProfileName(value); err != nil { + return choice{}, profileNameError(source, err) + } + return profileChoice(file, path, value, source) + case chosenByHostFlag, chosenByHostEnv: + host, err := config.NormalizeHost(value) + if err != nil { + return choice{}, &Error{Code: CodeUsage, Message: err.Error()} + } + names := file.ProfilesOnHost(host) + switch { + case len(names) == 0: + return choice{host: host, source: source}, nil + case len(names) == 1: + return choice{profile: names[0], host: host, source: source}, nil + } + if name, ok := file.HostProfile(host); ok && name == file.DefaultProfile { + return choice{profile: name, host: host, source: source}, nil + } + return choice{}, &Error{ + Code: CodeAmbiguous, + Message: fmt.Sprintf("%d profiles sign in to %s: %s", len(names), host, strings.Join(names, ", ")), + Hint: "Choose one with --profile , or set $MINKA_PROFILE.", + } + default: + if file.DefaultProfile == "" { + return choice{source: source}, nil + } + if _, ok := file.Profiles[file.DefaultProfile]; !ok { + return choice{}, &Error{ + Code: CodeConfig, + Message: fmt.Sprintf("the default profile %q is not among the profiles in %s", file.DefaultProfile, path), + Hint: "Make one of them the default: minka profiles default ", + } + } + return profileChoice(file, path, file.DefaultProfile, source) + } +} + +// profileChoice is the choice of a profile by its name. The host is read the +// way a sign-in writes it, so that every process makes the same key of it, and +// one that cannot be read is refused rather than carried into everything that +// prints a host. +func profileChoice(file *config.File, path, name, source string) (choice, error) { + profile, ok := file.Profiles[name] + if !ok { + return choice{}, unknownProfileError(file, name) + } + host, err := config.NormalizeHost(profile.Host) + if err != nil { + return choice{}, &Error{ + Code: CodeConfig, + Message: fmt.Sprintf("the host of the profile %s in %s cannot be read: %s", name, path, err), + Hint: "Correct \"host\" of that profile in the file, or take the profile out: minka profiles remove " + name, + } + } + return choice{profile: name, host: host, source: source}, nil +} + +func profileNameError(source string, err error) *Error { + return &Error{Code: CodeUsage, Message: source + ": " + err.Error(), Hint: "A profile name is lower case letters, digits, \"-\" and \".\", such as flownative; minka profiles list shows them."} +} + +// profileNamed refuses a name that is no profile name, before it is said back +// as one, and a profile that is not there. +func profileNamed(file *config.File, what, name string) error { + if err := config.CheckProfileName(name); err != nil { + return profileNameError(what, err) + } + if _, ok := file.Profiles[name]; !ok { + return unknownProfileError(file, name) + } + return nil +} + +func unknownProfileError(file *config.File, name string) *Error { + e := &Error{Code: CodeUsage, Message: "there is no profile " + name} + if names := file.ProfileNames(); len(names) > 0 { + e.Hint = "The profiles are: " + strings.Join(names, ", ") + ". A new one is made by signing in: minka auth login --profile " + name + " --host " + } else { + e.Hint = "There are no profiles yet. A profile is made by signing in: minka auth login --profile " + name + " --host " + } + return e +} + +// defaultToReport is the default profile and its host, for a report that names +// them beside the account a command uses. Both are empty where there is none. +// Where it or the configuration cannot be read, they are empty as well and the +// problem says why: a command given its account otherwise gets past both, while +// every command without one fails on them. +func (a *app) defaultToReport() (profile, host, problem string) { + path, file, err := a.loadConfig() + if err != nil { + return "", "", err.Error() + } + if file.DefaultProfile == "" { + return "", "", "" + } + c, err := chooseIn(file, path, chosenByDefault, "") + if err != nil { + return "", "", err.Error() + } + return c.profile, c.host, "" +} + +// accountInWords says which account a command uses and how it stands to the +// default profile, naming the default only where the two differ. +func accountInWords(c choice, defaultProfile, problem string) string { + var account string + switch { + case c.envToken != "": + account = "the token of $MINKA_TOKEN goes to " + c.host + ", named by " + c.source + case c.profile == "": + account = "no profile signs in to " + c.host + ", named by " + c.source + case c.source == chosenByDefault: + return "the profile " + c.profile + " is the default profile" + case c.profile == defaultProfile: + return "the profile " + c.profile + " comes from " + c.source + " and is the default profile" + default: + account = "the profile " + c.profile + " comes from " + c.source + } + switch { + case problem != "": + return account + ", and the default profile cannot be read: " + problem + case defaultProfile == "": + return account + ", and no default profile is set" + default: + return account + ", the default profile is " + defaultProfile + } +} + +// noAccountError is the refusal of a command that names no account where the +// configuration names no default profile either. Nothing picks a profile by +// itself, because the default is a choice and not what happened to be left over. +func noAccountError(file *config.File) *Error { + if len(file.Profiles) == 0 { + return &Error{Code: CodeAuth, Message: "not signed in to any Minka host", Hint: "Run: minka auth login --host https://minka.example.com"} + } + return &Error{ + Code: CodeAuth, + Message: "no default profile is set", + Hint: "Give the profile with --profile , or make one the default: minka profiles default . The profiles are: " + strings.Join(file.ProfileNames(), ", "), + } +} + +func (a *app) newProfilesCmd() *cobra.Command { + return group("profiles", "List, rename and remove the profiles you sign in with, and choose the default", + a.newProfilesListCmd(), + a.newProfilesRenameCmd(), + a.newProfilesRemoveCmd(), + a.newProfilesDefaultCmd(), + ) +} + +func (a *app) newProfilesListCmd() *cobra.Command { + return &cobra.Command{ + Use: "list", + Short: "Show the profiles, the default one and the one a command uses now", + Long: `Shows every profile: its name, its host, the account it signed in as, whether it +is the default, and which one a command run here now uses and why — --profile, +--host, $MINKA_PROFILE, $MINKA_HOST or the default. + +It asks nothing of the network. 'active' is null where no profile stands for +the account of a command, such as one signed in through $MINKA_TOKEN, and +'activeProblem' says why where the choice fails.`, + Args: requireArgs(), + RunE: func(*cobra.Command, []string) error { + path, file, err := a.loadConfig() + if err != nil { + return err + } + c, _, _, chooseErr := a.chooseAccount(true) + problem := "" + if chooseErr != nil { + problem = chooseErr.Error() + } + + rows := []map[string]any{} + for _, name := range file.ProfileNames() { + profile := file.Profiles[name] + rows = append(rows, map[string]any{ + "name": name, "host": config.HostForOutput(profile.Host), + "personName": nullable(profile.PersonName), "emailAddress": nullable(profile.EmailAddress), + "isDefault": name == file.DefaultProfile, "isActive": chooseErr == nil && c.envToken == "" && name == c.profile, + }) + } + var active any + if chooseErr == nil && c.profile != "" && c.envToken == "" { + active = map[string]any{"profile": c.profile, "source": c.source} + } + summary := plural(len(rows), "profile", "profiles") + return a.ok(success{ + data: map[string]any{ + "profiles": rows, "defaultProfile": nullable(file.DefaultProfile), "active": active, + "activeSource": nullable(c.source), "activeProblem": nullable(problem), "configPath": path, + }, + summary: summary, + text: func(w io.Writer) { + if len(rows) == 0 { + fmt.Fprintln(w, "No profile. Sign in with: minka auth login --host ") + return + } + for _, name := range file.ProfileNames() { + profile := file.Profiles[name] + marks := "" + if name == file.DefaultProfile { + marks += " (default)" + } + if chooseErr == nil && c.envToken == "" && name == c.profile { + marks += " (active: " + c.source + ")" + } + account := profile.PersonName + if profile.EmailAddress != "" { + account += " <" + profile.EmailAddress + ">" + } + fmt.Fprintf(w, "%s %s %s%s\n", name, config.HostForOutput(profile.Host), account, marks) + } + switch { + case problem != "": + fmt.Fprintf(w, "\nNo profile is active: %s\n", problem) + case c.envToken != "": + fmt.Fprintf(w, "\nNo profile is active: the token of $MINKA_TOKEN goes to %s.\n", c.host) + } + }, + }) + }, + } +} + +func (a *app) newProfilesRenameCmd() *cobra.Command { + return &cobra.Command{ + Use: "rename ", + Short: "Give a profile another name", + Long: `Gives a profile another name. It stays the default where it was, and the cards +it holds in the list of 'minka work start' go along with it.`, + Example: " minka profiles rename minka.flownative.com flownative", + Args: requireArgs("old", "new"), + RunE: func(cmd *cobra.Command, args []string) error { + from, to := args[0], args[1] + if err := config.CheckProfileName(to); err != nil { + return profileNameError("the new name", err) + } + path, file, err := a.loadConfig() + if err != nil { + return err + } + if err := profileNamed(file, "the profile", from); err != nil { + return err + } + if from == to { + return usageErrorf(cmd, "the profile is called %s already", to) + } + if _, taken := file.Profiles[to]; taken { + return &Error{Code: CodeUsage, Message: "there is a profile " + to + " already", Hint: "Choose another name, or take that profile out first: minka profiles remove " + to} + } + if err := file.RenameProfile(from, to); err != nil { + return &Error{Code: CodeUsage, Message: err.Error()} + } + if err := file.Save(path); err != nil { + return &Error{Code: CodeConfig, Message: err.Error()} + } + // The store follows the configuration, so that what it writes for an + // older version per host is the lists of the profile by its new name. + var notices []string + if err := a.renameInTheStore(from, to); err != nil { + notices = append(notices, "the cards of the profile could not be moved to its new name, so its list starts empty: "+err.Error()) + } + summary := "Renamed the profile " + from + " to " + to + return a.ok(success{ + data: map[string]any{"from": from, "to": to, "isDefault": file.DefaultProfile == to}, + notices: notices, + summary: summary, + text: func(w io.Writer) { fmt.Fprintf(w, "%s.\n", summary) }, + }) + }, + } +} + +func (a *app) newProfilesRemoveCmd() *cobra.Command { + var revoke bool + cmd := &cobra.Command{ + Use: "remove ", + Short: "Remove a profile and its token, and revoke the token with --revoke", + Long: `Removes a profile and its token from the config file, as 'minka auth logout' +does for the profile a command uses. Without --revoke the token itself stays +valid on the server until it is revoked there. + +--revoke revokes the token on the server first, and only then removes the +profile: it holds the one copy of the token this machine has, so it is kept +when the revocation fails, and the command exits with the code of that failure. + +Removing the default profile leaves no default: the next sign-in sets one, or +minka profiles default names one of the profiles left.`, + Example: " minka profiles remove familie --revoke", + Args: requireArgs("name"), + RunE: func(cmd *cobra.Command, args []string) error { + path, file, err := a.loadConfig() + if err != nil { + return err + } + if err := profileNamed(file, "the profile", args[0]); err != nil { + return err + } + return a.removeProfile(path, file, args[0], revoke) + }, + } + cmd.Flags().BoolVar(&revoke, "revoke", false, "Revoke the token on the server before removing the profile") + return cmd +} + +func (a *app) newProfilesDefaultCmd() *cobra.Command { + return &cobra.Command{ + Use: "default ", + Short: "Make a profile the default", + Long: `Makes a profile the default: the one a command uses that is given neither +--profile nor --host, and finds neither $MINKA_PROFILE nor $MINKA_HOST.`, + Example: " minka profiles default flownative", + Args: requireArgs("name"), + RunE: func(cmd *cobra.Command, args []string) error { + path, file, err := a.loadConfig() + if err != nil { + return err + } + if err := profileNamed(file, "the profile", args[0]); err != nil { + return err + } + previous := file.DefaultProfile + file.DefaultProfile = args[0] + if err := file.Save(path); err != nil { + return &Error{Code: CodeConfig, Message: err.Error()} + } + summary := args[0] + " is the default profile" + return a.ok(success{ + data: map[string]any{"defaultProfile": args[0], "previousDefaultProfile": nullable(previous), "host": config.HostForOutput(file.Profiles[args[0]].Host)}, + summary: summary, + text: func(w io.Writer) { fmt.Fprintf(w, "%s.\n", summary) }, + }) + }, + } +} diff --git a/internal/cli/profiles_test.go b/internal/cli/profiles_test.go new file mode 100644 index 0000000..9a1a674 --- /dev/null +++ b/internal/cli/profiles_test.go @@ -0,0 +1,655 @@ +package cli + +import ( + "encoding/json" + "net/http" + "os" + "strings" + "testing" + "time" + + "github.com/flownative/minka-cli/internal/config" + "github.com/flownative/minka-cli/internal/fakeapi" + "github.com/flownative/minka-cli/internal/work" +) + +// profileNamedAfter is the name a sign-in without --profile gives the first +// profile on a host. +func profileNamedAfter(host string) string { + return (&config.File{}).ProfileNameForHost(host) +} + +func (e *testEnv) config() *config.File { + e.t.Helper() + file, err := config.Load(e.vars["MINKA_CONFIG"]) + if err != nil { + e.t.Fatal(err) + } + return file +} + +// withProfiles signs in with two accounts on the host of the test, "work" as +// the person and "agent" as the agent, and with "familie" on another host, +// with nothing in the environment. "work" is the default. +func withProfiles(t *testing.T) (*testEnv, *fakeapi.Server, *fakeapi.Fixture) { + t.Helper() + e := newTestEnv(t) + other, otherFixture := fakeapi.New(t) + delete(e.vars, "MINKA_TOKEN") + delete(e.vars, "MINKA_HOST") + expectCode(t, e.run(e.fixture.Token, "auth", "login", "--profile", "work", "--host", e.server.URL, "--with-token"), ExitOK) + expectCode(t, e.run(e.fixture.AgentToken, "auth", "login", "--profile", "agent", "--host", e.server.URL, "--with-token"), ExitOK) + expectCode(t, e.run(otherFixture.AgentToken, "auth", "login", "--profile", "familie", "--host", other.URL, "--with-token"), ExitOK) + return e, other, otherFixture +} + +// lastToken is the token the last request to a server carried. +func lastToken(t *testing.T, server *fakeapi.Server) string { + t.Helper() + requests := server.Requests() + if len(requests) == 0 { + t.Fatal("no request reached the server") + } + return strings.TrimPrefix(requests[len(requests)-1].Header.Get("Authorization"), "Bearer ") +} + +func TestAProfileIsChosenByFlagEnvironmentOrDefault(t *testing.T) { + e, other, otherFixture := withProfiles(t) + if file := e.config(); file.DefaultProfile != "work" || len(file.Profiles) != 3 { + t.Fatalf("config %+v", file) + } + + cases := []struct { + name string + args []string + env map[string]string + server *fakeapi.Server + token string + source string + }{ + {"default", nil, nil, e.server, e.fixture.Token, chosenByDefault}, + {"--profile", []string{"--profile", "agent"}, nil, e.server, e.fixture.AgentToken, chosenByProfileFlag}, + {"$MINKA_PROFILE", nil, map[string]string{"MINKA_PROFILE": "familie"}, other, otherFixture.AgentToken, chosenByProfileEnv}, + {"--profile over $MINKA_PROFILE", []string{"--profile", "agent"}, map[string]string{"MINKA_PROFILE": "familie"}, e.server, e.fixture.AgentToken, chosenByProfileFlag}, + {"--host over $MINKA_PROFILE", []string{"--host", other.URL}, map[string]string{"MINKA_PROFILE": "agent"}, other, otherFixture.AgentToken, chosenByHostFlag}, + {"--profile over $MINKA_HOST", []string{"--profile", "familie"}, map[string]string{"MINKA_HOST": e.server.URL}, other, otherFixture.AgentToken, chosenByProfileFlag}, + {"$MINKA_PROFILE over $MINKA_HOST", nil, map[string]string{"MINKA_PROFILE": "familie", "MINKA_HOST": e.server.URL}, other, otherFixture.AgentToken, chosenByProfileEnv}, + // Of the two profiles on the host, the default one. + {"$MINKA_HOST", nil, map[string]string{"MINKA_HOST": e.server.URL}, e.server, e.fixture.Token, chosenByHostEnv}, + } + for _, c := range cases { + for name, value := range c.env { + e.vars[name] = value + } + env, r := e.runJSON("", append([]string{"auth", "status"}, c.args...)...) + for name := range c.env { + delete(e.vars, name) + } + expectCode(t, r, ExitOK) + if got := lastToken(t, c.server); got != c.token { + t.Errorf("%s: the request carried %q, want %q", c.name, got, c.token) + } + if data := decode(t, env.Data); data["profileSource"] != c.source || data["defaultProfile"] != "work" { + t.Errorf("%s: data %s", c.name, env.Data) + } + } +} + +func TestBothFlagsAndAnUnknownOrMisspeltProfileAreRefused(t *testing.T) { + e, other, _ := withProfiles(t) + + _, r := e.runJSON("", "me", "--profile", "work", "--host", other.URL) + expectCode(t, r, ExitUsage) + + env, r := e.runJSON("", "me", "--profile", "nobody") + expectCode(t, r, ExitUsage) + if !strings.Contains(env.Hint, "agent, familie, work") { + t.Errorf("the hint does not list the profiles: %q", env.Hint) + } + + e.vars["MINKA_PROFILE"] = "Not A Name" + env, r = e.runJSON("", "me") + expectCode(t, r, ExitUsage) + if !strings.Contains(env.Error, "$MINKA_PROFILE") { + t.Errorf("error %q", env.Error) + } + if len(e.server.Requests())+len(other.Requests()) != 3 { + t.Errorf("a refused choice sent a request") + } +} + +// A host with several profiles stands for the default one only; without it, +// which account writes is not to be guessed. +func TestAHostWithSeveralProfilesAndNoDefaultAmongThemIsAmbiguous(t *testing.T) { + e, other, _ := withProfiles(t) + expectCode(t, e.run("", "profiles", "default", "familie"), ExitOK) + before := len(e.server.Requests()) + + env, r := e.runJSON("", "me", "--host", e.server.URL) + expectCode(t, r, ExitAmbiguous) + if !strings.Contains(env.Error, "agent, work") || !strings.Contains(env.Hint, "--profile") { + t.Errorf("error %q, hint %q", env.Error, env.Hint) + } + if len(e.server.Requests()) != before { + t.Error("a request was sent") + } + + // A sign-in and the default by host refuse alike. + _, r = e.runJSON(e.fixture.Token, "auth", "login", "--host", e.server.URL, "--with-token") + expectCode(t, r, ExitAmbiguous) + _, r = e.runJSON("", "config", "set", "host", e.server.URL) + expectCode(t, r, ExitAmbiguous) + + // The one profile on a host is that host's. + expectCode(t, e.run("", "me", "--host", other.URL, "--json"), ExitOK) +} + +// $MINKA_TOKEN belongs to $MINKA_HOST and to no profile: a profile named +// signs in with its own token, even on that very host. +func TestTheEnvironmentTokenGoesToNoProfile(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars["MINKA_HOST"] = e.server.URL + e.vars["MINKA_TOKEN"] = e.fixture.StrangerToken + + env, r := e.runJSON("", "auth", "status") + expectCode(t, r, ExitOK) + if got := lastToken(t, e.server); got != e.fixture.StrangerToken { + t.Errorf("the token of $MINKA_HOST was not used for it: %q", got) + } + if data := decode(t, env.Data); data["profile"] != nil || data["tokenSource"] != tokenFromEnvironment { + t.Errorf("data %s", env.Data) + } + + for _, choose := range []func(){ + func() { e.vars["MINKA_PROFILE"] = "agent" }, + func() { delete(e.vars, "MINKA_PROFILE") }, + } { + choose() + args := []string{"auth", "status"} + if e.vars["MINKA_PROFILE"] == "" { + args = append(args, "--profile", "agent") + } + env, r = e.runJSON("", args...) + expectCode(t, r, ExitOK) + if got := lastToken(t, e.server); got != e.fixture.AgentToken { + t.Errorf("the profile signed in with %q, want its own token", got) + } + if data := decode(t, env.Data); data["profile"] != "agent" { + t.Errorf("data %s", env.Data) + } + if !strings.Contains(env.Notice, "$MINKA_TOKEN was not used") { + t.Errorf("nothing says the token of the environment was passed over: %q", env.Notice) + } + } +} + +// A sign-out by host follows the choice of every command: of two profiles on +// the host the default one, and none where the default is elsewhere. It never +// takes, nor revokes, one of them by chance. +func TestASignOutByHostOfSeveralProfilesTakesNoneByChance(t *testing.T) { + for _, revoke := range []bool{false, true} { + e, _, _ := withProfiles(t) + args := []string{"auth", "logout", "--host", e.server.URL} + if revoke { + args = append(args, "--revoke") + } + expectCode(t, e.run("", "profiles", "default", "familie"), ExitOK) + + _, r := e.runJSON("", args...) + expectCode(t, r, ExitAmbiguous) + if file := e.config(); len(file.Profiles) != 3 { + t.Errorf("revoke %v: a profile was removed: %v", revoke, file.ProfileNames()) + } + if e.revocations() != 0 { + t.Errorf("revoke %v: a token was revoked", revoke) + } + + expectCode(t, e.run("", "profiles", "default", "work"), ExitOK) + env, r := e.runJSON("", args...) + expectCode(t, r, ExitOK) + if data := decode(t, env.Data); data["profile"] != "work" { + t.Errorf("revoke %v: data %s", revoke, env.Data) + } + if _, left := e.config().Profiles["agent"]; !left { + t.Errorf("revoke %v: the other profile on the host was removed", revoke) + } + if revoke { + revocations := 0 + for _, request := range e.server.WritingRequests() { + if request.Method == http.MethodDelete && request.Path == "/api/v1/me/token" { + revocations++ + if got := request.Header.Get("Authorization"); got != "Bearer "+e.fixture.Token { + t.Errorf("the revocation carried %q", got) + } + } + } + if revocations != 1 { + t.Errorf("%d revocations", revocations) + } + } + } +} + +// The cards of a profile go with it. A later profile of the same name, on +// another host, must not report them there with its token. +func TestARemovedProfileLeavesNoCardsBehind(t *testing.T) { + e, other, otherFixture := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--profile", "agent", "--json"), ExitOK) + + expectCode(t, e.run("", "profiles", "remove", "agent", "--json"), ExitOK) + if _, left := e.storedHosts()["agent"]; left { + t.Fatalf("the cards of the removed profile are still in the store: %v", e.storedHosts()) + } + + expectCode(t, e.run(otherFixture.AgentToken, "auth", "login", "--profile", "agent", "--host", other.URL, "--with-token"), ExitOK) + expectCode(t, e.run("", "heartbeat", "--json"), ExitOK) + for _, request := range other.Requests() { + if request.Method == http.MethodPut && request.Path == "/api/v1/me/work" && strings.Contains(string(request.Body), e.fixture.CardInDoing.ID) { + t.Error("a card of the removed profile was reported to the other host") + } + } +} + +// A rename onto a name whose lists outlived their profile takes none of them. +func TestARenameMixesNoListsLeftOver(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--profile", "agent", "--json"), ExitOK) + handle, err := work.Open(e.storePath(), waitForTheStore) + if err != nil { + t.Fatal(err) + } + handle.File.Account("bot").List("a-session").Start(work.Card{ID: "left-over", StartedAt: time.Now()}) + if err := handle.Save(); err != nil { + t.Fatal(err) + } + handle.Close() + + expectCode(t, e.run("", "profiles", "rename", "agent", "bot", "--json"), ExitOK) + env, r := e.runJSON("", "work", "list", "--profile", "bot") + expectCode(t, r, ExitOK) + cards := decode(t, env.Data)["cards"].([]any) + if len(cards) != 1 || cards[0].(map[string]any)["id"] != e.fixture.CardInDoing.ID { + t.Errorf("cards %v", cards) + } +} + +// An older minka reads the store per host, so the store keeps per host the +// lists of the profile that host carries in the configuration. +func TestTheStoreKeepsTheHostsForOlderVersions(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--json"), ExitOK) + + content, err := os.ReadFile(e.storePath()) + if err != nil { + t.Fatal(err) + } + var older struct { + Hosts map[string]*work.Account `json:"hosts"` + } + if err := json.Unmarshal(content, &older); err != nil { + t.Fatal(err) + } + list, held := older.Hosts[e.server.URL].Sessions["a-session"] + if !held || len(list.Cards) != 1 || list.Cards[0].ID != e.fixture.CardInDoing.ID { + t.Errorf("the host does not carry the card of its profile: %s", content) + } +} + +// A host that cannot be read finds the profile written letter for letter like +// it, and of two such profiles neither. +func TestAProfileWrittenByHandIsSignedOutOfByItsHost(t *testing.T) { + const written = "https://minka.example.com;t=x" + e := newTestEnv(t) + delete(e.vars, "MINKA_HOST") + delete(e.vars, "MINKA_TOKEN") + e.writeConfig(`{"profiles": { + "one": {"host": "` + written + `", "token": "minka_pat_one"}, + "two": {"host": "` + written + `", "token": "minka_pat_two"}}}`) + + _, r := e.runJSON("", "auth", "logout", "--host", written) + expectCode(t, r, ExitAmbiguous) + if len(e.config().Profiles) != 2 { + t.Fatal("a profile was removed") + } + + expectCode(t, e.run("", "profiles", "remove", "two", "--json"), ExitOK) + env, r := e.runJSON("", "auth", "logout", "--host", written) + expectCode(t, r, ExitOK) + if data := decode(t, env.Data); data["profile"] != "one" { + t.Errorf("data %s", env.Data) + } +} + +// hostsOfTheStore is what the store writes per host for an older version. +func (e *testEnv) hostsOfTheStore() map[string]*work.Account { + e.t.Helper() + content, err := os.ReadFile(e.storePath()) + if err != nil { + e.t.Fatal(err) + } + var older struct { + Hosts map[string]*work.Account `json:"hosts"` + } + if err := json.Unmarshal(content, &older); err != nil { + e.t.Fatal(err) + } + return older.Hosts +} + +// What the store writes per host is a copy of the profile the host stood for +// then. Once another profile on the host is the default, that copy is still +// no card of the new one. +func TestACopyForOlderVersionsGoesToNoOtherProfile(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "profiles", "default", "agent"), ExitOK) + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--json"), ExitOK) + if _, copied := e.hostsOfTheStore()[e.server.URL]; !copied { + t.Fatal("the store keeps no copy for the host") + } + + expectCode(t, e.run("", "profiles", "default", "work"), ExitOK) + env, r := e.runJSON("", "work", "list", "--profile", "work") + expectCode(t, r, ExitOK) + if cards := decode(t, env.Data)["cards"].([]any); len(cards) != 0 { + t.Errorf("the card of agent is listed under work: %s", env.Data) + } +} + +// A rename writes the copy for older versions under the new name at once. +func TestARenameKeepsTheCopyForOlderVersions(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--json"), ExitOK) + expectCode(t, e.run("", "profiles", "rename", "work", "office", "--json"), ExitOK) + + list, held := e.hostsOfTheStore()[e.server.URL].Sessions["a-session"] + if !held || len(list.Cards) != 1 || list.Cards[0].ID != e.fixture.CardInDoing.ID { + t.Errorf("no copy for the host after the rename: %v", e.hostsOfTheStore()) + } +} + +// storeFails makes every opening of the store fail, as one held by another +// minka for longer than a command waits. +func storeFails(a *app) { + a.openTheStore = func(string, time.Duration, work.Accounts) (*work.Handle, error) { + return nil, work.ErrBusy + } +} + +// reportedTo says whether a signal to a server named a card. +func reportedTo(server *fakeapi.Server, cardID string) bool { + for _, request := range server.Requests() { + if request.Method == http.MethodPut && request.Path == "/api/v1/me/work" && strings.Contains(string(request.Body), cardID) { + return true + } + } + return false +} + +// Where the store could not follow a rename or a removal, the lists stay under +// a name no profile has. Nothing reports them, and a new profile of that name +// starts without them. +func TestListsUnderANameNoProfileHasAreDead(t *testing.T) { + for _, how := range []string{"rename", "remove"} { + e, other, otherFixture := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--profile", "agent", "--json"), ExitOK) + + args := []string{"profiles", "remove", "agent", "--json"} + if how == "rename" { + args = []string{"profiles", "rename", "agent", "bot", "--json"} + } + r := e.runWith(storeFails, "", args...) + expectCode(t, r, ExitOK) + if _, left := e.storedHosts()["agent"]; !left { + t.Fatalf("%s: the failure was not forced", how) + } + + expectCode(t, e.run("", "heartbeat", "--json"), ExitOK) + if reportedTo(e.server, e.fixture.CardInDoing.ID) { + t.Errorf("%s: the dead list was reported", how) + } + + expectCode(t, e.run(otherFixture.AgentToken, "auth", "login", "--profile", "agent", "--host", other.URL, "--with-token"), ExitOK) + expectCode(t, e.run("", "heartbeat", "--json"), ExitOK) + if reportedTo(other, e.fixture.CardInDoing.ID) { + t.Errorf("%s: the card of the old profile was reported to the other host", how) + } + } +} + +// A new profile clears whatever the store holds under its name before it is +// saved, and a store that cannot be cleared refuses the sign-in. +func TestANewProfileStartsWithoutCards(t *testing.T) { + e, other, otherFixture := withProfiles(t) + e.vars[sessionVariable] = "a-session" + handle, err := work.Open(e.storePath(), waitForTheStore) + if err != nil { + t.Fatal(err) + } + handle.File.Account("ghost").List("a-session").Start(work.Card{ID: e.fixture.CardInDoing.ID, StartedAt: time.Now()}) + if err := handle.Save(); err != nil { + t.Fatal(err) + } + handle.Close() + + r := e.runWith(storeFails, otherFixture.AgentToken, "auth", "login", "--profile", "ghost", "--host", other.URL, "--with-token", "--json") + expectCode(t, r, ExitUsage) + if _, saved := e.config().Profiles["ghost"]; saved { + t.Fatal("the sign-in was saved although the store could not be cleared") + } + + expectCode(t, e.run(otherFixture.AgentToken, "auth", "login", "--profile", "ghost", "--host", other.URL, "--with-token"), ExitOK) + if _, left := e.storedHosts()["ghost"]; left { + t.Error("the sign-in left the lists under its name") + } + expectCode(t, e.run("", "heartbeat", "--json"), ExitOK) + if reportedTo(other, e.fixture.CardInDoing.ID) { + t.Error("a card under the name was reported with the new profile") + } +} + +// The configuration may be read in the middle of a rename, between the file and +// the store, so a name it lacks is no reason to delete the lists under it. +func TestAStoreKeepsTheListsOfANameTheConfigurationLacks(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars[sessionVariable] = "a-session" + handle, err := work.Open(e.storePath(), waitForTheStore) + if err != nil { + t.Fatal(err) + } + handle.File.Account("in-the-middle").List("a-session").Start(work.Card{ID: e.fixture.CardInDoing.ID, StartedAt: time.Now()}) + if err := handle.Save(); err != nil { + t.Fatal(err) + } + handle.Close() + + expectCode(t, e.run("", "work", "start", e.fixture.CardInTriage.ID, "--json"), ExitOK) + expectCode(t, e.run("", "heartbeat", "--json"), ExitOK) + if _, kept := e.storedHosts()["in-the-middle"]; !kept { + t.Error("the store deleted the lists of a name the configuration lacks") + } + if reportedTo(e.server, e.fixture.CardInDoing.ID) { + t.Error("the lists of a name without a profile were reported") + } +} + +func TestProfilesRemoveAndDefaultRefuseANameThatIsNone(t *testing.T) { + e, _, _ := withProfiles(t) + for _, command := range []string{"remove", "default"} { + env, r := e.runJSON("", "profiles", command, "Not/A Name") + expectCode(t, r, ExitUsage) + if !strings.Contains(env.Error, "is no profile name") { + t.Errorf("%s: error %q", command, env.Error) + } + } +} + +func TestASignInOfAProfileKeepsItsHost(t *testing.T) { + e, other, _ := withProfiles(t) + + env, r := e.runJSON(e.fixture.Token, "auth", "login", "--profile", "work", "--host", other.URL, "--with-token") + expectCode(t, r, ExitUsage) + if !strings.Contains(env.Hint, "minka profiles remove work") { + t.Errorf("hint %q", env.Hint) + } + + // Signed in again without a host, it keeps its own and stays the default. + env, r = e.runJSON(e.fixture.Token, "auth", "login", "--profile", "work", "--with-token") + expectCode(t, r, ExitOK) + if data := decode(t, env.Data); data["host"] != e.server.URL || data["isDefault"] != true || data["profile"] != "work" { + t.Errorf("data %s", env.Data) + } + + // A new name needs a host. + _, r = e.runJSON(e.fixture.Token, "auth", "login", "--profile", "new", "--with-token") + expectCode(t, r, ExitUsage) +} + +func TestProfilesListNamesTheDefaultAndTheActiveOne(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars["MINKA_PROFILE"] = "familie" + + env, r := e.runJSON("", "profiles", "list") + expectCode(t, r, ExitOK) + data := decode(t, env.Data) + rows := data["profiles"].([]any) + if len(rows) != 3 || data["defaultProfile"] != "work" { + t.Fatalf("data %s", env.Data) + } + active := data["active"].(map[string]any) + if active["profile"] != "familie" || active["source"] != chosenByProfileEnv { + t.Errorf("active %v", active) + } + for _, row := range rows { + profile := row.(map[string]any) + if (profile["name"] == "work") != (profile["isDefault"] == true) || (profile["name"] == "familie") != (profile["isActive"] == true) { + t.Errorf("row %v", profile) + } + if profile["name"] == "work" && profile["personName"] != "Bruno" { + t.Errorf("row %v", profile) + } + } + if strings.Contains(r.stdout, e.fixture.Token) { + t.Error("the list carries a token") + } +} + +// A rename carries the default and the cards a session holds with the profile. +func TestARenameCarriesTheDefaultAndTheCards(t *testing.T) { + e, _, _ := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--profile", "agent", "--json"), ExitOK) + expectCode(t, e.run("", "profiles", "rename", "agent", "bot", "--json"), ExitOK) + expectCode(t, e.run("", "profiles", "rename", "work", "office", "--json"), ExitOK) + + if file := e.config(); file.DefaultProfile != "office" || file.Profiles["bot"].Token != e.fixture.AgentToken { + t.Errorf("config %+v", file) + } + if _, kept := e.storedHosts()["bot"]; !kept { + t.Errorf("the cards stayed behind: %v", e.storedHosts()) + } + env, r := e.runJSON("", "work", "list", "--profile", "bot") + expectCode(t, r, ExitOK) + if cards := decode(t, env.Data)["cards"].([]any); len(cards) != 1 { + t.Errorf("data %s", env.Data) + } + + _, r = e.runJSON("", "profiles", "rename", "bot", "familie") + expectCode(t, r, ExitUsage) + _, r = e.runJSON("", "profiles", "rename", "bot", "Bot") + expectCode(t, r, ExitUsage) +} + +// Removing the default profile leaves none, as a sign-out of it does. +func TestRemovingTheDefaultProfileLeavesNoDefault(t *testing.T) { + e, other, _ := withProfiles(t) + + env, r := e.runJSON("", "profiles", "remove", "work") + expectCode(t, r, ExitOK) + if !strings.Contains(env.Notice, "no profile is the default now") { + t.Errorf("notice %q", env.Notice) + } + file := e.config() + if file.DefaultProfile != "" || len(file.Profiles) != 2 { + t.Errorf("config %+v", file) + } + + env, r = e.runJSON("", "me") + expectCode(t, r, ExitAuth) + if env.Error != "no default profile is set" { + t.Errorf("error %q", env.Error) + } + // Of the two on the host, one is left, and the host stands for it now. + expectCode(t, e.run("", "me", "--host", e.server.URL, "--json"), ExitOK) + + expectCode(t, e.run("", "profiles", "default", "familie", "--json"), ExitOK) + expectCode(t, e.run("", "me", "--json"), ExitOK) + if got := lastToken(t, other); got == "" { + t.Error("the default profile was not used") + } +} + +// A card belongs to the account it was taken up with, and the beat of the +// session reports it with that account, whatever the mod's environment names. +func TestTheHeartbeatReportsEveryProfileWithItsOwnToken(t *testing.T) { + e, other, otherFixture := withProfiles(t) + e.vars[sessionVariable] = "a-session" + expectCode(t, e.run("", "work", "start", e.fixture.CardInDoing.ID, "--profile", "agent", "--json"), ExitOK) + expectCode(t, e.run("", "work", "start", otherFixture.CardInDoing.ID, "--profile", "familie", "--json"), ExitOK) + + // The mod's environment names the default profile, a person's. + e.vars["MINKA_PROFILE"] = "work" + env, r := e.runJSON("", "heartbeat", "--from-mod") + expectCode(t, r, ExitOK) + if data := decode(t, env.Data); data["sent"] != true || len(data["accounts"].([]any)) != 2 { + t.Fatalf("data %s", env.Data) + } + for server, token := range map[*fakeapi.Server]string{e.server: e.fixture.AgentToken, other: otherFixture.AgentToken} { + signalled := false + for _, request := range server.Requests() { + if request.Method == http.MethodPut && request.Path == "/api/v1/me/work" { + signalled = true + if got := request.Header.Get("Authorization"); got != "Bearer "+token { + t.Errorf("a signal carried %q", got) + } + } + } + if !signalled { + t.Errorf("no signal reached %s", server.URL) + } + } + if got := e.server.CardsAtWork(); len(got) != 1 || got[0] != e.fixture.CardInDoing.ID { + t.Errorf("at work here: %v", got) + } + if got := other.CardsAtWork(); len(got) != 1 || got[0] != otherFixture.CardInDoing.ID { + t.Errorf("at work there: %v", got) + } +} + +// A store written per host is handed to the profile its host became, so that a +// card somebody has in hand at the update stays reported. +func TestAStoreKeptPerHostGoesToTheProfileOfTheHost(t *testing.T) { + e := newAgentEnv(t) + host := e.server.URL + delete(e.vars, "MINKA_HOST") + delete(e.vars, "MINKA_TOKEN") + e.writeConfig(`{"defaultHost": "` + host + `", "hosts": {"` + host + `": {"token": "` + e.fixture.AgentToken + `"}}}`) + if err := os.MkdirAll(dirOf(e.storePath()), 0o700); err != nil { + t.Fatal(err) + } + stored := `{"hosts": {"` + host + `": {"sessions": {"": {"cards": [{"id": "` + e.fixture.CardInDoing.ID + `", "startedAt": "2099-01-01T00:00:00Z"}]}}}}}` + if err := os.WriteFile(e.storePath(), []byte(stored), 0o600); err != nil { + t.Fatal(err) + } + + env, r := e.runJSON("", "work", "list") + expectCode(t, r, ExitOK) + if cards := decode(t, env.Data)["cards"].([]any); len(cards) != 1 { + t.Errorf("data %s", env.Data) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 5ec33cc..eb50975 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -18,6 +18,7 @@ import ( "github.com/flownative/minka-cli/internal/cliupdate" "github.com/flownative/minka-cli/internal/config" "github.com/flownative/minka-cli/internal/readmark" + "github.com/flownative/minka-cli/internal/work" "github.com/spf13/cobra" "golang.org/x/term" ) @@ -90,7 +91,14 @@ type app struct { // clock instead. pause func(ctx context.Context, d time.Duration) error - hostFlag string + hostFlag string + profileFlag string + + // openTheStore opens the store of the cards at work; tests make it fail. + openTheStore func(path string, wait time.Duration, accounts work.Accounts) (*work.Handle, error) + + // runNotices are what this run has to say whatever the command answers. + runNotices []string jsonFlag bool quietFlag bool styledFlag bool @@ -150,6 +158,7 @@ func newApp(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, gete a.pause = pauseFor a.runClaude = a.runClaudeCommand a.executable = os.Executable + a.openTheStore = work.OpenFor a.stdinIsTerminal = func() bool { return isTerminal(stdin) } a.stdoutIsTerminal = func() bool { return isTerminal(stdout) } a.readSecret = func() (string, error) { @@ -224,8 +233,13 @@ First steps, on a terminal: Without a terminal, sign in with: minka auth login --host https://minka.example.com --with-token < token.txt +A profile is one account in one organization: a host, a token and who it acts +as. --profile or $MINKA_PROFILE chooses one; --host or $MINKA_HOST +chooses the profile on that host. A flag outweighs a variable, a profile a +host. Without either, a command uses the default profile. + $MINKA_HOST and $MINKA_TOKEN sign in without the config file. The token is -only used for the host in $MINKA_HOST.`, +only used for the host in $MINKA_HOST, and not where a profile is chosen.`, SilenceErrors: true, SilenceUsage: true, Version: version, @@ -236,7 +250,8 @@ only used for the host in $MINKA_HOST.`, root.CompletionOptions.HiddenDefaultCmd = true flags := root.PersistentFlags() - flags.StringVar(&a.hostFlag, "host", "", "Minka host (default: $MINKA_HOST, else the default host)") + flags.StringVar(&a.profileFlag, "profile", "", "Profile to use (default: $MINKA_PROFILE, else the default profile)") + flags.StringVar(&a.hostFlag, "host", "", "Minka host, for the profile on it (default: $MINKA_HOST)") flags.BoolVar(&a.jsonFlag, "json", false, "Print a JSON envelope") flags.BoolVarP(&a.quietFlag, "quiet", "q", false, "Print only the data as JSON") flags.BoolVar(&a.styledFlag, "styled", false, "Print text even when stdout is not a terminal") @@ -249,6 +264,7 @@ only used for the host in $MINKA_HOST.`, a.newSetupCmd(), a.newConfigCmd(), a.newAuthCmd(), + a.newProfilesCmd(), a.newMeCmd(), a.newProjectsCmd(), a.newBoardsCmd(), @@ -391,166 +407,56 @@ func (a *app) explicitHost() (string, error) { type session struct { client *api.Client host string + profile string // empty where the token came from the environment + source string // where the choice of the account came from + key string // what the state of the account on this machine is kept under tokenSource string configPath string // empty when the token came from the environment reader string // who reads comments here, named without the token } -// session finds the host and the token of a command. -// -// The host is --host, else $MINKA_HOST, else the default host of the config -// file. $MINKA_TOKEN belongs to $MINKA_HOST and is used for that host only. -// For any other host the token comes from the config file, so a token is -// never sent to a host it was not given for. +// session finds the account of a command and signs in with it. Which account +// that is, chooseAccount says. func (a *app) session() (*session, error) { - host, err := a.explicitHost() + c, path, file, err := a.chooseAccount(true) if err != nil { return nil, err } + return a.sessionOf(c, path, file) +} - if envToken := a.getenv("MINKA_TOKEN"); envToken != "" { - envHostValue := a.getenv("MINKA_HOST") - if envHostValue == "" { - return nil, &Error{Code: CodeUsage, Message: "$MINKA_TOKEN is set without $MINKA_HOST", Hint: "Set $MINKA_HOST to the host the token belongs to."} - } - envHost, err := config.NormalizeHost(envHostValue) - if err != nil { - return nil, &Error{Code: CodeUsage, Message: "$MINKA_HOST: " + err.Error()} - } - if host == envHost { - return &session{client: a.newClient(host, envToken), host: host, tokenSource: tokenFromEnvironment, reader: readmark.Reader(envToken)}, nil - } - } - - path, file, err := a.loadConfig() - if err != nil { - return nil, err +func (a *app) sessionOf(c choice, path string, file *config.File) (*session, error) { + if c.envToken != "" { + return &session{client: a.newClient(c.host, c.envToken), host: c.host, source: c.source, key: c.key(), tokenSource: tokenFromEnvironment, reader: readmark.Reader(c.envToken)}, nil } - if host == "" { - if host, err = defaultHostOf(file, path); err != nil { - return nil, err - } + if c.host == "" { + return nil, noAccountError(file) } - if host == "" { - return nil, noHostError(file) + if c.profile == "" { + return nil, &Error{Code: CodeAuth, Message: "not signed in to " + config.HostForOutput(c.host), Hint: "Run: minka auth login --host " + c.host} } - token := file.Hosts[host].Token + token := file.Profiles[c.profile].Token if token == "" { - e := &Error{Code: CodeAuth, Message: "not signed in to " + config.HostForOutput(host), Hint: "Run: minka auth login --host " + host} - if written := hostWrittenAnotherWay(file, host); written != "" { - e.Hint = "The configuration keeps this host as " + config.HostForOutput(written) + - ", the same host written another way, and the token under that entry is looked for under " + host + - ". Run: minka auth login --host " + host + " — or write that entry as " + host + "." - } - return nil, e - } - - return &session{client: a.newClient(host, token), host: host, tokenSource: tokenFromConfig, configPath: path, reader: readmark.Reader(token)}, nil -} - -// Where the host of a command comes from. -const ( - hostFromFlag = "flag" - hostFromEnvironment = "environment" - hostFromDefault = "default" -) - -// hostSource says where the host of a command comes from, in the order session -// looks for it. -func (a *app) hostSource() string { - switch { - case a.hostFlag != "": - return hostFromFlag - case a.getenv("MINKA_HOST") != "": - return hostFromEnvironment - default: - return hostFromDefault + return nil, &Error{Code: CodeAuth, Message: "the profile " + c.profile + " holds no token", Hint: "Run: minka auth login --profile " + c.profile} } -} -// defaultHostToReport is the default host as a sign-in writes it, for a report -// that names it beside the host a command uses. It is empty where there is -// none. Where it or the configuration cannot be read, it is empty as well and -// the problem says why: a command given its host by --host or $MINKA_HOST gets -// past both, while every command without one fails on them, and a report that -// called that no default would hide the failure. -func (a *app) defaultHostToReport() (host, problem string) { - _, file, err := a.loadConfig() - if err != nil { - return "", err.Error() - } - if file.DefaultHost == "" { - return "", "" - } - host, err = config.NormalizeHost(file.DefaultHost) - if err != nil { - return "", err.Error() - } - return host, "" + return &session{client: a.newClient(c.host, token), host: c.host, profile: c.profile, source: c.source, key: c.key(), tokenSource: tokenFromConfig, configPath: path, reader: readmark.Reader(token)}, nil } -// hostsInWords says how the host of a command stands to the default host, -// naming a host only where the two differ. -func hostsInWords(host, source, defaultHost, problem string) string { - given := "--host" - if source == hostFromEnvironment { - given = "$MINKA_HOST" - } - switch { - case problem != "": - return "the host comes from " + given + ", and the default host cannot be read: " + problem - case host == defaultHost: - return "it is the default host" - case defaultHost == "": - return "the host comes from " + given + ", and no default host is set" +// hostSource says where the host of a command comes from, in the words the +// output gave it before there were profiles: flag, environment, profile where +// a profile was named, and default. +func hostSource(source string) string { + switch source { + case chosenByHostFlag: + return "flag" + case chosenByHostEnv: + return "environment" + case chosenByProfileFlag, chosenByProfileEnv: + return "profile" default: - return "the host comes from " + given + ", the default host is " + defaultHost - } -} - -// noHostError is the refusal of a command that names no host where the -// configuration names no default host either. Where hosts are signed in to, the -// way on is to name one of them; nothing picks one by itself, because the -// default host is a choice and not what happened to be left over. -func noHostError(file *config.File) *Error { - if len(file.Hosts) == 0 { - return &Error{Code: CodeAuth, Message: "not signed in to any Minka host", Hint: "Run: minka auth login --host https://minka.example.com"} - } - return &Error{ - Code: CodeAuth, - Message: "no default host is set", - Hint: "Give the host with --host , or make a host signed in to the default: minka config set host ", - } -} - -// hostToPaste is the host a hint may put into a command line. Where what may be -// printed of a value is no address to sign in to, the line names what is to be -// filled in instead. That is no address on purpose: whoever runs the line as it -// stands, a person or an agent, must not reach a host that is not theirs. It is a -// plain word, so a shell hands it on and the line fails where it should, at -// minka. -func hostToPaste(shown string) string { - if host, err := config.NormalizeHost(shown); err == nil { - return host - } - - return "YOUR-INSTANCE-ADDRESS" -} - -// hostWrittenAnotherWay names an entry of the configuration that means the host -// asked for but is not written the way a sign-in writes it. The token under such -// an entry is never found, and a refusal that named only the host it looked for -// would name one that stands nowhere in the file. -func hostWrittenAnotherWay(file *config.File, host string) string { - for written, entry := range file.Hosts { - if written == host || entry.Token == "" { - continue - } - if same, err := config.NormalizeHost(written); err == nil && same == host { - return written - } + return "default" } - return "" } const neighbourCard = "the neighbour" diff --git a/internal/cli/settings.go b/internal/cli/settings.go index 5b171c0..c792e21 100644 --- a/internal/cli/settings.go +++ b/internal/cli/settings.go @@ -14,7 +14,7 @@ import ( // setting is one value of the configuration file that a command may read and // change. Tokens are not among them: they are what auth is for. The default -// host is, as one of the hosts auth has signed in to. +// host is, as the host of the profile that becomes the default. type setting struct { help string get func(*config.File) any @@ -23,7 +23,7 @@ type setting struct { var settings = map[string]setting{ "host": { - help: "The default host, which a command without --host and $MINKA_HOST goes to; one signed in to with auth login", + help: "The host of the default profile; setting it makes the one profile on that host the default", get: defaultHostSetting, set: setDefaultHost, }, @@ -41,35 +41,45 @@ var settings = map[string]setting{ }, } -// defaultHostSetting is the default host as a sign-in writes it, the value as -// far as it may be printed where it cannot be read, and null where there is -// none. +// defaultHostSetting is the host of the default profile as a sign-in writes +// it, the value as far as it may be printed where it cannot be read, and null +// where there is none. func defaultHostSetting(f *config.File) any { - if f.DefaultHost == "" { + profile, ok := f.Profiles[f.DefaultProfile] + if !ok { return nil } - if host, err := config.NormalizeHost(f.DefaultHost); err == nil { + if host, err := config.NormalizeHost(profile.Host); err == nil { return host } - return config.HostForOutput(f.DefaultHost) + return config.HostForOutput(profile.Host) } -// setDefaultHost takes a host only where the configuration holds a token for -// it. A default host without one would make every later command without --host -// fail, far from the command that caused it. +// setDefaultHost makes the profile on a host the default. It takes a host only +// where a profile signs in to it, and only one: a default without a token would +// make every later command fail far from the command that caused it, and of two +// accounts on one host none is to be guessed. func setDefaultHost(f *config.File, value string) error { host, err := config.NormalizeHost(value) if err != nil { return err } - if f.Hosts[host].Token == "" { + names := f.ProfilesOnHost(host) + switch { + case len(names) == 0: return &Error{ Code: CodeUsage, Message: "not signed in to " + host + ", so it cannot become the default host", Hint: "Sign in first, which makes it the default as well: minka auth login --host " + host + " --make-default --with-token < token.txt", } + case len(names) > 1: + return &Error{ + Code: CodeAmbiguous, + Message: fmt.Sprintf("%d profiles sign in to %s: %s", len(names), host, strings.Join(names, ", ")), + Hint: "Make one of them the default by its name: minka profiles default ", + } } - f.DefaultHost = host + f.DefaultProfile = names[0] return nil } diff --git a/internal/cli/setup.go b/internal/cli/setup.go index 54b0733..0ca9a27 100644 --- a/internal/cli/setup.go +++ b/internal/cli/setup.go @@ -66,22 +66,28 @@ func (a *app) runSetup(cmd *cobra.Command, withTheMod bool) error { a.skillIsTheTopic = true previousDefault := hostToOfferAgain(file) - host, err := a.setupHost(input, previousDefault) + previousProfile := file.DefaultProfile + name, host, err := a.setupProfile(cmd, input, file, previousDefault) if err != nil { return err } - person, err := a.setupSignIn(cmd, host, path, file) + person, err := a.setupSignIn(cmd, name, host, path, file) if err != nil { return err } - // Every command without --host goes to the default host, so a move of it - // is said, not left to be found out. + // Every command without --profile goes to the default profile, so a move + // of it is said, not left to be found out. movedFrom := "" if previousDefault != "" && previousDefault != host { movedFrom = previousDefault fmt.Fprintf(a.stderr, "%s is the default host now, instead of %s.\n", host, movedFrom) } + movedFromProfile := "" + if previousProfile != "" && previousProfile != name { + movedFromProfile = previousProfile + fmt.Fprintf(a.stderr, "%s is the default profile now, instead of %s.\n", name, movedFromProfile) + } skillPath, skillState, err := a.setupSkill(input) if err != nil { @@ -97,6 +103,7 @@ func (a *app) runSetup(cmd *cobra.Command, withTheMod bool) error { data: map[string]any{ "host": host, "configPath": path, "person": person.Raw, "defaultHost": host, "previousDefaultHost": nullable(movedFrom), + "profile": name, "defaultProfile": name, "previousDefaultProfile": nullable(movedFromProfile), "skill": map[string]string{"path": skillPath, "state": skillState}, "mod": installed.data(), "oldHook": installed.hook.data(), @@ -114,12 +121,16 @@ func (a *app) runSetup(cmd *cobra.Command, withTheMod bool) error { }) } -// hostToOfferAgain is the host of the configuration where it can be read, and -// nothing where it cannot. An entry setup is there to repair is no answer to +// hostToOfferAgain is the host of the default profile where it can be read, +// and nothing where it cannot. An entry setup is there to repair is no answer to // offer: taking it would only be refused, and putting it in the question would // print a value that may hold anything. func hostToOfferAgain(file *config.File) string { - host, err := config.NormalizeHost(file.DefaultHost) + profile, ok := file.Profiles[file.DefaultProfile] + if !ok { + return "" + } + host, err := config.NormalizeHost(profile.Host) if err != nil { return "" } @@ -127,6 +138,25 @@ func hostToOfferAgain(file *config.File) string { return host } +// setupProfile is the profile setup signs in with, and its host. A profile +// named by --profile or $MINKA_PROFILE that exists brings its host along; +// otherwise the host is --host, $MINKA_HOST or what the person types, and the +// profile is found on it the way auth login finds it. +func (a *app) setupProfile(cmd *cobra.Command, input *bufio.Reader, file *config.File, fallback string) (string, string, error) { + named := a.profileFlag + if named == "" && a.hostFlag == "" { + named = a.getenv("MINKA_PROFILE") + } + if _, exists := file.Profiles[named]; exists && a.hostFlag == "" { + return a.profileOnHost(cmd, file, "", false) + } + host, err := a.setupHost(input, fallback) + if err != nil { + return "", "", err + } + return a.profileOnHost(cmd, file, host, true) +} + // setupHost is --host or $MINKA_HOST when given, else what the person types; // an empty answer takes the default host. func (a *app) setupHost(input *bufio.Reader, fallback string) (string, error) { @@ -159,20 +189,20 @@ func (a *app) setupHost(input *bufio.Reader, fallback string) (string, error) { } // setupSignIn keeps a token that works and asks for one otherwise. The saved -// token it tries is the one of this host, never the one of another. Either way -// the host becomes the default: setup asks a person at the terminal which host -// this machine works with, and the answer is that choice. +// token it tries is the one of this profile, never the one of another. Either +// way the profile becomes the default: setup asks a person at the terminal which +// host this machine works with, and the answer is that choice. // // Only a host that refuses the saved token is a reason to ask for a new one. // A host that does not answer would not accept a new token either, and the // person would have created one for nothing. -func (a *app) setupSignIn(cmd *cobra.Command, host, path string, file *config.File) (api.Result[api.Me], error) { - if saved := file.Hosts[host].Token; saved != "" { +func (a *app) setupSignIn(cmd *cobra.Command, name, host, path string, file *config.File) (api.Result[api.Me], error) { + if saved := file.Profiles[name].Token; saved != "" { me, err := a.newClient(host, saved).Me(a.ctx) if err == nil { fmt.Fprintf(a.stderr, "Already signed in to %s as %s.\n", host, me.Value.Name) - if file.DefaultHost != host { - file.DefaultHost = host + if file.DefaultProfile != name { + file.DefaultProfile = name if err := file.Save(path); err != nil { return api.Result[api.Me]{}, &Error{Code: CodeConfig, Message: err.Error()} } @@ -190,7 +220,7 @@ func (a *app) setupSignIn(cmd *cobra.Command, host, path string, file *config.Fi if err != nil { return api.Result[api.Me]{}, err } - path, me, _, err := a.signIn(host, token, true) + path, me, _, err := a.signIn(name, host, token, true) if err != nil { return api.Result[api.Me]{}, err } diff --git a/internal/cli/work.go b/internal/cli/work.go index 797bda1..06ee22b 100644 --- a/internal/cli/work.go +++ b/internal/cli/work.go @@ -114,7 +114,7 @@ shows a card in an archive as alive.`, defer handle.Close() session := a.agentSession() - host := handle.File.Host(s.host) + host := handle.File.Account(s.key) forgotten, _ := host.ForgetWhatRanOut(session, a.now()) entry := host.List(session) entry.Beat(a.now()) @@ -170,7 +170,7 @@ has nothing to answer about.`, if err := a.checkTheSessionFlag(cmd); err != nil { return err } - hostName, err := a.hostOfTheStore() + key, err := a.keyOfTheStore() if err != nil { return err } @@ -180,12 +180,12 @@ has nothing to answer about.`, } defer handle.Close() - // A host that holds nothing gets no entry of its own here: there is + // An account that holds nothing gets no entry of its own here: there is // nothing to stop, and nothing to write down about it either. session := a.agentSession() - host, known := handle.File.Hosts[hostName] + host, known := handle.File.Accounts[key] if !known { - return a.ok(sayingFirst("Nothing to stop", a.workSuccess(&work.Host{}, session, "Nothing to stop", map[string]any{"stopped": cardList(nil)}, 0))) + return a.ok(sayingFirst("Nothing to stop", a.workSuccess(&work.Account{}, session, "Nothing to stop", map[string]any{"stopped": cardList(nil)}, 0))) } forgotten, swept := host.ForgetWhatRanOut(session, a.now()) entry, held := host.Sessions[session] @@ -243,7 +243,7 @@ has nothing to answer about.`, // stopElsewhere takes a card out of the list of every other session on the host // that holds it, and answers with the card as one of them remembered it. -func stopElsewhere(host *work.Host, name string) (work.Card, bool) { +func stopElsewhere(host *work.Account, name string) (work.Card, bool) { var stopped work.Card found := false for _, list := range host.Sessions { @@ -282,7 +282,7 @@ this is where it says why, for eight hours after it happened.`, if err := a.checkTheSessionFlag(cmd); err != nil { return err } - hostName, err := a.hostOfTheStore() + key, err := a.keyOfTheStore() if err != nil { return err } @@ -295,9 +295,9 @@ this is where it says why, for eight hours after it happened.`, // What ran out is gone for every reader; the next command that // writes the store takes it out of the file as well. session := a.agentSession() - host, known := handle.File.Hosts[hostName] + host, known := handle.File.Accounts[key] if !known { - host = &work.Host{} + host = &work.Account{} } forgotten, _ := host.ForgetWhatRanOut(session, a.now()) entry := listOf(host, session) @@ -305,7 +305,7 @@ this is where it says why, for eight hours after it happened.`, if len(entry.Cards) == 1 { summary = "1 card" } - listed := a.workSuccess(host, session, summary+" on "+hostName, nil, forgotten) + listed := a.workSuccess(host, session, summary+" on "+key, nil, forgotten) listed.notices = append(listed.notices, letGoNotices(entry.LetGo)...) return a.ok(listed) }, @@ -317,7 +317,7 @@ this is where it says why, for eight hours after it happened.`, // listOf is the list of a session as a command reads it, an empty one where the // session holds nothing. It is never put into the host: reading a list does not // make one. -func listOf(host *work.Host, session string) *work.List { +func listOf(host *work.Account, session string) *work.List { if list, held := host.Sessions[session]; held { return list } @@ -342,6 +342,11 @@ session's own: the session --session names, else $CLAUDE_CODE_SESSION_ID, the same one a command typed in that session goes by. Without either it reports the list of no session. 'session' says which it was. +A card belongs to the profile it was taken up with. The beat reports the list +of the session in every profile that holds one, each with the token of that +profile, whatever $MINKA_PROFILE says; 'accounts' has one entry per profile. +--profile or --host narrow it to one. + It always exits 0 and says nothing unless asked with --json, --quiet or on a terminal: a beat that fails loudly after every tool call would cost the agent its attention for something it cannot act on. Asked, it says in 'reason' what @@ -357,6 +362,7 @@ card out of anything and is reported as it came.`, Args: requireArgs(), RunE: func(*cobra.Command, []string) error { var beat signalled + var beats []signalled var session string switch { case a.sessionFlag != "" && !work.IsSession(a.sessionFlag): @@ -369,7 +375,8 @@ card out of anything and is reported as it came.`, beat = signalled{reason: "the mod names no session"} default: session = a.agentSession() - beat = a.signal(session, 0) + beats = a.beatEveryAccount(session) + beat = together(beats) } if beat.cards == nil { beat.cards = []string{} @@ -378,10 +385,19 @@ card out of anything and is reported as it came.`, if a.nobodyIsListening() { return nil } + accounts := []map[string]any{} + for _, each := range beats { + cards := each.cards + if cards == nil { + cards = []string{} + } + accounts = append(accounts, map[string]any{"profile": nullable(each.profile), "sent": each.sent, "reason": each.reason, "cardIds": cards}) + } summary := heartbeatSummary(beat.sent, beat.reason, beat.cards) return a.ok(success{ data: map[string]any{"sent": beat.sent, "reason": beat.reason, "cardIds": beat.cards, - "session": nullable(session), "letGo": letGoList(beat.letGo)}, + "session": nullable(session), "letGo": letGoList(beat.letGo), + "profile": nullable(beat.profile), "accounts": accounts}, summary: summary, notices: letGoNotices(beat.letGo), text: func(w io.Writer) { fmt.Fprintln(w, summary) }, @@ -406,10 +422,12 @@ func (a *app) nobodyIsListening() bool { // signalled is what became of one signal: whether it went out, why it did not, // which cards the host took, and what it said about the ones it did not. type signalled struct { - sent bool - reason string - cards []string - letGo []work.LetGoCard + sent bool + reason string + cards []string + letGo []work.LetGoCard + profile string // the profile of the account, empty where none stands for it + key string // the account in the store } // signal reports the cards of one session and says what it did. It reports @@ -430,23 +448,32 @@ func (a *app) signal(session string, wait time.Duration) signalled { if err != nil { return signalled{reason: "not signed in"} } + return a.signalWith(s, session, wait) +} - claimed, reason := a.claimTheSignal(path, s.host, session, wait) +// signalWith is signal for the account of a session that is signed in already. +func (a *app) signalWith(s *session, session string, wait time.Duration) signalled { + path, err := a.storePath() + if err != nil || work.Untouched(path) { + return signalled{reason: "nothing is remembered on this machine", profile: s.profile, key: s.key} + } + + claimed, reason := a.claimTheSignal(path, s.key, session, wait) if claimed == nil { - return signalled{reason: reason} + return signalled{reason: reason, profile: s.profile, key: s.key} } ctx, cancel := context.WithTimeout(a.ctx, signalTimeout) defer cancel() leftOut, err := s.client.NoteAtWork(ctx, claimed.clientID, claimed.cards) - noted := a.noteTheOutcome(path, s.host, session, err, leftOut) + noted := a.noteTheOutcome(path, s.key, session, err, leftOut) if err != nil { // The failure as the list keeps it, so that the one word an agent // reads here names the case: the status and the code of the API are // what tells a revoked token from a person's one. - return signalled{reason: err.Error(), cards: claimed.cards} + return signalled{reason: err.Error(), cards: claimed.cards, profile: s.profile, key: s.key} } - return signalled{sent: true, cards: whatTheHostTook(claimed.cards, leftOut), letGo: noted} + return signalled{sent: true, cards: whatTheHostTook(claimed.cards, leftOut), letGo: noted, profile: s.profile, key: s.key} } // whatTheHostTook is the set that is now at work on the host: what was sent, @@ -474,16 +501,16 @@ type claim struct { // signal is a process of its own: two that start together must not both // report, and one that fails must not have the next tool call try again at // once. It claims nothing where nothing is to be sent, and says why. -func (a *app) claimTheSignal(path, hostName, session string, wait time.Duration) (*claim, string) { - handle, err := work.Open(path, wait) +func (a *app) claimTheSignal(path, key, session string, wait time.Duration) (*claim, string) { + handle, err := a.openTheStore(path, wait, a.storeAccounts()) if err != nil { return nil, "the store is busy or unreadable" } defer handle.Close() - host, known := handle.File.Hosts[hostName] + host, known := handle.File.Accounts[key] if !known { - return nil, "nothing is remembered for " + hostName + return nil, "nothing is remembered for " + key } // What has run out is given up before anybody says they are still at it, so // that a beat which comes after the window cannot raise a card that is @@ -495,7 +522,7 @@ func (a *app) claimTheSignal(path, hostName, session string, wait time.Duration) } entry, held := host.Sessions[session] if !held { - return nil, a.saving(handle, changed, "nothing is remembered for this session on "+hostName) + return nil, a.saving(handle, changed, "nothing is remembered for this session on "+key) } if a.idle { if why := nobodyIsAtWorkOn(entry, a.now()); why != "" { @@ -507,7 +534,7 @@ func (a *app) claimTheSignal(path, hostName, session string, wait time.Duration) // Nothing to say, and nothing said before that would have to be taken // back: this is where the common case ends, before the network. if len(cards) == 0 && len(entry.SentCards) == 0 { - return nil, a.saving(handle, changed, "nothing is remembered for this session on "+hostName) + return nil, a.saving(handle, changed, "nothing is remembered for this session on "+key) } if slices.Equal(cards, entry.SentCards) && a.now().Sub(entry.SentAt) < signalEvery { return nil, a.saving(handle, changed, "the last signal is younger than a minute") @@ -539,7 +566,7 @@ func (a *app) claimTheSignal(path, hostName, session string, wait time.Duration) // keeps a card, and a process on a timer of its own is no work. Otherwise a // Claude Code left open would keep its cards glowing through a working day // while nobody is at them. -func (a *app) somebodyIsAtWork(host *work.Host, session string) bool { +func (a *app) somebodyIsAtWork(host *work.Account, session string) bool { if a.idle { return false } @@ -570,15 +597,15 @@ func (a *app) saving(handle *work.Handle, changed bool, reason string) string { // // A list that is gone by now — one whose empty set went out and was swept — // gets nothing written: there is nobody left to read it. -func (a *app) noteTheOutcome(path, hostName, session string, failed error, leftOut []api.LeftOutCard) []work.LetGoCard { - handle, err := work.Open(path, aBeatWaitsForTheStore) +func (a *app) noteTheOutcome(path, key, session string, failed error, leftOut []api.LeftOutCard) []work.LetGoCard { + handle, err := a.openTheStore(path, aBeatWaitsForTheStore, a.storeAccounts()) if err != nil { return nil } defer handle.Close() var noted []work.LetGoCard - host, known := handle.File.Hosts[hostName] + host, known := handle.File.Accounts[key] if !known { return nil } @@ -649,26 +676,26 @@ func noLongerInHand(told bool) string { // Whatever it meets on the way it passes over in silence: the card has been // moved, and neither a store another session holds at that moment nor a signal // that does not get through makes that untrue. -func (a *app) letGoOfTheCard(host, cardID string) (letGo, told bool) { +func (a *app) letGoOfTheCard(s *session, cardID string) (letGo, told bool) { session := a.agentSession() - gone, mine := a.takeOutOfTheLists(host, session, cardID) + gone, mine := a.takeOutOfTheLists(s.key, session, cardID) if !gone || !mine { return gone, false } - return true, a.signal(session, waitForTheStore).sent + return true, a.signalWith(s, session, waitForTheStore).sent } // takeOutOfTheLists is the half that holds the lock, kept apart so that it is // given back before the signal, which takes it for itself. It says whether the // card was in any list, and whether in the one of this session. -func (a *app) takeOutOfTheLists(hostName, session, cardID string) (gone, mine bool) { +func (a *app) takeOutOfTheLists(key, session, cardID string) (gone, mine bool) { handle, err := a.openStore(waitForTheStore) if err != nil { return false, false } defer handle.Close() - host, known := handle.File.Hosts[hostName] + host, known := handle.File.Accounts[key] if !known { return false, false } @@ -736,7 +763,7 @@ func (a *app) openStore(wait time.Duration) (*work.Handle, error) { if err != nil { return nil, err } - handle, err := work.Open(path, wait) + handle, err := a.openTheStore(path, wait, a.storeAccounts()) if err != nil { e := &Error{Code: CodeConfig, Message: err.Error()} if errors.Is(err, work.ErrBusy) { @@ -747,54 +774,96 @@ func (a *app) openStore(wait time.Duration) (*work.Handle, error) { return handle, nil } -// hostOfTheStore is the host whose cards a command works on. It needs no token: -// what is remembered lies here, and only the signal goes anywhere. -func (a *app) hostOfTheStore() (string, error) { - host, err := a.explicitHost() +// keyOfTheStore is the account whose cards a command works on. It needs no +// token where the account is a profile: what is remembered lies here, and only +// the signal goes anywhere. +func (a *app) keyOfTheStore() (string, error) { + c, _, file, err := a.chooseAccount(true) if err != nil { return "", err } - if host != "" { - return host, nil + if c.host == "" { + return "", noAccountError(file) } - path, file, err := a.loadConfig() - if err != nil { - return "", err + return c.key(), nil +} + +// storeAccounts says how the store meets the versions before profiles, by the +// profile each host carries in the configuration file: the lists of a host +// belong to that profile, and that profile's lists are what the store writes +// under the host. A host no profile signs in to stands for itself. +// +// The lists under a profile name the file does not hold are read by nobody: a +// move or a drop that failed left them, or a rename is between writing the +// configuration and the store. They are deleted only where a new profile takes +// the name. A key that is a host is always read, as nothing else signs in to it. +// +// A configuration that cannot be read leaves the lists of the hosts under the +// hosts, where a command that can read it finds nothing of them, which loses +// at most the cards of a working day. +func (a *app) storeAccounts() work.Accounts { + _, file, err := a.loadConfig() + live := func(key string) bool { + if config.CheckProfileName(key) != nil { + return true + } + _, ok := file.Profiles[key] + return ok } - host, err = defaultHostOf(file, path) if err != nil { - return "", err - } - if host == "" { - return "", noHostError(file) + file = &config.File{Profiles: map[string]config.Profile{}} + live = nil + } + return work.Accounts{ + Live: live, + Of: func(host string) string { + if name, ok := file.HostProfile(host); ok { + return name + } + return host + }, + On: func(host string) []string { + return append(file.ProfilesOnHost(host), host) + }, + Host: func(key string) (string, bool) { + if config.CheckProfileName(key) != nil { + return key, len(file.ProfilesOnHost(key)) == 0 + } + profile, ok := file.Profiles[key] + if !ok { + return "", false + } + host, err := config.NormalizeHost(profile.Host) + if err != nil { + return "", false + } + name, _ := file.HostProfile(host) + return host, name == key + }, } - return host, nil } -// defaultHostOf is the host of the configuration, read the way a sign-in writes -// it, and empty where the configuration names none. It is a key of the store, so -// every process has to make the same string of it: a host written into the file -// by hand, with a slash at the end or a capital in it, would have one process -// looking at another list than the next. -// -// A value that cannot be read at all is no host, and it is refused here rather -// than handed on. Handed on, it would stand in the session of every command that -// follows and from there reach whatever prints a host. -func defaultHostOf(file *config.File, path string) (string, error) { - if file.DefaultHost == "" { - return "", nil - } - host, err := config.NormalizeHost(file.DefaultHost) +// dropFromTheStore forgets the lists of a profile that is going away. +func (a *app) dropFromTheStore(key string) error { + path, err := a.storePath() if err != nil { - shown := config.HostForOutput(file.DefaultHost) - return "", &Error{ - Code: CodeConfig, - Message: "the default host in " + path + " cannot be read: " + err.Error(), - Hint: "Correct \"defaultHost\" in that file, or sign in again: minka auth login --host " + hostToPaste(shown), - } + return err } - - return host, nil + if work.Untouched(path) { + return nil + } + handle, err := a.openStore(waitForTheStore) + if err != nil { + return err + } + defer handle.Close() + if !handle.File.Drop(key) { + return nil + } + if err := handle.Save(); err != nil { + return &Error{Code: CodeConfig, Message: err.Error()} + } + return nil } // findCard reads a card by its ID or by the short identifier people call it @@ -831,7 +900,7 @@ func (s *session) findCard(ctx context.Context, name string) (api.Card, error) { // // What the other sessions of the machine hold stands beside it, so that whoever // looks can tell a card nobody holds from one another session reports. -func (a *app) workSuccess(host *work.Host, session, summary string, more map[string]any, forgotten int) success { +func (a *app) workSuccess(host *work.Account, session, summary string, more map[string]any, forgotten int) success { entry := listOf(host, session) elsewhere := cardsElsewhere(host, session) data := map[string]any{ @@ -893,7 +962,7 @@ func (a *app) workSuccess(host *work.Host, session, summary string, more map[str // cardsElsewhere are the cards of every session but the one named, each with the // session that holds it, in the order of the sessions' names so that two looks // at the same store read alike. -func cardsElsewhere(host *work.Host, session string) []map[string]any { +func cardsElsewhere(host *work.Account, session string) []map[string]any { list := []map[string]any{} for _, name := range otherSessions(host, session) { for _, card := range cardList(host.Sessions[name].Cards) { @@ -978,7 +1047,7 @@ func cardList(cards []work.Card) []map[string]any { // otherSessions are the names of every session of the host but the one named, // sorted. -func otherSessions(host *work.Host, session string) []string { +func otherSessions(host *work.Account, session string) []string { names := slices.Sorted(maps.Keys(host.Sessions)) return slices.DeleteFunc(names, func(name string) bool { return name == session }) } diff --git a/internal/cli/work_sessions_test.go b/internal/cli/work_sessions_test.go index 442a780..d399971 100644 --- a/internal/cli/work_sessions_test.go +++ b/internal/cli/work_sessions_test.go @@ -358,7 +358,7 @@ func TestAStoreOfTheMachineIsHandedOutToItsSessions(t *testing.T) { t.Fatal(err) } defer handle.Close() - sessions := handle.File.Hosts[host].Sessions + sessions := handle.File.Accounts[host].Sessions for session, want := range map[string]struct { card string beat time.Time diff --git a/internal/cli/work_store_test.go b/internal/cli/work_store_test.go index 1ca0011..8a22041 100644 --- a/internal/cli/work_store_test.go +++ b/internal/cli/work_store_test.go @@ -18,12 +18,12 @@ func (e *testEnv) storedHosts() map[string]map[string]any { e.t.Fatal(err) } var file struct { - Hosts map[string]map[string]any `json:"hosts"` + Accounts map[string]map[string]any `json:"accounts"` } if err := json.Unmarshal(content, &file); err != nil { e.t.Fatalf("the store is not JSON: %v: %s", err, content) } - return file.Hosts + return file.Accounts } // storedList is what the store holds for the host of these tests and the @@ -47,10 +47,10 @@ func asStored(at time.Time) string { return at.UTC().Format(time.RFC3339) } -// The host of the store is read the way a sign-in writes it, however it stands +// The store keeps the cards of a profile under its name, however its host stands // in the file: a default host written by hand with a slash at the end would // otherwise have one command at another list than the next. -func TestTheHostOfTheStoreIsReadAsASignInWritesIt(t *testing.T) { +func TestTheStoreIsKeyedByTheProfile(t *testing.T) { e := newAgentEnv(t) began := time.Date(2026, 9, 23, 10, 0, 0, 0, time.UTC) host := e.server.URL @@ -65,8 +65,8 @@ func TestTheHostOfTheStoreIsReadAsASignInWritesIt(t *testing.T) { if sent := decode(t, env.Data)["sent"]; sent != true { t.Fatalf("the beat sent nothing: %s", env.Data) } - if keys := slices.Sorted(maps.Keys(e.storedHosts())); len(keys) != 1 || keys[0] != host { - t.Errorf("the store is keyed by %v, want the one host %s", keys, host) + if keys := slices.Sorted(maps.Keys(e.storedHosts())); len(keys) != 1 || keys[0] != profileNamedAfter(host) { + t.Errorf("the store is keyed by %v, want the one profile %s", keys, profileNamedAfter(host)) } } diff --git a/internal/cli/work_test.go b/internal/cli/work_test.go index 4419bf3..a964bdb 100644 --- a/internal/cli/work_test.go +++ b/internal/cli/work_test.go @@ -953,10 +953,10 @@ func (e *testEnv) storedListAsItLies() *work.List { if err := json.Unmarshal(content, &file); err != nil { e.t.Fatalf("the store is not JSON: %v", err) } - if len(file.Hosts) != 1 { - e.t.Fatalf("%d hosts in the store, want one", len(file.Hosts)) + if len(file.Accounts) != 1 { + e.t.Fatalf("%d accounts in the store, want one", len(file.Accounts)) } - for _, host := range file.Hosts { + for _, host := range file.Accounts { return listOf(host, e.vars[sessionVariable]) } return nil diff --git a/internal/cli/workaccounts.go b/internal/cli/workaccounts.go new file mode 100644 index 0000000..522bcf5 --- /dev/null +++ b/internal/cli/workaccounts.go @@ -0,0 +1,124 @@ +package cli + +import ( + "slices" + "strings" + + "github.com/flownative/minka-cli/internal/config" + "github.com/flownative/minka-cli/internal/work" +) + +// beatEveryAccount reports the list of a session in every account that holds +// one, each with the token of its own profile. A card is reported by the +// account it was taken up with, and the mod that runs the beat knows nothing of +// that: its environment is the one Claude Code was started with, not the one of +// the command that took the card up. --profile and --host narrow the beat to +// the account they name. +func (a *app) beatEveryAccount(session string) []signalled { + if a.profileFlag != "" || a.hostFlag != "" { + return []signalled{a.signal(session, 0)} + } + path, err := a.storePath() + if err != nil || work.Untouched(path) { + return []signalled{{reason: "nothing is remembered on this machine"}} + } + keys := a.accountsHolding(path, session) + if len(keys) == 0 { + return []signalled{a.signal(session, 0)} + } + beats := make([]signalled, 0, len(keys)) + for _, key := range keys { + s, err := a.sessionForKey(key) + if err != nil { + beats = append(beats, signalled{reason: "not signed in with " + key, key: key}) + continue + } + beats = append(beats, a.signalWith(s, session, 0)) + } + return beats +} + +// accountsHolding are the accounts that hold a list of the session, sorted, +// without those no profile stands for any more. +func (a *app) accountsHolding(path, session string) []string { + handle, err := a.openTheStore(path, 0, a.storeAccounts()) + if err != nil { + return nil + } + defer handle.Close() + var keys []string + for key, account := range handle.File.Accounts { + if _, held := account.Sessions[session]; held && handle.IsLive(key) { + keys = append(keys, key) + } + } + slices.Sort(keys) + return keys +} + +// sessionForKey signs in with the account the store keeps a list under: a +// profile by its own token, a host only by $MINKA_TOKEN where $MINKA_HOST names +// it. A host that no profile stands for has no token anywhere else. +func (a *app) sessionForKey(key string) (*session, error) { + if config.CheckProfileName(key) == nil { + path, file, err := a.loadConfig() + if err != nil { + return nil, err + } + c, err := profileChoice(file, path, key, chosenByStore) + if err != nil { + return nil, err + } + return a.sessionOf(c, path, file) + } + token := a.getenv("MINKA_TOKEN") + host, err := config.NormalizeHost(a.getenv("MINKA_HOST")) + if token == "" || err != nil || host != key { + return nil, &Error{Code: CodeAuth, Message: "not signed in to " + key} + } + return a.sessionOf(choice{host: host, source: chosenByHostEnv, envToken: token}, "", nil) +} + +// together is what several beats of one session say as one: sent where any +// went out, with every card and every note, and the reasons each with its +// account. +func together(beats []signalled) signalled { + if len(beats) == 1 { + return beats[0] + } + var all signalled + var reasons []string + for _, beat := range beats { + all.sent = all.sent || beat.sent + all.cards = append(all.cards, beat.cards...) + all.letGo = append(all.letGo, beat.letGo...) + if beat.reason != "" { + reasons = append(reasons, beat.key+": "+beat.reason) + } + } + all.reason = strings.Join(reasons, "; ") + return all +} + +// renameInTheStore moves the lists of a profile to its new name. +func (a *app) renameInTheStore(from, to string) error { + path, err := a.storePath() + if err != nil { + return err + } + if work.Untouched(path) { + return nil + } + handle, err := a.openStore(waitForTheStore) + if err != nil { + return err + } + defer handle.Close() + if !handle.File.Rename(from, to) { + return nil + } + if err := handle.Save(); err != nil { + return &Error{Code: CodeConfig, Message: err.Error()} + } + return nil +} diff --git a/internal/config/config.go b/internal/config/config.go index d3f9b53..553452e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,4 +1,5 @@ -// Package config keeps the hosts the CLI is signed in to and their tokens. +// Package config keeps the profiles the CLI signs in with: an account each, a +// host and a token. // // The file holds access tokens in plain text. It is written with permissions // 0600 in a directory with 0700, and a file that others can read is refused @@ -21,11 +22,14 @@ import ( "unicode" ) +// File is the configuration of this machine. Profiles are what it is about: +// every profile is one account in one organization, a token for a host and who +// the token acts as. type File struct { - DefaultHost string `json:"defaultHost,omitempty"` - ClientID string `json:"clientId,omitempty"` - Hosts map[string]HostEntry `json:"hosts"` - Comments CommentSettings `json:"comments,omitzero"` + DefaultProfile string `json:"defaultProfile,omitempty"` + Profiles map[string]Profile `json:"profiles"` + ClientID string `json:"clientId,omitempty"` + Comments CommentSettings `json:"comments,omitzero"` } // CommentSettings are the settings of the comments on a card, for every host. @@ -35,12 +39,23 @@ type CommentSettings struct { RequireRead bool `json:"requireRead,omitempty"` } -type HostEntry struct { +// Profile is one account: where it signs in, with which token, and who the +// token acts as. +type Profile struct { + Host string `json:"host"` // as a sign-in writes it; one written by hand may be in another form Token string `json:"token"` PersonName string `json:"personName,omitempty"` // who the token acts as, at sign-in EmailAddress string `json:"emailAddress,omitempty"` // who the token acts as, at sign-in } +// HostEntry is the sign-in of one host in the form versions of minka before +// profiles read and write. +type HostEntry struct { + Token string `json:"token"` + PersonName string `json:"personName,omitempty"` + EmailAddress string `json:"emailAddress,omitempty"` +} + // ErrInsecurePermissions is returned for a config file that users other than // its owner may read or write. var ErrInsecurePermissions = errors.New("config file is accessible by other users") @@ -64,7 +79,7 @@ func Path(getenv func(string) string) (string, error) { // Load reads the config file. A missing file is an empty configuration. func Load(path string) (*File, error) { - file := &File{Hosts: map[string]HostEntry{}} + file := &File{Profiles: map[string]Profile{}} info, err := os.Stat(path) if errors.Is(err, fs.ErrNotExist) { @@ -81,14 +96,12 @@ func Load(path string) (*File, error) { if err != nil { return nil, fmt.Errorf("reading %s: %w", path, err) } - if err := json.Unmarshal(content, file); err != nil { + var stored onDisk + if err := json.Unmarshal(content, &stored); err != nil { return nil, fmt.Errorf("reading %s: %w", path, err) } - if file.Hosts == nil { - file.Hosts = map[string]HostEntry{} - } - return file, nil + return stored.file(), nil } // Save writes the file with permissions 0600. It writes a temporary file next @@ -106,7 +119,7 @@ func (f *File) Save(path string) error { return fmt.Errorf("creating %s: %w", dir, err) } - content, err := json.MarshalIndent(f, "", " ") + content, err := json.MarshalIndent(f.onDisk(), "", " ") if err != nil { return fmt.Errorf("encoding the config: %w", err) } @@ -149,21 +162,6 @@ func NewClientID() (string, error) { return hex.EncodeToString(bytes[:]), nil } -// RemoveHost forgets the token of a host. If it was the default host, there is -// no default host afterwards: which host a command reaches without being told -// is a choice, and a host that is merely left over is not one. -func (f *File) RemoveHost(host string) bool { - if _, ok := f.Hosts[host]; !ok { - return false - } - delete(f.Hosts, host) - if f.DefaultHost == host { - f.DefaultHost = "" - } - - return true -} - // NormalizeHost turns what a user types into the canonical form the config is // keyed by: scheme and host, without a path. "minka.localbeach.net", // "https://minka.localbeach.net/" and "https://minka.localbeach.net/api/v1" diff --git a/internal/config/config_test.go b/internal/config/config_test.go index cdc097e..0ae5f5b 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -11,7 +11,7 @@ import ( func TestSaveWritesAFileOnlyItsOwnerCanRead(t *testing.T) { path := filepath.Join(t.TempDir(), "minka", "config.json") - file := &File{DefaultHost: "https://a.example", Hosts: map[string]HostEntry{"https://a.example": {Token: "minka_pat_x"}}} + file := &File{DefaultProfile: "a", Profiles: map[string]Profile{"a": {Host: "https://a.example", Token: "minka_pat_x"}}} if err := file.Save(path); err != nil { t.Fatal(err) @@ -36,7 +36,7 @@ func TestSaveWritesAFileOnlyItsOwnerCanRead(t *testing.T) { if err != nil { t.Fatal(err) } - if loaded.Hosts["https://a.example"].Token != "minka_pat_x" || loaded.DefaultHost != "https://a.example" { + if loaded.Profiles["a"].Token != "minka_pat_x" || loaded.DefaultProfile != "a" { t.Errorf("loaded %+v", loaded) } } @@ -55,7 +55,7 @@ func TestSaveKeepsASymlinkedConfigFileALink(t *testing.T) { t.Fatal(err) } - file := &File{Hosts: map[string]HostEntry{"https://a.example": {Token: "minka_pat_x"}}} + file := &File{Profiles: map[string]Profile{"a": {Host: "https://a.example", Token: "minka_pat_x"}}} if err := file.Save(link); err != nil { t.Fatal(err) } @@ -63,7 +63,7 @@ func TestSaveKeepsASymlinkedConfigFileALink(t *testing.T) { if info, err := os.Lstat(link); err != nil || info.Mode()&os.ModeSymlink == 0 { t.Errorf("config file is no longer a symlink: %v", err) } - if loaded, err := Load(target); err != nil || loaded.Hosts["https://a.example"].Token != "minka_pat_x" { + if loaded, err := Load(target); err != nil || loaded.Profiles["a"].Token != "minka_pat_x" { t.Errorf("target not written: %+v, %v", loaded, err) } } @@ -87,30 +87,30 @@ func TestAMissingFileIsAnEmptyConfig(t *testing.T) { if err != nil { t.Fatal(err) } - if file.DefaultHost != "" || len(file.Hosts) != 0 { + if file.DefaultProfile != "" || len(file.Profiles) != 0 { t.Errorf("got %+v", file) } } -// A host that is merely left over is no choice of anybody's, so taking the -// default host away leaves none, and the other hosts keep their tokens. -func TestRemoveHostOfTheDefaultLeavesNoDefault(t *testing.T) { - file := &File{DefaultHost: "https://b.example", Hosts: map[string]HostEntry{ - "https://b.example": {Token: "1"}, - "https://c.example": {Token: "2"}, - "https://a.example": {Token: "3"}, +// A profile that is merely left over is no choice of anybody's, so taking the +// default profile away leaves none, and the other profiles keep their tokens. +func TestRemoveProfileOfTheDefaultLeavesNoDefault(t *testing.T) { + file := &File{DefaultProfile: "b", Profiles: map[string]Profile{ + "b": {Host: "https://b.example", Token: "1"}, + "c": {Host: "https://c.example", Token: "2"}, + "a": {Host: "https://a.example", Token: "3"}, }} - if !file.RemoveHost("https://b.example") { - t.Fatal("host not removed") + if !file.RemoveProfile("b") { + t.Fatal("profile not removed") } - if file.DefaultHost != "" { - t.Errorf("default host %q", file.DefaultHost) + if file.DefaultProfile != "" { + t.Errorf("default profile %q", file.DefaultProfile) } - if len(file.Hosts) != 2 { - t.Errorf("hosts %v", file.Hosts) + if len(file.Profiles) != 2 { + t.Errorf("profiles %v", file.Profiles) } - if file.RemoveHost("https://b.example") { + if file.RemoveProfile("b") { t.Error("removing twice reported a removal") } } diff --git a/internal/config/profiles.go b/internal/config/profiles.go new file mode 100644 index 0000000..869d03c --- /dev/null +++ b/internal/config/profiles.go @@ -0,0 +1,316 @@ +package config + +import ( + "fmt" + "maps" + "regexp" + "slices" + "strconv" + "strings" +) + +// MaxProfileName is the longest name a profile may have. +const MaxProfileName = 64 + +var profileNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]*$`) + +// CheckProfileName says what is wrong with a name for a profile, or nil. A name +// is lower case letters, digits, "-" and ".", starts with a letter or a digit +// and is at most 64 characters long, so that it is typed without quotes and +// never reads as a host. +func CheckProfileName(name string) error { + switch { + case name == "": + return fmt.Errorf("the name of a profile is empty") + case len(name) > MaxProfileName: + return fmt.Errorf("the profile name %q is longer than %d characters", name, MaxProfileName) + case !profileNamePattern.MatchString(name): + return fmt.Errorf("%q is no profile name: a name is lower case letters, digits, \"-\" and \".\", and starts with a letter or a digit", name) + } + return nil +} + +// ProfileNameForHost is the name a profile gets that is named after its host: +// the host without the scheme, with a port joined by "-", and a number behind +// it where the name is taken already. +func (f *File) ProfileNameForHost(host string) string { + name := nameOfAHost(host) + if _, taken := f.Profiles[name]; !taken { + return name + } + for i := 2; ; i++ { + suffix := "-" + strconv.Itoa(i) + candidate := name + if len(candidate)+len(suffix) > MaxProfileName { + candidate = candidate[:MaxProfileName-len(suffix)] + } + candidate += suffix + if _, taken := f.Profiles[candidate]; !taken { + return candidate + } + } +} + +// nameOfAHost makes a profile name of a host. It reads the host as far as it +// may be printed, so that a password written into an address never becomes +// part of a name. +func nameOfAHost(host string) string { + shown := HostForOutput(host) + if _, rest, found := strings.Cut(shown, "://"); found { + shown = rest + } + shown, _, _ = strings.Cut(shown, "/") + // An address in brackets is one of IPv6, whose colons would leave a run of + // dashes at the start of the name. + prefix := "" + if strings.HasPrefix(shown, "[") { + prefix = "ipv6-" + } + shown = strings.ToLower(strings.NewReplacer("[", "", "]", "", ":", "-").Replace(shown)) + name := strings.Map(func(r rune) rune { + if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '.' || r == '-' { + return r + } + return '-' + }, shown) + for strings.Contains(name, "--") { + name = strings.ReplaceAll(name, "--", "-") + } + name = strings.TrimLeft(name, ".-") + if name != "" { + name = prefix + name + } + if len(name) > MaxProfileName { + name = name[:MaxProfileName] + } + if name == "" { + return "profile" + } + return name +} + +// ProfilesOnHost are the names of the profiles on a host, sorted. A profile +// counts by its host read the way a sign-in writes it, so one written into the +// file by hand in another form counts as well. +func (f *File) ProfilesOnHost(host string) []string { + var names []string + for name, profile := range f.Profiles { + if profile.Host == host { + names = append(names, name) + continue + } + if same, err := NormalizeHost(profile.Host); err == nil && same == host { + names = append(names, name) + } + } + slices.Sort(names) + return names +} + +// ProfileNames are the names of all profiles, sorted. +func (f *File) ProfileNames() []string { + return slices.Sorted(maps.Keys(f.Profiles)) +} + +// RemoveProfile forgets a profile and its token. If it was the default profile, +// there is no default afterwards: which account a command uses without being +// told is a choice, and a profile that is merely left over is not one. +func (f *File) RemoveProfile(name string) bool { + if _, ok := f.Profiles[name]; !ok { + return false + } + delete(f.Profiles, name) + if f.DefaultProfile == name { + f.DefaultProfile = "" + } + return true +} + +// RenameProfile gives a profile another name and carries the default along. +func (f *File) RenameProfile(from, to string) error { + profile, ok := f.Profiles[from] + if !ok { + return fmt.Errorf("there is no profile %q", from) + } + if _, taken := f.Profiles[to]; taken { + return fmt.Errorf("there is a profile %q already", to) + } + delete(f.Profiles, from) + f.Profiles[to] = profile + if f.DefaultProfile == from { + f.DefaultProfile = to + } + return nil +} + +// HostProfile is the profile a host stands for where only a host is known: the +// default profile if it is on the host, else the first on it by name. It is +// what the file writes for older versions of minka under that host, and what +// state kept per host by those versions belongs to. +func (f *File) HostProfile(host string) (string, bool) { + names := f.ProfilesOnHost(host) + if len(names) == 0 { + return "", false + } + if slices.Contains(names, f.DefaultProfile) { + return f.DefaultProfile, true + } + return names[0], true +} + +// onDisk is the file as it lies on disk. Next to the profiles it carries the +// hosts and the default host in the form of the versions before profiles, so +// that such a version still finds a sign-in for every host. +type onDisk struct { + DefaultProfile string `json:"defaultProfile,omitempty"` + Profiles *map[string]Profile `json:"profiles,omitempty"` + DefaultHost string `json:"defaultHost,omitempty"` + ClientID string `json:"clientId,omitempty"` + Hosts map[string]HostEntry `json:"hosts"` + Comments CommentSettings `json:"comments,omitzero"` +} + +// onDisk writes every host of a profile with the account HostProfile names for +// it. +func (f *File) onDisk() onDisk { + profiles := f.Profiles + if profiles == nil { + profiles = map[string]Profile{} + } + stored := onDisk{ + DefaultProfile: f.DefaultProfile, + Profiles: &profiles, + ClientID: f.ClientID, + Hosts: map[string]HostEntry{}, + Comments: f.Comments, + } + for _, profile := range profiles { + host := profile.Host + if _, written := stored.Hosts[host]; written { + continue + } + name, _ := f.hostProfileAsWritten(host) + chosen := profiles[name] + stored.Hosts[host] = HostEntry{Token: chosen.Token, PersonName: chosen.PersonName, EmailAddress: chosen.EmailAddress} + } + if profile, ok := profiles[f.DefaultProfile]; ok { + stored.DefaultHost = profile.Host + } + return stored +} + +// hostProfileAsWritten is HostProfile for a host as a profile writes it, which +// may be one no sign-in writes. +func (f *File) hostProfileAsWritten(host string) (string, bool) { + if normalized, err := NormalizeHost(host); err == nil { + return f.HostProfile(normalized) + } + var names []string + for name, profile := range f.Profiles { + if profile.Host == host { + names = append(names, name) + } + } + slices.Sort(names) + if len(names) == 0 { + return "", false + } + if slices.Contains(names, f.DefaultProfile) { + return f.DefaultProfile, true + } + return names[0], true +} + +// file reads what lies on disk. +// +// Where the file has profiles, they are what holds, and the hosts beside them +// are what this version wrote for older ones. A token there that no profile +// holds was written by hand or by an older version and is taken over into a +// profile named after its host, so that no sign-in is lost. +// +// A file without profiles is one of an older version, or one an older version +// wrote last, which drops what it does not know. Every host in it becomes a +// profile named after the host, and the default host the default profile. +func (stored onDisk) file() *File { + file := &File{ + DefaultProfile: stored.DefaultProfile, + Profiles: map[string]Profile{}, + ClientID: stored.ClientID, + Comments: stored.Comments, + } + if stored.Profiles != nil { + maps.Copy(file.Profiles, *stored.Profiles) + } else { + file.DefaultProfile = "" + } + + // A token counts as held by the host it signs in to: one person may well + // have given two hosts the same one. + held := map[string]bool{} + for _, profile := range file.Profiles { + held[signIn(profile.Host, profile.Token)] = true + } + // Hosts in the form a sign-in writes come first, so that they keep the + // plain name where another entry means the same host. + keys := slices.SortedFunc(maps.Keys(stored.Hosts), func(a, b string) int { + aCanonical, bCanonical := isCanonical(a), isCanonical(b) + if aCanonical != bCanonical { + if aCanonical { + return -1 + } + return 1 + } + return strings.Compare(a, b) + }) + takenOver := map[string]string{} + for _, key := range keys { + entry := stored.Hosts[key] + host := key + if normalized, err := NormalizeHost(key); err == nil { + host = normalized + } + if entry.Token == "" || held[signIn(host, entry.Token)] { + continue + } + name := file.ProfileNameForHost(host) + file.Profiles[name] = Profile{Host: host, Token: entry.Token, PersonName: entry.PersonName, EmailAddress: entry.EmailAddress} + held[signIn(host, entry.Token)] = true + takenOver[key] = name + } + + if stored.Profiles == nil && stored.DefaultHost != "" { + file.DefaultProfile = defaultOfAnOlderFile(stored.DefaultHost, keys, takenOver) + } + return file +} + +// defaultOfAnOlderFile is the profile the default host of an older file became: +// the entry written letter for letter like it, else the first that means the +// same host. +func defaultOfAnOlderFile(defaultHost string, keys []string, takenOver map[string]string) string { + if name, ok := takenOver[defaultHost]; ok { + return name + } + wanted, err := NormalizeHost(defaultHost) + if err != nil { + return "" + } + for _, key := range keys { + if same, err := NormalizeHost(key); err == nil && same == wanted && takenOver[key] != "" { + return takenOver[key] + } + } + return "" +} + +func signIn(host, token string) string { + if normalized, err := NormalizeHost(host); err == nil { + host = normalized + } + return host + " " + token +} + +func isCanonical(host string) bool { + normalized, err := NormalizeHost(host) + return err == nil && normalized == host +} diff --git a/internal/config/profiles_test.go b/internal/config/profiles_test.go new file mode 100644 index 0000000..64bb60b --- /dev/null +++ b/internal/config/profiles_test.go @@ -0,0 +1,221 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func writeFile(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func load(t *testing.T, path string) *File { + t.Helper() + file, err := Load(path) + if err != nil { + t.Fatal(err) + } + return file +} + +// The file of a version before profiles is taken over whole: every host is a +// profile named after it, the default host is the default profile, and nothing +// else is lost. +func TestAFileOfHostsBecomesOneOfProfiles(t *testing.T) { + path := writeFile(t, `{"defaultHost": "https://minka.flownative.com", "clientId": "abc", "comments": {"requireRead": true}, "hosts": { + "https://minka.flownative.com": {"token": "minka_pat_a", "personName": "Robert", "emailAddress": "robert@example.com"}, + "http://127.0.0.1:8081": {"token": "minka_pat_b"}, + "https://forgotten.example": {"token": ""} + }}`) + + file := load(t, path) + if len(file.Profiles) != 2 { + t.Fatalf("profiles %v", file.Profiles) + } + want := Profile{Host: "https://minka.flownative.com", Token: "minka_pat_a", PersonName: "Robert", EmailAddress: "robert@example.com"} + if file.Profiles["minka.flownative.com"] != want { + t.Errorf("profile %+v", file.Profiles["minka.flownative.com"]) + } + if file.Profiles["127.0.0.1-8081"].Token != "minka_pat_b" || file.Profiles["127.0.0.1-8081"].Host != "http://127.0.0.1:8081" { + t.Errorf("profile with a port %+v", file.Profiles["127.0.0.1-8081"]) + } + if file.DefaultProfile != "minka.flownative.com" || file.ClientID != "abc" || !file.Comments.RequireRead { + t.Errorf("file %+v", file) + } +} + +// A plain read never writes: an older minka on the same machine keeps reading +// the file as it was until a command of this version changes something. +func TestLoadingAnOlderFileDoesNotRewriteIt(t *testing.T) { + content := `{"defaultHost": "https://a.example", "hosts": {"https://a.example": {"token": "minka_pat_a"}}}` + path := writeFile(t, content) + load(t, path) + if after, _ := os.ReadFile(path); string(after) != content { + t.Errorf("the file changed: %s", after) + } +} + +// A file this version writes still reads to an older one: every host carries +// the token of the default profile where that one is on it, else of the first +// profile on it by name, and the default host is the host of the default +// profile. +func TestSaveWritesTheHostsForOlderVersions(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + file := &File{DefaultProfile: "work", Profiles: map[string]Profile{ + "work": {Host: "https://a.example", Token: "minka_pat_work", PersonName: "Work"}, + "agent": {Host: "https://a.example", Token: "minka_pat_agent"}, + "family": {Host: "https://b.example", Token: "minka_pat_family"}, + "zoo": {Host: "https://b.example", Token: "minka_pat_zoo"}, + }} + if err := file.Save(path); err != nil { + t.Fatal(err) + } + + var older struct { + DefaultHost string `json:"defaultHost"` + Hosts map[string]HostEntry `json:"hosts"` + } + content, _ := os.ReadFile(path) + if err := json.Unmarshal(content, &older); err != nil { + t.Fatal(err) + } + if older.DefaultHost != "https://a.example" { + t.Errorf("default host %q", older.DefaultHost) + } + if older.Hosts["https://a.example"].Token != "minka_pat_work" || older.Hosts["https://a.example"].PersonName != "Work" { + t.Errorf("the default profile is not what its host carries: %+v", older.Hosts) + } + if older.Hosts["https://b.example"].Token != "minka_pat_family" { + t.Errorf("the first profile by name is not what its host carries: %+v", older.Hosts) + } + + // Read again by this version, the hosts are the profiles' own and add none. + if again := load(t, path); len(again.Profiles) != 4 || again.DefaultProfile != "work" { + t.Errorf("read again: %+v", again) + } +} + +// An older version drops the profiles when it writes the file, and keeps what +// it changed in the hosts. The next read takes those over, so that its sign-in +// is not lost; the names of the profiles are, and the account of a host that +// it never saw. +func TestAFileAnOlderVersionWroteLastKeepsItsSignIns(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + file := &File{DefaultProfile: "flownative", Profiles: map[string]Profile{ + "flownative": {Host: "https://a.example", Token: "minka_pat_old"}, + }} + if err := file.Save(path); err != nil { + t.Fatal(err) + } + + // What an older version writes after a sign-in of its own. + var older struct { + DefaultHost string `json:"defaultHost,omitempty"` + ClientID string `json:"clientId,omitempty"` + Hosts map[string]HostEntry `json:"hosts"` + } + content, _ := os.ReadFile(path) + if err := json.Unmarshal(content, &older); err != nil { + t.Fatal(err) + } + older.Hosts["https://a.example"] = HostEntry{Token: "minka_pat_new"} + older.Hosts["https://c.example"] = HostEntry{Token: "minka_pat_c"} + rewritten, _ := json.Marshal(older) + if err := os.WriteFile(path, rewritten, 0o600); err != nil { + t.Fatal(err) + } + + again := load(t, path) + if again.Profiles["a.example"].Token != "minka_pat_new" || again.Profiles["c.example"].Token != "minka_pat_c" { + t.Errorf("profiles %+v", again.Profiles) + } + if again.DefaultProfile != "a.example" { + t.Errorf("default profile %q", again.DefaultProfile) + } +} + +// Beside profiles, a host whose token no profile holds was written by hand, +// and it is taken over rather than lost. +func TestAHostBesideProfilesWithATokenOfItsOwnIsTakenOver(t *testing.T) { + path := writeFile(t, `{"defaultProfile": "a.example", "profiles": { + "a.example": {"host": "https://a.example", "token": "minka_pat_a"} + }, "hosts": { + "https://a.example": {"token": "minka_pat_a"}, + "https://b.example": {"token": "minka_pat_b"}, + "https://a.example/": {"token": "minka_pat_by_hand"} + }}`) + + file := load(t, path) + if len(file.Profiles) != 3 || file.Profiles["b.example"].Token != "minka_pat_b" || file.Profiles["a.example-2"].Token != "minka_pat_by_hand" { + t.Errorf("profiles %+v", file.Profiles) + } + if file.DefaultProfile != "a.example" { + t.Errorf("default profile %q", file.DefaultProfile) + } +} + +// A host written by hand in another form becomes a profile on the host as a +// sign-in writes it, and one that cannot be read keeps its form, under a name +// that carries no password written into it. +func TestAHostWrittenByHandBecomesAProfileWithoutItsCredentials(t *testing.T) { + path := writeFile(t, `{"defaultHost": "https://Minka.Example.com/", "hosts": { + "https://Minka.Example.com/": {"token": "minka_pat_a"}, + "https://robert:s3cret@minka.other.example": {"token": "minka_pat_b"} + }}`) + + file := load(t, path) + if file.Profiles["minka.example.com"].Host != "https://minka.example.com" || file.DefaultProfile != "minka.example.com" { + t.Errorf("profiles %+v, default %q", file.Profiles, file.DefaultProfile) + } + for name, profile := range file.Profiles { + if strings.Contains(name, "s3cret") || CheckProfileName(name) != nil { + t.Errorf("profile name %q", name) + } + if profile.Token == "minka_pat_b" && profile.Host != "https://robert:s3cret@minka.other.example" { + t.Errorf("the unreadable host was changed: %q", profile.Host) + } + } +} + +func TestProfileNames(t *testing.T) { + for _, name := range []string{"flownative", "familie", "a", "minka.flownative.com", "127.0.0.1-8081", "x-" + strings.Repeat("a", 62)} { + if err := CheckProfileName(name); err != nil { + t.Errorf("%q refused: %v", name, err) + } + } + for _, name := range []string{"", "Flownative", "-a", ".a", "a b", "a_b", "https://a.example", "a:1", strings.Repeat("a", 65), "ä"} { + if CheckProfileName(name) == nil { + t.Errorf("%q taken", name) + } + } + + file := &File{Profiles: map[string]Profile{"a.example": {}}} + if got := file.ProfileNameForHost("https://a.example"); got != "a.example-2" { + t.Errorf("name for a taken host %q", got) + } + if got := file.ProfileNameForHost("http://[::1]:8080"); got != "ipv6-1-8080" { + t.Errorf("name for an address in brackets %q", got) + } +} + +// A rename carries the default along and takes no name that is taken. +func TestRenameProfile(t *testing.T) { + file := &File{DefaultProfile: "a", Profiles: map[string]Profile{"a": {Token: "1"}, "b": {Token: "2"}}} + if err := file.RenameProfile("a", "b"); err == nil { + t.Error("renamed onto a profile that exists") + } + if err := file.RenameProfile("a", "c"); err != nil { + t.Fatal(err) + } + if file.DefaultProfile != "c" || file.Profiles["c"].Token != "1" { + t.Errorf("file %+v", file) + } +} diff --git a/internal/work/accounts_test.go b/internal/work/accounts_test.go new file mode 100644 index 0000000..36545d7 --- /dev/null +++ b/internal/work/accounts_test.go @@ -0,0 +1,50 @@ +package work + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// Beside the accounts, a host is taken over only where its account holds +// nothing: what this version writes per host is a copy of an account, and +// anything else under a host was written by somebody else. +func TestAHostNoAccountHoldsIsTakenOver(t *testing.T) { + path := filepath.Join(t.TempDir(), "work.json") + stored := `{"accounts": {"work": {"sessions": {"": {"cards": [{"id": "of-work", "startedAt": "2099-01-01T00:00:00Z"}]}}}}, + "hosts": { + "https://a.example": {"sessions": {"": {"cards": [{"id": "a-copy", "startedAt": "2099-01-01T00:00:00Z"}]}}}, + "https://b.example": {"sessions": {"": {"cards": [{"id": "of-b", "startedAt": "2099-01-01T00:00:00Z"}]}}} + }}` + if err := os.WriteFile(path, []byte(stored), 0o600); err != nil { + t.Fatal(err) + } + accounts := Accounts{ + Of: func(host string) string { + if host == "https://a.example" { + return "work" + } + return "familie" + }, + On: func(host string) []string { + if host == "https://a.example" { + return []string{"alpha", "work", host} + } + return []string{"familie", host} + }, + Host: func(key string) (string, bool) { return "", false }, + } + + handle, err := OpenFor(path, time.Second, accounts) + if err != nil { + t.Fatal(err) + } + defer handle.Close() + if cards := handle.File.Accounts["work"].Sessions[NoSession].Cards; len(cards) != 1 || cards[0].ID != "of-work" { + t.Errorf("the copy was taken over beside the account: %v", cards) + } + if cards := handle.File.Accounts["familie"].Sessions[NoSession].Cards; len(cards) != 1 || cards[0].ID != "of-b" { + t.Errorf("the host no account holds was not taken over: %v", handle.File.Accounts) + } +} diff --git a/internal/work/store.go b/internal/work/store.go index 25e25d7..827051b 100644 --- a/internal/work/store.go +++ b/internal/work/store.go @@ -1,7 +1,8 @@ // Package work keeps the cards the sessions on this machine are working on. // // There is one store per machine, next to the configuration, and in it one list -// per host and session. Every session reports its own list and nothing else, +// per account and session. An account is a profile, or a host where no profile +// stands for the account. Every session reports its own list and nothing else, // under a client of its own: the server keeps one set per client, so a session // that reported the cards of another would keep them alight after that one // died. Every change to the store is made while holding a lock of the kernel, so @@ -90,13 +91,14 @@ type LetGoCard struct { At time.Time `json:"at"` } -// Host is what is remembered for one Minka host: one list per session, keyed by -// the name of the session, and NoSession for whoever gave none. -type Host struct { +// Account is what is remembered for one account: one list per session, keyed +// by the name of the session, and NoSession for whoever gave none. +type Account struct { Sessions map[string]*List `json:"sessions"` } -// List is what one session has in hand on one host, and what it last reported. +// List is what one session has in hand in one account, and what it last +// reported. // // SentAt and SentCards are the throttle: they say what the last signal carried // and when it went out, whether it arrived or not. Every signal is a new @@ -128,7 +130,37 @@ type List struct { // File is the store as it lies on disk. type File struct { - Hosts map[string]*Host `json:"hosts"` + // Accounts are keyed by the name of a profile, or by the host where no + // profile stands for the account. A profile name never reads as a host. + Accounts map[string]*Account `json:"accounts"` + + // Hosts are the lists in the form of the versions before profiles, one per + // host. Save writes them for such a version beside the accounts, and + // TakeOverHosts hands what only they hold to an account. + Hosts map[string]*Account `json:"hosts,omitempty"` +} + +// Accounts says how the hosts of older versions and the accounts of this one +// meet. +type Accounts struct { + // Of is the account the lists of a host belong to. + Of func(host string) string + // On are the accounts on a host: its profiles, and the host itself. + On func(host string) []string + // Live says whether an account is still one. A reader passes over the + // lists of an account that is gone; nothing deletes them for that, as the + // configuration may be read in the middle of a rename. Nil is every account. + Live func(key string) bool + // Host is the host whose lists the lists of an account are for an older + // version, and false where they are no host's. + Host func(key string) (string, bool) +} + +// ByHost is Accounts for a store whose accounts are hosts. +var ByHost = Accounts{ + Of: func(host string) string { return host }, + On: func(host string) []string { return []string{host} }, + Host: func(key string) (string, bool) { return key, true }, } // Handle is an open store together with the lock that is held on it. The @@ -136,8 +168,9 @@ type File struct { type Handle struct { File *File - path string - lock *lock + path string + lock *lock + accounts Accounts } // Path is where the store lies: beside the configuration file, so that it @@ -156,8 +189,14 @@ func Untouched(path string) bool { // Open takes the lock on the store and reads it. It waits at most that long // for the lock; with no wait at all it gives up as soon as somebody else holds -// it, which is what a signal does rather than keep a session waiting. +// it, which is what a signal does rather than keep a session waiting. The lists +// of a store kept per host stay under their hosts. func Open(path string, wait time.Duration) (*Handle, error) { + return OpenFor(path, wait, ByHost) +} + +// OpenFor is Open, with the accounts the hosts of older versions stand for. +func OpenFor(path string, wait time.Duration, accounts Accounts) (*Handle, error) { dir := filepath.Dir(path) if err := os.MkdirAll(dir, 0o700); err != nil { return nil, fmt.Errorf("creating %s: %w", dir, err) @@ -167,7 +206,7 @@ func Open(path string, wait time.Duration) (*Handle, error) { return nil, err } - file := &File{Hosts: map[string]*Host{}} + file := &File{} content, err := os.ReadFile(path) switch { case errors.Is(err, fs.ErrNotExist): @@ -179,12 +218,18 @@ func Open(path string, wait time.Duration) (*Handle, error) { held.Release() return nil, fmt.Errorf("reading %s: %w", path, err) } - if file.Hosts == nil { - file.Hosts = map[string]*Host{} - } } + if file.Accounts == nil && file.Hosts == nil { + file.Accounts = map[string]*Account{} + } + file.TakeOverHosts(accounts) + + return &Handle{File: file, path: path, lock: held, accounts: accounts}, nil +} - return &Handle{File: file, path: path, lock: held}, nil +// IsLive says whether the lists of an account are still read. +func (h *Handle) IsLive(key string) bool { + return h.accounts.Live == nil || h.accounts.Live(key) } func (h *Handle) Close() { @@ -193,27 +238,100 @@ func (h *Handle) Close() { // Save writes the store where it lies. It writes a temporary file next to the // target and renames it, so that an interrupted write cannot leave a truncated -// store behind. +// store behind. Beside the accounts it writes per host the lists of the account +// that host stands for, so that an older version reads them. func (h *Handle) Save() error { - content, err := json.MarshalIndent(h.File, "", " ") + stored := File{Accounts: h.File.Accounts, Hosts: map[string]*Account{}} + for key, entry := range h.File.Accounts { + if host, ok := h.accounts.Host(key); ok { + stored.Hosts[host] = entry + } + } + content, err := json.MarshalIndent(stored, "", " ") if err != nil { return fmt.Errorf("encoding the store: %w", err) } return localfile.Write(h.path, ".work-*.json", append(content, '\n')) } -// Host is what this host holds, an empty one where it holds nothing yet. -func (f *File) Host(host string) *Host { - entry, ok := f.Hosts[host] +// Account is what this account holds, an empty one where it holds nothing yet. +func (f *File) Account(key string) *Account { + entry, ok := f.Accounts[key] if !ok { - entry = &Host{} - f.Hosts[host] = entry + entry = &Account{} + f.Accounts[key] = entry } return entry } +// TakeOverHosts hands the lists of the hosts to the accounts those hosts stand +// for now. Where the store has accounts, they are what holds, and a host is +// taken over only where no account on it holds anything: what this version +// writes per host is a copy of the account the host stood for then, which need +// not be the one it stands for now. A store an older version wrote last has +// lost its accounts, and its hosts are what is left. +func (f *File) TakeOverHosts(accounts Accounts) { + if f.Accounts == nil { + f.Accounts = map[string]*Account{} + } + for host, entry := range f.Hosts { + if slices.ContainsFunc(accounts.On(host), func(key string) bool { return f.Accounts[key] != nil }) { + continue + } + f.Account(accounts.Of(host)).takeOver(entry) + } + f.Hosts = nil +} + +// Drop forgets the lists of an account, and says whether there were any. +func (f *File) Drop(key string) bool { + if _, ok := f.Accounts[key]; !ok { + return false + } + delete(f.Accounts, key) + return true +} + +// Rename moves the lists of an account to another key, and says whether it +// changed anything. Lists left under the new key belong to an account that is +// gone and are dropped, never mixed with those of the one renamed. +func (f *File) Rename(from, to string) bool { + entry, ok := f.Accounts[from] + dropped := f.Drop(to) + if !ok { + return dropped + } + delete(f.Accounts, from) + f.Accounts[to] = entry + return true +} + +// takeOver adds the lists of another account to this one. Where both hold a +// list of the same session, the cards come together and the rest of the list +// stays as this one has it. +func (h *Account) takeOver(other *Account) { + if other == nil { + return + } + for session, list := range other.Sessions { + mine, held := h.Sessions[session] + if !held { + if h.Sessions == nil { + h.Sessions = map[string]*List{} + } + h.Sessions[session] = list + continue + } + for _, card := range list.Cards { + if !slices.ContainsFunc(mine.Cards, func(c Card) bool { return c.ID == card.ID }) { + mine.Cards = append(mine.Cards, card) + } + } + } +} + // List is the list of one session, an empty one where it holds nothing yet. -func (h *Host) List(session string) *List { +func (h *Account) List(session string) *List { if h.Sessions == nil { h.Sessions = map[string]*List{} } @@ -228,7 +346,7 @@ func (h *Host) List(session string) *List { // StillAtIt says again that a session is at work on the cards it took up, and // answers whether that was worth writing down. A session that gave no name // says nothing here: its cards go by the moment they were started. -func (h *Host) StillAtIt(session string, now time.Time) bool { +func (h *Account) StillAtIt(session string, now time.Time) bool { list, known := h.Sessions[session] if session == NoSession || !known { return false @@ -244,12 +362,12 @@ func (h *Host) StillAtIt(session string, now time.Time) bool { return written } -// ForgetWhatRanOut sweeps every list of the host, and drops a list that has +// ForgetWhatRanOut sweeps every list of the account, and drops a list that has // nothing left to hold, to say or to take back: no card, no note, and nothing // sent that the server could still be counting. It answers how many cards it // forgot in the list of the session named, which is the one a command speaks // for, and whether it changed anything at all. -func (h *Host) ForgetWhatRanOut(session string, now time.Time) (int, bool) { +func (h *Account) ForgetWhatRanOut(session string, now time.Time) (int, bool) { forgottenHere, changed := 0, false for name, list := range h.Sessions { forgotten, swept := list.ForgetWhatRanOut(now) @@ -276,7 +394,7 @@ func (h *Host) ForgetWhatRanOut(session string, now time.Time) (int, bool) { // A list is given the moment its own cards were last seen as the mark of its // beat, not the mark of the machine: a session that died long ago would // otherwise pass for one at work as long as any other was. -func (h *Host) UnmarshalJSON(content []byte) error { +func (h *Account) UnmarshalJSON(content []byte) error { var stored struct { Sessions map[string]*List `json:"sessions"` List diff --git a/internal/work/store_test.go b/internal/work/store_test.go index 0320a81..3584996 100644 --- a/internal/work/store_test.go +++ b/internal/work/store_test.go @@ -16,7 +16,7 @@ func TestTheStoreIsWrittenSoThatOnlyItsOwnerReadsIt(t *testing.T) { if err != nil { t.Fatal(err) } - handle.File.Host("https://minka.example.com").List(NoSession).Start(Card{ID: "a-card", StartedAt: time.Now()}) + handle.File.Account("https://minka.example.com").List(NoSession).Start(Card{ID: "a-card", StartedAt: time.Now()}) if err := handle.Save(); err != nil { t.Fatal(err) } @@ -45,7 +45,7 @@ func TestAStoreThatCannotBeWrittenKeepsWhatItHeld(t *testing.T) { if err != nil { t.Fatal(err) } - handle.File.Host(aHostOfTheStore).List(NoSession).Start(Card{ID: "the-one-card", StartedAt: time.Now()}) + handle.File.Account(aHostOfTheStore).List(NoSession).Start(Card{ID: "the-one-card", StartedAt: time.Now()}) if err := handle.Save(); err != nil { t.Fatal(err) } @@ -67,7 +67,7 @@ func TestAStoreThatCannotBeWrittenKeepsWhatItHeld(t *testing.T) { t.Fatal(err) } defer handle.Close() - handle.File.Host(aHostOfTheStore).List(NoSession).Start(Card{ID: "another-card", StartedAt: time.Now()}) + handle.File.Account(aHostOfTheStore).List(NoSession).Start(Card{ID: "another-card", StartedAt: time.Now()}) if err := handle.Save(); err == nil { t.Fatal("a save that cannot be carried out says it went well") } @@ -104,7 +104,7 @@ func TestStartingACardAgainSaysItIsStillTheTurnOfThatCard(t *testing.T) { // now — and it is on that that the window of a card rests. func TestACardTakenUpAnewGoesByTheNewMoment(t *testing.T) { first := time.Date(2026, 9, 23, 9, 0, 0, 0, time.UTC) - host := &Host{} + host := &Account{} entry := host.List("mine") entry.Start(Card{ID: "a-card", StartedAt: first}) host.StillAtIt("mine", first.Add(time.Hour)) @@ -140,7 +140,7 @@ func TestACardNobodyStartedAgainRunsOut(t *testing.T) { // work keeps nothing of a session that died alive, nor a card of nobody. func TestOnlyTheSessionThatTookACardUpKeepsItAlive(t *testing.T) { began := time.Date(2026, 9, 23, 9, 0, 0, 0, time.UTC) - host := &Host{} + host := &Account{} host.List("busy").Start(Card{ID: "of the busy session", StartedAt: began}) host.List("gone").Start(Card{ID: "of the session that died", StartedAt: began}) host.List(NoSession).Start(Card{ID: "of a person at a terminal", StartedAt: began}) @@ -164,7 +164,7 @@ func TestOnlyTheSessionThatTookACardUpKeepsItAlive(t *testing.T) { // empty set to report, until the server has forgotten what it was sent. func TestAListGoesOnceThereIsNothingLeftToTakeBack(t *testing.T) { sent := time.Date(2026, 9, 23, 9, 0, 0, 0, time.UTC) - host := &Host{} + host := &Account{} list := host.List("done") list.SentAt, list.SentCards = sent, []string{"a-card"} @@ -190,7 +190,7 @@ func TestAListGoesOnceThereIsNothingLeftToTakeBack(t *testing.T) { // hours, so it is written down once a minute and not once a tool call. func TestSayingItAgainIsWrittenDownOnceAMinute(t *testing.T) { began := time.Date(2026, 9, 23, 9, 0, 0, 0, time.UTC) - entry := &Host{} + entry := &Account{} entry.List("mine").Start(Card{ID: "one", StartedAt: began}) if !entry.StillAtIt("mine", began.Add(SeenEvery)) { @@ -237,7 +237,7 @@ func TestTheMarkOfABeatIsWrittenDownOnceAMinute(t *testing.T) { // brings. Such a card goes by the moment it was started. func TestACardWithoutASessionIsKeptAliveByNobody(t *testing.T) { began := time.Date(2026, 9, 23, 9, 0, 0, 0, time.UTC) - entry := &Host{} + entry := &Account{} entry.List(NoSession).Start(Card{ID: "of a person at a terminal", StartedAt: began}) for hour := 1; hour <= 9; hour++ { diff --git a/internal/work/store_unix_test.go b/internal/work/store_unix_test.go index fafce95..8638cf4 100644 --- a/internal/work/store_unix_test.go +++ b/internal/work/store_unix_test.go @@ -64,7 +64,7 @@ func TestNoCardIsLostWhenSeveralSessionsStartAtOnce(t *testing.T) { } defer handle.Close() var cards []string - for _, list := range handle.File.Host(aHostOfTheStore).Sessions { + for _, list := range handle.File.Account(aHostOfTheStore).Sessions { cards = append(cards, list.CardIDs()...) } if len(cards) != sessions { @@ -79,7 +79,7 @@ func startACard(path string, session int) error { return fmt.Errorf("session %d: %w", session, err) } defer handle.Close() - handle.File.Host(aHostOfTheStore).List(fmt.Sprintf("session-%02d", session)).Start(Card{ID: fmt.Sprintf("card-%02d", session), StartedAt: time.Now()}) + handle.File.Account(aHostOfTheStore).List(fmt.Sprintf("session-%02d", session)).Start(Card{ID: fmt.Sprintf("card-%02d", session), StartedAt: time.Now()}) if err := handle.Save(); err != nil { return fmt.Errorf("session %d: %w", session, err) } diff --git a/skills/minka/SKILL.md b/skills/minka/SKILL.md index f1f16c1..60289f3 100644 --- a/skills/minka/SKILL.md +++ b/skills/minka/SKILL.md @@ -36,14 +36,22 @@ references listed under "Where the rest stands". - Pass `--json` explicitly. Read `ok`, then `data`; on failure read `code`, `retryable`, `hint` and `meta.apiCode`. - Never put a token on the command line. Sign in once with - `minka auth login --host --with-token < file`, or set `MINKA_TOKEN` - together with `MINKA_HOST`; the environment token is only sent to that host. -- A command without `--host` and `MINKA_HOST` goes to the default host, which - other sessions on the machine share. Signing in to another host does not - move it (`data.isDefault` is false, `data.defaultHost` names it). For a - host you need now, pass `--host ` or set `MINKA_HOST`; move the default - with `auth login --make-default` or `minka config set host ` only when - it is really meant to move. + `minka auth login --profile --host --with-token < file`, or set + `MINKA_TOKEN` together with `MINKA_HOST`; the environment token is only sent + to that host, and never where a profile is chosen, which a `notice` says. +- A profile is one account in one organization: a name, a host and a token. + The account of a command is, strongest first: `--profile `, `--host + ` (the profile on that host), `MINKA_PROFILE`, `MINKA_HOST`, else the + default profile, which other sessions on the machine share. In a script or a + session that works for one organization, set `MINKA_PROFILE`; for a single + command, pass `--profile`. `--profile` and `--host` together exit 1. A host + with several profiles and none of them the default exits 8 and names them; + an unknown profile exits 1 and lists the profiles. `minka profiles list + --json` shows them, the default and which one is active and why. +- Signing in with another profile does not move the default + (`data.isDefault` is false, `data.defaultProfile` names it). Move it with + `auth login --make-default` or `minka profiles default ` only when it + is really meant to move. - Pass long or multi-line text through stdin with `-`, never through shell quoting: `--description -` for cards, `` = `-` for comments. Stdin has to be a pipe or a file, not a terminal. @@ -224,9 +232,12 @@ not expected in practice. answers and accepts the token, and the installed skill. It is a report and exits 0 whatever it finds: read `data.healthy`, and for every entry of `data.checks` its `status` (`ok`, `warn`, `fail`, or `skip` where a check - before it failed), `detail` and `hint`; `data.host` is the host of the - command and `data.defaultHost` the default one, as `auth status` names them - too. Run it first when a command fails in a way you do not understand. + before it failed), `detail` and `hint`; `data.profile` and `data.host` are + the account of the command, `data.defaultProfile` and `data.defaultHost` the + default one. `auth status` names them too, with `data.profileSource` saying + where the choice came from (`--profile`, `--host`, `$MINKA_PROFILE`, + `$MINKA_HOST` or `default`). Run it first when a command fails in a way you + do not understand. - `minka setup` is for a person on a terminal: it asks for the host and the token, offers to install this skill, and installs the mod (`--no-mod` leaves it out); `data.mod.state` is `installed`, `current`, `written` (Claude Code @@ -234,18 +245,27 @@ not expected in practice. be written) or `skipped`. Without a terminal it exits 1; take `minka auth login --host --with-token < file`, `minka skill install` and `minka hooks install` instead. -- `minka auth logout --host `: forget the token of a host. The token stays - valid until it is revoked on the server. `--revoke` revokes it there first - and removes the entry only then; when the revocation fails the entry is kept - and the exit code is the failure's (a `retryable` one may simply be run - again). A token Minka itself no longer accepts counts as revoked, with a - `notice`; a 401 of a proxy in front of Minka does not. A token in - `$MINKA_TOKEN` is never revoked, and a `notice` says so. `data` is `{host, - removed, revoked}`. Signing out of the default host leaves no default host, - with a `notice`. +- `minka auth login --profile [--host ] --with-token < file`: a new + name makes a profile and needs `--host`; an existing name signs that profile + in again and keeps its host (another `--host` exits 1). Without `--profile`, + the one profile on the host is signed in again, or a new one named after the + host is made. +- `minka profiles list`, `minka profiles rename `, `minka profiles + remove [--revoke]` and `minka profiles default `: the profiles + of this machine. A rename keeps the default and the cards of `work start`. +- `minka auth logout` (or `minka profiles remove `): forget the profile a + command uses and its token. The token stays valid until it is revoked on the + server. `--revoke` revokes it there first and removes the profile only then; + when the revocation fails the profile is kept and the exit code is the + failure's (a `retryable` one may simply be run again). A token Minka itself + no longer accepts counts as revoked, with a `notice`; a 401 of a proxy in + front of Minka does not. A token in `$MINKA_TOKEN` is never revoked, and a + `notice` says so. `data` is `{host, profile, removed, revoked}`. Removing the + default profile leaves no default, with a `notice`. - `minka config get --json` and `minka config set --json`: the settings of this machine, so far `comments.requireRead` and `host`, the - default host, which takes only a host signed in to (exit 1 otherwise). + host of the default profile; setting it makes the one profile on that host + the default (exit 1 without one, exit 8 with several). ## This skill diff --git a/skills/minka/references/work-and-heartbeat.md b/skills/minka/references/work-and-heartbeat.md index d090cc5..492cb0b 100644 --- a/skills/minka/references/work-and-heartbeat.md +++ b/skills/minka/references/work-and-heartbeat.md @@ -89,6 +89,13 @@ this: - A `reason` this CLI does not know takes no card out of the list: the card stays, the word is reported as it came, and the `notice` says so. Act on it yourself. +- A card belongs to the profile it was taken up with: `work start --profile + familie` keeps it in the list of that profile, and `work list` and `work + stop` show and stop the cards of the profile they are given. The heartbeat + reports the list of your session in every profile that holds one, each with + the token of that profile, whatever `MINKA_PROFILE` the mod was started with; + `data.accounts` has one entry per profile with `profile`, `sent`, `reason` + and `cardIds`. `--profile` or `--host` narrow it to one. - `minka heartbeat` always exits 0 and prints nothing unless you ask with `--json`, which names the session it reported for in `data.session`. Not signed in, no network, a token that was revoked: none of it stops your work,