@williamthorsen/toolbelt.secrets 0.0.0 → 0.2.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 (43) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/LICENSE +7 -0
  3. package/README.md +180 -1
  4. package/bin/tb-secret.js +27 -0
  5. package/dist/esm/1-proposed/index.d.ts +1 -0
  6. package/dist/esm/1-proposed/index.js +1 -0
  7. package/dist/esm/2-draft/index.d.ts +1 -0
  8. package/dist/esm/2-draft/index.js +1 -0
  9. package/dist/esm/3-candidate/SecretStore.d.ts +22 -0
  10. package/dist/esm/3-candidate/SecretStore.js +1 -0
  11. package/dist/esm/3-candidate/UnstorableSecretError.d.ts +10 -0
  12. package/dist/esm/3-candidate/UnstorableSecretError.js +2 -0
  13. package/dist/esm/3-candidate/createKeychainStore.d.ts +14 -0
  14. package/dist/esm/3-candidate/createKeychainStore.js +7 -0
  15. package/dist/esm/3-candidate/index.d.ts +4 -0
  16. package/dist/esm/3-candidate/index.js +3 -0
  17. package/dist/esm/3-candidate/promptSecret.d.ts +10 -0
  18. package/dist/esm/3-candidate/promptSecret.js +38 -0
  19. package/dist/esm/4-release/index.d.ts +1 -0
  20. package/dist/esm/4-release/index.js +1 -0
  21. package/dist/esm/bin/findOwningManifest.d.ts +15 -0
  22. package/dist/esm/bin/findOwningManifest.js +24 -0
  23. package/dist/esm/bin/readStreamText.d.ts +7 -0
  24. package/dist/esm/bin/readStreamText.js +7 -0
  25. package/dist/esm/bin/resolveSelfVersion.d.ts +8 -0
  26. package/dist/esm/bin/resolveSelfVersion.js +8 -0
  27. package/dist/esm/bin/runTbSecret.d.ts +23 -0
  28. package/dist/esm/bin/runTbSecret.js +204 -0
  29. package/dist/esm/bin/tb-secret.d.ts +1 -0
  30. package/dist/esm/bin/tb-secret.js +23 -0
  31. package/dist/esm/internal/assertMacosPlatform.d.ts +7 -0
  32. package/dist/esm/internal/assertMacosPlatform.js +6 -0
  33. package/dist/esm/internal/assertStorableSecret.d.ts +7 -0
  34. package/dist/esm/internal/assertStorableSecret.js +5 -0
  35. package/dist/esm/internal/buildKeychainStore.d.ts +8 -0
  36. package/dist/esm/internal/buildKeychainStore.js +58 -0
  37. package/dist/esm/internal/parseSecurityPassword.d.ts +9 -0
  38. package/dist/esm/internal/parseSecurityPassword.js +31 -0
  39. package/dist/esm/internal/runSecurity.d.ts +16 -0
  40. package/dist/esm/internal/runSecurity.js +16 -0
  41. package/dist/esm/internal/securityCommands.d.ts +33 -0
  42. package/dist/esm/internal/securityCommands.js +50 -0
  43. package/package.json +59 -2
