goals-cli 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +130 -2
  3. package/dist/args.js +96 -0
  4. package/dist/auth/command.js +16 -0
  5. package/dist/auth/help.js +82 -0
  6. package/dist/auth/list.js +41 -0
  7. package/dist/auth/login.js +203 -0
  8. package/dist/auth/logout.js +25 -0
  9. package/dist/auth/select.js +30 -0
  10. package/dist/auth/status.js +43 -0
  11. package/dist/auth/use.js +10 -0
  12. package/dist/cli.js +112 -0
  13. package/dist/commands/export-help.js +49 -0
  14. package/dist/commands/export.js +194 -0
  15. package/dist/commands/goal-flags.js +111 -0
  16. package/dist/commands/goal-format.js +95 -0
  17. package/dist/commands/goal-help.js +214 -0
  18. package/dist/commands/goal-read.js +80 -0
  19. package/dist/commands/goal-write.js +186 -0
  20. package/dist/commands/goal.js +15 -0
  21. package/dist/commands/initiative-help.js +38 -0
  22. package/dist/commands/initiative.js +81 -0
  23. package/dist/commands/list-output.js +13 -0
  24. package/dist/commands/skill-help.js +18 -0
  25. package/dist/commands/skill.js +36 -0
  26. package/dist/credentials.js +270 -0
  27. package/dist/deps.js +46 -0
  28. package/dist/dispatch.js +16 -0
  29. package/dist/endpoints.js +82 -0
  30. package/dist/errors.js +29 -0
  31. package/dist/help.js +105 -0
  32. package/dist/http.js +199 -0
  33. package/dist/iso-week.js +18 -0
  34. package/dist/open-browser.js +47 -0
  35. package/dist/output.js +29 -0
  36. package/dist/vendor/cli-contract/index.js +26 -0
  37. package/dist/vendor/quarterly-markdown/dateFormat.js +101 -0
  38. package/dist/vendor/quarterly-markdown/generate.js +450 -0
  39. package/dist/vendor/quarterly-markdown/htmlToPlainText.js +101 -0
  40. package/dist/vendor/quarterly-markdown/index.js +4 -0
  41. package/dist/vendor/quarterly-markdown/types.js +1 -0
  42. package/dist/vendor/quarterly-markdown/year.js +45 -0
  43. package/dist/version.js +9 -0
  44. package/package.json +37 -4
  45. package/skills/goals-cli/REFERENCE.md +212 -0
  46. package/skills/goals-cli/SKILL.md +12 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## 1.3.0 - 2026-11-20
