Skip to content

Commit fc039af

Browse files
authored
chore: fix op scripts for users with only 1 account (#277)
Always setting OP_ACCOUNT="team-clerk" doesn't work for everyone. The theory behind this is that if you only have one account in 1Password then you don't need to specify an account. You can use empty string.
1 parent bcf8191 commit fc039af

1 file changed

Lines changed: 36 additions & 1 deletion

File tree

scripts/lib/op.ts

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import { $ } from "bun";
88

9-
const OP_ACCOUNT = "team-clerk";
9+
const TEAM_CLERK_ACCOUNT = "team-clerk";
1010

1111
const INSTALL_HINT =
1212
"1Password CLI is not installed. Install it with `brew install 1password-cli`.";
@@ -27,11 +27,45 @@ export async function ensureOpInstalled(): Promise<void> {
2727
}
2828
}
2929

30+
/**
31+
* Finds the number of 1Password accounts available locally.
32+
*
33+
* @returns `0` if `op` is missing, the command fails, or the output is not a JSON array.
34+
*/
35+
async function getOpAccountCount(): Promise<number> {
36+
const res = await $`op account list --format json`
37+
.env({ ...process.env })
38+
.quiet()
39+
.nothrow();
40+
41+
if (res.exitCode !== 0) {
42+
return 0;
43+
}
44+
45+
try {
46+
const parsed: unknown = JSON.parse(res.stdout.toString());
47+
return Array.isArray(parsed) ? parsed.length : 0;
48+
} catch {
49+
return 0;
50+
}
51+
}
52+
53+
/**
54+
* Gets the 1Password account to use for the current operation.
55+
*
56+
* @returns the team-clerk account if there are multiple accounts, otherwise an empty string.
57+
*/
58+
async function getOpAccount(): Promise<string> {
59+
const opAccountCount = await getOpAccountCount();
60+
return opAccountCount > 1 ? TEAM_CLERK_ACCOUNT : "";
61+
}
62+
3063
/**
3164
* Read a secret or document from 1Password by `op://` reference.
3265
* Throws with a helpful hint if the read fails.
3366
*/
3467
export async function readOpItem(reference: string): Promise<string> {
68+
const OP_ACCOUNT = await getOpAccount();
3569
const result = await $`op read ${reference}`
3670
.env({ ...process.env, OP_ACCOUNT })
3771
.quiet()
@@ -58,6 +92,7 @@ export async function runWithOpSecrets(
5892
throw new Error("runWithOpSecrets requires at least one command argument.");
5993
}
6094

95+
const OP_ACCOUNT = await getOpAccount();
6196
const proc = Bun.spawn(["op", "run", "--", ...command], {
6297
stdio: ["inherit", "inherit", "inherit"],
6398
env: { ...process.env, OP_ACCOUNT, ...references },

0 commit comments

Comments
 (0)