package/CHANGELOG.md ADDED
@@ -0,0 +1,57 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## 0.2.0 — 2026-09-06
6
+
7
+ ### Features
8
+
9
+ - Add createKeychainStore and tb-secret to toolbelt.secrets (#276)
10
+
11
+ Adds the first exports to `@williamthorsen/toolbelt.secrets`: `createKeychainStore`, which stores and reads secrets in the macOS keychain with no external dependency. Also adds `tb-secret`, a command that exposes the same store to a shell caller.
12
+
13
+ Supports macOS only.
14
+
15
+ - Ship the tb-jira CLI and document toolbelt.atlassian (#295)
16
+
17
+ - Adds the `tb-jira` binary to `@williamthorsen/toolbelt.atlassian`: Its `configure-project` subcommand reconciles a Jira project's statuses, workflow transitions, and board features against a spec file owned by the consuming repo, and `--dry-run` prints the plan and writes nothing.
18
+ - Adds a `tb-jira auth` subcommand, which stores, replaces, and removes the Jira API token in the keychain and reports which source would supply it without printing the token.
19
+ - Adds `resolveJiraSite`, `findJiraTokenSource`, and `JiraTransportError` to `@williamthorsen/toolbelt.atlassian/candidate`, so library code can resolve the site, name which link of the token chain would answer without reading the token, and tell a request that Jira rejected from one that never reached Jira.
20
+ - Adds `promptSecret` and `UnstorableSecretError` to `@williamthorsen/toolbelt.secrets/candidate`, so a caller outside that package can prompt for a secret without echoing it and can tell a token refused by the keychain from a keychain that could not be reached.
21
+
22
+ ### Bug fixes
23
+
24
+ - Stop truncating a secret longer than 128 characters (#278)
25
+
26
+ Fixes an issue where `tb-secret set` and `setSecret` stored the first 128 bytes of a longer secret and reported success, so an API token of ordinary length was silently corrupted. Secrets of up to ~2,000 bytes can now be stored; an empty secret or a secret that exceeds the limit is refused.
27
+
28
+ At a terminal, `tb-secret set` now prompts for the secret twice. An abandoned prompt reports that nothing was stored.
29
+
30
+ Separately, a write can now target a named keychain: `createKeychainStore` returns a writable store for any keychain, and `tb-secret set` now has a `--keychain` option.
31
+
32
+ - Point every package bin at a committed wrapper (#296)
33
+
34
+ - Points the `tb-git`, `tb-jira`, and `tb-secret` commands at committed wrappers under each package's `bin/`, so the target exists when the package manager links the command rather than only after a build.
35
+
36
+ - Fix piped-stdin reads and unhandled EPIPE in the CLIs (#301)
37
+
38
+ - Fixes an issue where `tb-secret set` and `tb-jira auth set` failed with `EAGAIN: resource temporarily unavailable` when the producer of a piped credential delayed its first byte, as `tb-secret get`, `op read`, and `gh auth token` all do.
39
+ - Stops `tb-secret`, `tb-jira`, and `tb-git` from crashing with an unhandled `EPIPE` when the reader on their stdout or stderr exits first, so that `tb-secret get | head -1` ends quietly, as a program that ignores `SIGPIPE` does.
40
+
41
+ ### Documentation
42
+
43
+ - Repair the repository's prose and record every rejection's ground (#290)
44
+
45
+ Applies one repo-wide `revise-prose` sweep across the repository's READMEs, `AGENTS.md`, source comments, doc descriptions, and test names.
46
+
47
+ - Restore relativizers across atlassian, secrets, and the workflows (#304)
48
+
49
+ - Revises documentation and comments to align with plain-speech doctrine and writing conventions.
50
+
51
+ ### Internal
52
+
53
+ - Scaffold toolbelt.secrets for credential storage (#275)
54
+
55
+ Scaffolds `packages/secrets`, an empty workspace for storing and retrieving secrets in the OS credential store, publishing to npm as `@williamthorsen/toolbelt.secrets`.
56
+
57
+ <!-- Generated by release-kit. Do not edit this file. Use .meta/changelog-overrides.json to override entries. -->
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 William Thorsen
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
6
+
7
+ The software is provided "as is" and the author disclaims all warranties with regard to this software including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, direct, indirect, or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software.
package/README.md CHANGED
@@ -1 +1,180 @@
1
- Placeholder for `@williamthorsen/toolbelt.secrets` — awaiting first release.
1
+ # @williamthorsen/toolbelt.secrets
2
+
3
+ Utilities for storing and retrieving secrets in the OS credential store.
4
+
5
+ <!-- section:release-notes -->
6
+ ## Release notes — v0.2.0 (2026-09-06)
7
+
8
+ ### Features
9
+
10
+ - Add createKeychainStore and tb-secret to toolbelt.secrets (#276)
11
+
12
+ Adds the first exports to `@williamthorsen/toolbelt.secrets`: `createKeychainStore`, which stores and reads secrets in the macOS keychain with no external dependency. Also adds `tb-secret`, a command that exposes the same store to a shell caller.
13
+
14
+ Supports macOS only.
15
+
16
+ - Ship the tb-jira CLI and document toolbelt.atlassian (#295)
17
+
18
+ - Adds the `tb-jira` binary to `@williamthorsen/toolbelt.atlassian`: Its `configure-project` subcommand reconciles a Jira project's statuses, workflow transitions, and board features against a spec file owned by the consuming repo, and `--dry-run` prints the plan and writes nothing.
19
+ - Adds a `tb-jira auth` subcommand, which stores, replaces, and removes the Jira API token in the keychain and reports which source would supply it without printing the token.
20
+ - Adds `resolveJiraSite`, `findJiraTokenSource`, and `JiraTransportError` to `@williamthorsen/toolbelt.atlassian/candidate`, so library code can resolve the site, name which link of the token chain would answer without reading the token, and tell a request that Jira rejected from one that never reached Jira.
21
+ - Adds `promptSecret` and `UnstorableSecretError` to `@williamthorsen/toolbelt.secrets/candidate`, so a caller outside that package can prompt for a secret without echoing it and can tell a token refused by the keychain from a keychain that could not be reached.
22
+
23
+ ### Bug fixes
24
+
25
+ - Stop truncating a secret longer than 128 characters (#278)
26
+
27
+ Fixes an issue where `tb-secret set` and `setSecret` stored the first 128 bytes of a longer secret and reported success, so an API token of ordinary length was silently corrupted. Secrets of up to ~2,000 bytes can now be stored; an empty secret or a secret that exceeds the limit is refused.
28
+
29
+ At a terminal, `tb-secret set` now prompts for the secret twice. An abandoned prompt reports that nothing was stored.
30
+
31
+ Separately, a write can now target a named keychain: `createKeychainStore` returns a writable store for any keychain, and `tb-secret set` now has a `--keychain` option.
32
+
33
+ - Point every package bin at a committed wrapper (#296)
34
+
35
+ - Points the `tb-git`, `tb-jira`, and `tb-secret` commands at committed wrappers under each package's `bin/`, so the target exists when the package manager links the command rather than only after a build.
36
+
37
+ - Fix piped-stdin reads and unhandled EPIPE in the CLIs (#301)
38
+
39
+ - Fixes an issue where `tb-secret set` and `tb-jira auth set` failed with `EAGAIN: resource temporarily unavailable` when the producer of a piped credential delayed its first byte, as `tb-secret get`, `op read`, and `gh auth token` all do.
40
+ - Stops `tb-secret`, `tb-jira`, and `tb-git` from crashing with an unhandled `EPIPE` when the reader on their stdout or stderr exits first, so that `tb-secret get | head -1` ends quietly, as a program that ignores `SIGPIPE` does.
41
+
42
+ ### Internal
43
+
44
+ - Scaffold toolbelt.secrets for credential storage (#275)
45
+
46
+ Scaffolds `packages/secrets`, an empty workspace for storing and retrieving secrets in the OS credential store, publishing to npm as `@williamthorsen/toolbelt.secrets`.
47
+ <!-- /section:release-notes -->
48
+
49
+ ## Installation
50
+
51
+ ```sh
52
+ pnpm add @williamthorsen/toolbelt.secrets
53
+ ```
54
+
55
+ Requires Node.js 24 or later, and macOS: the one backend is the macOS keychain, reached through `/usr/bin/security`. Constructing a store on another platform throws, naming the platform, rather than failing later at the first call.
56
+
57
+ ## How a secret is stored
58
+
59
+ 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.
60
+
61
+ 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 carries every byte, a line break included, and every write is read back and compared before it is reported as stored.
62
+
63
+ One command line carries 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.
64
+
65
+ An item created here is local to the Mac that created it. `security` offers no iCloud Keychain synchronization, so a secret stored on one machine has to be stored again on the next.
66
+
67
+ ## CLI
68
+
69
+ The package ships a `tb-secret` command exposing the store to a shell caller.
70
+
71
+ ```sh
72
+ pnpm add --global @williamthorsen/toolbelt.secrets # puts tb-secret on PATH
73
+ npx @williamthorsen/toolbelt.secrets get my-token # or run it without installing
74
+ ```
75
+
76
+ `tb-secret --help`, each subcommand's `--help`, and `tb-secret --version` report the surface and the installed version.
77
+
78
+ | Subcommand | Effect |
79
+ | ---------------------------- | ---------------------------------------------------- |
80
+ | `tb-secret delete <service>` | Removes a secret |
81
+ | `tb-secret get <service>` | Prints a secret |
82
+ | `tb-secret has <service>` | Reports whether a secret is stored, printing nothing |
83
+ | `tb-secret set <service>` | Stores a secret |
84
+
85
+ | Option | Effect |
86
+ | ----------------------- | ------------------------------------------------------- |
87
+ | `-a, --account <name>` | Account holding the secret (default: the empty account) |
88
+ | `-k, --keychain <path>` | Keychain to act on, rather than the default search list |
89
+
90
+ 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.
91
+
92
+ ```sh
93
+ tb-secret set atlassian-api-token --account me@example.com # prompts, echoing nothing
94
+
95
+ pbpaste | tb-secret set atlassian-api-token # or pipe it
96
+
97
+ export ATLASSIAN_API_TOKEN=$(tb-secret get atlassian-api-token --account me@example.com)
98
+ ```
99
+
100
+ ### Exit codes
101
+
102
+ | Code | Meaning |
103
+ | ---- | ------------------------------------------------------------- |
104
+ | `0` | The command succeeded |
105
+ | `1` | No secret is stored under that service and account |
106
+ | `2` | Usage or validation error, with the message on stderr |
107
+ | `3` | The keychain could not be reached, with the message on stderr |
108
+
109
+ An absent secret is `1` and a keychain that could not be reached is `3`, so a script can tell one from the other.
110
+
111
+ ```sh
112
+ if token=$(tb-secret get atlassian-api-token); then
113
+ curl --user "me@example.com:$token" https://example.atlassian.net/rest/api/3/myself
114
+ elif [ $? -eq 1 ]; then
115
+ echo 'No token stored. Run `tb-secret set atlassian-api-token`.' >&2
116
+ fi
117
+ ```
118
+
119
+ ## `createKeychainStore`
120
+
121
+ ```ts
122
+ createKeychainStore(options?: { keychain: string }): WritableSecretStore;
123
+
124
+ interface SecretQuery {
125
+ readonly account?: string | undefined;
126
+ readonly service: string;
127
+ }
128
+
129
+ interface SecretStore {
130
+ deleteSecret(query: SecretQuery): boolean;
131
+ findSecret(query: SecretQuery): string | undefined;
132
+ hasSecret(query: SecretQuery): boolean;
133
+ }
134
+
135
+ interface WritableSecretStore extends SecretStore {
136
+ setSecret(query: SecretQuery, secret: string): void;
137
+ }
138
+ ```
139
+
140
+ Opens the macOS keychain as a secret store. Every call is synchronous.
141
+
142
+ ```ts
143
+ import { createKeychainStore } from '@williamthorsen/toolbelt.secrets/candidate';
144
+
145
+ const store = createKeychainStore();
146
+
147
+ store.setSecret({ account: 'me@example.com', service: 'atlassian-api-token' }, token);
148
+ store.findSecret({ account: 'me@example.com', service: 'atlassian-api-token' });
149
+ // the token
150
+ ```
151
+
152
+ `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.
153
+
154
+ `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.
155
+
156
+ `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 carries it. Both are `UnstorableSecretError`, which is exported: nothing was attempted, so a caller can tell a value that the keychain cannot carry 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.
157
+
158
+ ```ts
159
+ const projectStore = createKeychainStore({ keychain: '/Users/me/Library/Keychains/project.keychain-db' });
160
+
161
+ projectStore.findSecret({ service: 'deploy-key' });
162
+ ```
163
+
164
+ A named keychain accepts a write like the default search list does. `SecretStore` remains the read-only half of the surface, for a backend that accepts no new secret.
165
+
166
+ ## `promptSecret`
167
+
168
+ ```ts
169
+ promptSecret(input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Promise<string>;
170
+ ```
171
+
172
+ 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.
173
+
174
+ ```ts
175
+ import { promptSecret } from '@williamthorsen/toolbelt.secrets/candidate';
176
+
177
+ const secret = await promptSecret(process.stdin, process.stderr);
178
+ ```
179
+
180
+ 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.
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Imports only node builtins: a top-level import resolves before the gate below runs, so an unresolvable
4
+ // dependency would replace this file's build-first message with ERR_MODULE_NOT_FOUND.
5
+ import { existsSync } from 'node:fs';
6
+
7
+ // Thin wrapper so pnpm can link the bin at install time, before `dist/` exists. The real entry point loads
8
+ // at runtime from the build output.
9
+ const entryPoint = new URL('../dist/esm/bin/tb-secret.js', import.meta.url);
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
13
+ // of its imports is missing.
14
+ if (!existsSync(entryPoint)) {
15
+ process.stderr.write(
16
+ 'tb-secret: build output not found. In a source checkout, run `nmr build`; otherwise reinstall the package.\n',
17
+ );
18
+ process.exit(1);
19
+ }
20
+
21
+ try {
22
+ await import(entryPoint.href);
23
+ } catch (error) {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ process.stderr.write(`tb-secret: failed to load: ${message}\n`);
26
+ process.exit(1);
27
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ /** Names one stored secret. An omitted account is the empty account, which is matched exactly. */
2
+ export interface SecretQuery {
3
+ readonly account?: string | undefined;
4
+ readonly service: string;
5
+ }
6
+ /**
7
+ * A secret store that can be read from and removed from. A backend that accepts no new secret supports no more
8
+ * than this.
9
+ */
10
+ export interface SecretStore {
11
+ /** Removes a secret, reporting whether one was there to remove. */
12
+ deleteSecret(query: SecretQuery): boolean;
13
+ /** Reads a secret, returning `undefined` where none is stored. */
14
+ findSecret(query: SecretQuery): string | undefined;
15
+ /** Reports whether a secret is stored, without reading it. */
16
+ hasSecret(query: SecretQuery): boolean;
17
+ }
18
+ /** A secret store that also accepts a new secret. */
19
+ export interface WritableSecretStore extends SecretStore {
20
+ /** Stores a secret, replacing one already held under the same service and account. */
21
+ setSecret(query: SecretQuery, secret: string): void;
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
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 carry.
4
+ *
5
+ * @category Secrets
6
+ * @experimental
7
+ * @stage candidate
8
+ */
9
+ export declare class UnstorableSecretError extends Error {
10
+ }
@@ -0,0 +1,2 @@
1
+ export class UnstorableSecretError extends Error {
2
+ }
@@ -0,0 +1,14 @@
1
+ import type { WritableSecretStore } from './SecretStore.js';
2
+ /**
3
+ * Opens a macOS keychain as a secret store, or the default search list where no keychain is named. Throws off
4
+ * macOS.
5
+ *
6
+ * @category Secrets
7
+ * @experimental
8
+ * @stage candidate
9
+ */
10
+ export declare function createKeychainStore(options?: KeychainStoreOptions): WritableSecretStore;
11
+ export interface KeychainStoreOptions {
12
+ /** Path of the keychain to open, such as `~/Library/Keychains/project.keychain-db`, expanded by the caller. */
13
+ readonly keychain: string;
14
+ }
@@ -0,0 +1,7 @@
1
+ import { assertMacosPlatform } from "../internal/assertMacosPlatform.js";
2
+ import { buildKeychainStore } from "../internal/buildKeychainStore.js";
3
+ import { runSecurity } from "../internal/runSecurity.js";
4
+ export function createKeychainStore(options) {
5
+ assertMacosPlatform();
6
+ return buildKeychainStore(runSecurity, options?.keychain);
7
+ }
@@ -0,0 +1,4 @@
1
+ export { createKeychainStore, type KeychainStoreOptions } from './createKeychainStore.js';
2
+ export { promptSecret } from './promptSecret.js';
3
+ export type { SecretQuery, SecretStore, WritableSecretStore } from './SecretStore.js';
4
+ export { UnstorableSecretError } from './UnstorableSecretError.js';
@@ -0,0 +1,3 @@
1
+ export { createKeychainStore } from "./createKeychainStore.js";
2
+ export { promptSecret } from "./promptSecret.js";
3
+ export { UnstorableSecretError } from "./UnstorableSecretError.js";
@@ -0,0 +1,10 @@
1
+ /**
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
4
+ * verify, so the secret is read here instead.
5
+ *
6
+ * @category Secrets
7
+ * @experimental
8
+ * @stage candidate
9
+ */
10
+ export declare function promptSecret(input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Promise<string>;
@@ -0,0 +1,38 @@
1
+ import readline from 'node:readline/promises';
2
+ import { Writable } from 'node:stream';
3
+ const CONFIRM_PROMPT = 'Retype secret: ';
4
+ const SECRET_PROMPT = 'Secret: ';
5
+ export async function promptSecret(input, output) {
6
+ const reader = readline.createInterface({ input, output: createSink(), terminal: true });
7
+ const abandoned = new AbortController();
8
+ reader.once('close', () => abandoned.abort());
9
+ try {
10
+ const secret = await ask(reader, output, abandoned.signal, SECRET_PROMPT);
11
+ const confirmation = await ask(reader, output, abandoned.signal, CONFIRM_PROMPT);
12
+ if (secret !== confirmation)
13
+ throw new Error('The two entries differ. Nothing was stored.');
14
+ return secret;
15
+ }
16
+ finally {
17
+ reader.close();
18
+ }
19
+ }
20
+ async function ask(reader, output, signal, prompt) {
21
+ output.write(prompt);
22
+ try {
23
+ const answer = await reader.question('', { signal });
24
+ output.write('\n');
25
+ return answer;
26
+ }
27
+ catch (error) {
28
+ output.write('\n');
29
+ throw signal.aborted ? new Error('The prompt ended before a secret was entered. Nothing was stored.') : error;
30
+ }
31
+ }
32
+ function createSink() {
33
+ return new Writable({
34
+ write(_chunk, _encoding, callback) {
35
+ callback();
36
+ },
37
+ });
38
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Finds the manifest of the package owning a directory, ascending to the first `package.json` declaring a
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.
6
+ *
7
+ * @internal
8
+ */
9
+ export declare function findOwningManifest(startDir: string): OwningManifest;
10
+ export interface OwningManifest {
11
+ readonly manifest: {
12
+ readonly version?: unknown;
13
+ };
14
+ readonly manifestPath: string;
15
+ }
@@ -0,0 +1,24 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ export function findOwningManifest(startDir) {
4
+ let dir = startDir;
5
+ for (;;) {
6
+ const manifestPath = path.join(dir, 'package.json');
7
+ if (fs.existsSync(manifestPath)) {
8
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
9
+ if (isNamedManifest(manifest))
10
+ return { manifest, manifestPath };
11
+ }
12
+ const parent = path.dirname(dir);
13
+ if (parent === dir)
14
+ throw new Error(`No package manifest declaring a name at or above ${startDir}.`);
15
+ dir = parent;
16
+ }
17
+ }
18
+ function isNamedManifest(value) {
19
+ return (typeof value === 'object' &&
20
+ value !== null &&
21
+ !Array.isArray(value) &&
22
+ 'name' in value &&
23
+ typeof value.name === 'string');
24
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Reads a stream to end as text, awaiting a producer that has not yet written. A synchronous read of a
3
+ * non-blocking pipe fails with `EAGAIN` rather than waiting, and a piped secret arrives on such a pipe.
4
+ *
5
+ * @internal
6
+ */
7
+ export declare function readStreamText(stream: NodeJS.ReadableStream): Promise<string>;
@@ -0,0 +1,7 @@
1
+ export async function readStreamText(stream) {
2
+ stream.setEncoding('utf8');
3
+ const chunks = [];
4
+ for await (const chunk of stream)
5
+ chunks.push(String(chunk));
6
+ return chunks.join('');
7
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Reads the version declared by the package owning a directory, defaulting to this module's own, which is
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.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function resolveSelfVersion(fromDir?: string): string;
@@ -0,0 +1,8 @@
1
+ import { findOwningManifest } from "./findOwningManifest.js";
2
+ export function resolveSelfVersion(fromDir = import.meta.dirname) {
3
+ const { manifest, manifestPath } = findOwningManifest(fromDir);
4
+ if (typeof manifest.version !== 'string') {
5
+ throw new TypeError(`No version declared in the package manifest at ${manifestPath}.`);
6
+ }
7
+ return manifest.version;
8
+ }
@@ -0,0 +1,23 @@
1
+ import type { WritableSecretStore } from '../3-candidate/SecretStore.js';
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.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function runTbSecret(args: string[], effects: TbSecretEffects): Promise<TbSecretResult>;
9
+ /** The effects deferred to the entry point, which is what keeps the runner free of I/O. */
10
+ export interface TbSecretEffects {
11
+ readonly createStore: (keychain: string | undefined) => WritableSecretStore;
12
+ readonly isStdinTty: () => boolean;
13
+ /** Reads a secret from the terminal, echoing nothing and asking twice. */
14
+ readonly promptSecret: () => Promise<string>;
15
+ readonly readStdin: () => Promise<string>;
16
+ readonly resolveVersion: () => string;
17
+ }
18
+ /** What the caller should write to each stream and exit with. */
19
+ export interface TbSecretResult {
20
+ readonly exitCode: number;
21
+ readonly stderr: string;
22
+ readonly stdout: string;
23
+ }
@@ -0,0 +1,204 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { UnstorableSecretError } from "../3-candidate/UnstorableSecretError.js";
3
+ const EXIT_OK = 0;
4
+ const EXIT_NO_RESULT = 1;
5
+ const EXIT_USAGE = 2;
6
+ 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
26
+ is local to this Mac: \`security\` offers no iCloud Keychain synchronization.
27
+
28
+ Exit codes:
29
+ 0 The command succeeded
30
+ 1 No secret is stored under that service and account
31
+ 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.
65
+
66
+ The stored secret is read back and compared before this command reports success. Replacing an item that
67
+ another program created can therefore raise a keychain access prompt, since verifying the write reads the
68
+ secret.
69
+
70
+ 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`;
77
+ 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
+ }
86
+ }
87
+ class KeystoreError extends Error {
88
+ }
89
+ function buildQuery(positionals, account) {
90
+ return { account, service: selectService(positionals) };
91
+ }
92
+ function callKeystore(operation) {
93
+ try {
94
+ return operation();
95
+ }
96
+ catch (error) {
97
+ if (error instanceof UnstorableSecretError)
98
+ throw error;
99
+ throw new KeystoreError(describeError(error));
100
+ }
101
+ }
102
+ function describeError(error) {
103
+ return error instanceof Error ? error.message : String(error);
104
+ }
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);
152
+ }
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();
165
+ }
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));
177
+ const secret = effects.isStdinTty()
178
+ ? await effects.promptSecret()
179
+ : stripOneTrailingNewline(await effects.readStdin());
180
+ 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: '' };
201
+ }
202
+ function stripOneTrailingNewline(input) {
203
+ return input.replace(/\r?\n$/, '');
204
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ import { createKeychainStore } from "../3-candidate/createKeychainStore.js";
2
+ import { promptSecret } from "../3-candidate/promptSecret.js";
3
+ import { readStreamText } from "./readStreamText.js";
4
+ import { resolveSelfVersion } from "./resolveSelfVersion.js";
5
+ import { runTbSecret } from "./runTbSecret.js";
6
+ for (const stream of [process.stdout, process.stderr]) {
7
+ stream.on('error', (error) => {
8
+ if (error.code !== 'EPIPE')
9
+ throw error;
10
+ });
11
+ }
12
+ const { exitCode, stderr, stdout } = await runTbSecret(process.argv.slice(2), {
13
+ createStore: (keychain) => (keychain === undefined ? createKeychainStore() : createKeychainStore({ keychain })),
14
+ isStdinTty: () => process.stdin.isTTY,
15
+ promptSecret: () => promptSecret(process.stdin, process.stderr),
16
+ readStdin: () => readStreamText(process.stdin),
17
+ resolveVersion: () => resolveSelfVersion(),
18
+ });
19
+ if (stdout !== '')
20
+ process.stdout.write(stdout);
21
+ if (stderr !== '')
22
+ process.stderr.write(stderr);
23
+ process.exitCode = exitCode;
@@ -0,0 +1,7 @@
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.
4
+ *
5
+ * @internal
6
+ */
7
+ export declare function assertMacosPlatform(platform?: string): void;
@@ -0,0 +1,6 @@
1
+ const MACOS = 'darwin';
2
+ export function assertMacosPlatform(platform = process.platform) {
3
+ if (platform === MACOS)
4
+ return;
5
+ throw new Error(`A keychain store needs macOS, which supplies /usr/bin/security. This platform is ${platform}.`);
6
+ }
@@ -0,0 +1,7 @@
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 carries any byte sequence.
4
+ *
5
+ * @internal
6
+ */
7
+ export declare function assertStorableSecret(secret: string): void;
@@ -0,0 +1,5 @@
1
+ import { UnstorableSecretError } from "../3-candidate/UnstorableSecretError.js";
2
+ export function assertStorableSecret(secret) {
3
+ if (secret === '')
4
+ throw new UnstorableSecretError('The secret is empty.');
5
+ }
@@ -0,0 +1,8 @@
1
+ import type { WritableSecretStore } from '../3-candidate/SecretStore.js';
2
+ import type { SecurityRunner } from './runSecurity.js';
3
+ /**
4
+ * Builds a store over one keychain, or over the default search list where none is named.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function buildKeychainStore(run: SecurityRunner, keychain?: string): WritableSecretStore;
@@ -0,0 +1,58 @@
1
+ import { assertStorableSecret } from "./assertStorableSecret.js";
2
+ import { parseSecurityPassword } from "./parseSecurityPassword.js";
3
+ import { buildDeleteArgs, buildFindArgs, buildHasArgs, composeSetLine } from "./securityCommands.js";
4
+ const EXIT_NOT_FOUND = 44;
5
+ const INTERACTIVE_ARGS = ['-i'];
6
+ export function buildKeychainStore(run, keychain) {
7
+ function findSecret(query) {
8
+ const result = run(buildFindArgs(query, keychain));
9
+ if (result.exitCode === EXIT_NOT_FOUND)
10
+ return undefined;
11
+ assertSucceeded(result, 'read the secret');
12
+ return parseSecurityPassword(result.stderr);
13
+ }
14
+ function readBack(query) {
15
+ try {
16
+ return findSecret(query);
17
+ }
18
+ catch (error) {
19
+ const detail = error instanceof Error ? error.message : String(error);
20
+ throw new Error(`The secret was written but could not be read back to verify it. ${detail}`, { cause: error });
21
+ }
22
+ }
23
+ return {
24
+ deleteSecret(query) {
25
+ const result = run(buildDeleteArgs(query, keychain));
26
+ if (result.exitCode === EXIT_NOT_FOUND)
27
+ return false;
28
+ assertSucceeded(result, 'delete the secret');
29
+ return true;
30
+ },
31
+ findSecret,
32
+ hasSecret(query) {
33
+ const result = run(buildHasArgs(query, keychain));
34
+ if (result.exitCode === EXIT_NOT_FOUND)
35
+ return false;
36
+ assertSucceeded(result, 'look up the secret');
37
+ return true;
38
+ },
39
+ setSecret(query, secret) {
40
+ assertStorableSecret(secret);
41
+ const line = composeSetLine(query, secret, keychain);
42
+ assertSucceeded(run(INTERACTIVE_ARGS, `${line}\n`), 'store the secret');
43
+ assertStoredIntact(readBack(query), secret);
44
+ },
45
+ };
46
+ }
47
+ function assertStoredIntact(stored, secret) {
48
+ if (stored === secret)
49
+ return;
50
+ const found = stored === undefined ? 'nothing was stored' : `${stored.length} characters came back`;
51
+ throw new Error(`The secret was written but not stored intact: ${secret.length} characters went in and ${found}.`);
52
+ }
53
+ function assertSucceeded(result, action) {
54
+ if (result.exitCode === 0)
55
+ return;
56
+ const detail = result.stderr.trim();
57
+ throw new Error(`Could not ${action}. \`security\` exited ${result.exitCode}${detail === '' ? '' : `: ${detail}`}`);
58
+ }
@@ -0,0 +1,9 @@
1
+ /**
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
4
+ * `0x<hex> "<escaped>"` otherwise. Only the hex form is unambiguous, so the quoted form is read verbatim and
5
+ * a value that fits neither throws, since a wrong secret is worse than a failure.
6
+ *
7
+ * @internal
8
+ */
9
+ export declare function parseSecurityPassword(stderr: string): string;
@@ -0,0 +1,31 @@
1
+ const HEX_FORM_PATTERN = /^0x(?<hex>(?:[\dA-Fa-f]{2})+)(?:\s|$)/;
2
+ const PASSWORD_LINE_PATTERN = /^password: ?(?<value>.*)$/m;
3
+ const HEX_PREFIX = '0x';
4
+ const QUOTE = '"';
5
+ export function parseSecurityPassword(stderr) {
6
+ const value = PASSWORD_LINE_PATTERN.exec(stderr)?.groups?.['value'];
7
+ if (value === undefined)
8
+ throw new Error(`No password line in the output of \`security\`: ${summarize(stderr)}`);
9
+ if (value.startsWith(HEX_PREFIX))
10
+ return decodeHexForm(value);
11
+ if (value === '')
12
+ return '';
13
+ return readQuotedForm(value);
14
+ }
15
+ function decodeHexForm(value) {
16
+ const hex = HEX_FORM_PATTERN.exec(value)?.groups?.['hex'];
17
+ if (hex === undefined)
18
+ throw new Error(`Malformed hexadecimal password in the output of \`security\`: ${value}`);
19
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(hex, 'hex'));
20
+ }
21
+ function readQuotedForm(value) {
22
+ const end = value.lastIndexOf(QUOTE);
23
+ if (!value.startsWith(QUOTE) || end === 0) {
24
+ throw new Error(`Unquoted password in the output of \`security\`: ${value}`);
25
+ }
26
+ return value.slice(QUOTE.length, end);
27
+ }
28
+ function summarize(output) {
29
+ const collapsed = output.trim().replaceAll(/\s+/g, ' ');
30
+ return collapsed.length > 200 ? `${collapsed.slice(0, 200)}...` : collapsed;
31
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Runs macOS's `security` command and reports what it wrote and exited with. An exit code is data here, so only
3
+ * a failure to launch the binary or a run that outlives the timeout throws. The path is absolute because `PATH`
4
+ * must not decide which program receives a secret.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function runSecurity(args: string[], input?: string): SecurityResult;
9
+ /** Runs `security` with the given arguments, writing `input` to its stdin. */
10
+ export type SecurityRunner = (args: string[], input?: string) => SecurityResult;
11
+ /** What one `security` run wrote and exited with. */
12
+ export interface SecurityResult {
13
+ readonly exitCode: number;
14
+ readonly stderr: string;
15
+ readonly stdout: string;
16
+ }
@@ -0,0 +1,16 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ const SECURITY_PATH = '/usr/bin/security';
3
+ const TIMEOUT_MS = 30_000;
4
+ export function runSecurity(args, input) {
5
+ const { error, status, stderr, stdout } = spawnSync(SECURITY_PATH, args, {
6
+ encoding: 'utf8',
7
+ input,
8
+ timeout: TIMEOUT_MS,
9
+ });
10
+ if (error !== undefined)
11
+ throw new Error(`Could not run ${SECURITY_PATH}: ${error.message}`);
12
+ if (status === null) {
13
+ throw new Error(`${SECURITY_PATH} was killed before it exited. It may have been waiting on a prompt.`);
14
+ }
15
+ return { exitCode: status, stderr, stdout };
16
+ }
@@ -0,0 +1,33 @@
1
+ import type { SecretQuery } from '../3-candidate/SecretStore.js';
2
+ /**
3
+ * Builds the arguments that delete a secret.
4
+ *
5
+ * @internal
6
+ */
7
+ export declare function buildDeleteArgs(query: SecretQuery, keychain?: string): string[];
8
+ /**
9
+ * Builds the arguments that read a secret. `-g` is what prints it, in the two forms that
10
+ * `parseSecurityPassword` reads.
11
+ *
12
+ * @internal
13
+ */
14
+ export declare function buildFindArgs(query: SecretQuery, keychain?: string): string[];
15
+ /**
16
+ * Builds the arguments that report whether a secret is stored. Without `-g` the command reads the item's
17
+ * attributes alone, so it never retrieves the secret and cannot raise a keychain access prompt.
18
+ *
19
+ * @internal
20
+ */
21
+ export declare function buildHasArgs(query: SecretQuery, keychain?: string): string[];
22
+ /**
23
+ * Composes the one command line that `security -i` runs to store a secret. Interactive mode takes the whole
24
+ * command on stdin, which keeps the secret off argv, where any local process could read it, and away from the
25
+ * 128-byte buffer that `security` fills when `-w` carries no value.
26
+ *
27
+ * The secret goes in as `-X <hex>`. Its alphabet is closed, so no secret can alter the line's structure, and
28
+ * every byte sequence is representable, a line break included. The service, account, and keychain have no such
29
+ * form, so they are quoted instead and a line break in one is refused.
30
+ *
31
+ * @internal
32
+ */
33
+ export declare function composeSetLine(query: SecretQuery, secret: string, keychain?: string): string;
@@ -0,0 +1,50 @@
1
+ import { UnstorableSecretError } from "../3-candidate/UnstorableSecretError.js";
2
+ const MAX_LINE_BYTES = 4_095;
3
+ const HEX_CHARACTERS_PER_BYTE = 2;
4
+ const LINE_BREAK_PATTERN = /[\n\r]/;
5
+ export function buildDeleteArgs(query, keychain) {
6
+ return ['delete-generic-password', ...itemArgs(query), ...keychainArgs(keychain)];
7
+ }
8
+ export function buildFindArgs(query, keychain) {
9
+ return ['find-generic-password', ...itemArgs(query), '-g', ...keychainArgs(keychain)];
10
+ }
11
+ export function buildHasArgs(query, keychain) {
12
+ return ['find-generic-password', ...itemArgs(query), ...keychainArgs(keychain)];
13
+ }
14
+ export function composeSetLine(query, secret, keychain) {
15
+ const { account = '', service } = query;
16
+ assertOneLine(account, 'account');
17
+ assertOneLine(service, 'service');
18
+ if (keychain !== undefined)
19
+ assertOneLine(keychain, 'keychain');
20
+ const head = `add-generic-password -U -a ${quote(account)} -s ${quote(service)} -X`;
21
+ const tail = keychain === undefined ? '' : ` ${quote(keychain)}`;
22
+ const line = `${head} ${encodeHex(secret)}${tail}`;
23
+ assertLineFits(line, Buffer.byteLength(`${head} ${tail}`, 'utf8'));
24
+ return line;
25
+ }
26
+ function assertLineFits(line, fixedBytes) {
27
+ const lineBytes = Buffer.byteLength(line, 'utf8');
28
+ if (lineBytes <= MAX_LINE_BYTES)
29
+ return;
30
+ const availableBytes = Math.floor((MAX_LINE_BYTES - fixedBytes) / HEX_CHARACTERS_PER_BYTE);
31
+ throw new UnstorableSecretError(`The secret is too long to store. The command line would be ${lineBytes} bytes and \`security\` reads at ` +
32
+ `most ${MAX_LINE_BYTES}. The rest of the command leaves room for a secret of ${availableBytes} bytes.`);
33
+ }
34
+ function assertOneLine(value, field) {
35
+ if (!LINE_BREAK_PATTERN.test(value))
36
+ return;
37
+ throw new UnstorableSecretError(`The ${field} carries a line break, which \`security\` reads as the end of a command.`);
38
+ }
39
+ function encodeHex(secret) {
40
+ return Buffer.from(secret, 'utf8').toString('hex');
41
+ }
42
+ function itemArgs({ account = '', service }) {
43
+ return ['-a', account, '-s', service];
44
+ }
45
+ function keychainArgs(keychain) {
46
+ return keychain === undefined ? [] : [keychain];
47
+ }
48
+ function quote(value) {
49
+ return `"${value.replaceAll('\\', '\\\\').replaceAll('"', String.raw `\"`)}"`;
50
+ }
package/package.json CHANGED
@@ -1,4 +1,61 @@
1
1
  {
2
2
  "name": "@williamthorsen/toolbelt.secrets",
3
- "version": "0.0.0"
4
- }
3
+ "version": "0.2.0",
4
+ "description": "Utilities for storing and retrieving secrets in the OS credential store",
5
+ "keywords": [
6
+ "credentials",
7
+ "esm",
8
+ "keychain",
9
+ "keystore",
10
+ "secrets",
11
+ "toolbelt",
12
+ "typescript",
13
+ "utilities"
14
+ ],
15
+ "homepage": "https://github.com/williamthorsen/toolbelt/tree/main/packages/secrets#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/williamthorsen/toolbelt/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/williamthorsen/toolbelt.git",
22
+ "directory": "packages/secrets"
23
+ },
24
+ "license": "ISC",
25
+ "author": "William Thorsen <william@thorsen.dev> (https://github.com/williamthorsen)",
26
+ "sideEffects": false,
27
+ "type": "module",
28
+ "exports": {
29
+ ".": {
30
+ "import": "./dist/esm/4-release/index.js"
31
+ },
32
+ "./candidate": {
33
+ "import": "./dist/esm/3-candidate/index.js"
34
+ },
35
+ "./draft": {
36
+ "import": "./dist/esm/2-draft/index.js"
37
+ },
38
+ "./proposed": {
39
+ "import": "./dist/esm/1-proposed/index.js"
40
+ }
41
+ },
42
+ "bin": {
43
+ "tb-secret": "./bin/tb-secret.js"
44
+ },
45
+ "files": [
46
+ "bin/*",
47
+ "CHANGELOG.md",
48
+ "dist/*"
49
+ ],
50
+ "devDependencies": {
51
+ "@williamthorsen/toolbelt.filesystem": "0.8.3"
52
+ },
53
+ "engines": {
54
+ "node": ">=24.0.0"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public",
58
+ "registry": "https://registry.npmjs.org"
59
+ },
60
+ "scripts": {}
61
+ }