keypin 0.3.0 → 0.5.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.
@@ -2,8 +2,9 @@
2
2
  import {
3
3
  messageOf,
4
4
  errorCode,
5
- installProblem
6
- } from "./chunk-8agfxsqt.js";
5
+ installProblem,
6
+ selfCommand
7
+ } from "./chunk-j6kpw8ge.js";
7
8
 
8
9
  // src/start.ts
9
10
  import { homedir as homedir2 } from "os";
@@ -38,13 +39,54 @@ async function generationOf(secret) {
38
39
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 16);
39
40
  }
40
41
  // ../../packages/core/src/contracts.ts
41
- var ENVIRONMENTS = ["dev", "prod"];
42
+ var DEFAULT_ENVIRONMENTS = ["dev", "prod"];
42
43
  // ../../packages/core/src/map.ts
43
44
  var {TOML } = globalThis.Bun;
44
45
 
45
46
  // ../../packages/core/src/record.ts
46
47
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
47
48
 
49
+ // ../../packages/core/src/reference.ts
50
+ var SCHEME = "op://";
51
+ function parseReference(text) {
52
+ if (!text.startsWith(SCHEME))
53
+ return `must start with ${SCHEME}`;
54
+ if (/[?#]/.test(text))
55
+ return "can't have a query such as ?attribute=";
56
+ const parts = text.slice(SCHEME.length).split("/");
57
+ if (parts.length < 3 || parts.length > 4 || parts.some((part) => !part.trim())) {
58
+ return `must be ${SCHEME}<vault>/<item>/<field> or ${SCHEME}<vault>/<item>/<section>/<field>`;
59
+ }
60
+ const [vault = "", item = "", ...rest] = parts;
61
+ return {
62
+ vault,
63
+ item,
64
+ section: rest.length === 2 ? rest[0] ?? null : null,
65
+ field: rest.at(-1) ?? ""
66
+ };
67
+ }
68
+ function formatReference(ref) {
69
+ const parts = [ref.vault, ref.item, ...ref.section === null ? [] : [ref.section], ref.field];
70
+ return `${SCHEME}${parts.join("/")}`;
71
+ }
72
+ var sameName = (a, b) => a === b || a !== null && b !== null && a.toLowerCase() === b.toLowerCase();
73
+ function sameItem(a, b) {
74
+ return a.kind === b.kind && a.account === b.account && sameName(a.vault, b.vault) && sameName(a.item, b.item);
75
+ }
76
+ function sameRef(a, b) {
77
+ return sameItem(a, b) && sameName(a.section, b.section) && sameName(a.field, b.field);
78
+ }
79
+ function storedRefWithPasswordDefault(value) {
80
+ if (!isRecord(value) || value.kind !== "1password")
81
+ return null;
82
+ const { account, vault, item, section = null, field = "password" } = value;
83
+ if (typeof account !== "string" || typeof vault !== "string" || typeof item !== "string")
84
+ return null;
85
+ if (typeof field !== "string" || section !== null && typeof section !== "string")
86
+ return null;
87
+ return { kind: "1password", account, vault, item, section, field };
88
+ }
89
+
48
90
  // ../../packages/core/src/rotation.ts
49
91
  var DUE_SOON_DAYS = 14;
50
92
  var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
@@ -79,6 +121,15 @@ function addDays(day, days) {
79
121
  // ../../packages/core/src/map.ts
80
122
  var DESTINATION_KINDS = ["cloudflare-worker", "github-actions"];
81
123
  var PROVIDER_KINDS = ["cloudflare-account-token"];
124
+ function runEnvironment(map) {
125
+ return map.environments[0] ?? "dev";
126
+ }
127
+ function publishEnvironment(map) {
128
+ return map.environments.at(-1) ?? "prod";
129
+ }
130
+ function envFlag(environment, fallback) {
131
+ return environment === fallback ? "" : ` --env ${environment}`;
132
+ }
82
133
  function destinationId(target, secretName) {
83
134
  return `${placeId(target)}:${secretName}`;
84
135
  }
@@ -112,59 +163,70 @@ function parseMap(text, file) {
112
163
  }
113
164
  return validateMap(data, file);
114
165
  }
115
- var KEY_ID = /^[a-z0-9][a-z0-9-]*$/;
116
- var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
166
+ var ENVIRONMENT_NAME = /^[a-z][a-z0-9-]*$/;
167
+ var KEY_FIELDS = ["rotate_every"];
168
+ var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
117
169
  var REPO = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
118
- var VAULT_KINDS = ["1password"];
170
+ var REMOVED_KEY_FIELDS = ["owner", "consumers"];
171
+ var OLD_FORMAT = "see docs/configuration.md for the current format";
119
172
  function validateMap(data, file) {
120
173
  const errors = [];
121
174
  const fail = (where, message) => errors.push(`${file}: ${where}${message}`);
122
175
  if (!isRecord(data))
123
176
  return { ok: false, errors: [`${file}: expected a table at the top level`] };
124
- unknownFields(data, ["vaults", "keys"], (field) => fail("", `unknown top-level field "${field}"`));
125
- const vaults = new Map;
126
- const rawVaults = data.vaults ?? {};
127
- if (!isRecord(rawVaults))
128
- fail("", `"vaults" must be a table`);
129
- else {
130
- for (const [name, raw] of Object.entries(rawVaults)) {
131
- const at = `vault "${name}": `;
132
- if (!isRecord(raw)) {
133
- fail(at, "must be a table");
134
- continue;
135
- }
136
- unknownFields(raw, ["kind", "account", "vault"], (field) => fail(at, `unknown field "${field}"`));
137
- const kind = requiredString(raw, "kind", (m) => fail(at, m));
138
- const account = requiredString(raw, "account", (m) => fail(at, m));
139
- const vault = requiredString(raw, "vault", (m) => fail(at, m));
140
- if (kind !== undefined && !VAULT_KINDS.includes(kind)) {
141
- fail(at, `field "kind" must be one of: ${VAULT_KINDS.join(", ")}`);
142
- } else if (kind !== undefined && account !== undefined && vault !== undefined) {
143
- vaults.set(name, { kind: "1password", account, vault });
144
- }
145
- }
146
- }
177
+ unknownFields(data, ["environments", "1password", "keys"], (field) => fail("", field === "vaults" ? `[vaults] is from keypin 0.4; use [1password] and op:// references (${OLD_FORMAT})` : `unknown top-level field "${field}"`));
178
+ const environments = validateEnvironments(data.environments, (message) => fail("", message));
179
+ const account = validateAccount(data["1password"], (message) => fail("[1password]: ", message));
147
180
  const keys = [];
148
181
  const rawKeys = data.keys ?? {};
149
182
  if (!isRecord(rawKeys))
150
183
  fail("", `"keys" must be a table`);
151
184
  else {
152
- for (const [id, raw] of Object.entries(rawKeys)) {
153
- const entry = validateKey(id, raw, vaults, (where, message) => fail(`key "${id}"${where}: `, message));
185
+ Object.entries(rawKeys).forEach(([id, raw], index) => {
186
+ const label = VARIABLE_NAME.test(id) ? `key "${id}"` : `keys[${index}]`;
187
+ const entry = validateKey(id, raw, account, environments, (where, message) => fail(`${label}${where}: `, message));
154
188
  if (entry)
155
189
  keys.push(entry);
156
- }
190
+ });
157
191
  }
158
- sharedDestinations(keys, (where, message) => fail(where, message));
159
- return errors.length ? { ok: false, errors } : { ok: true, map: { file, keys } };
192
+ sharedDestinations(keys, environments, (where, message) => fail(where, message));
193
+ return errors.length ? { ok: false, errors } : { ok: true, map: { file, account: account ?? null, environments, keys } };
160
194
  }
161
- function sharedDestinations(keys, fail) {
195
+ function validateAccount(raw, fail) {
196
+ if (raw === undefined)
197
+ return;
198
+ if (!isRecord(raw)) {
199
+ fail("must be a table");
200
+ return;
201
+ }
202
+ unknownFields(raw, ["account"], (field) => fail(`unknown field "${field}"`));
203
+ return requiredString(raw, "account", fail);
204
+ }
205
+ function validateEnvironments(raw, fail) {
206
+ if (raw === undefined)
207
+ return DEFAULT_ENVIRONMENTS;
208
+ if (!Array.isArray(raw) || !raw.length || !raw.every((name) => typeof name === "string")) {
209
+ fail(`"environments" must be a list of names, such as ["dev", "staging", "prod"]`);
210
+ return DEFAULT_ENVIRONMENTS;
211
+ }
212
+ const names = [];
213
+ for (const name of raw) {
214
+ if (!ENVIRONMENT_NAME.test(name)) {
215
+ fail(`environment "${name}": a name starts with a lowercase letter and uses only lowercase letters, digits and dashes`);
216
+ } else if (names.includes(name)) {
217
+ fail(`environment "${name}" is listed twice`);
218
+ } else
219
+ names.push(name);
220
+ }
221
+ return names;
222
+ }
223
+ function sharedDestinations(keys, environments, fail) {
162
224
  const owners = new Map;
163
225
  for (const key of keys) {
164
- for (const environment of ENVIRONMENTS) {
226
+ for (const environment of environments) {
165
227
  key.environments[environment]?.publish.forEach((target, i) => {
166
- const where = `key "${key.id}" ${environment} publish[${i}]`;
167
- const secret = secretKey(target, key.env);
228
+ const where = `key "${key.name}" ${environment} publish[${i}]`;
229
+ const secret = secretKey(target, key.name);
168
230
  const owner = owners.get(secret);
169
231
  if (owner === undefined)
170
232
  owners.set(secret, where);
@@ -174,68 +236,47 @@ function sharedDestinations(keys, fail) {
174
236
  }
175
237
  }
176
238
  }
177
- function validateKey(id, raw, vaults, fail) {
239
+ function validateKey(id, raw, account, environmentNames, fail) {
178
240
  let failures = 0;
179
241
  const err = (where, message) => {
180
242
  failures++;
181
243
  fail(where, message);
182
244
  };
183
- if (!KEY_ID.test(id))
184
- err("", "a key ID uses lowercase letters, digits and dashes");
245
+ if (!VARIABLE_NAME.test(id))
246
+ err("", "the table name is the variable your program reads: letters, digits and _, not starting with a digit");
185
247
  if (!isRecord(raw)) {
186
248
  err("", "must be a table");
187
249
  return;
188
250
  }
189
- unknownFields(raw, ["env", "owner", "rotate_every", "consumers", ...ENVIRONMENTS], (field) => err("", `unknown field "${field}"`));
190
- const env = requiredString(raw, "env", (m) => err("", m));
191
- if (env !== undefined && !ENV_NAME.test(env))
192
- err("", `field "env" must be a variable name: letters, digits and _, not starting with a digit`);
193
- const owner = requiredString(raw, "owner", (m) => err("", m));
251
+ unknownFields(raw, [...KEY_FIELDS, ...environmentNames], (field) => err("", field === "env" ? `field "env" is from keypin 0.4; name the table after the variable, such as [keys.API_TOKEN] (${OLD_FORMAT})` : REMOVED_KEY_FIELDS.includes(field) ? `field "${field}" is no longer used; delete it` : `unknown field "${field}"; environments are ${environmentNames.map((n) => `"${n}"`).join(", ")}`));
194
252
  const rotateEvery = optionalString(raw, "rotate_every", (m) => err("", m));
195
253
  if (rotateEvery !== undefined && periodDays(rotateEvery) === undefined) {
196
254
  err("", `field "rotate_every" must be <n>d, <n>w, <n>m or never`);
197
255
  }
198
- const environments = {};
199
- for (const name of ENVIRONMENTS) {
200
- if (raw[name] === undefined)
201
- continue;
202
- const entry = validateEnv(raw[name], vaults, (m) => err(` ${name}`, m));
256
+ const environments = Object.create(null);
257
+ const declared = environmentNames.filter((name) => Object.hasOwn(raw, name));
258
+ for (const name of declared) {
259
+ const entry = validateEnv(raw[name], account, (m) => err(` ${name}`, m));
203
260
  if (entry)
204
261
  environments[name] = entry;
205
262
  }
206
263
  for (const [name, entry] of Object.entries(environments)) {
207
264
  const index = entry.publish.findIndex((target) => target.to === "github-actions");
208
- if (env !== undefined && index !== -1 && /^GITHUB_/i.test(env)) {
209
- err(` ${name}`, `publish[${index}]: github-actions can't take this key, because GitHub reserves secret names that start with GITHUB_; rename field "env"`);
265
+ if (index !== -1 && /^GITHUB_/i.test(id)) {
266
+ err(` ${name}`, `publish[${index}]: github-actions can't take this key, because GitHub reserves secret names that start with GITHUB_`);
210
267
  }
211
268
  }
212
- if (!ENVIRONMENTS.some((name) => raw[name] !== undefined)) {
213
- err("", `needs at least one of ${ENVIRONMENTS.map((n) => `"${n}"`).join(", ")}`);
269
+ if (!declared.length) {
270
+ err("", `needs at least one of ${environmentNames.map((n) => `"${n}"`).join(", ")}`);
214
271
  }
215
- const consumers = [];
216
- if (raw.consumers !== undefined) {
217
- if (!Array.isArray(raw.consumers))
218
- err("", `field "consumers" must be a list`);
219
- else {
220
- raw.consumers.forEach((c, i) => {
221
- const at = ` consumers[${i}]`;
222
- if (!isRecord(c))
223
- return err(at, "must be a table");
224
- unknownFields(c, ["name", "kind"], (field) => err(at, `unknown field "${field}"`));
225
- const name = requiredString(c, "name", (m) => err(at, m));
226
- const kind = requiredString(c, "kind", (m) => err(at, m));
227
- if (name !== undefined && kind !== undefined)
228
- consumers.push({ name, kind });
229
- });
230
- }
231
- }
232
- if (failures || env === undefined || owner === undefined)
272
+ if (failures)
233
273
  return;
234
- return { id, env, owner, rotateEvery: rotateEvery ?? null, environments, consumers };
274
+ return { name: id, rotateEvery: rotateEvery ?? null, environments };
235
275
  }
236
- function validateEnv(raw, vaults, fail) {
276
+ function validateEnv(given, account, fail) {
277
+ const raw = typeof given === "string" ? { from: given } : given;
237
278
  if (!isRecord(raw)) {
238
- fail("must be a table");
279
+ fail(`must be an op:// reference, or a table with "from"`);
239
280
  return;
240
281
  }
241
282
  let failed = false;
@@ -243,12 +284,8 @@ function validateEnv(raw, vaults, fail) {
243
284
  failed = true;
244
285
  fail(message);
245
286
  };
246
- unknownFields(raw, ["vault", "item", "publish", "issue"], (field) => err(`unknown field "${field}"`));
247
- const vaultName = requiredString(raw, "vault", err);
248
- const item = requiredString(raw, "item", err);
249
- const vault = vaultName === undefined ? undefined : vaults.get(vaultName);
250
- if (vaultName !== undefined && !vault)
251
- err(`field "vault" names a vault that isn't under [vaults]`);
287
+ unknownFields(raw, ["from", "publish", "issue"], (field) => err(field === "vault" || field === "item" ? `"vault" and "item" are from keypin 0.4; use from = "op://<vault>/<item>/<field>" (${OLD_FORMAT})` : `unknown field "${field}"`));
288
+ const ref = reference(raw, "from", account, err);
252
289
  const publish = [];
253
290
  const firstAt = new Map;
254
291
  if (raw.publish !== undefined) {
@@ -269,13 +306,28 @@ function validateEnv(raw, vaults, fail) {
269
306
  });
270
307
  }
271
308
  }
272
- const issue = raw.issue === undefined || !vault || item === undefined ? undefined : validateIssue(raw.issue, vault, item, (m) => err(`issue: ${m}`));
273
- if (failed || !vault || item === undefined)
309
+ const issue = raw.issue === undefined || !ref ? undefined : validateIssue(raw.issue, ref, account, (m) => err(`issue: ${m}`));
310
+ if (failed || !ref)
311
+ return;
312
+ return { ref, publish, ...issue ? { issue } : {} };
313
+ }
314
+ function reference(table, field, account, fail) {
315
+ const text = requiredString(table, field, fail);
316
+ if (text === undefined)
274
317
  return;
275
- return { ref: { ...vault, item }, publish, ...issue ? { issue } : {} };
318
+ const parsed = parseReference(text);
319
+ if (typeof parsed === "string") {
320
+ fail(`field "${field}" ${parsed}`);
321
+ return;
322
+ }
323
+ if (account === undefined) {
324
+ fail(`field "${field}" needs your 1Password account: add [1password] with account = "..."`);
325
+ return;
326
+ }
327
+ return { kind: "1password", account, ...parsed };
276
328
  }
277
329
  var ACCOUNT_ID = /^[0-9a-f]{32}$/;
278
- function validateIssue(raw, vault, item, fail) {
330
+ function validateIssue(raw, own, vaultAccount, fail) {
279
331
  if (!isRecord(raw)) {
280
332
  fail("must be a table");
281
333
  return;
@@ -288,17 +340,17 @@ function validateIssue(raw, vault, item, fail) {
288
340
  unknownFields(raw, ["provider", "account", "admin"], (field) => err(`unknown field "${field}"`));
289
341
  const provider = requiredString(raw, "provider", err);
290
342
  const account = requiredString(raw, "account", err);
291
- const admin = requiredString(raw, "admin", err);
343
+ const admin = reference(raw, "admin", vaultAccount, err);
292
344
  const kind = PROVIDER_KINDS.find((known) => known === provider);
293
345
  if (provider !== undefined && !kind)
294
346
  err(`field "provider" must be one of: ${PROVIDER_KINDS.join(", ")}`);
295
347
  if (account !== undefined && !ACCOUNT_ID.test(account))
296
348
  err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
297
- if (admin !== undefined && admin === item)
349
+ if (admin && sameItem(admin, own))
298
350
  err(`field "admin" names the key's own item; the admin token needs its own item`);
299
351
  if (failed || !kind || account === undefined || admin === undefined)
300
352
  return;
301
- return { provider: kind, account, admin: { ...vault, item: admin } };
353
+ return { provider: kind, account, admin };
302
354
  }
303
355
  function validateTarget(raw, fail) {
304
356
  if (!isRecord(raw)) {
@@ -317,6 +369,8 @@ function validateTarget(raw, fail) {
317
369
  unknownFields(raw, ["to", "account", "worker"], (field) => err(`unknown field "${field}" for ${to}`));
318
370
  const account = requiredString(raw, "account", err);
319
371
  const worker = requiredString(raw, "worker", err);
372
+ if (account !== undefined && !ACCOUNT_ID.test(account))
373
+ err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
320
374
  return failed || account === undefined || worker === undefined ? undefined : { to, account, worker };
321
375
  }
322
376
  if (to === "github-actions") {
@@ -442,14 +496,19 @@ function projectPath(project) {
442
496
  return project.replace(/(.)\/+$/, "$1");
443
497
  }
444
498
  // ../../packages/core/src/state.ts
445
- var STATE_VERSION = 2;
499
+ var STATE_VERSION = 3;
446
500
  var emptyState = () => ({ version: STATE_VERSION, receipts: [], operations: [] });
447
501
  async function loadState(files, path) {
448
- const data = await readVersionedJson(files, path, [1, STATE_VERSION], "state file");
502
+ const data = await readVersionedJson(files, path, [1, 2, STATE_VERSION], "state file");
449
503
  if (!data)
450
504
  return emptyState();
451
- const { operations } = data;
452
- const receipts = Array.isArray(data.receipts) ? data.receipts.map((r) => data.version === 1 && isRecord(r) ? { ...r, source: null } : r) : data.receipts;
505
+ const mapFile = (r) => data.version === STATE_VERSION ? r.mapFile : null;
506
+ const receipts = Array.isArray(data.receipts) ? data.receipts.map((r) => isRecord(r) ? {
507
+ ...r,
508
+ mapFile: mapFile(r),
509
+ source: data.version === 1 ? null : storedSource(r.source)
510
+ } : r) : data.receipts;
511
+ const operations = Array.isArray(data.operations) ? data.operations.map((o) => isRecord(o) ? { ...o, mapFile: mapFile(o) } : o) : data.operations;
453
512
  if (!Array.isArray(receipts) || !receipts.every(isReceipt)) {
454
513
  throw new Error(`${path}: the state file's "receipts" must be a list of receipts`);
455
514
  }
@@ -461,6 +520,9 @@ async function loadState(files, path) {
461
520
  async function saveState(files, path, state) {
462
521
  await writeJsonAtomic(files, path, state);
463
522
  }
523
+ function ownedBy(entry, owner) {
524
+ return entry.mapFile === owner.mapFile && entry.keyId === owner.keyId && entry.environment === owner.environment;
525
+ }
464
526
  function startOperation(state, operation) {
465
527
  if (state.operations.some((o) => o.id === operation.id))
466
528
  throw new Error(`operation ${operation.id} already exists`);
@@ -474,20 +536,26 @@ function recordReceipt(state, receipt, operationId) {
474
536
  function finishOperation(state, operationId) {
475
537
  return { ...state, operations: state.operations.filter((o) => o.id !== operationId) };
476
538
  }
477
- function unfinishedOperations(state, keyId, environment) {
478
- return state.operations.filter((o) => o.keyId === keyId && o.environment === environment);
539
+ function unfinishedOperations(state, owner) {
540
+ return state.operations.filter((o) => ownedBy(o, owner));
479
541
  }
480
542
  var isText = (value) => typeof value === "string";
543
+ var isTextOrNull = (value) => value === null || typeof value === "string";
481
544
  function isReceipt(r) {
482
- return isRecord(r) && [r.keyId, r.environment, r.destinationId, r.generation, r.at].every(isText) && isRecord(r.account) && isText(r.account.pinned) && isText(r.account.publisher) && isText(r.account.destinationAccount) && (r.source === null || isKeyRef(r.source)) && typeof r.evidence === "object" && r.evidence !== null;
545
+ return isRecord(r) && [r.keyId, r.environment, r.destinationId, r.generation, r.at].every(isText) && isTextOrNull(r.mapFile) && isRecord(r.account) && isText(r.account.pinned) && isText(r.account.publisher) && isText(r.account.destinationAccount) && (r.source === null || storedRefWithPasswordDefault(r.source) !== null) && typeof r.evidence === "object" && r.evidence !== null;
483
546
  }
484
- function isKeyRef(ref) {
485
- return isRecord(ref) && ref.kind === "1password" && [ref.account, ref.vault, ref.item].every(isText);
547
+ function storedSource(source) {
548
+ return source === null ? null : storedRefWithPasswordDefault(source) ?? source;
486
549
  }
487
550
  function isOperation(o) {
488
- return isRecord(o) && [o.id, o.keyId, o.environment, o.generation, o.startedAt].every(isText) && Array.isArray(o.planned) && o.planned.every(isText) && Array.isArray(o.done) && o.done.every(isText);
551
+ return isRecord(o) && [o.id, o.keyId, o.environment, o.generation, o.startedAt].every(isText) && isTextOrNull(o.mapFile) && Array.isArray(o.planned) && o.planned.every(isText) && Array.isArray(o.done) && o.done.every(isText);
489
552
  }
490
553
  // ../../packages/core/src/plan.ts
554
+ var ownerOf = ({ key, environment, mapFile }) => ({
555
+ keyId: key.name,
556
+ environment,
557
+ mapFile
558
+ });
491
559
  function approvalsFor(input) {
492
560
  return judge(input).flatMap(({ id, approval }) => approval ? [{ destinationId: id, ...approval }] : []);
493
561
  }
@@ -514,8 +582,8 @@ function planPublish(input) {
514
582
  approval: null
515
583
  };
516
584
  });
517
- const listed = new Set(steps.flatMap((s) => [secretKey(s.target, key.env), s.destinationId]));
518
- const removed = latestPerSecret(input.receipts).filter((r) => r.keyId === key.id && r.environment === environment).filter((r) => !listed.has(receiptSecretKey(r)) && !listed.has(r.destinationId)).map((r) => ({
585
+ const listed = new Set(steps.flatMap((s) => [secretKey(s.target, key.name), s.destinationId]));
586
+ const removed = latestPerSecret(input.receipts).filter((r) => ownedBy(r, ownerOf(input))).filter((r) => !listed.has(receiptSecretKey(r)) && !listed.has(r.destinationId)).map((r) => ({
519
587
  destinationId: r.destinationId,
520
588
  lastReceipt: {
521
589
  generation: r.generation,
@@ -524,7 +592,7 @@ function planPublish(input) {
524
592
  }
525
593
  }));
526
594
  return {
527
- keyId: key.id,
595
+ keyId: key.name,
528
596
  environment,
529
597
  generation,
530
598
  steps,
@@ -536,14 +604,15 @@ function judge(input) {
536
604
  const { key, environment } = input;
537
605
  const entry = key.environments[environment];
538
606
  if (!entry)
539
- throw new Error(`key "${key.id}" has no ${environment} entry in the map`);
607
+ throw new Error(`key "${key.name}" has no ${environment} entry in the map`);
540
608
  const newest = latestPerSecret(input.receipts);
541
609
  const latest = new Map(newest.map((r) => [receiptSecretKey(r), r]));
542
- const ours = newest.filter((r) => r.keyId === key.id && r.environment === environment);
543
- const published = input.receipts.some((r) => r.keyId === key.id && r.environment === environment);
610
+ const owner = ownerOf(input);
611
+ const ours = newest.filter((r) => ownedBy(r, owner));
612
+ const published = input.receipts.some((r) => ownedBy(r, owner));
544
613
  return entry.publish.map((target) => {
545
- const id = destinationId(target, key.env);
546
- const receipt = latest.get(secretKey(target, key.env)) ?? ours.find((r) => r.destinationId === id);
614
+ const id = destinationId(target, key.name);
615
+ const receipt = latest.get(secretKey(target, key.name)) ?? ours.find((r) => r.destinationId === id);
547
616
  const needs = (reason, approval) => ({
548
617
  id,
549
618
  target,
@@ -572,21 +641,22 @@ function latestPerSecret(receipts) {
572
641
  }
573
642
  return [...latest.values()];
574
643
  }
575
- function sameRef(a, b) {
576
- return a.kind === b.kind && a.account === b.account && a.vault === b.vault && a.item === b.item;
577
- }
578
644
  function describeRef(ref) {
579
- return `item "${ref.item}" (1Password account ${ref.account}, vault "${ref.vault}")`;
645
+ return `${formatReference(ref)} (1Password account ${ref.account})`;
580
646
  }
581
647
  // ../../packages/core/src/rotations.ts
582
- var ROTATIONS_VERSION = 1;
648
+ var ROTATIONS_VERSION = 2;
583
649
  var ROTATION_STAGES = ["issuing", "issued", "stored", "published", "revoked"];
584
650
  var emptyRotations = () => ({ version: ROTATIONS_VERSION, rotations: [] });
585
651
  async function loadRotations(files, path) {
586
- const data = await readVersionedJson(files, path, [ROTATIONS_VERSION], "rotations file");
652
+ const data = await readVersionedJson(files, path, [1, ROTATIONS_VERSION], "rotations file");
587
653
  if (!data)
588
654
  return emptyRotations();
589
- const { rotations } = data;
655
+ const rotations = Array.isArray(data.rotations) ? data.rotations.map((r) => isRecord(r) ? {
656
+ ...r,
657
+ mapFile: data.version === ROTATIONS_VERSION ? r.mapFile : null,
658
+ item: storedRefWithPasswordDefault(r.item) ?? r.item
659
+ } : r) : data.rotations;
590
660
  if (!Array.isArray(rotations) || !rotations.every(isRotation)) {
591
661
  throw new Error(`${path}: the rotations file's "rotations" must be a list of rotations`);
592
662
  }
@@ -595,11 +665,11 @@ async function loadRotations(files, path) {
595
665
  async function saveRotations(files, path, data) {
596
666
  await writeJsonAtomic(files, path, data);
597
667
  }
598
- function unfinishedRotation(data, keyId, environment, item) {
599
- return data.rotations.find((r) => r.keyId === keyId && r.environment === environment && sameRef(r.item, item) && r.stage !== "revoked");
668
+ function unfinishedRotation(data, owner, item) {
669
+ return data.rotations.find((r) => ownedBy(r, owner) && sameRef(r.item, item) && r.stage !== "revoked");
600
670
  }
601
- function rotateCommand(keyId, environment) {
602
- return `keypin rotate ${keyId}${environment === "prod" ? "" : ` --env ${environment}`}`;
671
+ function rotateCommand(keyId, environment, fallback) {
672
+ return `keypin rotate ${keyId}${envFlag(environment, fallback)}`;
603
673
  }
604
674
  function putRotation(data, rotation) {
605
675
  return {
@@ -611,12 +681,12 @@ function dropRotation(data, id) {
611
681
  return { ...data, rotations: data.rotations.filter((r) => r.id !== id) };
612
682
  }
613
683
  var isText2 = (value) => typeof value === "string";
614
- var isTextOrNull = (value) => value === null || typeof value === "string";
684
+ var isTextOrNull2 = (value) => value === null || typeof value === "string";
615
685
  function isTokenRecord(t) {
616
- return isRecord(t) && isText2(t.name) && [t.id, t.expiresOn, t.generation].every(isTextOrNull);
686
+ return isRecord(t) && isText2(t.name) && [t.id, t.expiresOn, t.generation].every(isTextOrNull2);
617
687
  }
618
688
  function isRotation(r) {
619
- return isRecord(r) && [r.id, r.keyId, r.environment, r.provider, r.account, r.startedAt, r.updatedAt].every(isText2) && ROTATION_STAGES.some((stage) => stage === r.stage) && isRecord(r.item) && r.item.kind === "1password" && [r.item.account, r.item.vault, r.item.item].every(isText2) && isTokenRecord(r.old) && isTokenRecord(r.new);
689
+ return isRecord(r) && [r.id, r.keyId, r.environment, r.provider, r.account, r.startedAt, r.updatedAt].every(isText2) && isTextOrNull2(r.mapFile) && ROTATION_STAGES.some((stage) => stage === r.stage) && storedRefWithPasswordDefault(r.item) !== null && isTokenRecord(r.old) && isTokenRecord(r.new);
620
690
  }
621
691
  // ../../packages/core/src/status.ts
622
692
  var NOTICES = ["due-soon", "authority-unknown", "rotation-unfinished"];
@@ -648,12 +718,13 @@ function buildStatus(input) {
648
718
  }
649
719
  const latest = new Map(latestPerSecret(input.receipts).map((r) => [receiptSecretKey(r), r]));
650
720
  for (const key of result.map.keys) {
651
- for (const environment of ENVIRONMENTS) {
721
+ for (const environment of result.map.environments) {
652
722
  const entry = key.environments[environment];
653
723
  if (!entry)
654
724
  continue;
655
- const where = { project, keyId: key.id, environment };
656
- const label = `${key.id} (${environment})`;
725
+ const where = { project, keyId: key.name, environment };
726
+ const owner = { keyId: key.name, environment, mapFile: result.map.file };
727
+ const label = `${key.name} (${environment})`;
657
728
  const add = (kind, message, extra = {}) => problems.push({
658
729
  kind,
659
730
  severity: NOTICES.includes(kind) ? "notice" : "problem",
@@ -662,15 +733,15 @@ function buildStatus(input) {
662
733
  message
663
734
  });
664
735
  const metadata = input.metadata(entry.ref);
665
- const rotateEvery = key.rotateEvery ?? metadata?.rotateEvery ?? null;
736
+ const rotateEvery = key.rotateEvery;
666
737
  const rotated = metadata?.rotated ?? null;
667
738
  const due = rotationDue({ label, metadata, rotated, rotateEvery, today: input.today, add });
668
739
  add("authority-unknown", `${label}: what this key grants is unknown, because keypin didn't create it`);
669
- const current = input.generation?.(key.id, environment);
740
+ const current = input.generation?.(key.name, environment);
670
741
  const destinations = entry.publish.map((target) => {
671
- const id = destinationId(target, key.env);
672
- const last = latest.get(secretKey(target, key.env));
673
- const ours = last && (last.keyId === key.id && last.environment === environment || last.source !== null && sameRef(last.source, entry.ref));
742
+ const id = destinationId(target, key.name);
743
+ const last = latest.get(secretKey(target, key.name));
744
+ const ours = last && (ownedBy(last, owner) || last.source !== null && sameRef(last.source, entry.ref));
674
745
  const receipt = ours ? last : undefined;
675
746
  if (!receipt) {
676
747
  add("missing-receipt", `${label}: no receipt for ${id}, so what it holds is unknown`, {
@@ -692,14 +763,12 @@ function buildStatus(input) {
692
763
  stale
693
764
  };
694
765
  });
695
- const rotation = unfinishedRotation({ version: 1, rotations: [...input.rotations ?? []] }, key.id, environment, entry.ref);
766
+ const rotation = unfinishedRotation({ version: ROTATIONS_VERSION, rotations: [...input.rotations ?? []] }, owner, entry.ref);
696
767
  if (rotation) {
697
- add("rotation-unfinished", `${label}: a rotation started ${rotation.startedAt} is at stage "${rotation.stage}"; run ${rotateCommand(key.id, environment)} to continue`);
768
+ add("rotation-unfinished", `${label}: a rotation started ${rotation.startedAt} is at stage "${rotation.stage}"; run ${rotateCommand(key.name, environment, publishEnvironment(result.map))} to continue`);
698
769
  }
699
770
  rows.push({
700
771
  ...where,
701
- env: key.env,
702
- owner: key.owner,
703
772
  ref: entry.ref,
704
773
  rotated,
705
774
  rotateEvery,
@@ -715,7 +784,7 @@ function buildStatus(input) {
715
784
  function rotationDue(input) {
716
785
  const { label, metadata, rotated, rotateEvery, today, add } = input;
717
786
  if (!metadata) {
718
- add("rotation-unreadable", `${label}: the vault's rotation fields couldn't be read, so whether it's due is unknown`);
787
+ add("rotation-unreadable", `${label}: the vault item's rotated date couldn't be read, so whether it's due is unknown`);
719
788
  return null;
720
789
  }
721
790
  if (!rotated || !isDay(rotated)) {
@@ -724,7 +793,7 @@ function rotationDue(input) {
724
793
  }
725
794
  const days = periodDays(rotateEvery);
726
795
  if (days === undefined) {
727
- add("bad-rotation-period", `${label}: rotate_every is ${rotateEvery ? `"${rotateEvery}"` : "missing"}; use <n>d, <n>w, <n>m or never`);
796
+ add("bad-rotation-period", rotateEvery ? `${label}: rotate_every is "${rotateEvery}"; use <n>d, <n>w, <n>m or never` : `${label}: keypin.toml has no rotate_every for this key; add one, such as "90d", or "never"`);
728
797
  return null;
729
798
  }
730
799
  if (days === null)
@@ -1035,7 +1104,7 @@ function buildDiscovery(input) {
1035
1104
  }
1036
1105
  }
1037
1106
  for (const key of input.map?.keys ?? []) {
1038
- add(key.env, { kind: "map", path: input.map?.file ?? "keypin.toml", keyId: key.id });
1107
+ add(key.name, { kind: "map", path: input.map?.file ?? "keypin.toml", keyId: key.name });
1039
1108
  }
1040
1109
  const cloudUnknown = unknowns.some((u) => u.cloud);
1041
1110
  const names = [...sources.entries()].map(([name, list]) => {
@@ -1060,12 +1129,16 @@ function workerLabel(worker) {
1060
1129
  }
1061
1130
  function draftMap(names, options) {
1062
1131
  const lines = [];
1063
- const taken = new Set(options.takenIds);
1064
- const vault = options.vault ?? {
1065
- name: "personal",
1066
- account: "<your 1Password account>",
1067
- vault: "<your vault>"
1068
- };
1132
+ const runName = runEnvironment(options);
1133
+ const publishName = publishEnvironment(options);
1134
+ const vault = options.map?.vault ?? "<your vault>";
1135
+ const project = options.project.replace(/[^A-Za-z0-9 ._-]/g, "-");
1136
+ const from = (environment, what) => str(formatReference({
1137
+ vault,
1138
+ item: `${project} ${environment} ${what}`,
1139
+ section: null,
1140
+ field: "password"
1141
+ }));
1069
1142
  for (const row of names) {
1070
1143
  if (row.mapped.length)
1071
1144
  continue;
@@ -1097,43 +1170,34 @@ function draftMap(names, options) {
1097
1170
  continue;
1098
1171
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(row.name))
1099
1172
  continue;
1100
- const id = freeId(keyIdFor(row.name), taken);
1101
- const what = row.name.toLowerCase().replaceAll("_", " ").trim();
1102
- lines.push("", `[keys.${id}]`, `env = ${str(row.name)}`, `owner = ${str(options.owner)}`);
1103
- if (local) {
1104
- lines.push("", `[keys.${id}.dev]`, `vault = ${str(vault.name)}`, `item = ${str(`${options.owner} dev ${what}`)}`);
1173
+ const name = row.name;
1174
+ const what = name.toLowerCase().replaceAll("_", " ").trim();
1175
+ lines.push("", `[keys.${name}]`, `rotate_every = "90d"`);
1176
+ if (local && !(publish.length && runName === publishName)) {
1177
+ lines.push(`${runName} = ${from(runName, what)}`);
1105
1178
  }
1106
1179
  if (publish.length) {
1107
- lines.push("", `[keys.${id}.prod]`, `vault = ${str(vault.name)}`, `item = ${str(`${options.owner} prod ${what}`)}`);
1108
- for (const target of publish)
1109
- lines.push("", `[[keys.${id}.prod.publish]]`, ...target);
1180
+ lines.push("", `[keys.${name}.${publishName}]`, `from = ${from(publishName, what)}`);
1181
+ for (const target of publish) {
1182
+ lines.push("", `[[keys.${name}.${publishName}.publish]]`, ...target);
1183
+ }
1110
1184
  }
1111
1185
  }
1112
1186
  if (!lines.length)
1113
1187
  return null;
1188
+ const account = options.map?.account ?? "<your 1Password account>";
1114
1189
  const header = [
1115
- "# Draft from keypin discover; nothing was written. Vault item names are placeholders.",
1116
- options.vault ? "# The vault is the one in this project's keypin.toml; copy only the [keys.*] tables." : "# Fill in the vault, then save this as keypin.toml.",
1190
+ "# Draft from keypin discover; nothing was written. The op:// references are placeholders.",
1191
+ !options.map?.account ? "# Fill in your account and vault, then save this as keypin.toml." : options.map.vault === null ? "# Fill in the vault, then copy only the [keys.*] tables into this project's keypin.toml." : "# The vault is the one this project's keypin.toml uses; copy only the [keys.*] tables.",
1192
+ ...options.environments.join() === DEFAULT_ENVIRONMENTS.join() ? [] : ["", `environments = [${options.environments.map(str).join(", ")}]`],
1117
1193
  "",
1118
- `[vaults.${/^[A-Za-z_][A-Za-z0-9_-]*$/.test(vault.name) ? vault.name : str(vault.name)}]`,
1119
- 'kind = "1password"',
1120
- `account = ${str(vault.account)}`,
1121
- `vault = ${str(vault.vault)}`
1194
+ "[1password]",
1195
+ `account = ${str(account)}`
1122
1196
  ];
1123
1197
  return `${[...header, ...lines].join(`
1124
1198
  `)}
1125
1199
  `;
1126
1200
  }
1127
- function keyIdFor(name) {
1128
- return name.toLowerCase().replaceAll("_", "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-") || "key";
1129
- }
1130
- function freeId(base, taken) {
1131
- let id = base;
1132
- for (let n = 2;taken.has(id); n++)
1133
- id = `${base}-${n}`;
1134
- taken.add(id);
1135
- return id;
1136
- }
1137
1201
  function str(value) {
1138
1202
  return JSON.stringify(value);
1139
1203
  }
@@ -1825,7 +1889,6 @@ var desktopConnect = async (account) => {
1825
1889
  // ../../packages/vault-1password/src/backend.ts
1826
1890
  var VALUE_FIELD = "password";
1827
1891
  var ROTATED = "rotated";
1828
- var ROTATE_EVERY = "rotate_every";
1829
1892
  var DAY2 = /^\d{4}-\d{2}-\d{2}$/;
1830
1893
  var UNIX_SECONDS = /^\d+$/;
1831
1894
  function onePasswordBackend(connect = desktopConnect) {
@@ -1842,7 +1905,7 @@ function onePasswordBackend(connect = desktopConnect) {
1842
1905
  return pending;
1843
1906
  }
1844
1907
  async function vaultId(sdk, scope) {
1845
- const matches = (await sdk.vaults.list()).filter((vault) => vault.title === scope.vault);
1908
+ const matches = named(await sdk.vaults.list(), scope.vault);
1846
1909
  const [match] = matches;
1847
1910
  if (!match) {
1848
1911
  throw new Error(`1Password account "${scope.account}" has no vault "${scope.vault}"`);
@@ -1853,7 +1916,7 @@ function onePasswordBackend(connect = desktopConnect) {
1853
1916
  return match.id;
1854
1917
  }
1855
1918
  async function find(sdk, id, ref) {
1856
- const matches = (await sdk.items.list(id)).filter((item) => item.title === ref.item);
1919
+ const matches = named(await sdk.items.list(id), ref.item);
1857
1920
  if (matches.length > 1)
1858
1921
  throw new Error(`${where(ref)}: ${matches.length} items have this name`);
1859
1922
  return matches[0] ?? null;
@@ -1870,10 +1933,7 @@ function onePasswordBackend(connect = desktopConnect) {
1870
1933
  capabilities: { read: true, write: true, list: true, metadata: true },
1871
1934
  async read(ref) {
1872
1935
  const item = await get(ref);
1873
- const field = valueField(item.fields);
1874
- if (!field)
1875
- throw new Error(`${where(ref)}: no "${VALUE_FIELD}" field`);
1876
- return new Secret(field.value);
1936
+ return new Secret(valueField(item, ref).value);
1877
1937
  },
1878
1938
  async write(ref, secret, options = {}) {
1879
1939
  const rotated = options.rotated;
@@ -1884,6 +1944,9 @@ function onePasswordBackend(connect = desktopConnect) {
1884
1944
  const id = await vaultId(sdk, ref);
1885
1945
  const found = await find(sdk, id, ref);
1886
1946
  if (!found) {
1947
+ if (ref.field !== VALUE_FIELD || ref.section !== null) {
1948
+ throw new Error(`${where(ref)}: no such item; create it in 1Password first`);
1949
+ }
1887
1950
  const fields = [passwordField(secret)];
1888
1951
  if (rotated)
1889
1952
  fields.push(rotatedField(rotated));
@@ -1897,11 +1960,8 @@ function onePasswordBackend(connect = desktopConnect) {
1897
1960
  }
1898
1961
  const item = await sdk.items.get(id, found.id);
1899
1962
  const fields = [...item.fields];
1900
- const value = valueField(fields);
1901
- if (value)
1902
- fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
1903
- else
1904
- fields.push(passwordField(secret));
1963
+ const value = valueField(item, ref);
1964
+ fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
1905
1965
  if (rotated) {
1906
1966
  const existing = fields.find((field) => field.title === ROTATED);
1907
1967
  if (existing)
@@ -1928,16 +1988,32 @@ function onePasswordBackend(connect = desktopConnect) {
1928
1988
  async metadata(ref) {
1929
1989
  const item = await get(ref);
1930
1990
  const rotated = plainField(item.fields, ROTATED, ref);
1931
- const rotateEvery = plainField(item.fields, ROTATE_EVERY, ref);
1932
- return { rotated: rotated === null ? null : toDay(rotated, ref), rotateEvery };
1991
+ return { rotated: rotated === null ? null : toDay(rotated, ref) };
1933
1992
  }
1934
1993
  };
1935
1994
  }
1936
1995
  function where(ref) {
1937
- return `1Password ${ref.account} / ${ref.vault} / ${ref.item}`;
1996
+ return `${formatReference(ref)} (1Password account ${ref.account})`;
1938
1997
  }
1939
- function valueField(fields) {
1940
- return fields.find((field) => field.id === VALUE_FIELD) ?? fields.find((field) => field.title === VALUE_FIELD);
1998
+ function named(candidates, name) {
1999
+ const wanted = name.toLowerCase();
2000
+ return candidates.filter((candidate) => candidate.id.toLowerCase() === wanted || candidate.title.toLowerCase() === wanted);
2001
+ }
2002
+ function valueField(item, ref) {
2003
+ const sections = ref.section === null ? [] : named(item.sections, ref.section);
2004
+ if (ref.section !== null && !sections.length) {
2005
+ throw new Error(`${where(ref)}: the item has no section "${ref.section}"`);
2006
+ }
2007
+ const [field, ...more] = named(item.fields.filter((field) => ref.section === null || sections.some((section) => section.id === field.sectionId)), ref.field);
2008
+ if (!field)
2009
+ throw new Error(`${where(ref)}: the item has no field "${ref.field}"`);
2010
+ if (more.length) {
2011
+ throw new Error(`${where(ref)}: ${more.length + 1} fields are named "${ref.field}"; name a section`);
2012
+ }
2013
+ if (field.title === ROTATED) {
2014
+ throw new Error(`${where(ref)}: "${ROTATED}" holds the day the value last changed; put the value in another field`);
2015
+ }
2016
+ return field;
1941
2017
  }
1942
2018
  function passwordField(secret) {
1943
2019
  return {
@@ -1975,7 +2051,6 @@ function messageOf2(error) {
1975
2051
  // src/commands/discover.ts
1976
2052
  import { basename, join as join3, relative, resolve } from "path";
1977
2053
  import { parseArgs } from "util";
1978
- var {TOML: TOML3 } = globalThis.Bun;
1979
2054
 
1980
2055
  // src/deps.ts
1981
2056
  class UsageError extends Error {
@@ -2004,6 +2079,12 @@ async function findMap(files, cwd) {
2004
2079
  }
2005
2080
  }
2006
2081
  }
2082
+ function pickEnvironment(map, requested, fallback) {
2083
+ if (requested === undefined || map.environments.includes(requested))
2084
+ return requested ?? fallback;
2085
+ const names = map.environments.map((name) => `"${name}"`).join(", ");
2086
+ throw new UsageError(`--env is one of ${names} in ${map.file}, got "${requested}"`);
2087
+ }
2007
2088
 
2008
2089
  // src/commands/discover.ts
2009
2090
  async function discover(args, deps) {
@@ -2098,12 +2179,11 @@ async function discover(args, deps) {
2098
2179
  });
2099
2180
  }
2100
2181
  const discovery = buildDiscovery({ envFiles, workflows, workers, github, map, unknowns });
2101
- const owner = map?.keys[0]?.owner ?? basename(folder);
2102
2182
  const draft = draftMap(discovery.names, {
2103
- owner,
2183
+ project: basename(folder),
2104
2184
  githubAccount: login,
2105
- vault: map && mapText !== null ? firstVault(mapText) : null,
2106
- takenIds: map?.keys.map((k) => k.id) ?? []
2185
+ map: map ? { account: map.account, vault: firstVault(map) } : null,
2186
+ environments: map?.environments ?? DEFAULT_ENVIRONMENTS
2107
2187
  });
2108
2188
  if (draft !== null) {
2109
2189
  const check = parseMap(draft, "draft");
@@ -2204,22 +2284,9 @@ async function githubOrigin(deps, folder) {
2204
2284
  return { reason: "the origin remote isn't on github.com" };
2205
2285
  return { repo: `${match[1]}/${match[2]}`, owner: match[1] };
2206
2286
  }
2207
- function firstVault(text) {
2208
- let data;
2209
- try {
2210
- data = TOML3.parse(text);
2211
- } catch {
2212
- return null;
2213
- }
2214
- const vaults = isRecord(data) && isRecord(data.vaults) ? data.vaults : {};
2215
- for (const [name, raw] of Object.entries(vaults)) {
2216
- if (!isRecord(raw))
2217
- continue;
2218
- const { account, vault } = raw;
2219
- if (typeof account === "string" && typeof vault === "string")
2220
- return { name, account, vault };
2221
- }
2222
- return null;
2287
+ function firstVault(map) {
2288
+ const [entry] = map.keys.flatMap((key) => Object.values(key.environments).filter((e) => e));
2289
+ return entry?.ref.vault ?? null;
2223
2290
  }
2224
2291
  var WHERE = {
2225
2292
  both: "local and cloud",
@@ -2350,34 +2417,25 @@ function rotationsPath(deps) {
2350
2417
  var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
2351
2418
  # Uncomment and edit. Every field is checked; an unknown one is an error.
2352
2419
  #
2353
- # A vault the keys below read from. The name ("personal") is yours to choose.
2354
- # [vaults.personal]
2355
- # kind = "1password"
2420
+ # The 1Password account the keys below read from: its sign-in address or account ID.
2421
+ # [1password]
2356
2422
  # account = "my.1password.com"
2357
- # vault = "Private"
2358
2423
  #
2359
- # A key. Its ID ("example-api-key") stays the same when vault items are renamed.
2360
- # [keys.example-api-key]
2361
- # env = "EXAMPLE_API_KEY" # the variable your program reads
2362
- # owner = "my-project"
2363
- # rotate_every = "180d" # <n>d, <n>w, <n>m or never; leave out to use the vault item's rotate_every
2424
+ # A key, named after the variable your program reads.
2425
+ # [keys.EXAMPLE_API_KEY]
2426
+ # rotate_every = "180d" # <n>d, <n>w, <n>m or never
2427
+ # dev = "op://Private/my-project dev example api key/password" # what keypin run reads
2364
2428
  #
2365
- # Where keypin run reads the value from.
2366
- # [keys.example-api-key.dev]
2367
- # vault = "personal"
2368
- # item = "my-project dev example api key"
2429
+ # What keypin publish reads, and every place it writes it.
2430
+ # [keys.EXAMPLE_API_KEY.prod]
2431
+ # from = "op://Private/my-project prod example api key/password"
2369
2432
  #
2370
- # Where keypin publish reads it from, and every place it writes it.
2371
- # [keys.example-api-key.prod]
2372
- # vault = "personal"
2373
- # item = "my-project prod example api key"
2374
- #
2375
- # [[keys.example-api-key.prod.publish]]
2433
+ # [[keys.EXAMPLE_API_KEY.prod.publish]]
2376
2434
  # to = "cloudflare-worker"
2377
2435
  # account = "<cloudflare account ID>"
2378
2436
  # worker = "my-worker"
2379
2437
  #
2380
- # [[keys.example-api-key.prod.publish]]
2438
+ # [[keys.EXAMPLE_API_KEY.prod.publish]]
2381
2439
  # to = "github-actions"
2382
2440
  # repo = "owner/repo"
2383
2441
  `;
@@ -2406,7 +2464,7 @@ async function init(args, deps) {
2406
2464
  import { parseArgs as parseArgs3 } from "util";
2407
2465
 
2408
2466
  // src/publishing.ts
2409
- var NEEDS_APPROVAL = 2;
2467
+ var NEEDS_APPROVAL = 3;
2410
2468
  async function locked(deps, body) {
2411
2469
  const path = statePath(deps);
2412
2470
  const lockFile = `${path}.lock`;
@@ -2437,11 +2495,11 @@ Account checks:`);
2437
2495
  const checked = new Map;
2438
2496
  let failed = false;
2439
2497
  for (const target of entry.publish) {
2440
- const label = describeTarget(target, key.env);
2498
+ const label = describeTarget(target, key.name);
2441
2499
  try {
2442
2500
  const destination = deps.destination(target);
2443
2501
  const check = await destination.checkAccount();
2444
- checked.set(destinationId(target, key.env), { target, destination, check });
2502
+ checked.set(destinationId(target, key.name), { target, destination, check });
2445
2503
  say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
2446
2504
  if (!check.ok)
2447
2505
  failed = true;
@@ -2463,24 +2521,26 @@ function writesFor(steps, checked) {
2463
2521
  });
2464
2522
  }
2465
2523
  async function writeAll(input) {
2466
- const { key, environment, entry, secret, generation, writes, path, deps, say } = input;
2524
+ const { key, environment, mapFile, entry, secret, generation, writes, path, deps, say } = input;
2467
2525
  const id = crypto.randomUUID();
2468
2526
  let state = startOperation(input.state, {
2469
2527
  id,
2470
- keyId: key.id,
2528
+ keyId: key.name,
2471
2529
  environment,
2530
+ mapFile,
2472
2531
  generation,
2473
2532
  startedAt: deps.now().toISOString(),
2474
2533
  planned: writes.map((w) => w.destinationId)
2475
2534
  });
2476
2535
  await saveState(deps.files, path, state);
2477
2536
  for (const { destinationId: written, found } of writes) {
2478
- const label = describeTarget(found.target, key.env);
2537
+ const label = describeTarget(found.target, key.name);
2479
2538
  try {
2480
- const evidence = await found.destination.write(key.env, secret);
2539
+ const evidence = await found.destination.write(key.name, secret);
2481
2540
  state = recordReceipt(state, {
2482
- keyId: key.id,
2541
+ keyId: key.name,
2483
2542
  environment,
2543
+ mapFile,
2484
2544
  source: entry.ref,
2485
2545
  destinationId: written,
2486
2546
  generation,
@@ -2499,12 +2559,12 @@ async function writeAll(input) {
2499
2559
  return { ok: false, state };
2500
2560
  }
2501
2561
  }
2502
- state = finishAll(state, key.id, environment);
2562
+ state = finishAll(state, { keyId: key.name, environment, mapFile });
2503
2563
  await saveState(deps.files, path, state);
2504
2564
  return { ok: true, state };
2505
2565
  }
2506
- function finishAll(state, keyId, environment) {
2507
- return unfinishedOperations(state, keyId, environment).reduce((s, op) => finishOperation(s, op.id), state);
2566
+ function finishAll(state, owner) {
2567
+ return unfinishedOperations(state, owner).reduce((s, op) => finishOperation(s, op.id), state);
2508
2568
  }
2509
2569
  function rerun(deps, command, args) {
2510
2570
  const words = [...deps.self, command, ...args].map(shellWord).join(" ");
@@ -2525,12 +2585,11 @@ function describeTarget(target, secretName) {
2525
2585
  function announce(stderr, what, refs) {
2526
2586
  const groups = new Map;
2527
2587
  for (const ref of refs) {
2528
- const where = `1Password account ${ref.account}, vault "${ref.vault}"`;
2529
- groups.set(where, (groups.get(where) ?? new Set).add(ref.item));
2588
+ const where = `1Password account ${ref.account}`;
2589
+ groups.set(where, (groups.get(where) ?? new Set).add(formatReference(ref)));
2530
2590
  }
2531
- for (const [where, items] of groups) {
2532
- const names = [...items].map((item) => `"${item}"`).join(", ");
2533
- stderr.write(`keypin: reading ${what} from ${where}: ${names}
2591
+ for (const [where, references] of groups) {
2592
+ stderr.write(`keypin: reading ${what} from ${where}: ${[...references].join(", ")}
2534
2593
  `);
2535
2594
  }
2536
2595
  }
@@ -2541,35 +2600,33 @@ function distinctRefs(refs) {
2541
2600
  seen.set(refKey(ref), ref);
2542
2601
  return [...seen.values()];
2543
2602
  }
2544
- var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item]);
2603
+ var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item, ref.section, ref.field]);
2545
2604
 
2546
2605
  // src/commands/publish.ts
2547
2606
  async function publish(args, deps) {
2548
- const request = parseRequest(args);
2607
+ const { keyId, env, yes } = parseRequest(args);
2549
2608
  const map = await findMap(deps.files, deps.cwd);
2550
- return locked(deps, (path) => publishLocked({ ...request, args }, map, path, deps));
2609
+ const environment = pickEnvironment(map, env, publishEnvironment(map));
2610
+ const request = { keyId, environment, yes, args };
2611
+ return locked(deps, (path) => publishLocked(request, map, path, deps));
2551
2612
  }
2552
2613
  function parseRequest(args) {
2553
2614
  const { values, positionals } = parseArgs3({
2554
2615
  args,
2555
2616
  options: {
2556
- env: { type: "string", default: "prod" },
2617
+ env: { type: "string" },
2557
2618
  yes: { type: "boolean", default: false }
2558
2619
  },
2559
2620
  allowPositionals: true
2560
2621
  });
2561
2622
  const [keyId, ...extra] = positionals;
2562
2623
  if (keyId === undefined || extra.length)
2563
- throw new UsageError("keypin publish takes one key ID");
2564
- const environment = ENVIRONMENTS.find((name) => name === values.env);
2565
- if (!environment) {
2566
- throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
2567
- }
2568
- return { keyId, environment, yes: values.yes };
2624
+ throw new UsageError("keypin publish takes one key: the variable name");
2625
+ return { keyId, env: values.env, yes: values.yes };
2569
2626
  }
2570
2627
  async function publishLocked(request, map, path, deps) {
2571
2628
  const { keyId, environment } = request;
2572
- const key = map.keys.find((k) => k.id === keyId);
2629
+ const key = map.keys.find((k) => k.name === keyId);
2573
2630
  if (!key)
2574
2631
  throw new Error(`${map.file} has no key "${keyId}"`);
2575
2632
  const entry = key.environments[environment];
@@ -2577,16 +2634,17 @@ async function publishLocked(request, map, path, deps) {
2577
2634
  throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
2578
2635
  const say = (text) => deps.stderr.write(`${text}
2579
2636
  `);
2580
- say(`Publishing ${keyId} (${environment}) as ${key.env}, from item "${entry.ref.item}"`);
2581
- say(` vault: 1Password account ${entry.ref.account}, vault "${entry.ref.vault}"`);
2637
+ say(`Publishing ${keyId} (${environment}) from ${formatReference(entry.ref)}`);
2638
+ say(` 1Password account: ${entry.ref.account}`);
2582
2639
  for (const target of entry.publish)
2583
- say(` to: ${describeTarget(target, key.env)}`);
2640
+ say(` to: ${describeTarget(target, key.name)}`);
2584
2641
  if (!entry.publish.length) {
2585
2642
  say(`The map lists no destinations for ${keyId} (${environment}); nothing to publish.`);
2586
2643
  return 1;
2587
2644
  }
2588
2645
  const state = await loadState(deps.files, path);
2589
- for (const op of unfinishedOperations(state, keyId, environment)) {
2646
+ const owner = { keyId, environment, mapFile: map.file };
2647
+ for (const op of unfinishedOperations(state, owner)) {
2590
2648
  say(`An earlier publish (started ${op.startedAt}, generation ${op.generation}) didn't finish: wrote ${op.done.length} of ${op.planned.length} (${op.done.join(", ") || "none"}). This run plans again from the receipts.`);
2591
2649
  }
2592
2650
  const checked = await checkAccounts(key, entry, deps, say);
@@ -2594,7 +2652,12 @@ async function publishLocked(request, map, path, deps) {
2594
2652
  say("Stopped: an account check failed. Nothing was read and nothing was written.");
2595
2653
  return 1;
2596
2654
  }
2597
- const approvals = approvalsFor({ key, environment, receipts: state.receipts });
2655
+ const approvals = approvalsFor({
2656
+ key,
2657
+ environment,
2658
+ mapFile: map.file,
2659
+ receipts: state.receipts
2660
+ });
2598
2661
  if (approvals.length && !deps.isTerminal) {
2599
2662
  say(`
2600
2663
  Needs approval:`);
@@ -2609,17 +2672,23 @@ Needs approval:`);
2609
2672
  try {
2610
2673
  secret = await deps.vault().read(entry.ref);
2611
2674
  } catch (error) {
2612
- say(`Stopped: couldn't read ${keyId} (item "${entry.ref.item}"): ${messageOf(error)}`);
2675
+ say(`Stopped: couldn't read ${keyId} (${formatReference(entry.ref)}): ${messageOf(error)}`);
2613
2676
  return 1;
2614
2677
  }
2615
2678
  const generation = await generationOf(secret);
2616
- const plan = planPublish({ key, environment, receipts: state.receipts, generation });
2679
+ const plan = planPublish({
2680
+ key,
2681
+ environment,
2682
+ mapFile: map.file,
2683
+ receipts: state.receipts,
2684
+ generation
2685
+ });
2617
2686
  say(`
2618
2687
  Plan for generation ${generation}:`);
2619
2688
  const writes = writesFor(plan.steps, checked);
2620
2689
  for (const step of plan.steps) {
2621
2690
  const found = checked.get(step.destinationId);
2622
- say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
2691
+ say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
2623
2692
  if (found)
2624
2693
  say(` ${accountFacts(found.check)}`);
2625
2694
  if (step.approval)
@@ -2630,8 +2699,8 @@ Plan for generation ${generation}:`);
2630
2699
  }
2631
2700
  if (!writes.length) {
2632
2701
  say("Nothing to write: every destination already has this generation.");
2633
- if (unfinishedOperations(state, keyId, environment).length) {
2634
- await saveState(deps.files, path, finishAll(state, keyId, environment));
2702
+ if (unfinishedOperations(state, owner).length) {
2703
+ await saveState(deps.files, path, finishAll(state, owner));
2635
2704
  }
2636
2705
  return 0;
2637
2706
  }
@@ -2640,6 +2709,7 @@ Plan for generation ${generation}:`);
2640
2709
  const written = await writeAll({
2641
2710
  key,
2642
2711
  environment,
2712
+ mapFile: map.file,
2643
2713
  entry,
2644
2714
  secret,
2645
2715
  generation,
@@ -2674,26 +2744,24 @@ async function confirmed(deps, needsApproval, request) {
2674
2744
  }
2675
2745
 
2676
2746
  // src/commands/rotate.ts
2747
+ import { join as join6 } from "path";
2677
2748
  import { parseArgs as parseArgs4 } from "util";
2678
2749
  var GRACE_DAYS = DUE_SOON_DAYS;
2679
2750
  async function rotate(args, deps) {
2680
2751
  const { values, positionals } = parseArgs4({
2681
2752
  args,
2682
2753
  options: {
2683
- env: { type: "string", default: "prod" },
2754
+ env: { type: "string" },
2684
2755
  yes: { type: "boolean", default: false }
2685
2756
  },
2686
2757
  allowPositionals: true
2687
2758
  });
2688
2759
  const [keyId, ...extra] = positionals;
2689
2760
  if (keyId === undefined || extra.length)
2690
- throw new UsageError("keypin rotate takes one key ID");
2691
- const environment = ENVIRONMENTS.find((name) => name === values.env);
2692
- if (!environment) {
2693
- throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
2694
- }
2761
+ throw new UsageError("keypin rotate takes one key: the variable name");
2695
2762
  const map = await findMap(deps.files, deps.cwd);
2696
- const key = map.keys.find((k) => k.id === keyId);
2763
+ const environment = pickEnvironment(map, values.env, publishEnvironment(map));
2764
+ const key = map.keys.find((k) => k.name === keyId);
2697
2765
  if (!key)
2698
2766
  throw new Error(`${map.file} has no key "${keyId}"`);
2699
2767
  const entry = key.environments[environment];
@@ -2707,6 +2775,7 @@ async function rotate(args, deps) {
2707
2775
  `);
2708
2776
  return locked(deps, async (statePath) => {
2709
2777
  const run = {
2778
+ map,
2710
2779
  key,
2711
2780
  entry,
2712
2781
  issue,
@@ -2719,10 +2788,10 @@ async function rotate(args, deps) {
2719
2788
  say
2720
2789
  };
2721
2790
  const data = await loadRotations(deps.files, run.rotationsPath);
2722
- const open = unfinishedRotation(data, key.id, environment, entry.ref);
2791
+ const open = unfinishedRotation(data, keyOwner(run), entry.ref);
2723
2792
  if (!open)
2724
2793
  return start(run, data);
2725
- say(`An unfinished rotation of ${key.id} (${environment}), started ${open.startedAt}, is at stage "${open.stage}".`);
2794
+ say(`An unfinished rotation of ${key.name} (${environment}), started ${open.startedAt}, is at stage "${open.stage}".`);
2726
2795
  if (open.provider !== issue.provider || open.account !== issue.account) {
2727
2796
  say(`Stopped: that rotation made its token as ${open.provider} in account ${open.account}, and the map now says ${issue.provider} in account ${issue.account}. Put the map back to finish it. Nothing was changed.`);
2728
2797
  return 1;
@@ -2742,13 +2811,19 @@ async function rotate(args, deps) {
2742
2811
  }
2743
2812
  async function start(run, data) {
2744
2813
  const { key, entry, issue, environment, deps, say } = run;
2745
- say(`Rotating ${key.id} (${environment}) as ${key.env}, item "${entry.ref.item}"`);
2746
- say(` vault: 1Password account ${entry.ref.account}, vault "${entry.ref.vault}"`);
2747
- say(` new token: ${issue.provider} in account ${issue.account}, made with the admin token in item "${issue.admin.item}"`);
2814
+ say(`Rotating ${key.name} (${environment}) from ${formatReference(entry.ref)}`);
2815
+ say(` 1Password account: ${entry.ref.account}`);
2816
+ say(` new token: ${issue.provider} in account ${issue.account}, made with the admin token in ${formatReference(issue.admin)}`);
2748
2817
  for (const target of entry.publish)
2749
- say(` to: ${describeTarget(target, key.env)}`);
2818
+ say(` to: ${describeTarget(target, key.name)}`);
2750
2819
  if (!entry.publish.length) {
2751
- say(`Stopped: the map lists no destinations for ${key.id} (${environment}), so nothing would get the new token. Nothing was changed.`);
2820
+ say(`Stopped: the map lists no destinations for ${key.name} (${environment}), so nothing would get the new token. Nothing was changed.`);
2821
+ return 1;
2822
+ }
2823
+ const every = key.rotateEvery;
2824
+ const days = periodDays(every);
2825
+ if (!days) {
2826
+ say(`Stopped: rotate needs a rotation period to set the new token's expiry, and ${every ? `rotate_every is "${every}"` : "keypin.toml has no rotate_every for this key"}. Nothing was changed.`);
2752
2827
  return 1;
2753
2828
  }
2754
2829
  const state = await loadState(deps.files, run.statePath);
@@ -2757,7 +2832,7 @@ async function start(run, data) {
2757
2832
  say("Stopped: an account check failed. Nothing was read and nothing was changed.");
2758
2833
  return 1;
2759
2834
  }
2760
- const approvals = approvalsFor({ key, environment, receipts: state.receipts });
2835
+ const approvals = approvalsFor({ ...planFor(run), receipts: state.receipts });
2761
2836
  if (!deps.isTerminal && (approvals.length || !run.yes)) {
2762
2837
  for (const approval of approvals)
2763
2838
  say(` needs approval: ${approval.approval}`);
@@ -2765,25 +2840,19 @@ async function start(run, data) {
2765
2840
  say(rerun(deps, "rotate", run.args));
2766
2841
  return NEEDS_APPROVAL;
2767
2842
  }
2768
- announce(deps.stderr, "the current value, its rotation fields and the admin token", [
2769
- entry.ref,
2770
- issue.admin
2771
- ]);
2843
+ announce(deps.stderr, "the current value and the admin token", [entry.ref, issue.admin]);
2772
2844
  const vault = deps.vault();
2773
2845
  let current;
2774
2846
  let admin;
2775
- let every;
2776
2847
  try {
2777
2848
  current = await vault.read(entry.ref);
2778
- every = key.rotateEvery ?? (await vault.metadata(entry.ref)).rotateEvery;
2779
2849
  admin = await vault.read(issue.admin);
2780
2850
  } catch (error) {
2781
2851
  say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
2782
2852
  return 1;
2783
2853
  }
2784
- const days = periodDays(every);
2785
- if (!days) {
2786
- say(`Stopped: rotate needs a rotation period to set the new token's expiry, and rotate_every is ${every ? `"${every}"` : "missing"}. Nothing was changed.`);
2854
+ if (current.reveal() === admin.reveal()) {
2855
+ say(`Stopped: ${formatReference(issue.admin)} holds the same value as ${formatReference(entry.ref)}. The admin token needs its own field, or rotating would overwrite it. Nothing was changed.`);
2787
2856
  return 1;
2788
2857
  }
2789
2858
  const provider = deps.provider(issue, admin);
@@ -2806,10 +2875,10 @@ Plan:`);
2806
2875
  say(` new token: "${name}", expires ${expiresOn} (rotate_every ${every} plus ${GRACE_DAYS} days' grace)`);
2807
2876
  for (const line of describeAccess(old))
2808
2877
  say(` ${line}`);
2809
- say(` store in: item "${entry.ref.item}", with rotated ${today}`);
2878
+ say(` store in: ${formatReference(entry.ref)}, with rotated ${today}`);
2810
2879
  for (const target of entry.publish) {
2811
- const found = checked.get(destinationId(target, key.env));
2812
- say(` publish to: ${describeTarget(target, key.env)}`);
2880
+ const found = checked.get(destinationId(target, key.name));
2881
+ say(` publish to: ${describeTarget(target, key.name)}`);
2813
2882
  if (found)
2814
2883
  say(` ${accountFacts(found.check)}`);
2815
2884
  }
@@ -2821,8 +2890,9 @@ Plan:`);
2821
2890
  const now = deps.now().toISOString();
2822
2891
  let rotation = {
2823
2892
  id: crypto.randomUUID(),
2824
- keyId: key.id,
2893
+ keyId: key.name,
2825
2894
  environment,
2895
+ mapFile: run.map.file,
2826
2896
  item: entry.ref,
2827
2897
  provider: issue.provider,
2828
2898
  account: issue.account,
@@ -2837,7 +2907,7 @@ Plan:`);
2837
2907
  },
2838
2908
  new: { id: null, name, expiresOn, generation: null }
2839
2909
  };
2840
- data = putRotation(withoutFinished(data, key.id, environment), rotation);
2910
+ data = putRotation(withoutFinished(data, keyOwner(run)), rotation);
2841
2911
  await saveRotations(deps.files, run.rotationsPath, data);
2842
2912
  const made = await provider.issue({ name, like: old, expiresOn });
2843
2913
  if ("refused" in made) {
@@ -2862,7 +2932,7 @@ Plan:`);
2862
2932
  return deleteUnchecked(run, data, rotation, provider);
2863
2933
  }
2864
2934
  say(` checked: ${made.token.id} is active and has the same policies as ${old.id}`);
2865
- say(`keypin: writing the new value to item "${entry.ref.item}", with rotated ${today}`);
2935
+ say(`keypin: writing the new value to ${formatReference(entry.ref)}, with rotated ${today}`);
2866
2936
  try {
2867
2937
  await vault.write(entry.ref, made.value, { rotated: today });
2868
2938
  const stored = await generationOf(await vault.read(entry.ref));
@@ -2895,7 +2965,7 @@ async function publishNew(run, data, rotation, fresh) {
2895
2965
  return 1;
2896
2966
  }
2897
2967
  checked = found;
2898
- if (!deps.isTerminal && approvalsFor({ key, environment, receipts: state.receipts }).length) {
2968
+ if (!deps.isTerminal && approvalsFor({ ...planFor(run), receipts: state.receipts }).length) {
2899
2969
  say("Stopped before reading the value: publishing needs approval, and --yes can't give it.");
2900
2970
  say(rerun(deps, "rotate", run.args));
2901
2971
  return NEEDS_APPROVAL;
@@ -2907,7 +2977,7 @@ async function publishNew(run, data, rotation, fresh) {
2907
2977
  value = await deps.vault().read(entry.ref);
2908
2978
  const generation = await generationOf(value);
2909
2979
  if (generation !== rotation.new.generation) {
2910
- say(`Stopped: item "${entry.ref.item}" holds generation ${generation}, not the rotation's ${rotation.new.generation}. Something else changed it. Nothing was written.`);
2980
+ say(`Stopped: ${formatReference(entry.ref)} holds generation ${generation}, not the rotation's ${rotation.new.generation}. Something else changed it. Nothing was written.`);
2911
2981
  return 1;
2912
2982
  }
2913
2983
  const problem = await recheck(run, rotation, value);
@@ -2918,11 +2988,11 @@ async function publishNew(run, data, rotation, fresh) {
2918
2988
  say(` checked: ${rotation.new.id} is active and has the same policies as ${rotation.old.id}`);
2919
2989
  }
2920
2990
  const generation = rotation.new.generation ?? await generationOf(value);
2921
- const plan = planPublish({ key, environment, receipts: state.receipts, generation });
2991
+ const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
2922
2992
  say(`
2923
2993
  Publishing generation ${generation}:`);
2924
2994
  for (const step of plan.steps) {
2925
- say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
2995
+ say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
2926
2996
  if (step.approval)
2927
2997
  say(` needs approval: ${step.approval}`);
2928
2998
  }
@@ -2933,6 +3003,7 @@ Publishing generation ${generation}:`);
2933
3003
  const written = await writeAll({
2934
3004
  key,
2935
3005
  environment,
3006
+ mapFile: run.map.file,
2936
3007
  entry,
2937
3008
  secret: value,
2938
3009
  generation,
@@ -2956,9 +3027,7 @@ Publishing generation ${generation}:`);
2956
3027
  Published. The old token ${rotation.old.id} "${rotation.old.name}" is still active.`);
2957
3028
  say("Next, check that every consumer works with the new value:");
2958
3029
  for (const target of entry.publish)
2959
- say(` ${describeTarget(target, key.env)}`);
2960
- for (const consumer of key.consumers)
2961
- say(` ${consumer.name} (${consumer.kind})`);
3030
+ say(` ${describeTarget(target, key.name)}`);
2962
3031
  say(`Then run ${again(run)} again to revoke the old token.`);
2963
3032
  return 0;
2964
3033
  }
@@ -2969,26 +3038,44 @@ async function revokeOld(run, data, rotation) {
2969
3038
  throw new Error(`rotation ${rotation.id} has no new generation or token IDs`);
2970
3039
  }
2971
3040
  const state = await loadState(deps.files, run.statePath);
2972
- const plan = planPublish({ key, environment, receipts: state.receipts, generation });
3041
+ const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
2973
3042
  const behind = plan.steps.filter((step) => step.action === "write");
2974
3043
  for (const step of behind) {
2975
3044
  say(` ${step.destinationId} doesn't have generation ${generation}: ${step.reason}`);
2976
3045
  }
2977
3046
  const retired = plan.removed.filter((removed) => removed.lastReceipt.generation === rotation.old.generation);
2978
3047
  if (behind.length) {
2979
- say(`Stopped: run keypin publish ${key.id}${environment === "prod" ? "" : ` --env ${environment}`} first. Nothing was revoked.`);
3048
+ say(`Stopped: run keypin publish ${key.name}${envFlag(environment, publishEnvironment(run.map))} first. Nothing was revoked.`);
2980
3049
  return 1;
2981
3050
  }
2982
- say(`Every destination's receipt has generation ${generation}.`);
3051
+ say(`Every destination of ${key.name} (${environment}) has generation ${generation}.`);
2983
3052
  for (const removed of retired) {
2984
3053
  say(` ${removed.destinationId} left the map and its receipt has the old token (generation ${removed.lastReceipt.generation}); revoking breaks it unless that secret is gone`);
2985
3054
  }
3055
+ const others = await otherHolders(run, state.receipts, rotation.old.generation, retired);
3056
+ if (others === null)
3057
+ return 1;
3058
+ if (others.length) {
3059
+ say(`Stopped: these destinations still have the old token. Put the new value in each one's vault item, then run its keypin publish. Nothing was revoked.`);
3060
+ for (const { receipt, owner } of others) {
3061
+ say(` ${describeHolder(receipt)}: ${publishCommand(owner)}`);
3062
+ }
3063
+ return 1;
3064
+ }
2986
3065
  if (!deps.isTerminal) {
2987
3066
  say("Stopped: revoking needs yes typed in a terminal, and --yes can't give it. Nothing was revoked.");
2988
3067
  say(rerun(deps, "rotate", run.args));
2989
3068
  return NEEDS_APPROVAL;
2990
3069
  }
2991
- announce(deps.stderr, "the admin token", [issue.admin]);
3070
+ announce(deps.stderr, "the current value, to check it's the new token, and the admin token", [
3071
+ run.entry.ref,
3072
+ issue.admin
3073
+ ]);
3074
+ const holds = await generationOf(await deps.vault().read(run.entry.ref));
3075
+ if (holds !== generation) {
3076
+ say(`Stopped: ${formatReference(run.entry.ref)} holds generation ${holds}, not the new ${generation}. Something else changed it, and revoking would leave it with a dead token. Nothing was revoked.`);
3077
+ return 1;
3078
+ }
2992
3079
  const provider = deps.provider(issue, await deps.vault().read(issue.admin));
2993
3080
  const current = await provider.details(rotation.new.id);
2994
3081
  if (current?.status !== "active") {
@@ -3015,7 +3102,7 @@ Old token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "n
3015
3102
  async function finish(run, data, rotation) {
3016
3103
  const done = { ...rotation, stage: "revoked", updatedAt: run.deps.now().toISOString() };
3017
3104
  await saveRotations(run.deps.files, run.rotationsPath, putRotation(data, done));
3018
- run.say(`Rotated ${run.key.id} (${run.environment}): ${rotation.new.id} replaced ${rotation.old.id}.`);
3105
+ run.say(`Rotated ${run.key.name} (${run.environment}): ${rotation.new.id} replaced ${rotation.old.id}.`);
3019
3106
  return 0;
3020
3107
  }
3021
3108
  async function abandon(run, data, rotation) {
@@ -3031,11 +3118,26 @@ async function abandon(run, data, rotation) {
3031
3118
  };
3032
3119
  const next = putRotation(data, stored);
3033
3120
  await saveRotations(deps.files, run.rotationsPath, next);
3034
- say(`Item "${entry.ref.item}" already holds the new value (generation ${holds}).`);
3121
+ say(`${formatReference(entry.ref)} already holds the new value (generation ${holds}).`);
3035
3122
  return publishNew(run, next, stored, null);
3036
3123
  }
3037
3124
  if (holds !== rotation.old.generation) {
3038
- say(`Stopped: item "${entry.ref.item}" holds generation ${holds}, neither the old ${rotation.old.generation} nor the new ${rotation.new.generation}. Something else changed it. Nothing was changed.`);
3125
+ say(`Stopped: ${formatReference(entry.ref)} holds generation ${holds}, neither the old ${rotation.old.generation} nor the new ${rotation.new.generation}. Something else changed it. Nothing was changed.`);
3126
+ return 1;
3127
+ }
3128
+ }
3129
+ if (rotation.new.generation) {
3130
+ const state = await loadState(deps.files, run.statePath);
3131
+ const holders = holdersOf(state.receipts, rotation.new.generation);
3132
+ if (holders.length) {
3133
+ say(`Stopped: the new token ${rotation.new.id} was published, so keypin won't delete it. Nothing was changed. Either put the new value back in ${formatReference(entry.ref)} and run ${again(run)} again to finish, or publish the old value to each destination that has the new one:`);
3134
+ const owners = await listedOwners(run);
3135
+ if (owners === null)
3136
+ return 1;
3137
+ for (const r of holders) {
3138
+ const owner = ownerOf2(r, owners);
3139
+ say(` ${describeHolder(r)}: ${owner ? publishCommand(owner) : "no registered map lists it; set that secret to the old value by hand"}`);
3140
+ }
3039
3141
  return 1;
3040
3142
  }
3041
3143
  }
@@ -3095,8 +3197,77 @@ async function recheck(run, rotation, value) {
3095
3197
  return `the old token ${rotation.old.id} is gone, so its policies can't be compared`;
3096
3198
  return checkNew(provider, rotation.new.id, value, old);
3097
3199
  }
3200
+ function holdersOf(receipts, generation) {
3201
+ return latestPerSecret(receipts).filter((r) => r.generation === generation);
3202
+ }
3203
+ function describeHolder(receipt) {
3204
+ return `${receipt.destinationId} (${receipt.keyId}, ${receipt.environment})`;
3205
+ }
3206
+ function publishCommand(owner) {
3207
+ const env = envFlag(owner.environment, owner.publishDefault);
3208
+ const where = owner.project === null ? "" : `cd ${shellWord(owner.project)} && `;
3209
+ return `${where}keypin publish ${owner.keyId}${env}`;
3210
+ }
3211
+ async function listedOwners(run) {
3212
+ const { deps, say } = run;
3213
+ const owners = new Map;
3214
+ const list = (map, project) => {
3215
+ for (const k of map.keys) {
3216
+ for (const [name, entry] of Object.entries(k.environments)) {
3217
+ for (const target of entry?.publish ?? []) {
3218
+ const secret = secretKey(target, k.name);
3219
+ owners.set(secret, [
3220
+ ...owners.get(secret) ?? [],
3221
+ {
3222
+ project,
3223
+ keyId: k.name,
3224
+ environment: name,
3225
+ mapFile: map.file,
3226
+ publishDefault: publishEnvironment(map)
3227
+ }
3228
+ ]);
3229
+ }
3230
+ }
3231
+ }
3232
+ };
3233
+ list(run.map, null);
3234
+ const registry = await loadRegistry(deps.files, registryPath(deps));
3235
+ for (const project of registry.projects) {
3236
+ const file = join6(project, MAP_FILE);
3237
+ if (file === run.map.file)
3238
+ continue;
3239
+ const text = await deps.files.read(file);
3240
+ const result = text === null ? null : parseMap(text, file);
3241
+ if (!result?.ok) {
3242
+ say(`Stopped: ${file} ${result ? "has errors" : "is missing"}, so keypin can't tell which keys use these destinations. Fix it or run keypin unregister ${shellWord(project)}. Nothing was changed.`);
3243
+ return null;
3244
+ }
3245
+ list(result.map, project);
3246
+ }
3247
+ return owners;
3248
+ }
3249
+ function ownerOf2(receipt, owners) {
3250
+ const found = owners.get(receiptSecretKey(receipt)) ?? [];
3251
+ return found.find((o) => ownedBy(receipt, o)) ?? found.find((o) => o.keyId === receipt.keyId && o.environment === receipt.environment) ?? found[0];
3252
+ }
3253
+ var UNLISTED = "no registered map lists it any more; revoking breaks it unless that secret is gone";
3254
+ async function otherHolders(run, receipts, generation, retired) {
3255
+ const owners = await listedOwners(run);
3256
+ if (owners === null)
3257
+ return null;
3258
+ const shown = new Set(retired.map((r) => r.destinationId));
3259
+ return holdersOf(receipts, generation).flatMap((receipt) => {
3260
+ const owner = ownerOf2(receipt, owners);
3261
+ if (owner)
3262
+ return [{ receipt, owner }];
3263
+ if (!shown.has(receipt.destinationId)) {
3264
+ run.say(` ${describeHolder(receipt)} has the old token, and ${UNLISTED}`);
3265
+ }
3266
+ return [];
3267
+ });
3268
+ }
3098
3269
  function again(run) {
3099
- return rotateCommand(run.key.id, run.environment);
3270
+ return rotateCommand(run.key.name, run.environment, publishEnvironment(run.map));
3100
3271
  }
3101
3272
  async function checkNew(provider, id, value, old) {
3102
3273
  try {
@@ -3130,12 +3301,18 @@ async function confirmed2(run, needsApproval, what) {
3130
3301
  say(rerun(deps, "rotate", run.args));
3131
3302
  return false;
3132
3303
  }
3133
- function withoutFinished(data, keyId, environment) {
3304
+ function withoutFinished(data, owner) {
3134
3305
  return {
3135
3306
  ...data,
3136
- rotations: data.rotations.filter((r) => !(r.keyId === keyId && r.environment === environment && r.stage === "revoked"))
3307
+ rotations: data.rotations.filter((r) => !(ownedBy(r, owner) && r.stage === "revoked"))
3137
3308
  };
3138
3309
  }
3310
+ function keyOwner(run) {
3311
+ return { keyId: run.key.name, environment: run.environment, mapFile: run.map.file };
3312
+ }
3313
+ function planFor(run) {
3314
+ return { key: run.key, environment: run.environment, mapFile: run.map.file };
3315
+ }
3139
3316
  var DATED = /^(.*) (\d{4}-\d{2}-\d{2})(?: #(\d+))?$/;
3140
3317
  function nextName(old, today) {
3141
3318
  const match = DATED.exec(old);
@@ -3160,28 +3337,29 @@ function describeAccess(token) {
3160
3337
  // src/commands/run.ts
3161
3338
  import { parseArgs as parseArgs5 } from "util";
3162
3339
  async function run(args, deps) {
3163
- const { positionals } = parseArgs5({ args, options: {}, allowPositionals: true });
3340
+ const { values, positionals } = parseArgs5({
3341
+ args,
3342
+ options: { env: { type: "string" } },
3343
+ allowPositionals: true
3344
+ });
3164
3345
  if (!positionals.length)
3165
3346
  throw new UsageError("keypin run needs a command after --");
3166
3347
  const map = await findMap(deps.files, deps.cwd);
3348
+ const environment = pickEnvironment(map, values.env, runEnvironment(map));
3167
3349
  const keys = map.keys.flatMap((key) => {
3168
- const dev = key.environments.dev;
3169
- return dev ? [{ key, ref: dev.ref }] : [];
3350
+ const entry = key.environments[environment];
3351
+ return entry ? [{ key, ref: entry.ref }] : [];
3170
3352
  });
3171
- const skipped = map.keys.filter((key) => !key.environments.dev).map((key) => key.id);
3172
- if (skipped.length)
3173
- deps.stderr.write(`keypin: no dev entry, not added: ${skipped.join(", ")}
3174
- `);
3175
- const values = new Map;
3353
+ const found = new Map;
3176
3354
  if (keys.length) {
3177
- announce(deps.stderr, "dev values", keys.map((k) => k.ref));
3355
+ announce(deps.stderr, `${environment} values`, keys.map((k) => k.ref));
3178
3356
  const vault = deps.vault();
3179
3357
  const failures = [];
3180
3358
  for (const { key, ref } of keys) {
3181
3359
  try {
3182
- values.set(key.env, await vault.read(ref));
3360
+ found.set(key.name, await vault.read(ref));
3183
3361
  } catch (error) {
3184
- failures.push(`${key.id} (item "${ref.item}"): ${messageOf(error)}`);
3362
+ failures.push(`${key.name} (${formatReference(ref)}): ${messageOf(error)}`);
3185
3363
  }
3186
3364
  }
3187
3365
  if (failures.length) {
@@ -3196,7 +3374,7 @@ async function run(args, deps) {
3196
3374
  for (const [name, value] of Object.entries(deps.env))
3197
3375
  if (value !== undefined)
3198
3376
  env[name] = value;
3199
- for (const [name, secret] of values) {
3377
+ for (const [name, secret] of found) {
3200
3378
  if (env[name] !== undefined) {
3201
3379
  deps.stderr.write(`keypin: ${name} was already set; using the vault's value
3202
3380
  `);
@@ -3226,7 +3404,7 @@ async function run(args, deps) {
3226
3404
  }
3227
3405
 
3228
3406
  // src/commands/status.ts
3229
- import { join as join6 } from "path";
3407
+ import { join as join7 } from "path";
3230
3408
  import { parseArgs as parseArgs6 } from "util";
3231
3409
  async function status(args, deps) {
3232
3410
  const { values, positionals } = parseArgs6({
@@ -3241,7 +3419,7 @@ async function status(args, deps) {
3241
3419
  const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
3242
3420
  const maps = new Map;
3243
3421
  for (const project of registry.projects) {
3244
- const file = join6(project, MAP_FILE);
3422
+ const file = join7(project, MAP_FILE);
3245
3423
  try {
3246
3424
  const text = await deps.files.read(file);
3247
3425
  if (text !== null)
@@ -3251,10 +3429,10 @@ async function status(args, deps) {
3251
3429
  `);
3252
3430
  }
3253
3431
  }
3254
- const refs = distinctRefs([...maps.values()].flatMap((result) => result.ok ? result.map.keys.flatMap((key) => Object.values(key.environments).map((e) => e.ref)) : []));
3432
+ const refs = distinctRefs([...maps.values()].flatMap((result) => result.ok ? result.map.keys.flatMap((key) => Object.values(key.environments).flatMap((e) => e ? [e.ref] : [])) : []));
3255
3433
  const metadata = new Map;
3256
3434
  if (refs.length) {
3257
- announce(deps.stderr, "rotation fields (no values)", refs);
3435
+ announce(deps.stderr, "rotated dates (no values)", refs);
3258
3436
  const vault = deps.vault();
3259
3437
  for (const ref of refs) {
3260
3438
  try {
@@ -3287,13 +3465,11 @@ function render2(result, projects) {
3287
3465
  return `No projects registered. Run "keypin init" in a project folder.
3288
3466
  `;
3289
3467
  const lines = [];
3290
- const header = ["KEY", "ENV", "VARIABLE", "OWNER", "ITEM", "ROTATED", "EVERY", "DUE"];
3468
+ const header = ["KEY", "ENV", "FROM", "ROTATED", "EVERY", "DUE"];
3291
3469
  const cells = (row) => [
3292
3470
  row.keyId,
3293
3471
  row.environment,
3294
- row.env,
3295
- row.owner,
3296
- row.ref.item,
3472
+ formatReference(row.ref),
3297
3473
  row.rotated ?? "-",
3298
3474
  row.rotateEvery ?? "-",
3299
3475
  row.due ?? (row.rotateEvery === "never" ? "never" : "unknown")
@@ -3371,7 +3547,7 @@ async function unregister2(args, deps) {
3371
3547
  return 0;
3372
3548
  }
3373
3549
  // ../../package.json
3374
- var version = "0.3.0";
3550
+ var version = "0.5.0";
3375
3551
 
3376
3552
  // src/cli.ts
3377
3553
  var USAGE = `Usage:
@@ -3381,13 +3557,22 @@ var USAGE = `Usage:
3381
3557
  keypin status [--json] every key in every registered project, with problems
3382
3558
  keypin discover [folder] [--json]
3383
3559
  every key name a project uses, local and in the cloud, and a draft map
3384
- keypin run -- <command> run a command with this project's dev keys in its environment
3385
- keypin publish <key-id> [--env prod|dev] [--yes]
3560
+ keypin run [--env <name>] -- <command>
3561
+ run a command with one environment's keys (default: the first, dev)
3562
+ keypin publish <VARIABLE> [--env <name>] [--yes]
3386
3563
  check accounts, plan, confirm, then write the key to every destination
3387
- keypin rotate <key-id> [--env prod|dev] [--yes]
3564
+ (default environment: the last, prod)
3565
+ keypin rotate <VARIABLE> [--env <name>] [--yes]
3388
3566
  replace a token with a new one that has the same permissions, publish it,
3389
3567
  and revoke the old one on the next run
3390
3568
  keypin --version print the version
3569
+
3570
+ Exit codes:
3571
+ 0 done
3572
+ 1 failed, or status found a problem
3573
+ 2 usage error
3574
+ 3 stopped for approval: run the printed command in a terminal and type yes
3575
+ keypin run exits 1 if it can't start the command, then with the command's own code.
3391
3576
  `;
3392
3577
  var COMMANDS = new Map([
3393
3578
  ["init", init],
@@ -3415,6 +3600,11 @@ async function cli(argv, deps) {
3415
3600
  ${USAGE}`);
3416
3601
  return 2;
3417
3602
  }
3603
+ const own = args.includes("--") ? args.slice(0, args.indexOf("--")) : args;
3604
+ if (own.includes("--help") || own.includes("-h")) {
3605
+ deps.stdout.write(USAGE);
3606
+ return 0;
3607
+ }
3418
3608
  try {
3419
3609
  return await command(args, deps);
3420
3610
  } catch (error) {
@@ -3618,7 +3808,7 @@ async function ask(question) {
3618
3808
  function main() {
3619
3809
  return cli(process.argv.slice(2), {
3620
3810
  cwd: process.cwd(),
3621
- self: process.argv.slice(0, 2),
3811
+ self: selfCommand(process.argv[0] ?? "bun", process.argv[1] ?? "keypin"),
3622
3812
  env: process.env,
3623
3813
  home: homedir2(),
3624
3814
  files: diskFiles,