8
+
9
+ ### Changed
10
+
11
+ - Version aligned with the rest of the workspace at 1.3.0. There is no functional change since 0.1.0.
12
+ - Publishing moved into the master `deploy-prod.yml` pipeline, gated on a version newer than npm. This is release tooling only; CLI behaviour is unchanged.
13
+
14
+ ## 0.1.0 - 2026-11-20
15
+
16
+ ### Added
17
+
18
+ - Browser-approved login with a verification code, plus multiple named identities that can be
19
+ listed, selected and revoked.
20
+ - `goals goal` commands to list, read, create, rename, complete, reopen and delete quarterly,
21
+ weekly, daily and adhoc goals.
22
+ - `goals initiative` commands to list initiatives and the goals tagged with them.
23
+ - `goals export markdown` for a whole year or one quarter, matching the webapp markdown export.
24
+ - `goals skill activate`, which prints the versioned agent skill stub and full reference.
25
+ - Production endpoints as the default for `goals auth login`, so logging in needs no flags.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ # goals-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Command-line access to your [Goals](https://goals-ten.vercel.app) app data. Read and manage
4
+ quarterly, weekly, daily and adhoc goals, list initiatives, and export the same markdown
5
+ summary the webapp produces.
6
+
7
+ ## Requirements
8
+
9
+ Node.js 20 or newer.
10
+
11
+ ## Install
12
+
13
+ Install the CLI globally:
14
+
15
+ ```bash
16
+ npm i -g goals-cli
17
+ ```
18
+
19
+ Or run it without installing:
20
+
21
+ ```bash
22
+ npx goals-cli --version
23
+ ```
24
+
25
+ ## Log in
26
+
27
+ ```bash
28
+ goals auth login
29
+ ```
30
+
31
+ The CLI opens a browser approval page and prints a verification code on stderr. Open the
32
+ URL, type the code, and approve. The credential is stored locally and sent only to the Goals
33
+ API. No flags are needed for the production app; `--webapp-url` together with `--convex-url`
34
+ overrides both endpoints for a local or self-hosted deployment.
35
+
36
+ ```bash
37
+ goals auth status
38
+ ```
39
+
40
+ You can review and revoke CLI credentials at any time in the webapp profile page's **CLI
41
+ Access** section.
42
+
43
+ ## Commands
44
+
45
+ | Command | What it does |
46
+ | ------------------------------ | -------------------------------------------------------------- |
47
+ | `goals auth login` | Log in through the browser and store a credential. |
48
+ | `goals auth logout` | Revoke a credential and remove it from this machine. |
49
+ | `goals auth status` | Show the current identity and whether its credential is valid. |
50
+ | `goals auth list` | List stored identities. |
51
+ | `goals auth use <label>` | Set the default identity. |
52
+ | `goals goal list` | List goals in one scope for a year. |
53
+ | `goals goal get <id>` | Show one goal with its parent, children and details. |
54
+ | `goals goal create` | Create a quarterly, weekly, daily or adhoc goal. |
55
+ | `goals goal rename <id>` | Rename one goal. |
56
+ | `goals goal complete <id>` | Mark a goal complete. |
57
+ | `goals goal reopen <id>` | Mark a goal incomplete again. |
58
+ | `goals goal delete <id> --yes` | Delete a goal and all of its child goals. |
59
+ | `goals initiative list` | List initiatives. |
60
+ | `goals initiative get <id>` | Show one initiative and the goals tagged with it. |
61
+ | `goals export markdown` | Print the markdown summary for a quarter or a year. |
62
+ | `goals skill activate` | Print the agent skill and full command reference. |
63
+
64
+ Run `goals <command> --help` or `goals <command> <action> --help` for every flag and example.
65
+ Add `--json` to a read command for machine-readable output, and `--as <label>` to choose an
66
+ identity for one invocation.
67
+
68
+ ## For agents
69
+
70
+ `goals skill activate` prints a versioned skill stub followed by the full reference. It needs
71
+ no login, makes no network call and writes no files. Install the stub as a `goals-cli` skill
72
+ so your agent can find it again.
73
+
74
+ ## Exit codes
75
+
76
+ | Code | Meaning |
77
+ | ---- | ---------------------------------------------- |
78
+ | `0` | Success. |
79
+ | `1` | Runtime, backend or authentication failure. |
80
+ | `2` | Usage error; the message starts with `Usage:`. |
81
+
82
+ stdout carries data. Progress and diagnostics go to stderr, so redirecting stdout is safe.
83
+
84
+ ## Credential file
85
+
86
+ The credential file is created with mode `0600` inside a `0700` directory:
87
+
88
+ - macOS: `~/Library/Application Support/goals/credentials.json`
89
+ - Linux: `$XDG_CONFIG_HOME/goals/credentials.json`, or `~/.config/goals/credentials.json`
90
+ - Windows: `%APPDATA%\goals\credentials.json`
91
+
92
+ The token is never printed. Use `goals auth logout` to revoke it, or revoke it in the webapp
93
+ profile page's CLI Access section.
94
+
95
+ ## Releasing
96
+
97
+ 1. Bump `version` in `packages/cli/package.json` (and add a `CHANGELOG.md` entry).
98
+ 2. Merge to `master`. The **Production Deployment** workflow (`deploy-prod.yml`) deploys the backend
99
+ and publishes goals-cli only if the version is newer than the one on npm; an equal or older
100
+ version is a green no-op for the publish step. A CLI-only merge also redeploys the Convex backend
101
+ (idempotent).
102
+ 3. Watch the **Production Deployment** run in GitHub Actions.
103
+
104
+ Publishing uses npm trusted publishing (GitHub OIDC); there is no npm token. Do not add an
105
+ `NPM_TOKEN`. The trusted workflow filename is `deploy-prod.yml`; never rename it.
106
+
107
+ ### One-time setup
108
+
109
+ Trusted publishing can only be configured for a package that already exists, so publish the first
110
+ version manually from a clean checkout of `master`, with your 2FA:
111
+
112
+ ```bash
113
+ pnpm install
114
+ pnpm --filter goals-cli build
115
+ cd packages/cli
116
+ npm pack
117
+ npm publish goals-cli-1.3.0.tgz --access public
118
+ ```
119
+
120
+ Then, within 2 days, register the trusted publisher against `deploy-prod.yml`:
121
+
122
+ ```bash
123
+ npm trust github goals-cli --file deploy-prod.yml --repo conradkoh/goals --allow-publish
124
+ ```
125
+
126
+ (or npmjs.com → the package's **Settings** → **Trusted Publisher** → GitHub Actions, owner
127
+ `conradkoh`, repository `goals`, workflow filename `deploy-prod.yml`). If the package was set up
128
+ earlier against any workflow file other than `deploy-prod.yml` (the retired publish workflow),
129
+ that workflow no longer exists: re-register against
130
+ `deploy-prod.yml` with the same command before the next version bump. Full maintainer notes:
131
+ [docs/developer/goals-cli-release.md](https://github.com/conradkoh/goals/blob/master/docs/developer/goals-cli-release.md).
package/dist/args.js ADDED
@@ -0,0 +1,96 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { UsageError } from './errors.js';
3
+ const NO_POSITIONALS = { min: 0, max: 0, name: '' };
4
+ function usageSuffix(hint) {
5
+ return `Run \`${hint}\` for usage.`;
6
+ }
7
+ /** Node's parseArgs message is multi-sentence; the CLI keeps only the first sentence. */
8
+ function firstSentence(message) {
9
+ const head = message.split('. ')[0] ?? message;
10
+ return head.endsWith('.') ? head.slice(0, -1) : head;
11
+ }
12
+ function isParseArgsError(error) {
13
+ const code = error.code;
14
+ return typeof code === 'string' && code.startsWith('ERR_PARSE_ARGS_');
15
+ }
16
+ /** `parseArgs` types values as possibly-array; without `multiple` only single values occur. */
17
+ function singleValue(value) {
18
+ return Array.isArray(value) ? value[value.length - 1] : value;
19
+ }
20
+ function isMultipleFlag(spec, name) {
21
+ return spec[name]?.multiple === true;
22
+ }
23
+ /** Every string value of a `multiple` flag, or `undefined` when it was not passed. */
24
+ function multipleValues(value) {
25
+ if (value === undefined)
26
+ return undefined;
27
+ if (!Array.isArray(value))
28
+ return [String(value)];
29
+ return value.filter((entry) => typeof entry === 'string');
30
+ }
31
+ /**
32
+ * A `multiple` flag keeps every value as `string[]` (absent stays `undefined`); every other flag
33
+ * keeps `parseArgs`'s last-wins behaviour.
34
+ */
35
+ function normalizedValue(spec, name, value) {
36
+ if (isMultipleFlag(spec, name))
37
+ return multipleValues(value);
38
+ return singleValue(value);
39
+ }
40
+ function normalizeValues(values, spec) {
41
+ const entries = Object.entries(values).map(([key, value]) => [key, normalizedValue(spec, key, value)]);
42
+ return Object.fromEntries(entries);
43
+ }
44
+ function toUsageError(error, hint) {
45
+ if (isParseArgsError(error)) {
46
+ const message = error instanceof Error ? error.message : String(error);
47
+ return new UsageError(`${firstSentence(message)}. ${usageSuffix(hint)}`);
48
+ }
49
+ throw error;
50
+ }
51
+ function checkPositionals(positionals, rule, hint) {
52
+ if (positionals.length < rule.min) {
53
+ throw new UsageError(`missing required argument ${rule.name}. ${usageSuffix(hint)}`);
54
+ }
55
+ const extra = positionals[rule.max];
56
+ if (extra !== undefined) {
57
+ throw new UsageError(`unexpected argument '${extra}'. ${usageSuffix(hint)}`);
58
+ }
59
+ }
60
+ /**
61
+ * Strict `parseArgs` wrapper: renders every parse failure as a `UsageError` ending with the
62
+ * help hint, and enforces the positional count before the command sees anything.
63
+ */
64
+ export function parseFlags(args, spec, hint, positionals = NO_POSITIONALS) {
65
+ let parsed;
66
+ try {
67
+ parsed = parseArgs({ args: [...args], options: spec, strict: true, allowPositionals: true });
68
+ }
69
+ catch (error) {
70
+ throw toUsageError(error, hint);
71
+ }
72
+ const collected = [...parsed.positionals];
73
+ checkPositionals(collected, positionals, hint);
74
+ return { flags: normalizeValues(parsed.values, spec), positionals: collected };
75
+ }
76
+ /**
77
+ * A usage error whose message ends with the command's help hint, e.g.
78
+ * `Usage: --week is not supported for quarterly goals. Run \`goals goal list --help\` for usage.`
79
+ */
80
+ export function usageFailure(message, hint) {
81
+ return new UsageError(`${message}. ${usageSuffix(hint)}`);
82
+ }
83
+ /** The flag's string value, or `undefined` when absent (`--as ""` is returned as `''`). */
84
+ export function stringFlag(parsed, name) {
85
+ const value = parsed.flags[name];
86
+ return typeof value === 'string' ? value : undefined;
87
+ }
88
+ /** True only when the flag was passed. */
89
+ export function booleanFlag(parsed, name) {
90
+ return parsed.flags[name] === true;
91
+ }
92
+ /** Every value of a `multiple` flag, in the order given; `[]` when absent. */
93
+ export function listFlag(parsed, name) {
94
+ const value = parsed.flags[name];
95
+ return Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
96
+ }
@@ -0,0 +1,16 @@
1
+ import { runFamilyAction } from '../dispatch.js';
2
+ import { runList } from './list.js';
3
+ import { runLogin } from './login.js';
4
+ import { runLogout } from './logout.js';
5
+ import { runStatus } from './status.js';
6
+ import { runUse } from './use.js';
7
+ const ACTIONS = {
8
+ login: runLogin,
9
+ logout: runLogout,
10
+ status: runStatus,
11
+ list: runList,
12
+ use: runUse,
13
+ };
14
+ export async function runAuthCommand(args, ctx) {
15
+ await runFamilyAction('auth', ACTIONS, args, ctx);
16
+ }
@@ -0,0 +1,82 @@
1
+ /** Help data for the `auth` family; the text is pinned by `src/__views__/auth-*-help.txt`. */
2
+ export const authHelp = {
3
+ name: 'auth',
4
+ summary: 'Log in, log out and manage identities.',
5
+ actions: {
6
+ login: {
7
+ summary: 'Log in through your browser and store a credential.',
8
+ usage: 'goals auth login [--name <label>] [--env <qualifier>] [--webapp-url <url> --convex-url <url>]',
9
+ options: [
10
+ {
11
+ syntax: '--name <label>',
12
+ description: 'Name this identity (default: the environment qualifier, else "default").',
13
+ },
14
+ {
15
+ syntax: '--env <qualifier>',
16
+ description: 'Environment qualifier such as "dev"; shown in status and list.',
17
+ },
18
+ {
19
+ syntax: '--webapp-url <url>',
20
+ description: 'Override the webapp origin used for browser approval (default: https://goals-ten.vercel.app). Pass together with --convex-url.',
21
+ },
22
+ {
23
+ syntax: '--convex-url <url>',
24
+ description: 'Override the Goals HTTP origin, the .convex.site URL (default: https://happy-otter-123.convex.site). Pass together with --webapp-url.',
25
+ },
26
+ ],
27
+ examples: [
28
+ 'goals auth login',
29
+ 'goals auth login --name dev --env dev --webapp-url http://localhost:3000 --convex-url http://127.0.0.1:3211',
30
+ ],
31
+ notes: [
32
+ 'The approval URL and a verification code are printed on stderr; type the code in the browser to approve.',
33
+ 'Use the override pair only for a local or self-hosted deployment; the endpoints are stored with the credential and used for every later command.',
34
+ 'The credential is saved in your user config directory (goals/credentials.json, mode 0600) and is never printed.',
35
+ ],
36
+ },
37
+ logout: {
38
+ summary: 'Revoke the credential and remove it from this machine.',
39
+ usage: 'goals auth logout [--as <label>]',
40
+ options: [
41
+ {
42
+ syntax: '--as <label>',
43
+ description: 'Identity to log out (default: the default identity).',
44
+ },
45
+ ],
46
+ examples: ['goals auth logout', 'goals auth logout --as dev'],
47
+ notes: [
48
+ 'The local entry is always removed, even if the server cannot be reached.',
49
+ 'Identity selection: --as, then GOALS_AS, then the default identity, then the only stored identity.',
50
+ ],
51
+ },
52
+ status: {
53
+ summary: 'Show the current identity and whether its credential is valid.',
54
+ usage: 'goals auth status [--as <label>] [--json]',
55
+ options: [
56
+ {
57
+ syntax: '--as <label>',
58
+ description: 'Identity to inspect (default: the default identity).',
59
+ },
60
+ { syntax: '--json', description: 'Print one JSON object instead of text.' },
61
+ ],
62
+ examples: ['goals auth status', 'goals auth status --as dev --json'],
63
+ notes: [
64
+ 'The credential itself is never shown.',
65
+ 'Identity selection: --as, then GOALS_AS, then the default identity, then the only stored identity.',
66
+ ],
67
+ },
68
+ list: {
69
+ summary: 'List stored identities.',
70
+ usage: 'goals auth list [--json]',
71
+ options: [{ syntax: '--json', description: 'Print a JSON array instead of a table.' }],
72
+ examples: ['goals auth list'],
73
+ notes: ['Reads the local file only; no network call. * marks the default identity.'],
74
+ },
75
+ use: {
76
+ summary: 'Set the default identity.',
77
+ usage: 'goals auth use <label>',
78
+ options: [{ syntax: '<label>', description: 'A label shown by `goals auth list`.' }],
79
+ examples: ['goals auth use dev'],
80
+ },
81
+ },
82
+ };
@@ -0,0 +1,41 @@
1
+ import { booleanFlag, parseFlags } from '../args.js';
2
+ import { effectiveDefaultLabel, readCredentials } from '../credentials.js';
3
+ import { formatTable, toJson } from '../output.js';
4
+ const HINT = 'goals auth list --help';
5
+ const FLAGS = { json: { type: 'boolean' } };
6
+ const HEADERS = ['LABEL', 'NAME', 'ENVIRONMENT', 'SERVER'];
7
+ const EMPTY = 'No identities stored. Run `goals auth login`.\n';
8
+ function hostOf(convexUrl) {
9
+ return new URL(convexUrl).host;
10
+ }
11
+ function tableRow(account) {
12
+ return [account.label, account.name, account.environment ?? 'default', hostOf(account.convexUrl)];
13
+ }
14
+ function jsonRow(account, defaultLabel) {
15
+ return {
16
+ label: account.label,
17
+ name: account.name,
18
+ userId: account.userId,
19
+ environment: account.environment ?? null,
20
+ convexHost: hostOf(account.convexUrl),
21
+ isDefault: account.label === defaultLabel,
22
+ createdAt: account.createdAt,
23
+ expiresAt: account.expiresAt,
24
+ };
25
+ }
26
+ export async function runList(args, ctx) {
27
+ const parsed = parseFlags(args, FLAGS, HINT);
28
+ const { credentials } = await readCredentials(ctx.deps.storeOptions);
29
+ const json = booleanFlag(parsed, 'json');
30
+ if (credentials.accounts.length === 0) {
31
+ ctx.deps.stdout.write(json ? toJson([]) : EMPTY);
32
+ return;
33
+ }
34
+ const defaultLabel = effectiveDefaultLabel(credentials);
35
+ if (json) {
36
+ ctx.deps.stdout.write(toJson(credentials.accounts.map((account) => jsonRow(account, defaultLabel))));
37
+ return;
38
+ }
39
+ const markers = credentials.accounts.map((account) => account.label === defaultLabel ? '* ' : ' ');
40
+ ctx.deps.stdout.write(formatTable(HEADERS, credentials.accounts.map(tableRow), markers));
41
+ }
@@ -0,0 +1,203 @@
1
+ import { parseFlags, stringFlag } from '../args.js';
2
+ import { identityKey, LABEL_PATTERN, normalizeEnvironment, readCredentials, upsertCredential, writeCredentials, } from '../credentials.js';
3
+ import { resolveEndpoints } from '../endpoints.js';
4
+ import { CliError, UsageError } from '../errors.js';
5
+ const HINT = 'goals auth login --help';
6
+ const FLAGS = {
7
+ name: { type: 'string' },
8
+ env: { type: 'string' },
9
+ 'webapp-url': { type: 'string' },
10
+ 'convex-url': { type: 'string' },
11
+ };
12
+ const MACHINE_NAME_FALLBACK = 'Goals computer';
13
+ const MACHINE_NAME_MAX = 64;
14
+ const MIN_INTERVAL_MS = 100;
15
+ const MAX_INTERVAL_MS = 60000;
16
+ const CANCELED = 'Login cancelled';
17
+ const EXPIRED = 'Login expired; run the command again.';
18
+ const POLL_FAILURES = {
19
+ denied: 'Login denied; run the command again.',
20
+ expired: EXPIRED,
21
+ consumed: 'Login request was already used; run the command again.',
22
+ not_found: 'Login request not found; run the command again.',
23
+ };
24
+ /** Validates every flag before any file or network access. */
25
+ function parseLoginArgs(args) {
26
+ const parsed = parseFlags(args, FLAGS, HINT);
27
+ const endpoints = resolveEndpoints({
28
+ webappUrl: stringFlag(parsed, 'webapp-url'),
29
+ convexUrl: stringFlag(parsed, 'convex-url'),
30
+ });
31
+ const environment = normalizeEnvironment(stringFlag(parsed, 'env'));
32
+ const requestedName = stringFlag(parsed, 'name');
33
+ if (requestedName !== undefined && !LABEL_PATTERN.test(requestedName)) {
34
+ throw new UsageError('--name must be 1-64 characters of A-Z, a-z, 0-9, ".", "_" or "-"');
35
+ }
36
+ return { requestedName, environment, endpoints };
37
+ }
38
+ function machineName(deps) {
39
+ let raw;
40
+ try {
41
+ raw = deps.hostname();
42
+ }
43
+ catch {
44
+ return MACHINE_NAME_FALLBACK;
45
+ }
46
+ const cleaned = raw
47
+ .replace(/[\u0000-\u001f\u007f]/g, '')
48
+ .trim()
49
+ .slice(0, MACHINE_NAME_MAX);
50
+ return cleaned === '' ? MACHINE_NAME_FALLBACK : cleaned;
51
+ }
52
+ function loginBody(credentials, environment, deps) {
53
+ return {
54
+ installationId: credentials.installationId,
55
+ machineName: machineName(deps),
56
+ ...(environment === undefined ? {} : { environment }),
57
+ };
58
+ }
59
+ function verificationUrl(endpoints, requestId) {
60
+ const url = new URL('/cli/authorize', endpoints.webappUrl);
61
+ url.searchParams.set('request', requestId);
62
+ return url.toString();
63
+ }
64
+ /** Progress goes to stderr so stdout stays data-only; the code is typed by a human. */
65
+ function announce(deps, url, userCode) {
66
+ deps.stderr.write(`Open ${url}\nVerification code: ${userCode}\nWaiting for approval... Press Ctrl+C to cancel.\n`);
67
+ }
68
+ /** A browser that cannot start (headless server, no xdg-open) must never fail the login. */
69
+ function openBrowserQuietly(deps, url) {
70
+ try {
71
+ void deps.openBrowser(url).catch(() => undefined);
72
+ }
73
+ catch {
74
+ // Best effort only.
75
+ }
76
+ }
77
+ function clampInterval(ms) {
78
+ return Math.min(Math.max(ms, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
79
+ }
80
+ async function exchange(api, convexUrl, request, signal) {
81
+ try {
82
+ return await api.exchangeLoginRequest({ convexUrl }, { requestId: request.requestId, deviceCode: request.deviceCode }, signal);
83
+ }
84
+ catch (error) {
85
+ if (signal.aborted)
86
+ throw new CliError(CANCELED);
87
+ throw error;
88
+ }
89
+ }
90
+ /** Throws before every poll when the user cancelled or the request has expired. */
91
+ function assertStillWaiting(deps, request, signal) {
92
+ if (signal.aborted)
93
+ throw new CliError(CANCELED);
94
+ if (deps.now() >= request.expiresAt)
95
+ throw new CliError(EXPIRED);
96
+ }
97
+ async function pollUntilApproved(api, deps, endpoints, request, controller) {
98
+ for (;;) {
99
+ assertStillWaiting(deps, request, controller.signal);
100
+ const result = await exchange(api, endpoints.convexUrl, request, controller.signal);
101
+ if (result.status === 'approved')
102
+ return result;
103
+ if (result.status === 'pending') {
104
+ await deps.sleep(clampInterval(result.intervalMs), controller.signal);
105
+ continue;
106
+ }
107
+ throw new CliError(POLL_FAILURES[result.status]);
108
+ }
109
+ }
110
+ /** The identity label a fresh credential gets, before collisions are checked. */
111
+ function draftLabel(environment) {
112
+ return environment ?? 'default';
113
+ }
114
+ function credentialDraft(options, approved, issuedAt) {
115
+ const { account } = approved;
116
+ return {
117
+ label: draftLabel(options.environment),
118
+ userId: account.userId,
119
+ name: account.name,
120
+ ...(account.email === undefined ? {} : { email: account.email }),
121
+ ...(options.environment === undefined ? {} : { environment: options.environment }),
122
+ webappUrl: options.endpoints.webappUrl,
123
+ convexUrl: options.endpoints.convexUrl,
124
+ credentialId: approved.tokenId,
125
+ token: approved.token,
126
+ createdAt: new Date(issuedAt).toISOString(),
127
+ expiresAt: new Date(approved.expiresAt).toISOString(),
128
+ };
129
+ }
130
+ function accountsInSlot(accounts, convexUrl, environment) {
131
+ return accounts.filter((account) => account.convexUrl === convexUrl && account.environment === environment);
132
+ }
133
+ function takenLabelMessage(label) {
134
+ return `identity label '${label}' is already used by another account; pass --name ${label} to choose a different one`;
135
+ }
136
+ /** The label that will certainly be used, when it can be known before approval. */
137
+ function certainLabel(requestedName, environment, slot) {
138
+ if (requestedName !== undefined)
139
+ return requestedName;
140
+ return slot.length === 0 ? draftLabel(environment) : undefined;
141
+ }
142
+ function ensureLabelAvailable(accounts, label, slot) {
143
+ const taken = accounts.some((account) => account.label === label && !slot.includes(account));
144
+ if (taken)
145
+ throw new UsageError(takenLabelMessage(label));
146
+ }
147
+ /** `--name`, else the label this identity already has, else the environment, else "default". */
148
+ function finalLabel(credentials, draft, requestedName) {
149
+ if (requestedName !== undefined)
150
+ return requestedName;
151
+ const key = identityKey(draft);
152
+ const existing = credentials.accounts.find((account) => identityKey(account) === key);
153
+ return existing?.label ?? draft.label;
154
+ }
155
+ /**
156
+ * Re-reads the credential file right before writing so a login/logout that finished while this
157
+ * one waited for browser approval is never overwritten. A rejected write (or a label that was
158
+ * taken in the meantime) revokes the fresh server token so nothing is orphaned.
159
+ */
160
+ async function persist(ctx, options, draft, installationId) {
161
+ try {
162
+ const { credentials } = await readCredentials(ctx.deps.storeOptions);
163
+ // The re-read makes a new installationId when the file is still missing; keep the one the
164
+ // create request already sent so this machine is identified consistently by the server.
165
+ // Accepted residual race: two simultaneous first-ever logins can each register a different
166
+ // installationId; the slower writer keeps the id already in the file, and the other
167
+ // credential stays active until it expires.
168
+ const file = credentials.accounts.length === 0 ? { ...credentials, installationId } : credentials;
169
+ const label = finalLabel(file, draft, options.requestedName);
170
+ const slot = accountsInSlot(file.accounts, draft.convexUrl, draft.environment);
171
+ ensureLabelAvailable(file.accounts, label, slot);
172
+ const stored = { ...draft, label };
173
+ await writeCredentials(upsertCredential(file, stored), ctx.deps.storeOptions);
174
+ return stored;
175
+ }
176
+ catch (error) {
177
+ await ctx.api.revoke(draft).catch(() => undefined);
178
+ throw error;
179
+ }
180
+ }
181
+ export async function runLogin(args, ctx) {
182
+ const options = parseLoginArgs(args);
183
+ const { credentials } = await readCredentials(ctx.deps.storeOptions);
184
+ const slot = accountsInSlot(credentials.accounts, options.endpoints.convexUrl, options.environment);
185
+ const earlyLabel = certainLabel(options.requestedName, options.environment, slot);
186
+ if (earlyLabel !== undefined)
187
+ ensureLabelAvailable(credentials.accounts, earlyLabel, slot);
188
+ const controller = new AbortController();
189
+ const request = await ctx.api.createLoginRequest({ convexUrl: options.endpoints.convexUrl }, loginBody(credentials, options.environment, ctx.deps), controller.signal);
190
+ const url = verificationUrl(options.endpoints, request.requestId);
191
+ announce(ctx.deps, url, request.userCode);
192
+ openBrowserQuietly(ctx.deps, url);
193
+ const unregister = ctx.deps.onSigint(() => controller.abort());
194
+ let approved;
195
+ try {
196
+ approved = await pollUntilApproved(ctx.api, ctx.deps, options.endpoints, request, controller);
197
+ }
198
+ finally {
199
+ unregister();
200
+ }
201
+ const stored = await persist(ctx, options, credentialDraft(options, approved, ctx.deps.now()), credentials.installationId);
202
+ ctx.deps.stdout.write(`Logged in as ${stored.name} (identity '${stored.label}', environment ${stored.environment ?? 'default'}).\n`);
203
+ }
@@ -0,0 +1,25 @@
1
+ import { readCredentials, removeCredential, writeCredentials } from '../credentials.js';
2
+ import { safeMessage } from '../errors.js';
3
+ import { parseAndSelect } from './select.js';
4
+ const HINT = 'goals auth logout --help';
5
+ const FLAGS = { as: { type: 'string' } };
6
+ function warningText(error) {
7
+ const detail = safeMessage(error instanceof Error ? error.message : error, 'unexpected error');
8
+ return `Warning: could not revoke the credential on the server (${detail}); it was removed from this machine only.\n`;
9
+ }
10
+ export async function runLogout(args, ctx) {
11
+ const { credential } = await parseAndSelect(args, FLAGS, HINT, ctx);
12
+ try {
13
+ await ctx.api.revoke(credential);
14
+ }
15
+ catch (error) {
16
+ ctx.deps.stderr.write(warningText(error));
17
+ }
18
+ // Re-read: another login/logout may have changed the file while the revoke was in flight.
19
+ const { credentials } = await readCredentials(ctx.deps.storeOptions);
20
+ const current = credentials.accounts.find((account) => account.label === credential.label);
21
+ if (current?.credentialId === credential.credentialId) {
22
+ await writeCredentials(removeCredential(credentials, credential.label), ctx.deps.storeOptions);
23
+ }
24
+ ctx.deps.stdout.write(`Logged out of '${credential.label}'.\n`);
25
+ }
@@ -0,0 +1,30 @@
1
+ import { parseFlags, stringFlag } from '../args.js';
2
+ import { readCredentials, selectCredential } from '../credentials.js';
3
+ /**
4
+ * Reads the store and selects the target identity with the one selection order every command
5
+ * shares (`--as`, GOALS_AS, the default, then the only account).
6
+ *
7
+ * Call this only after every flag has been parsed and validated, so usage errors never touch
8
+ * the credentials file.
9
+ */
10
+ export async function selectIdentity(parsed, ctx) {
11
+ const { credentials } = await readCredentials(ctx.deps.storeOptions);
12
+ const credential = selectCredential(credentials, {
13
+ as: stringFlag(parsed, 'as'),
14
+ env: ctx.deps.env,
15
+ });
16
+ return { credential, file: credentials };
17
+ }
18
+ /** Parses a command's flags, then selects the identity; the shape every auth command uses. */
19
+ export async function parseAndSelect(args, flags, hint, ctx) {
20
+ const parsed = parseFlags(args, flags, hint);
21
+ return { parsed, ...(await selectIdentity(parsed, ctx)) };
22
+ }
23
+ /**
24
+ * Selects the identity and runs one gateway op with it. Every command calls this only after
25
+ * all flags are validated, so a usage error never reads the store or sends a request.
26
+ */
27
+ export async function callAsIdentity(ctx, parsed, op, args) {
28
+ const { credential } = await selectIdentity(parsed, ctx);
29
+ return await ctx.api.call(credential, op, args);
30
+ }