@williamthorsen/toolbelt.secrets 0.3.0 โ†’ 0.4.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,25 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## 0.4.0 โ€” 2026-10-06
6
+
7
+ ### ๐ŸŽ‰ Features
8
+
9
+ - Moves the argument parsing, dispatch, and help of `tb-git`, `tb-jira`, `tb-node`, and `tb-secret` to `@williamthorsen/toolbelt.cli`, which generates each command's help from its schema and reports a usage error as `Error: <message>`, followed by a `Did you mean` line for a mistyped command and a pointer to that command's `--help`. (#365)
10
+ - Adds `-V` to `tb-git`, `tb-jira`, `tb-node`, and `tb-secret` as a short form of `--version`. (#365)
11
+
12
+ ## 0.3.1 โ€” 2026-10-02
13
+
14
+ ### ๐Ÿงช Tests
15
+
16
+ - Corrects test titles and one test input that misstated what their tests check, among them an `asNonEmptyArray` title that called a mutable array immutable and a `setDifference` test named for arrays that passed `Set` instances. (#353)
17
+
18
+ ### ๐Ÿ“š Documentation
19
+
20
+ - Audits the comments in every authored TypeScript, JavaScript, shell, and YAML source and every `tsconfig*.json` against the comment discipline, cutting comments that paraphrase the code or narrate history, rewriting doc descriptions in the third-person indicative, and adding descriptions to the functions, methods, and classes that had none. (#353)
21
+ - Revises READMEs, doc comments, and test names across the repository to follow the current `plain-speech` and writing-preference rules. (#354)
22
+ - Rewords the help text and messages printed by `tb-jira`, `tb-node`, and `tb-secret`, and the advice and skip reasons reported by the adoption kits, to follow the same writing conventions. (#354)
23
+
5
24
  ## 0.3.0 โ€” 2026-09-15
6
25
 
7
26
  ### ๐ŸŽ‰ Features
package/README.md CHANGED
@@ -3,15 +3,12 @@
3
3
  Utilities for storing and retrieving secrets in the OS credential store.
4
4
 
5
5
  <!-- section:release-notes -->
6
- ## Release notes โ€” v0.3.0 (2026-09-15)
6
+ ## Release notes โ€” v0.4.0 (2026-10-06)
7
7
 
8
8
  ### ๐ŸŽ‰ Features
9
9
 
10
- - ๐Ÿšจ **Breaking:** Move createTempTree from toolbelt.filesystem to toolbelt.testing (#313)
11
-
12
- - Moves `CreateTempTreeOptions` and the `TempTree` handle to `@williamthorsen/toolbelt.testing/candidate` along with `createTempTree`.
13
-
14
- Migration: Import `createTempTree`, `CreateTempTreeOptions`, and `TempTree` from `@williamthorsen/toolbelt.testing/candidate`, and declare `@williamthorsen/toolbelt.testing` in the manifest that declared `@williamthorsen/toolbelt.filesystem` for them.
10
+ - Moves the argument parsing, dispatch, and help of `tb-git`, `tb-jira`, `tb-node`, and `tb-secret` to `@williamthorsen/toolbelt.cli`, which generates each command's help from its schema and reports a usage error as `Error: <message>`, followed by a `Did you mean` line for a mistyped command and a pointer to that command's `--help`. (#365)
11
+ - Adds `-V` to `tb-git`, `tb-jira`, `tb-node`, and `tb-secret` as a short form of `--version`. (#365)
15
12
  <!-- /section:release-notes -->
16
13
 
17
14
  ## Installation
@@ -24,9 +21,9 @@ Requires Node.js 24 or later, and macOS: The one backend is the macOS keychain,
24
21
 
25
22
  ## How a secret is stored
26
23
 
27
- An item is named by a **service** and an **account**. The service is the caller's own name for the secret, never derived from a host or a URL, so one item can serve every product that accepts the same token. The account is optional and defaults to the empty account, which is matched exactly: A lookup on a service holding several accounts returns the one that is asked for, rather than an arbitrary one.
24
+ An item is named by a **service** and an **account**. The service is the caller's own name for the secret, never derived from a host or a URL, so one item can serve every product that accepts the same token. The account is optional and defaults to the empty account, which is matched exactly: A lookup on a service with several accounts returns the one that is asked for, rather than an arbitrary one.
28
25
 
29
- A secret reaches `security` through its interactive mode, which takes a whole command on stdin, so the secret never sits in an argument vector that any local process could read. It travels as hexadecimal, which encodes every byte, a line break included, and every write is read back and compared before it is reported as stored.
26
+ Because the store passes a secret to `security` through its interactive mode, which takes a whole command on stdin, the secret never appears in an argument vector that any local process could read. It is sent as hexadecimal, which encodes every byte, a line break included, and every write is read back and compared before it is reported as stored.
30
27
 
31
28
  One command line contains the secret together with the service, the account, and the keychain, and `security` reads at most 4,095 bytes of it. That leaves room for a secret of roughly 2,000 bytes, and the exact ceiling falls as the other three grow. A secret that would not fit is refused, naming the room left; none is ever stored in part.
32
29
 
@@ -34,14 +31,14 @@ An item created here is local to the Mac that created it. `security` offers no i
34
31
 
35
32
  ## CLI
36
33
 
37
- The package ships a `tb-secret` command exposing the store to a shell caller.
34
+ The package includes a `tb-secret` command exposing the store to a shell caller.
38
35
 
39
36
  ```sh
40
37
  pnpm add --global @williamthorsen/toolbelt.secrets # puts tb-secret on PATH
41
38
  npx @williamthorsen/toolbelt.secrets get my-token # or run it without installing
42
39
  ```
43
40
 
44
- `tb-secret --help`, each subcommand's `--help`, and `tb-secret --version` report the surface and the installed version.
41
+ `tb-secret --help`, each subcommand's `--help`, and `tb-secret --version` (or `-V`) report the surface and the installed version.
45
42
 
46
43
  | Subcommand | Effect |
47
44
  | ---------------------------- | ---------------------------------------------------- |
@@ -52,7 +49,7 @@ npx @williamthorsen/toolbelt.secrets get my-token # or run it without install
52
49
 
53
50
  | Option | Effect |
54
51
  | ----------------------- | ------------------------------------------------------- |
55
- | `-a, --account <name>` | Account holding the secret (default: the empty account) |
52
+ | `-a, --account <name>` | Account of the secret (default: the empty account) |
56
53
  | `-k, --keychain <path>` | Keychain to act on, rather than the default search list |
57
54
 
58
55
  At a terminal, `set` prompts for the secret twice and echoes nothing; piped, it reads stdin and drops one trailing newline, since `echo` adds one. The secret passes through this process either way.
@@ -117,11 +114,11 @@ store.findSecret({ account: 'me@example.com', service: 'atlassian-api-token' });
117
114
  // the token
118
115
  ```
119
116
 
120
- `findSecret` returns `undefined` where no item is stored, and throws where the keychain could not be reached, so absence is never confused with a failure. `deleteSecret` reports whether an item was there to remove.
117
+ `findSecret` returns `undefined` when no item is stored, and throws when the keychain could not be reached, so absence is never confused with a failure. `deleteSecret` reports whether an item was there to remove.
121
118
 
122
- `hasSecret` reads the item's attributes rather than its data. That is the difference worth knowing: Retrieving a secret can raise a keychain access prompt where the item was created by another program, and an attribute lookup cannot.
119
+ `hasSecret` reads the item's attributes rather than its data. That is the difference worth knowing: Retrieving a secret can raise a keychain access prompt when the item was created by another program, and an attribute lookup cannot.
123
120
 
124
- `setSecret` rejects an empty secret, which the keychain would hold as an item indistinguishable from a stray one, and one too long for the command line that contains it. Both are `UnstorableSecretError`, which is exported: Nothing was attempted, so a caller can tell a value that the keychain cannot store from a keychain that it could not reach. Every other secret is stored and returned byte for byte, whatever it holds. Each write is read back and compared, so a secret that did not survive the round trip fails at the write rather than at a later caller. That readback retrieves the secret, so replacing an item created by another program can raise the keychain access prompt described above, and a write whose readback is refused is reported as unverified rather than as stored.
121
+ `setSecret` rejects an empty secret, which the keychain would store as an item indistinguishable from a stray one, and one too long for the command line that contains it. Both are `UnstorableSecretError`, which is exported: Nothing was attempted, so a caller can tell a value that the keychain cannot store from a keychain that it could not reach. Every other secret is stored and returned byte for byte, whatever it contains. Each write is read back and compared: A secret that did not survive the round trip fails at the write rather than at a later caller. Because that readback retrieves the secret, replacing an item created by another program can raise the keychain access prompt described above, and a write whose readback is refused is reported as unverified rather than as stored.
125
122
 
126
123
  ```ts
127
124
  const projectStore = createKeychainStore({ keychain: '/Users/me/Library/Keychains/project.keychain-db' });
@@ -137,7 +134,7 @@ A named keychain accepts a write like the default search list does. `SecretStore
137
134
  promptSecret(input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Promise<string>;
138
135
  ```
139
136
 
140
- Reads a secret from a terminal without echoing it, asking twice and comparing, since nothing on screen shows what was typed. It rejects where the two entries differ, and where the input ends before a secret is entered, which is the one event that `Ctrl-C`, `Ctrl-D`, and a closed stream all share.
137
+ Reads a secret from a terminal without echoing it, asking twice and comparing, since nothing on screen shows what was typed. It rejects when the two entries differ, and when the input ends before a secret is entered, which is the one event that `Ctrl-C`, `Ctrl-D`, and a closed stream all share.
141
138
 
142
139
  ```ts
143
140
  import { promptSecret } from '@williamthorsen/toolbelt.secrets/candidate';
@@ -145,4 +142,4 @@ import { promptSecret } from '@williamthorsen/toolbelt.secrets/candidate';
145
142
  const secret = await promptSecret(process.stdin, process.stderr);
146
143
  ```
147
144
 
148
- The prompts go to `output` and the line being edited does not, so a caller passing `process.stderr` leaves `stdout` free for the command's own result. `security` has a prompt of its own, but it fills a 128-byte buffer and hands back nothing to verify, which is why this reads the secret instead.
145
+ The prompts go to `output` and the line being edited does not, so a caller passing `process.stderr` leaves `stdout` free for the command's own result. `security` has a prompt of its own, but it fills a 128-byte buffer and returns nothing to verify, which is why this reads the secret instead.
package/bin/tb-secret.js CHANGED
@@ -4,12 +4,12 @@
4
4
  // dependency would replace this file's build-first message with ERR_MODULE_NOT_FOUND.
5
5
  import { existsSync } from 'node:fs';
6
6
 
7
- // Thin wrapper so pnpm can link the bin at install time, before `dist/` exists. The real entry point loads
7
+ // Thin wrapper so that pnpm can link the bin at install time, before `dist/` exists. The real entry point loads
8
8
  // at runtime from the build output.
9
9
  const entryPoint = new URL('../dist/esm/bin/tb-secret.js', import.meta.url);
10
10
 
11
- // Gate on the entry file itself: Node raises ERR_MODULE_NOT_FOUND for any unresolved module in the graph,
12
- // so keying the build-first message off the error code would also fire when the build is present and one
11
+ // Gate on the entry file itself: Because Node raises ERR_MODULE_NOT_FOUND for any unresolved module in the
12
+ // graph, keying the build-first message off the error code would also fire when the build is present and one
13
13
  // of its imports is missing.
14
14
  if (!existsSync(entryPoint)) {
15
15
  process.stderr.write(
@@ -10,13 +10,13 @@ export interface SecretQuery {
10
10
  export interface SecretStore {
11
11
  /** Removes a secret, reporting whether one was there to remove. */
12
12
  deleteSecret(query: SecretQuery): boolean;
13
- /** Reads a secret, returning `undefined` where none is stored. */
13
+ /** Reads a secret, returning `undefined` when none is stored. */
14
14
  findSecret(query: SecretQuery): string | undefined;
15
15
  /** Reports whether a secret is stored, without reading it. */
16
16
  hasSecret(query: SecretQuery): boolean;
17
17
  }
18
18
  /** A secret store that also accepts a new secret. */
19
19
  export interface WritableSecretStore extends SecretStore {
20
- /** Stores a secret, replacing one already held under the same service and account. */
20
+ /** Stores a secret, replacing one already stored under the same service and account. */
21
21
  setSecret(query: SecretQuery, secret: string): void;
22
22
  }
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Reports a value that cannot reach `security` intact. It is distinct from a failure to reach the keychain,
3
- * since nothing was attempted: The caller gave a secret, service, or account that no command line can contain.
2
+ * The error for a value that cannot be passed to `security` intact. It is distinct from a failure to reach the
3
+ * keychain, since nothing was attempted: The caller gave a secret, service, or account that the command line cannot
4
+ * contain.
4
5
  *
5
6
  * @category Secrets
6
7
  * @experimental
@@ -1,6 +1,6 @@
1
1
  import type { WritableSecretStore } from './SecretStore.js';
2
2
  /**
3
- * Opens a macOS keychain as a secret store, or the default search list where no keychain is named. Throws off
3
+ * Opens a macOS keychain as a secret store, or the default search list when no keychain is named. Throws off
4
4
  * macOS.
5
5
  *
6
6
  * @category Secrets
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Reads a secret from a terminal without echoing it, asking twice and comparing, since nothing on screen shows
3
- * what was typed. `security` has a prompt of its own, but it fills a 128-byte buffer and hands back nothing to
3
+ * what was typed. `security` has a prompt of its own, but it fills a 128-byte buffer and returns nothing to
4
4
  * verify, so the secret is read here instead.
5
5
  *
6
6
  * @category Secrets
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Finds the manifest of the package owning a directory, ascending to the first `package.json` declaring a
3
3
  * `name`. One declaring none is a marker manifest, such as the `{"type": "commonjs"}` file left in `dist/`
4
- * by a dual-format build, and the ascent passes over it, so the answer is the owning package rather than
5
- * the nearest manifest. Throws where no ancestor declares a name.
4
+ * by a dual-format build, and the ascent passes over it, so the function returns the owning package's
5
+ * manifest rather than the nearest one. Throws when no ancestor declares a name.
6
6
  *
7
7
  * @internal
8
8
  */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Reads the version declared by the package owning a directory, defaulting to this module's own, which is
3
3
  * this package whether it runs from source under the test runner or from the build output once installed.
4
- * Throws where the owning manifest declares no string version.
4
+ * Throws when the owning manifest declares no string version.
5
5
  *
6
6
  * @internal
7
7
  */
@@ -1,7 +1,7 @@
1
1
  import type { WritableSecretStore } from '../3-candidate/SecretStore.js';
2
2
  /**
3
- * Runs the `tb-secret` command line, returning what to write and exit with rather than doing either, so the
4
- * whole surface is exercisable without a process. Every failure is reported through the result: Nothing throws.
3
+ * Runs the `tb-secret` command line, returning what to write and exit with rather than doing either, so that
4
+ * the whole surface is exercisable without a process. Every failure is reported through the result: Nothing throws.
5
5
  *
6
6
  * @internal
7
7
  */
@@ -1,93 +1,109 @@
1
- import { parseArgs } from 'node:util';
1
+ import { createCli, runCli, UsageError } from '@williamthorsen/toolbelt.cli/candidate';
2
2
  import { UnstorableSecretError } from "../3-candidate/UnstorableSecretError.js";
3
3
  const EXIT_OK = 0;
4
4
  const EXIT_NO_RESULT = 1;
5
- const EXIT_USAGE = 2;
6
5
  const EXIT_KEYSTORE = 3;
7
- const SUBCOMMANDS = new Set(['delete', 'get', 'has', 'set']);
8
- const ACCOUNT_OPTION = { account: { type: 'string', short: 'a' } };
9
- const HELP_OPTION = { help: { type: 'boolean', short: 'h' } };
10
- const KEYCHAIN_OPTION = { keychain: { type: 'string', short: 'k' } };
11
- const ROOT_HELP = `Usage: tb-secret <subcommand> <service> [options]
12
-
13
- Store and read secrets in the macOS keychain. Requires macOS.
14
-
15
- Subcommands:
16
- delete Remove a secret
17
- get Print a secret
18
- has Report whether a secret is stored, printing nothing
19
- set Store a secret
20
-
21
- Options:
22
- -h, --help Print this help; each subcommand takes its own --help
23
- --version Print the installed version
24
-
25
- A secret is named by a service and an optional account, so one service can hold a secret per account. An item
6
+ const { defineCommand, defineGroup } = createCli();
7
+ const SERVICE_OPERAND = { name: 'service', description: 'The service that names the secret' };
8
+ const SECRET_FLAGS = {
9
+ account: {
10
+ type: 'string',
11
+ description: 'Account holding the secret (default: the empty account)',
12
+ short: 'a',
13
+ valueHint: 'name',
14
+ },
15
+ keychain: {
16
+ type: 'string',
17
+ description: 'Keychain to act on, rather than the default search list',
18
+ short: 'k',
19
+ valueHint: 'path',
20
+ },
21
+ };
22
+ const ROOT = defineGroup({
23
+ summary: 'Store and read secrets in the macOS keychain. Requires macOS.',
24
+ epilog: `A secret is named by a service and an optional account, so one service can hold a secret per account. An item
26
25
  is local to this Mac: \`security\` offers no iCloud Keychain synchronization.
27
26
 
28
27
  Exit codes:
29
28
  0 The command succeeded
30
29
  1 No secret is stored under that service and account
31
30
  2 Usage or validation error
32
- 3 The keychain could not be reached`;
33
- const DELETE_HELP = `Usage: tb-secret delete <service> [options]
34
-
35
- Remove a secret, exiting 1 where none is stored.
36
-
37
- Options:
38
- -h, --help Print this help
39
- -a, --account <name> Account holding the secret (default: the empty account)
40
- -k, --keychain <path> Keychain to act on, rather than the default search list`;
41
- const GET_HELP = `Usage: tb-secret get <service> [options]
42
-
43
- Print a secret, exiting 1 where none is stored.
44
-
45
- Options:
46
- -h, --help Print this help
47
- -a, --account <name> Account holding the secret (default: the empty account)
48
- -k, --keychain <path> Keychain to read, rather than the default search list`;
49
- const HAS_HELP = `Usage: tb-secret has <service> [options]
50
-
51
- Exit 0 where a secret is stored and 1 where none is, printing nothing either way. The secret itself is never
52
- read, so this raises no keychain access prompt.
53
-
54
- Options:
55
- -h, --help Print this help
56
- -a, --account <name> Account holding the secret (default: the empty account)
57
- -k, --keychain <path> Keychain to read, rather than the default search list`;
58
- const SET_HELP = `Usage: tb-secret set <service> [options]
59
-
60
- Store a secret, replacing one already held under the same service and account.
61
-
62
- At a terminal the secret is prompted for twice and echoed nowhere; piped, it is read from stdin and one
63
- trailing newline is dropped, since \`echo\` adds one. Either way it reaches \`security\` inside a command that
64
- travels on stdin, so it never enters an argument vector that any local process could read.
31
+ 3 The keychain could not be reached`,
32
+ commands: {
33
+ delete: defineCommand({
34
+ summary: 'Remove a secret',
35
+ description: 'Remove a secret, exiting 1 when none is stored.',
36
+ flags: SECRET_FLAGS,
37
+ operands: [SERVICE_OPERAND],
38
+ run: ({ context, flags, operands, stderr }) => reportFailures(stderr, () => {
39
+ const query = buildQuery(operands.service, flags.account);
40
+ const removed = callKeystore(() => context.createStore(flags.keychain).deleteSecret(query));
41
+ return removed ? EXIT_OK : EXIT_NO_RESULT;
42
+ }),
43
+ }),
44
+ get: defineCommand({
45
+ summary: 'Print a secret',
46
+ description: 'Print a secret, exiting 1 when none is stored.',
47
+ flags: SECRET_FLAGS,
48
+ operands: [SERVICE_OPERAND],
49
+ run: ({ context, flags, operands, stderr, stdout }) => reportFailures(stderr, () => {
50
+ const query = buildQuery(operands.service, flags.account);
51
+ const secret = callKeystore(() => context.createStore(flags.keychain).findSecret(query));
52
+ if (secret === undefined)
53
+ return EXIT_NO_RESULT;
54
+ stdout.write(`${secret}\n`);
55
+ return EXIT_OK;
56
+ }),
57
+ }),
58
+ has: defineCommand({
59
+ summary: 'Report whether a secret is stored, printing nothing',
60
+ description: `Exit 0 when a secret is stored and 1 when none is, printing nothing either way. The secret itself is never
61
+ read, so this raises no keychain access prompt.`,
62
+ flags: SECRET_FLAGS,
63
+ operands: [SERVICE_OPERAND],
64
+ run: ({ context, flags, operands, stderr }) => reportFailures(stderr, () => {
65
+ const query = buildQuery(operands.service, flags.account);
66
+ const stored = callKeystore(() => context.createStore(flags.keychain).hasSecret(query));
67
+ return stored ? EXIT_OK : EXIT_NO_RESULT;
68
+ }),
69
+ }),
70
+ set: defineCommand({
71
+ summary: 'Store a secret',
72
+ description: 'Store a secret, replacing one already stored under the same service and account.',
73
+ epilog: `At a terminal the secret is prompted for twice and echoed nowhere; piped, it is read from stdin and one
74
+ trailing newline is dropped, since \`echo\` adds one. Either way it is passed to \`security\` inside a command
75
+ sent on stdin, so it never enters an argument vector that any local process could read.
65
76
 
66
77
  The stored secret is read back and compared before this command reports success. Replacing an item that
67
78
  another program created can therefore raise a keychain access prompt, since verifying the write reads the
68
79
  secret.
69
80
 
70
81
  A secret can be about 2,000 bytes long. The exact ceiling depends on the service, account, and keychain, which
71
- share one 4,095-byte command line with it; a secret that would not fit is refused rather than stored in part.
72
-
73
- Options:
74
- -h, --help Print this help
75
- -a, --account <name> Account to hold the secret (default: the empty account)
76
- -k, --keychain <path> Keychain to write to, rather than the default search list`;
82
+ share one 4,095-byte command line with it; a secret that would not fit is refused rather than stored in part.`,
83
+ flags: SECRET_FLAGS,
84
+ operands: [SERVICE_OPERAND],
85
+ run: ({ context, flags, operands, stderr }) => reportFailures(stderr, () => runSet(operands.service, flags, context)),
86
+ }),
87
+ },
88
+ });
77
89
  export async function runTbSecret(args, effects) {
78
- try {
79
- return await dispatch(args, effects);
80
- }
81
- catch (error) {
82
- if (error instanceof KeystoreError)
83
- return { exitCode: EXIT_KEYSTORE, stderr: `${error.message}\n`, stdout: '' };
84
- return fail(describeError(error), args[0]);
85
- }
90
+ const stdout = createTextBuffer();
91
+ const stderr = createTextBuffer();
92
+ const exitCode = await runCli(args, ROOT, {
93
+ name: 'tb-secret',
94
+ context: effects,
95
+ version: () => resolveVersion(effects),
96
+ stdout,
97
+ stderr,
98
+ });
99
+ return { exitCode, stderr: stderr.text, stdout: stdout.text };
86
100
  }
87
101
  class KeystoreError extends Error {
88
102
  }
89
- function buildQuery(positionals, account) {
90
- return { account, service: selectService(positionals) };
103
+ function buildQuery(service, account) {
104
+ if (service === '')
105
+ throw new Error('The service name is empty.');
106
+ return { account, service };
91
107
  }
92
108
  function callKeystore(operation) {
93
109
  try {
@@ -99,105 +115,50 @@ function callKeystore(operation) {
99
115
  throw new KeystoreError(describeError(error));
100
116
  }
101
117
  }
118
+ function createTextBuffer() {
119
+ let text = '';
120
+ return {
121
+ get text() {
122
+ return text;
123
+ },
124
+ write(chunk) {
125
+ text += chunk;
126
+ },
127
+ };
128
+ }
102
129
  function describeError(error) {
103
130
  return error instanceof Error ? error.message : String(error);
104
131
  }
105
- async function dispatch(args, effects) {
106
- const [command, ...rest] = args;
107
- if (command === 'delete')
108
- return runDelete(rest, effects);
109
- if (command === 'get')
110
- return runGet(rest, effects);
111
- if (command === 'has')
112
- return runHas(rest, effects);
113
- if (command === 'set')
114
- return await runSet(rest, effects);
115
- if (command === '--help' || command === '-h')
116
- return succeed(ROOT_HELP);
117
- if (command === '--version')
118
- return succeed(effects.resolveVersion());
119
- if (command === undefined)
120
- return fail('A subcommand is required.', command);
121
- return fail(`Unknown ${command.startsWith('-') ? 'option' : 'subcommand'}: ${command}`, command);
122
- }
123
- function fail(message, command) {
124
- const scope = command !== undefined && SUBCOMMANDS.has(command) ? `tb-secret ${command}` : 'tb-secret';
125
- return { exitCode: EXIT_USAGE, stderr: `${message}\nTry \`${scope} --help\`.\n`, stdout: '' };
126
- }
127
- function runDelete(args, effects) {
128
- const { positionals, values } = parseArgs({
129
- allowPositionals: true,
130
- args,
131
- options: { ...ACCOUNT_OPTION, ...HELP_OPTION, ...KEYCHAIN_OPTION },
132
- strict: true,
133
- });
134
- if (values.help === true)
135
- return succeed(DELETE_HELP);
136
- const query = buildQuery(positionals, values.account);
137
- const removed = callKeystore(() => effects.createStore(values.keychain).deleteSecret(query));
138
- return removed ? succeedSilently() : reportNoResult();
139
- }
140
- function runGet(args, effects) {
141
- const { positionals, values } = parseArgs({
142
- allowPositionals: true,
143
- args,
144
- options: { ...ACCOUNT_OPTION, ...HELP_OPTION, ...KEYCHAIN_OPTION },
145
- strict: true,
146
- });
147
- if (values.help === true)
148
- return succeed(GET_HELP);
149
- const query = buildQuery(positionals, values.account);
150
- const secret = callKeystore(() => effects.createStore(values.keychain).findSecret(query));
151
- return secret === undefined ? reportNoResult() : succeed(secret);
132
+ async function reportFailures(stderr, body) {
133
+ try {
134
+ return await body();
135
+ }
136
+ catch (error) {
137
+ if (error instanceof UsageError)
138
+ throw error;
139
+ if (error instanceof KeystoreError) {
140
+ stderr.write(`${error.message}\n`);
141
+ return EXIT_KEYSTORE;
142
+ }
143
+ throw new UsageError(describeError(error), { cause: error });
144
+ }
152
145
  }
153
- function runHas(args, effects) {
154
- const { positionals, values } = parseArgs({
155
- allowPositionals: true,
156
- args,
157
- options: { ...ACCOUNT_OPTION, ...HELP_OPTION, ...KEYCHAIN_OPTION },
158
- strict: true,
159
- });
160
- if (values.help === true)
161
- return succeed(HAS_HELP);
162
- const query = buildQuery(positionals, values.account);
163
- const stored = callKeystore(() => effects.createStore(values.keychain).hasSecret(query));
164
- return stored ? succeedSilently() : reportNoResult();
146
+ function resolveVersion(effects) {
147
+ try {
148
+ return effects.resolveVersion();
149
+ }
150
+ catch (error) {
151
+ throw new UsageError(describeError(error), { cause: error });
152
+ }
165
153
  }
166
- async function runSet(args, effects) {
167
- const { positionals, values } = parseArgs({
168
- allowPositionals: true,
169
- args,
170
- options: { ...ACCOUNT_OPTION, ...HELP_OPTION, ...KEYCHAIN_OPTION },
171
- strict: true,
172
- });
173
- if (values.help === true)
174
- return succeed(SET_HELP);
175
- const query = buildQuery(positionals, values.account);
176
- const store = callKeystore(() => effects.createStore(values.keychain));
154
+ async function runSet(service, flags, effects) {
155
+ const query = buildQuery(service, flags.account);
156
+ const store = callKeystore(() => effects.createStore(flags.keychain));
177
157
  const secret = effects.isStdinTty()
178
158
  ? await effects.promptSecret()
179
159
  : stripOneTrailingNewline(await effects.readStdin());
180
160
  callKeystore(() => store.setSecret(query, secret));
181
- return succeedSilently();
182
- }
183
- function reportNoResult() {
184
- return { exitCode: EXIT_NO_RESULT, stderr: '', stdout: '' };
185
- }
186
- function selectService(positionals) {
187
- if (positionals.length > 1)
188
- throw new Error(`Expected one service name. Received ${positionals.length}.`);
189
- const [service] = positionals;
190
- if (service === undefined)
191
- throw new Error('A service name is required.');
192
- if (service === '')
193
- throw new Error('The service name is empty.');
194
- return service;
195
- }
196
- function succeed(output) {
197
- return { exitCode: EXIT_OK, stderr: '', stdout: `${output}\n` };
198
- }
199
- function succeedSilently() {
200
- return { exitCode: EXIT_OK, stderr: '', stdout: '' };
161
+ return EXIT_OK;
201
162
  }
202
163
  function stripOneTrailingNewline(input) {
203
164
  return input.replace(/\r?\n$/, '');
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Rejects a platform that ships no `security` command, at construction rather than at the first call, so a
3
- * caller learns where its keystore is missing rather than what failed to run.
2
+ * Rejects a platform that has no `security` command, at construction rather than at the first call, so
3
+ * that a caller learns where its keystore is missing rather than what failed to run.
4
4
  *
5
5
  * @internal
6
6
  */
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Rejects an empty secret, which the keychain would hold as an item indistinguishable from a stray one. Every
3
- * other value is storable: The secret reaches `security` as hexadecimal, which encodes any byte sequence.
2
+ * Rejects an empty secret, which the keychain would store as an item indistinguishable from a stray one. Every
3
+ * other value is storable: The secret is passed to `security` as hexadecimal, which encodes any byte sequence.
4
4
  *
5
5
  * @internal
6
6
  */
@@ -1,7 +1,7 @@
1
1
  import type { WritableSecretStore } from '../3-candidate/SecretStore.js';
2
2
  import type { SecurityRunner } from './runSecurity.js';
3
3
  /**
4
- * Builds a store over one keychain, or over the default search list where none is named.
4
+ * Builds a store over one keychain, or over the default search list when none is named.
5
5
  *
6
6
  * @internal
7
7
  */
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Extracts the secret from what `security find-generic-password -g` writes to stderr. That command prints the
3
- * secret in whichever of two forms fits: raw between quotes where every byte is printable ASCII, and
3
+ * secret in whichever of two forms fits: raw between quotes when every byte is printable ASCII, and
4
4
  * `0x<hex> "<escaped>"` otherwise. Only the hex form is unambiguous, so the quoted form is read verbatim and
5
5
  * a value that fits neither throws, since a wrong secret is worse than a failure.
6
6
  *
@@ -24,8 +24,8 @@ export declare function buildHasArgs(query: SecretQuery, keychain?: string): str
24
24
  * 128-byte buffer that `security` fills when `-w` has no value.
25
25
  *
26
26
  * The secret goes in as `-X <hex>`. Its alphabet is closed, so no secret can alter the line's structure, and
27
- * every byte sequence is representable, a line break included. The service, account, and keychain have no such
28
- * form, so they are quoted instead and a line break in one is refused.
27
+ * every byte sequence is representable, a line break included. Because the service, account, and keychain have
28
+ * no such form, they are quoted instead and a line break in one is refused.
29
29
  *
30
30
  * @internal
31
31
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@williamthorsen/toolbelt.secrets",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Utilities for storing and retrieving secrets in the OS credential store",
5
5
  "keywords": [
6
6
  "credentials",
@@ -47,8 +47,11 @@
47
47
  "CHANGELOG.md",
48
48
  "dist/*"
49
49
  ],
50
+ "dependencies": {
51
+ "@williamthorsen/toolbelt.cli": "0.2.0"
52
+ },
50
53
  "devDependencies": {
51
- "@williamthorsen/toolbelt.testing": "0.6.0"
54
+ "@williamthorsen/toolbelt.testing": "0.6.2"
52
55
  },
53
56
  "engines": {
54
57
  "node": ">=24.0.0"