keypin 0.4.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.
@@ -39,13 +39,54 @@ async function generationOf(secret) {
39
39
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 16);
40
40
  }
41
41
  // ../../packages/core/src/contracts.ts
42
- var ENVIRONMENTS = ["dev", "prod"];
42
+ var DEFAULT_ENVIRONMENTS = ["dev", "prod"];
43
43
  // ../../packages/core/src/map.ts
44
44
  var {TOML } = globalThis.Bun;
45
45
 
46
46
  // ../../packages/core/src/record.ts
47
47
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
48
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
+
49
90
  // ../../packages/core/src/rotation.ts
50
91
  var DUE_SOON_DAYS = 14;
51
92
  var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
@@ -80,6 +121,15 @@ function addDays(day, days) {
80
121
  // ../../packages/core/src/map.ts
81
122
  var DESTINATION_KINDS = ["cloudflare-worker", "github-actions"];
82
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
+ }
83
133
  function destinationId(target, secretName) {
84
134
  return `${placeId(target)}:${secretName}`;
85
135
  }
@@ -113,59 +163,70 @@ function parseMap(text, file) {
113
163
  }
114
164
  return validateMap(data, file);
115
165
  }
116
- var KEY_ID = /^[a-z0-9][a-z0-9-]*$/;
117
- 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_]*$/;
118
169
  var REPO = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
119
- var VAULT_KINDS = ["1password"];
170
+ var REMOVED_KEY_FIELDS = ["owner", "consumers"];
171
+ var OLD_FORMAT = "see docs/configuration.md for the current format";
120
172
  function validateMap(data, file) {
121
173
  const errors = [];
122
174
  const fail = (where, message) => errors.push(`${file}: ${where}${message}`);
123
175
  if (!isRecord(data))
124
176
  return { ok: false, errors: [`${file}: expected a table at the top level`] };
125
- unknownFields(data, ["vaults", "keys"], (field) => fail("", `unknown top-level field "${field}"`));
126
- const vaults = new Map;
127
- const rawVaults = data.vaults ?? {};
128
- if (!isRecord(rawVaults))
129
- fail("", `"vaults" must be a table`);
130
- else {
131
- for (const [name, raw] of Object.entries(rawVaults)) {
132
- const at = `vault "${name}": `;
133
- if (!isRecord(raw)) {
134
- fail(at, "must be a table");
135
- continue;
136
- }
137
- unknownFields(raw, ["kind", "account", "vault"], (field) => fail(at, `unknown field "${field}"`));
138
- const kind = requiredString(raw, "kind", (m) => fail(at, m));
139
- const account = requiredString(raw, "account", (m) => fail(at, m));
140
- const vault = requiredString(raw, "vault", (m) => fail(at, m));
141
- if (kind !== undefined && !VAULT_KINDS.includes(kind)) {
142
- fail(at, `field "kind" must be one of: ${VAULT_KINDS.join(", ")}`);
143
- } else if (kind !== undefined && account !== undefined && vault !== undefined) {
144
- vaults.set(name, { kind: "1password", account, vault });
145
- }
146
- }
147
- }
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));
148
180
  const keys = [];
149
181
  const rawKeys = data.keys ?? {};
150
182
  if (!isRecord(rawKeys))
151
183
  fail("", `"keys" must be a table`);
152
184
  else {
153
- for (const [id, raw] of Object.entries(rawKeys)) {
154
- 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));
155
188
  if (entry)
156
189
  keys.push(entry);
157
- }
190
+ });
191
+ }
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 } };
194
+ }
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);
158
220
  }
159
- sharedDestinations(keys, (where, message) => fail(where, message));
160
- return errors.length ? { ok: false, errors } : { ok: true, map: { file, keys } };
221
+ return names;
161
222
  }
162
- function sharedDestinations(keys, fail) {
223
+ function sharedDestinations(keys, environments, fail) {
163
224
  const owners = new Map;
164
225
  for (const key of keys) {
165
- for (const environment of ENVIRONMENTS) {
226
+ for (const environment of environments) {
166
227
  key.environments[environment]?.publish.forEach((target, i) => {
167
- const where = `key "${key.id}" ${environment} publish[${i}]`;
168
- const secret = secretKey(target, key.env);
228
+ const where = `key "${key.name}" ${environment} publish[${i}]`;
229
+ const secret = secretKey(target, key.name);
169
230
  const owner = owners.get(secret);
170
231
  if (owner === undefined)
171
232
  owners.set(secret, where);
@@ -175,68 +236,47 @@ function sharedDestinations(keys, fail) {
175
236
  }
176
237
  }
177
238
  }
178
- function validateKey(id, raw, vaults, fail) {
239
+ function validateKey(id, raw, account, environmentNames, fail) {
179
240
  let failures = 0;
180
241
  const err = (where, message) => {
181
242
  failures++;
182
243
  fail(where, message);
183
244
  };
184
- if (!KEY_ID.test(id))
185
- 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");
186
247
  if (!isRecord(raw)) {
187
248
  err("", "must be a table");
188
249
  return;
189
250
  }
190
- unknownFields(raw, ["env", "owner", "rotate_every", "consumers", ...ENVIRONMENTS], (field) => err("", `unknown field "${field}"`));
191
- const env = requiredString(raw, "env", (m) => err("", m));
192
- if (env !== undefined && !ENV_NAME.test(env))
193
- err("", `field "env" must be a variable name: letters, digits and _, not starting with a digit`);
194
- 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(", ")}`));
195
252
  const rotateEvery = optionalString(raw, "rotate_every", (m) => err("", m));
196
253
  if (rotateEvery !== undefined && periodDays(rotateEvery) === undefined) {
197
254
  err("", `field "rotate_every" must be <n>d, <n>w, <n>m or never`);
198
255
  }
199
- const environments = {};
200
- for (const name of ENVIRONMENTS) {
201
- if (raw[name] === undefined)
202
- continue;
203
- 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));
204
260
  if (entry)
205
261
  environments[name] = entry;
206
262
  }
207
263
  for (const [name, entry] of Object.entries(environments)) {
208
264
  const index = entry.publish.findIndex((target) => target.to === "github-actions");
209
- if (env !== undefined && index !== -1 && /^GITHUB_/i.test(env)) {
210
- 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_`);
211
267
  }
212
268
  }
213
- if (!ENVIRONMENTS.some((name) => raw[name] !== undefined)) {
214
- err("", `needs at least one of ${ENVIRONMENTS.map((n) => `"${n}"`).join(", ")}`);
215
- }
216
- const consumers = [];
217
- if (raw.consumers !== undefined) {
218
- if (!Array.isArray(raw.consumers))
219
- err("", `field "consumers" must be a list`);
220
- else {
221
- raw.consumers.forEach((c, i) => {
222
- const at = ` consumers[${i}]`;
223
- if (!isRecord(c))
224
- return err(at, "must be a table");
225
- unknownFields(c, ["name", "kind"], (field) => err(at, `unknown field "${field}"`));
226
- const name = requiredString(c, "name", (m) => err(at, m));
227
- const kind = requiredString(c, "kind", (m) => err(at, m));
228
- if (name !== undefined && kind !== undefined)
229
- consumers.push({ name, kind });
230
- });
231
- }
269
+ if (!declared.length) {
270
+ err("", `needs at least one of ${environmentNames.map((n) => `"${n}"`).join(", ")}`);
232
271
  }
233
- if (failures || env === undefined || owner === undefined)
272
+ if (failures)
234
273
  return;
235
- return { id, env, owner, rotateEvery: rotateEvery ?? null, environments, consumers };
274
+ return { name: id, rotateEvery: rotateEvery ?? null, environments };
236
275
  }
237
- function validateEnv(raw, vaults, fail) {
276
+ function validateEnv(given, account, fail) {
277
+ const raw = typeof given === "string" ? { from: given } : given;
238
278
  if (!isRecord(raw)) {
239
- fail("must be a table");
279
+ fail(`must be an op:// reference, or a table with "from"`);
240
280
  return;
241
281
  }
242
282
  let failed = false;
@@ -244,12 +284,8 @@ function validateEnv(raw, vaults, fail) {
244
284
  failed = true;
245
285
  fail(message);
246
286
  };
247
- unknownFields(raw, ["vault", "item", "publish", "issue"], (field) => err(`unknown field "${field}"`));
248
- const vaultName = requiredString(raw, "vault", err);
249
- const item = requiredString(raw, "item", err);
250
- const vault = vaultName === undefined ? undefined : vaults.get(vaultName);
251
- if (vaultName !== undefined && !vault)
252
- 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);
253
289
  const publish = [];
254
290
  const firstAt = new Map;
255
291
  if (raw.publish !== undefined) {
@@ -270,13 +306,28 @@ function validateEnv(raw, vaults, fail) {
270
306
  });
271
307
  }
272
308
  }
273
- const issue = raw.issue === undefined || !vault || item === undefined ? undefined : validateIssue(raw.issue, vault, item, (m) => err(`issue: ${m}`));
274
- 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)
317
+ return;
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 = "..."`);
275
325
  return;
276
- return { ref: { ...vault, item }, publish, ...issue ? { issue } : {} };
326
+ }
327
+ return { kind: "1password", account, ...parsed };
277
328
  }
278
329
  var ACCOUNT_ID = /^[0-9a-f]{32}$/;
279
- function validateIssue(raw, vault, item, fail) {
330
+ function validateIssue(raw, own, vaultAccount, fail) {
280
331
  if (!isRecord(raw)) {
281
332
  fail("must be a table");
282
333
  return;
@@ -289,17 +340,17 @@ function validateIssue(raw, vault, item, fail) {
289
340
  unknownFields(raw, ["provider", "account", "admin"], (field) => err(`unknown field "${field}"`));
290
341
  const provider = requiredString(raw, "provider", err);
291
342
  const account = requiredString(raw, "account", err);
292
- const admin = requiredString(raw, "admin", err);
343
+ const admin = reference(raw, "admin", vaultAccount, err);
293
344
  const kind = PROVIDER_KINDS.find((known) => known === provider);
294
345
  if (provider !== undefined && !kind)
295
346
  err(`field "provider" must be one of: ${PROVIDER_KINDS.join(", ")}`);
296
347
  if (account !== undefined && !ACCOUNT_ID.test(account))
297
348
  err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
298
- if (admin !== undefined && admin === item)
349
+ if (admin && sameItem(admin, own))
299
350
  err(`field "admin" names the key's own item; the admin token needs its own item`);
300
351
  if (failed || !kind || account === undefined || admin === undefined)
301
352
  return;
302
- return { provider: kind, account, admin: { ...vault, item: admin } };
353
+ return { provider: kind, account, admin };
303
354
  }
304
355
  function validateTarget(raw, fail) {
305
356
  if (!isRecord(raw)) {
@@ -318,6 +369,8 @@ function validateTarget(raw, fail) {
318
369
  unknownFields(raw, ["to", "account", "worker"], (field) => err(`unknown field "${field}" for ${to}`));
319
370
  const account = requiredString(raw, "account", err);
320
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)`);
321
374
  return failed || account === undefined || worker === undefined ? undefined : { to, account, worker };
322
375
  }
323
376
  if (to === "github-actions") {
@@ -443,14 +496,19 @@ function projectPath(project) {
443
496
  return project.replace(/(.)\/+$/, "$1");
444
497
  }
445
498
  // ../../packages/core/src/state.ts
446
- var STATE_VERSION = 2;
499
+ var STATE_VERSION = 3;
447
500
  var emptyState = () => ({ version: STATE_VERSION, receipts: [], operations: [] });
448
501
  async function loadState(files, path) {
449
- const data = await readVersionedJson(files, path, [1, STATE_VERSION], "state file");
502
+ const data = await readVersionedJson(files, path, [1, 2, STATE_VERSION], "state file");
450
503
  if (!data)
451
504
  return emptyState();
452
- const { operations } = data;
453
- 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;
454
512
  if (!Array.isArray(receipts) || !receipts.every(isReceipt)) {
455
513
  throw new Error(`${path}: the state file's "receipts" must be a list of receipts`);
456
514
  }
@@ -462,6 +520,9 @@ async function loadState(files, path) {
462
520
  async function saveState(files, path, state) {
463
521
  await writeJsonAtomic(files, path, state);
464
522
  }
523
+ function ownedBy(entry, owner) {
524
+ return entry.mapFile === owner.mapFile && entry.keyId === owner.keyId && entry.environment === owner.environment;
525
+ }
465
526
  function startOperation(state, operation) {
466
527
  if (state.operations.some((o) => o.id === operation.id))
467
528
  throw new Error(`operation ${operation.id} already exists`);
@@ -475,20 +536,26 @@ function recordReceipt(state, receipt, operationId) {
475
536
  function finishOperation(state, operationId) {
476
537
  return { ...state, operations: state.operations.filter((o) => o.id !== operationId) };
477
538
  }
478
- function unfinishedOperations(state, keyId, environment) {
479
- 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));
480
541
  }
481
542
  var isText = (value) => typeof value === "string";
543
+ var isTextOrNull = (value) => value === null || typeof value === "string";
482
544
  function isReceipt(r) {
483
- 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;
484
546
  }
485
- function isKeyRef(ref) {
486
- 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;
487
549
  }
488
550
  function isOperation(o) {
489
- 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);
490
552
  }
491
553
  // ../../packages/core/src/plan.ts
554
+ var ownerOf = ({ key, environment, mapFile }) => ({
555
+ keyId: key.name,
556
+ environment,
557
+ mapFile
558
+ });
492
559
  function approvalsFor(input) {
493
560
  return judge(input).flatMap(({ id, approval }) => approval ? [{ destinationId: id, ...approval }] : []);
494
561
  }
@@ -515,8 +582,8 @@ function planPublish(input) {
515
582
  approval: null
516
583
  };
517
584
  });
518
- const listed = new Set(steps.flatMap((s) => [secretKey(s.target, key.env), s.destinationId]));
519
- 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) => ({
520
587
  destinationId: r.destinationId,
521
588
  lastReceipt: {
522
589
  generation: r.generation,
@@ -525,7 +592,7 @@ function planPublish(input) {
525
592
  }
526
593
  }));
527
594
  return {
528
- keyId: key.id,
595
+ keyId: key.name,
529
596
  environment,
530
597
  generation,
531
598
  steps,
@@ -537,14 +604,15 @@ function judge(input) {
537
604
  const { key, environment } = input;
538
605
  const entry = key.environments[environment];
539
606
  if (!entry)
540
- 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`);
541
608
  const newest = latestPerSecret(input.receipts);
542
609
  const latest = new Map(newest.map((r) => [receiptSecretKey(r), r]));
543
- const ours = newest.filter((r) => r.keyId === key.id && r.environment === environment);
544
- 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));
545
613
  return entry.publish.map((target) => {
546
- const id = destinationId(target, key.env);
547
- 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);
548
616
  const needs = (reason, approval) => ({
549
617
  id,
550
618
  target,
@@ -573,21 +641,22 @@ function latestPerSecret(receipts) {
573
641
  }
574
642
  return [...latest.values()];
575
643
  }
576
- function sameRef(a, b) {
577
- return a.kind === b.kind && a.account === b.account && a.vault === b.vault && a.item === b.item;
578
- }
579
644
  function describeRef(ref) {
580
- return `item "${ref.item}" (1Password account ${ref.account}, vault "${ref.vault}")`;
645
+ return `${formatReference(ref)} (1Password account ${ref.account})`;
581
646
  }
582
647
  // ../../packages/core/src/rotations.ts
583
- var ROTATIONS_VERSION = 1;
648
+ var ROTATIONS_VERSION = 2;
584
649
  var ROTATION_STAGES = ["issuing", "issued", "stored", "published", "revoked"];
585
650
  var emptyRotations = () => ({ version: ROTATIONS_VERSION, rotations: [] });
586
651
  async function loadRotations(files, path) {
587
- const data = await readVersionedJson(files, path, [ROTATIONS_VERSION], "rotations file");
652
+ const data = await readVersionedJson(files, path, [1, ROTATIONS_VERSION], "rotations file");
588
653
  if (!data)
589
654
  return emptyRotations();
590
- 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;
591
660
  if (!Array.isArray(rotations) || !rotations.every(isRotation)) {
592
661
  throw new Error(`${path}: the rotations file's "rotations" must be a list of rotations`);
593
662
  }
@@ -596,11 +665,11 @@ async function loadRotations(files, path) {
596
665
  async function saveRotations(files, path, data) {
597
666
  await writeJsonAtomic(files, path, data);
598
667
  }
599
- function unfinishedRotation(data, keyId, environment, item) {
600
- 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");
601
670
  }
602
- function rotateCommand(keyId, environment) {
603
- return `keypin rotate ${keyId}${environment === "prod" ? "" : ` --env ${environment}`}`;
671
+ function rotateCommand(keyId, environment, fallback) {
672
+ return `keypin rotate ${keyId}${envFlag(environment, fallback)}`;
604
673
  }
605
674
  function putRotation(data, rotation) {
606
675
  return {
@@ -612,12 +681,12 @@ function dropRotation(data, id) {
612
681
  return { ...data, rotations: data.rotations.filter((r) => r.id !== id) };
613
682
  }
614
683
  var isText2 = (value) => typeof value === "string";
615
- var isTextOrNull = (value) => value === null || typeof value === "string";
684
+ var isTextOrNull2 = (value) => value === null || typeof value === "string";
616
685
  function isTokenRecord(t) {
617
- 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);
618
687
  }
619
688
  function isRotation(r) {
620
- 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);
621
690
  }
622
691
  // ../../packages/core/src/status.ts
623
692
  var NOTICES = ["due-soon", "authority-unknown", "rotation-unfinished"];
@@ -649,12 +718,13 @@ function buildStatus(input) {
649
718
  }
650
719
  const latest = new Map(latestPerSecret(input.receipts).map((r) => [receiptSecretKey(r), r]));
651
720
  for (const key of result.map.keys) {
652
- for (const environment of ENVIRONMENTS) {
721
+ for (const environment of result.map.environments) {
653
722
  const entry = key.environments[environment];
654
723
  if (!entry)
655
724
  continue;
656
- const where = { project, keyId: key.id, environment };
657
- 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})`;
658
728
  const add = (kind, message, extra = {}) => problems.push({
659
729
  kind,
660
730
  severity: NOTICES.includes(kind) ? "notice" : "problem",
@@ -663,15 +733,15 @@ function buildStatus(input) {
663
733
  message
664
734
  });
665
735
  const metadata = input.metadata(entry.ref);
666
- const rotateEvery = key.rotateEvery ?? metadata?.rotateEvery ?? null;
736
+ const rotateEvery = key.rotateEvery;
667
737
  const rotated = metadata?.rotated ?? null;
668
738
  const due = rotationDue({ label, metadata, rotated, rotateEvery, today: input.today, add });
669
739
  add("authority-unknown", `${label}: what this key grants is unknown, because keypin didn't create it`);
670
- const current = input.generation?.(key.id, environment);
740
+ const current = input.generation?.(key.name, environment);
671
741
  const destinations = entry.publish.map((target) => {
672
- const id = destinationId(target, key.env);
673
- const last = latest.get(secretKey(target, key.env));
674
- 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));
675
745
  const receipt = ours ? last : undefined;
676
746
  if (!receipt) {
677
747
  add("missing-receipt", `${label}: no receipt for ${id}, so what it holds is unknown`, {
@@ -693,14 +763,12 @@ function buildStatus(input) {
693
763
  stale
694
764
  };
695
765
  });
696
- 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);
697
767
  if (rotation) {
698
- 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`);
699
769
  }
700
770
  rows.push({
701
771
  ...where,
702
- env: key.env,
703
- owner: key.owner,
704
772
  ref: entry.ref,
705
773
  rotated,
706
774
  rotateEvery,
@@ -716,7 +784,7 @@ function buildStatus(input) {
716
784
  function rotationDue(input) {
717
785
  const { label, metadata, rotated, rotateEvery, today, add } = input;
718
786
  if (!metadata) {
719
- 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`);
720
788
  return null;
721
789
  }
722
790
  if (!rotated || !isDay(rotated)) {
@@ -725,7 +793,7 @@ function rotationDue(input) {
725
793
  }
726
794
  const days = periodDays(rotateEvery);
727
795
  if (days === undefined) {
728
- 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"`);
729
797
  return null;
730
798
  }
731
799
  if (days === null)
@@ -1036,7 +1104,7 @@ function buildDiscovery(input) {
1036
1104
  }
1037
1105
  }
1038
1106
  for (const key of input.map?.keys ?? []) {
1039
- 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 });
1040
1108
  }
1041
1109
  const cloudUnknown = unknowns.some((u) => u.cloud);
1042
1110
  const names = [...sources.entries()].map(([name, list]) => {
@@ -1061,12 +1129,16 @@ function workerLabel(worker) {
1061
1129
  }
1062
1130
  function draftMap(names, options) {
1063
1131
  const lines = [];
1064
- const taken = new Set(options.takenIds);
1065
- const vault = options.vault ?? {
1066
- name: "personal",
1067
- account: "<your 1Password account>",
1068
- vault: "<your vault>"
1069
- };
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
+ }));
1070
1142
  for (const row of names) {
1071
1143
  if (row.mapped.length)
1072
1144
  continue;
@@ -1098,43 +1170,34 @@ function draftMap(names, options) {
1098
1170
  continue;
1099
1171
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(row.name))
1100
1172
  continue;
1101
- const id = freeId(keyIdFor(row.name), taken);
1102
- const what = row.name.toLowerCase().replaceAll("_", " ").trim();
1103
- lines.push("", `[keys.${id}]`, `env = ${str(row.name)}`, `owner = ${str(options.owner)}`);
1104
- if (local) {
1105
- 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)}`);
1106
1178
  }
1107
1179
  if (publish.length) {
1108
- lines.push("", `[keys.${id}.prod]`, `vault = ${str(vault.name)}`, `item = ${str(`${options.owner} prod ${what}`)}`);
1109
- for (const target of publish)
1110
- 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
+ }
1111
1184
  }
1112
1185
  }
1113
1186
  if (!lines.length)
1114
1187
  return null;
1188
+ const account = options.map?.account ?? "<your 1Password account>";
1115
1189
  const header = [
1116
- "# Draft from keypin discover; nothing was written. Vault item names are placeholders.",
1117
- 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(", ")}]`],
1118
1193
  "",
1119
- `[vaults.${/^[A-Za-z_][A-Za-z0-9_-]*$/.test(vault.name) ? vault.name : str(vault.name)}]`,
1120
- 'kind = "1password"',
1121
- `account = ${str(vault.account)}`,
1122
- `vault = ${str(vault.vault)}`
1194
+ "[1password]",
1195
+ `account = ${str(account)}`
1123
1196
  ];
1124
1197
  return `${[...header, ...lines].join(`
1125
1198
  `)}
1126
1199
  `;
1127
1200
  }
1128
- function keyIdFor(name) {
1129
- return name.toLowerCase().replaceAll("_", "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-") || "key";
1130
- }
1131
- function freeId(base, taken) {
1132
- let id = base;
1133
- for (let n = 2;taken.has(id); n++)
1134
- id = `${base}-${n}`;
1135
- taken.add(id);
1136
- return id;
1137
- }
1138
1201
  function str(value) {
1139
1202
  return JSON.stringify(value);
1140
1203
  }
@@ -1826,7 +1889,6 @@ var desktopConnect = async (account) => {
1826
1889
  // ../../packages/vault-1password/src/backend.ts
1827
1890
  var VALUE_FIELD = "password";
1828
1891
  var ROTATED = "rotated";
1829
- var ROTATE_EVERY = "rotate_every";
1830
1892
  var DAY2 = /^\d{4}-\d{2}-\d{2}$/;
1831
1893
  var UNIX_SECONDS = /^\d+$/;
1832
1894
  function onePasswordBackend(connect = desktopConnect) {
@@ -1843,7 +1905,7 @@ function onePasswordBackend(connect = desktopConnect) {
1843
1905
  return pending;
1844
1906
  }
1845
1907
  async function vaultId(sdk, scope) {
1846
- const matches = (await sdk.vaults.list()).filter((vault) => vault.title === scope.vault);
1908
+ const matches = named(await sdk.vaults.list(), scope.vault);
1847
1909
  const [match] = matches;
1848
1910
  if (!match) {
1849
1911
  throw new Error(`1Password account "${scope.account}" has no vault "${scope.vault}"`);
@@ -1854,7 +1916,7 @@ function onePasswordBackend(connect = desktopConnect) {
1854
1916
  return match.id;
1855
1917
  }
1856
1918
  async function find(sdk, id, ref) {
1857
- const matches = (await sdk.items.list(id)).filter((item) => item.title === ref.item);
1919
+ const matches = named(await sdk.items.list(id), ref.item);
1858
1920
  if (matches.length > 1)
1859
1921
  throw new Error(`${where(ref)}: ${matches.length} items have this name`);
1860
1922
  return matches[0] ?? null;
@@ -1871,10 +1933,7 @@ function onePasswordBackend(connect = desktopConnect) {
1871
1933
  capabilities: { read: true, write: true, list: true, metadata: true },
1872
1934
  async read(ref) {
1873
1935
  const item = await get(ref);
1874
- const field = valueField(item.fields);
1875
- if (!field)
1876
- throw new Error(`${where(ref)}: no "${VALUE_FIELD}" field`);
1877
- return new Secret(field.value);
1936
+ return new Secret(valueField(item, ref).value);
1878
1937
  },
1879
1938
  async write(ref, secret, options = {}) {
1880
1939
  const rotated = options.rotated;
@@ -1885,6 +1944,9 @@ function onePasswordBackend(connect = desktopConnect) {
1885
1944
  const id = await vaultId(sdk, ref);
1886
1945
  const found = await find(sdk, id, ref);
1887
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
+ }
1888
1950
  const fields = [passwordField(secret)];
1889
1951
  if (rotated)
1890
1952
  fields.push(rotatedField(rotated));
@@ -1898,11 +1960,8 @@ function onePasswordBackend(connect = desktopConnect) {
1898
1960
  }
1899
1961
  const item = await sdk.items.get(id, found.id);
1900
1962
  const fields = [...item.fields];
1901
- const value = valueField(fields);
1902
- if (value)
1903
- fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
1904
- else
1905
- fields.push(passwordField(secret));
1963
+ const value = valueField(item, ref);
1964
+ fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
1906
1965
  if (rotated) {
1907
1966
  const existing = fields.find((field) => field.title === ROTATED);
1908
1967
  if (existing)
@@ -1929,16 +1988,32 @@ function onePasswordBackend(connect = desktopConnect) {
1929
1988
  async metadata(ref) {
1930
1989
  const item = await get(ref);
1931
1990
  const rotated = plainField(item.fields, ROTATED, ref);
1932
- const rotateEvery = plainField(item.fields, ROTATE_EVERY, ref);
1933
- return { rotated: rotated === null ? null : toDay(rotated, ref), rotateEvery };
1991
+ return { rotated: rotated === null ? null : toDay(rotated, ref) };
1934
1992
  }
1935
1993
  };
1936
1994
  }
1937
1995
  function where(ref) {
1938
- return `1Password ${ref.account} / ${ref.vault} / ${ref.item}`;
1996
+ return `${formatReference(ref)} (1Password account ${ref.account})`;
1939
1997
  }
1940
- function valueField(fields) {
1941
- 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;
1942
2017
  }
1943
2018
  function passwordField(secret) {
1944
2019
  return {
@@ -1976,7 +2051,6 @@ function messageOf2(error) {
1976
2051
  // src/commands/discover.ts
1977
2052
  import { basename, join as join3, relative, resolve } from "path";
1978
2053
  import { parseArgs } from "util";
1979
- var {TOML: TOML3 } = globalThis.Bun;
1980
2054
 
1981
2055
  // src/deps.ts
1982
2056
  class UsageError extends Error {
@@ -2005,6 +2079,12 @@ async function findMap(files, cwd) {
2005
2079
  }
2006
2080
  }
2007
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
+ }
2008
2088
 
2009
2089
  // src/commands/discover.ts
2010
2090
  async function discover(args, deps) {
@@ -2099,12 +2179,11 @@ async function discover(args, deps) {
2099
2179
  });
2100
2180
  }
2101
2181
  const discovery = buildDiscovery({ envFiles, workflows, workers, github, map, unknowns });
2102
- const owner = map?.keys[0]?.owner ?? basename(folder);
2103
2182
  const draft = draftMap(discovery.names, {
2104
- owner,
2183
+ project: basename(folder),
2105
2184
  githubAccount: login,
2106
- vault: map && mapText !== null ? firstVault(mapText) : null,
2107
- takenIds: map?.keys.map((k) => k.id) ?? []
2185
+ map: map ? { account: map.account, vault: firstVault(map) } : null,
2186
+ environments: map?.environments ?? DEFAULT_ENVIRONMENTS
2108
2187
  });
2109
2188
  if (draft !== null) {
2110
2189
  const check = parseMap(draft, "draft");
@@ -2205,22 +2284,9 @@ async function githubOrigin(deps, folder) {
2205
2284
  return { reason: "the origin remote isn't on github.com" };
2206
2285
  return { repo: `${match[1]}/${match[2]}`, owner: match[1] };
2207
2286
  }
2208
- function firstVault(text) {
2209
- let data;
2210
- try {
2211
- data = TOML3.parse(text);
2212
- } catch {
2213
- return null;
2214
- }
2215
- const vaults = isRecord(data) && isRecord(data.vaults) ? data.vaults : {};
2216
- for (const [name, raw] of Object.entries(vaults)) {
2217
- if (!isRecord(raw))
2218
- continue;
2219
- const { account, vault } = raw;
2220
- if (typeof account === "string" && typeof vault === "string")
2221
- return { name, account, vault };
2222
- }
2223
- 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;
2224
2290
  }
2225
2291
  var WHERE = {
2226
2292
  both: "local and cloud",
@@ -2351,34 +2417,25 @@ function rotationsPath(deps) {
2351
2417
  var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
2352
2418
  # Uncomment and edit. Every field is checked; an unknown one is an error.
2353
2419
  #
2354
- # A vault the keys below read from. The name ("personal") is yours to choose.
2355
- # [vaults.personal]
2356
- # kind = "1password"
2420
+ # The 1Password account the keys below read from: its sign-in address or account ID.
2421
+ # [1password]
2357
2422
  # account = "my.1password.com"
2358
- # vault = "Private"
2359
2423
  #
2360
- # A key. Its ID ("example-api-key") stays the same when vault items are renamed.
2361
- # [keys.example-api-key]
2362
- # env = "EXAMPLE_API_KEY" # the variable your program reads
2363
- # owner = "my-project"
2364
- # 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
2365
2428
  #
2366
- # Where keypin run reads the value from.
2367
- # [keys.example-api-key.dev]
2368
- # vault = "personal"
2369
- # 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"
2370
2432
  #
2371
- # Where keypin publish reads it from, and every place it writes it.
2372
- # [keys.example-api-key.prod]
2373
- # vault = "personal"
2374
- # item = "my-project prod example api key"
2375
- #
2376
- # [[keys.example-api-key.prod.publish]]
2433
+ # [[keys.EXAMPLE_API_KEY.prod.publish]]
2377
2434
  # to = "cloudflare-worker"
2378
2435
  # account = "<cloudflare account ID>"
2379
2436
  # worker = "my-worker"
2380
2437
  #
2381
- # [[keys.example-api-key.prod.publish]]
2438
+ # [[keys.EXAMPLE_API_KEY.prod.publish]]
2382
2439
  # to = "github-actions"
2383
2440
  # repo = "owner/repo"
2384
2441
  `;
@@ -2438,11 +2495,11 @@ Account checks:`);
2438
2495
  const checked = new Map;
2439
2496
  let failed = false;
2440
2497
  for (const target of entry.publish) {
2441
- const label = describeTarget(target, key.env);
2498
+ const label = describeTarget(target, key.name);
2442
2499
  try {
2443
2500
  const destination = deps.destination(target);
2444
2501
  const check = await destination.checkAccount();
2445
- checked.set(destinationId(target, key.env), { target, destination, check });
2502
+ checked.set(destinationId(target, key.name), { target, destination, check });
2446
2503
  say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
2447
2504
  if (!check.ok)
2448
2505
  failed = true;
@@ -2464,24 +2521,26 @@ function writesFor(steps, checked) {
2464
2521
  });
2465
2522
  }
2466
2523
  async function writeAll(input) {
2467
- const { key, environment, entry, secret, generation, writes, path, deps, say } = input;
2524
+ const { key, environment, mapFile, entry, secret, generation, writes, path, deps, say } = input;
2468
2525
  const id = crypto.randomUUID();
2469
2526
  let state = startOperation(input.state, {
2470
2527
  id,
2471
- keyId: key.id,
2528
+ keyId: key.name,
2472
2529
  environment,
2530
+ mapFile,
2473
2531
  generation,
2474
2532
  startedAt: deps.now().toISOString(),
2475
2533
  planned: writes.map((w) => w.destinationId)
2476
2534
  });
2477
2535
  await saveState(deps.files, path, state);
2478
2536
  for (const { destinationId: written, found } of writes) {
2479
- const label = describeTarget(found.target, key.env);
2537
+ const label = describeTarget(found.target, key.name);
2480
2538
  try {
2481
- const evidence = await found.destination.write(key.env, secret);
2539
+ const evidence = await found.destination.write(key.name, secret);
2482
2540
  state = recordReceipt(state, {
2483
- keyId: key.id,
2541
+ keyId: key.name,
2484
2542
  environment,
2543
+ mapFile,
2485
2544
  source: entry.ref,
2486
2545
  destinationId: written,
2487
2546
  generation,
@@ -2500,12 +2559,12 @@ async function writeAll(input) {
2500
2559
  return { ok: false, state };
2501
2560
  }
2502
2561
  }
2503
- state = finishAll(state, key.id, environment);
2562
+ state = finishAll(state, { keyId: key.name, environment, mapFile });
2504
2563
  await saveState(deps.files, path, state);
2505
2564
  return { ok: true, state };
2506
2565
  }
2507
- function finishAll(state, keyId, environment) {
2508
- 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);
2509
2568
  }
2510
2569
  function rerun(deps, command, args) {
2511
2570
  const words = [...deps.self, command, ...args].map(shellWord).join(" ");
@@ -2526,12 +2585,11 @@ function describeTarget(target, secretName) {
2526
2585
  function announce(stderr, what, refs) {
2527
2586
  const groups = new Map;
2528
2587
  for (const ref of refs) {
2529
- const where = `1Password account ${ref.account}, vault "${ref.vault}"`;
2530
- 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)));
2531
2590
  }
2532
- for (const [where, items] of groups) {
2533
- const names = [...items].map((item) => `"${item}"`).join(", ");
2534
- 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(", ")}
2535
2593
  `);
2536
2594
  }
2537
2595
  }
@@ -2542,35 +2600,33 @@ function distinctRefs(refs) {
2542
2600
  seen.set(refKey(ref), ref);
2543
2601
  return [...seen.values()];
2544
2602
  }
2545
- 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]);
2546
2604
 
2547
2605
  // src/commands/publish.ts
2548
2606
  async function publish(args, deps) {
2549
- const request = parseRequest(args);
2607
+ const { keyId, env, yes } = parseRequest(args);
2550
2608
  const map = await findMap(deps.files, deps.cwd);
2551
- 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));
2552
2612
  }
2553
2613
  function parseRequest(args) {
2554
2614
  const { values, positionals } = parseArgs3({
2555
2615
  args,
2556
2616
  options: {
2557
- env: { type: "string", default: "prod" },
2617
+ env: { type: "string" },
2558
2618
  yes: { type: "boolean", default: false }
2559
2619
  },
2560
2620
  allowPositionals: true
2561
2621
  });
2562
2622
  const [keyId, ...extra] = positionals;
2563
2623
  if (keyId === undefined || extra.length)
2564
- throw new UsageError("keypin publish takes one key ID");
2565
- const environment = ENVIRONMENTS.find((name) => name === values.env);
2566
- if (!environment) {
2567
- throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
2568
- }
2569
- 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 };
2570
2626
  }
2571
2627
  async function publishLocked(request, map, path, deps) {
2572
2628
  const { keyId, environment } = request;
2573
- const key = map.keys.find((k) => k.id === keyId);
2629
+ const key = map.keys.find((k) => k.name === keyId);
2574
2630
  if (!key)
2575
2631
  throw new Error(`${map.file} has no key "${keyId}"`);
2576
2632
  const entry = key.environments[environment];
@@ -2578,16 +2634,17 @@ async function publishLocked(request, map, path, deps) {
2578
2634
  throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
2579
2635
  const say = (text) => deps.stderr.write(`${text}
2580
2636
  `);
2581
- say(`Publishing ${keyId} (${environment}) as ${key.env}, from item "${entry.ref.item}"`);
2582
- 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}`);
2583
2639
  for (const target of entry.publish)
2584
- say(` to: ${describeTarget(target, key.env)}`);
2640
+ say(` to: ${describeTarget(target, key.name)}`);
2585
2641
  if (!entry.publish.length) {
2586
2642
  say(`The map lists no destinations for ${keyId} (${environment}); nothing to publish.`);
2587
2643
  return 1;
2588
2644
  }
2589
2645
  const state = await loadState(deps.files, path);
2590
- for (const op of unfinishedOperations(state, keyId, environment)) {
2646
+ const owner = { keyId, environment, mapFile: map.file };
2647
+ for (const op of unfinishedOperations(state, owner)) {
2591
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.`);
2592
2649
  }
2593
2650
  const checked = await checkAccounts(key, entry, deps, say);
@@ -2595,7 +2652,12 @@ async function publishLocked(request, map, path, deps) {
2595
2652
  say("Stopped: an account check failed. Nothing was read and nothing was written.");
2596
2653
  return 1;
2597
2654
  }
2598
- 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
+ });
2599
2661
  if (approvals.length && !deps.isTerminal) {
2600
2662
  say(`
2601
2663
  Needs approval:`);
@@ -2610,17 +2672,23 @@ Needs approval:`);
2610
2672
  try {
2611
2673
  secret = await deps.vault().read(entry.ref);
2612
2674
  } catch (error) {
2613
- say(`Stopped: couldn't read ${keyId} (item "${entry.ref.item}"): ${messageOf(error)}`);
2675
+ say(`Stopped: couldn't read ${keyId} (${formatReference(entry.ref)}): ${messageOf(error)}`);
2614
2676
  return 1;
2615
2677
  }
2616
2678
  const generation = await generationOf(secret);
2617
- 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
+ });
2618
2686
  say(`
2619
2687
  Plan for generation ${generation}:`);
2620
2688
  const writes = writesFor(plan.steps, checked);
2621
2689
  for (const step of plan.steps) {
2622
2690
  const found = checked.get(step.destinationId);
2623
- say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
2691
+ say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
2624
2692
  if (found)
2625
2693
  say(` ${accountFacts(found.check)}`);
2626
2694
  if (step.approval)
@@ -2631,8 +2699,8 @@ Plan for generation ${generation}:`);
2631
2699
  }
2632
2700
  if (!writes.length) {
2633
2701
  say("Nothing to write: every destination already has this generation.");
2634
- if (unfinishedOperations(state, keyId, environment).length) {
2635
- await saveState(deps.files, path, finishAll(state, keyId, environment));
2702
+ if (unfinishedOperations(state, owner).length) {
2703
+ await saveState(deps.files, path, finishAll(state, owner));
2636
2704
  }
2637
2705
  return 0;
2638
2706
  }
@@ -2641,6 +2709,7 @@ Plan for generation ${generation}:`);
2641
2709
  const written = await writeAll({
2642
2710
  key,
2643
2711
  environment,
2712
+ mapFile: map.file,
2644
2713
  entry,
2645
2714
  secret,
2646
2715
  generation,
@@ -2682,20 +2751,17 @@ async function rotate(args, deps) {
2682
2751
  const { values, positionals } = parseArgs4({
2683
2752
  args,
2684
2753
  options: {
2685
- env: { type: "string", default: "prod" },
2754
+ env: { type: "string" },
2686
2755
  yes: { type: "boolean", default: false }
2687
2756
  },
2688
2757
  allowPositionals: true
2689
2758
  });
2690
2759
  const [keyId, ...extra] = positionals;
2691
2760
  if (keyId === undefined || extra.length)
2692
- throw new UsageError("keypin rotate takes one key ID");
2693
- const environment = ENVIRONMENTS.find((name) => name === values.env);
2694
- if (!environment) {
2695
- throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
2696
- }
2761
+ throw new UsageError("keypin rotate takes one key: the variable name");
2697
2762
  const map = await findMap(deps.files, deps.cwd);
2698
- 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);
2699
2765
  if (!key)
2700
2766
  throw new Error(`${map.file} has no key "${keyId}"`);
2701
2767
  const entry = key.environments[environment];
@@ -2722,10 +2788,10 @@ async function rotate(args, deps) {
2722
2788
  say
2723
2789
  };
2724
2790
  const data = await loadRotations(deps.files, run.rotationsPath);
2725
- const open = unfinishedRotation(data, key.id, environment, entry.ref);
2791
+ const open = unfinishedRotation(data, keyOwner(run), entry.ref);
2726
2792
  if (!open)
2727
2793
  return start(run, data);
2728
- 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}".`);
2729
2795
  if (open.provider !== issue.provider || open.account !== issue.account) {
2730
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.`);
2731
2797
  return 1;
@@ -2745,13 +2811,19 @@ async function rotate(args, deps) {
2745
2811
  }
2746
2812
  async function start(run, data) {
2747
2813
  const { key, entry, issue, environment, deps, say } = run;
2748
- say(`Rotating ${key.id} (${environment}) as ${key.env}, item "${entry.ref.item}"`);
2749
- say(` vault: 1Password account ${entry.ref.account}, vault "${entry.ref.vault}"`);
2750
- 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)}`);
2751
2817
  for (const target of entry.publish)
2752
- say(` to: ${describeTarget(target, key.env)}`);
2818
+ say(` to: ${describeTarget(target, key.name)}`);
2753
2819
  if (!entry.publish.length) {
2754
- 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.`);
2755
2827
  return 1;
2756
2828
  }
2757
2829
  const state = await loadState(deps.files, run.statePath);
@@ -2760,7 +2832,7 @@ async function start(run, data) {
2760
2832
  say("Stopped: an account check failed. Nothing was read and nothing was changed.");
2761
2833
  return 1;
2762
2834
  }
2763
- const approvals = approvalsFor({ key, environment, receipts: state.receipts });
2835
+ const approvals = approvalsFor({ ...planFor(run), receipts: state.receipts });
2764
2836
  if (!deps.isTerminal && (approvals.length || !run.yes)) {
2765
2837
  for (const approval of approvals)
2766
2838
  say(` needs approval: ${approval.approval}`);
@@ -2768,25 +2840,19 @@ async function start(run, data) {
2768
2840
  say(rerun(deps, "rotate", run.args));
2769
2841
  return NEEDS_APPROVAL;
2770
2842
  }
2771
- announce(deps.stderr, "the current value, its rotation fields and the admin token", [
2772
- entry.ref,
2773
- issue.admin
2774
- ]);
2843
+ announce(deps.stderr, "the current value and the admin token", [entry.ref, issue.admin]);
2775
2844
  const vault = deps.vault();
2776
2845
  let current;
2777
2846
  let admin;
2778
- let every;
2779
2847
  try {
2780
2848
  current = await vault.read(entry.ref);
2781
- every = key.rotateEvery ?? (await vault.metadata(entry.ref)).rotateEvery;
2782
2849
  admin = await vault.read(issue.admin);
2783
2850
  } catch (error) {
2784
2851
  say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
2785
2852
  return 1;
2786
2853
  }
2787
- const days = periodDays(every);
2788
- if (!days) {
2789
- 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.`);
2790
2856
  return 1;
2791
2857
  }
2792
2858
  const provider = deps.provider(issue, admin);
@@ -2809,10 +2875,10 @@ Plan:`);
2809
2875
  say(` new token: "${name}", expires ${expiresOn} (rotate_every ${every} plus ${GRACE_DAYS} days' grace)`);
2810
2876
  for (const line of describeAccess(old))
2811
2877
  say(` ${line}`);
2812
- say(` store in: item "${entry.ref.item}", with rotated ${today}`);
2878
+ say(` store in: ${formatReference(entry.ref)}, with rotated ${today}`);
2813
2879
  for (const target of entry.publish) {
2814
- const found = checked.get(destinationId(target, key.env));
2815
- say(` publish to: ${describeTarget(target, key.env)}`);
2880
+ const found = checked.get(destinationId(target, key.name));
2881
+ say(` publish to: ${describeTarget(target, key.name)}`);
2816
2882
  if (found)
2817
2883
  say(` ${accountFacts(found.check)}`);
2818
2884
  }
@@ -2824,8 +2890,9 @@ Plan:`);
2824
2890
  const now = deps.now().toISOString();
2825
2891
  let rotation = {
2826
2892
  id: crypto.randomUUID(),
2827
- keyId: key.id,
2893
+ keyId: key.name,
2828
2894
  environment,
2895
+ mapFile: run.map.file,
2829
2896
  item: entry.ref,
2830
2897
  provider: issue.provider,
2831
2898
  account: issue.account,
@@ -2840,7 +2907,7 @@ Plan:`);
2840
2907
  },
2841
2908
  new: { id: null, name, expiresOn, generation: null }
2842
2909
  };
2843
- data = putRotation(withoutFinished(data, key.id, environment), rotation);
2910
+ data = putRotation(withoutFinished(data, keyOwner(run)), rotation);
2844
2911
  await saveRotations(deps.files, run.rotationsPath, data);
2845
2912
  const made = await provider.issue({ name, like: old, expiresOn });
2846
2913
  if ("refused" in made) {
@@ -2865,7 +2932,7 @@ Plan:`);
2865
2932
  return deleteUnchecked(run, data, rotation, provider);
2866
2933
  }
2867
2934
  say(` checked: ${made.token.id} is active and has the same policies as ${old.id}`);
2868
- 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}`);
2869
2936
  try {
2870
2937
  await vault.write(entry.ref, made.value, { rotated: today });
2871
2938
  const stored = await generationOf(await vault.read(entry.ref));
@@ -2898,7 +2965,7 @@ async function publishNew(run, data, rotation, fresh) {
2898
2965
  return 1;
2899
2966
  }
2900
2967
  checked = found;
2901
- if (!deps.isTerminal && approvalsFor({ key, environment, receipts: state.receipts }).length) {
2968
+ if (!deps.isTerminal && approvalsFor({ ...planFor(run), receipts: state.receipts }).length) {
2902
2969
  say("Stopped before reading the value: publishing needs approval, and --yes can't give it.");
2903
2970
  say(rerun(deps, "rotate", run.args));
2904
2971
  return NEEDS_APPROVAL;
@@ -2910,7 +2977,7 @@ async function publishNew(run, data, rotation, fresh) {
2910
2977
  value = await deps.vault().read(entry.ref);
2911
2978
  const generation = await generationOf(value);
2912
2979
  if (generation !== rotation.new.generation) {
2913
- 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.`);
2914
2981
  return 1;
2915
2982
  }
2916
2983
  const problem = await recheck(run, rotation, value);
@@ -2921,11 +2988,11 @@ async function publishNew(run, data, rotation, fresh) {
2921
2988
  say(` checked: ${rotation.new.id} is active and has the same policies as ${rotation.old.id}`);
2922
2989
  }
2923
2990
  const generation = rotation.new.generation ?? await generationOf(value);
2924
- const plan = planPublish({ key, environment, receipts: state.receipts, generation });
2991
+ const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
2925
2992
  say(`
2926
2993
  Publishing generation ${generation}:`);
2927
2994
  for (const step of plan.steps) {
2928
- say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
2995
+ say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
2929
2996
  if (step.approval)
2930
2997
  say(` needs approval: ${step.approval}`);
2931
2998
  }
@@ -2936,6 +3003,7 @@ Publishing generation ${generation}:`);
2936
3003
  const written = await writeAll({
2937
3004
  key,
2938
3005
  environment,
3006
+ mapFile: run.map.file,
2939
3007
  entry,
2940
3008
  secret: value,
2941
3009
  generation,
@@ -2959,9 +3027,7 @@ Publishing generation ${generation}:`);
2959
3027
  Published. The old token ${rotation.old.id} "${rotation.old.name}" is still active.`);
2960
3028
  say("Next, check that every consumer works with the new value:");
2961
3029
  for (const target of entry.publish)
2962
- say(` ${describeTarget(target, key.env)}`);
2963
- for (const consumer of key.consumers)
2964
- say(` ${consumer.name} (${consumer.kind})`);
3030
+ say(` ${describeTarget(target, key.name)}`);
2965
3031
  say(`Then run ${again(run)} again to revoke the old token.`);
2966
3032
  return 0;
2967
3033
  }
@@ -2972,17 +3038,17 @@ async function revokeOld(run, data, rotation) {
2972
3038
  throw new Error(`rotation ${rotation.id} has no new generation or token IDs`);
2973
3039
  }
2974
3040
  const state = await loadState(deps.files, run.statePath);
2975
- const plan = planPublish({ key, environment, receipts: state.receipts, generation });
3041
+ const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
2976
3042
  const behind = plan.steps.filter((step) => step.action === "write");
2977
3043
  for (const step of behind) {
2978
3044
  say(` ${step.destinationId} doesn't have generation ${generation}: ${step.reason}`);
2979
3045
  }
2980
3046
  const retired = plan.removed.filter((removed) => removed.lastReceipt.generation === rotation.old.generation);
2981
3047
  if (behind.length) {
2982
- 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.`);
2983
3049
  return 1;
2984
3050
  }
2985
- say(`Every destination of ${key.id} (${environment}) has generation ${generation}.`);
3051
+ say(`Every destination of ${key.name} (${environment}) has generation ${generation}.`);
2986
3052
  for (const removed of retired) {
2987
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`);
2988
3054
  }
@@ -3007,7 +3073,7 @@ async function revokeOld(run, data, rotation) {
3007
3073
  ]);
3008
3074
  const holds = await generationOf(await deps.vault().read(run.entry.ref));
3009
3075
  if (holds !== generation) {
3010
- say(`Stopped: item "${run.entry.ref.item}" holds generation ${holds}, not the new ${generation}. Something else changed it, and revoking would leave it with a dead token. Nothing was revoked.`);
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.`);
3011
3077
  return 1;
3012
3078
  }
3013
3079
  const provider = deps.provider(issue, await deps.vault().read(issue.admin));
@@ -3036,7 +3102,7 @@ Old token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "n
3036
3102
  async function finish(run, data, rotation) {
3037
3103
  const done = { ...rotation, stage: "revoked", updatedAt: run.deps.now().toISOString() };
3038
3104
  await saveRotations(run.deps.files, run.rotationsPath, putRotation(data, done));
3039
- 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}.`);
3040
3106
  return 0;
3041
3107
  }
3042
3108
  async function abandon(run, data, rotation) {
@@ -3052,11 +3118,11 @@ async function abandon(run, data, rotation) {
3052
3118
  };
3053
3119
  const next = putRotation(data, stored);
3054
3120
  await saveRotations(deps.files, run.rotationsPath, next);
3055
- say(`Item "${entry.ref.item}" already holds the new value (generation ${holds}).`);
3121
+ say(`${formatReference(entry.ref)} already holds the new value (generation ${holds}).`);
3056
3122
  return publishNew(run, next, stored, null);
3057
3123
  }
3058
3124
  if (holds !== rotation.old.generation) {
3059
- 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.`);
3060
3126
  return 1;
3061
3127
  }
3062
3128
  }
@@ -3064,12 +3130,12 @@ async function abandon(run, data, rotation) {
3064
3130
  const state = await loadState(deps.files, run.statePath);
3065
3131
  const holders = holdersOf(state.receipts, rotation.new.generation);
3066
3132
  if (holders.length) {
3067
- 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 item "${entry.ref.item}" and run ${again(run)} again to finish, or publish the old value to each destination that has the new one:`);
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:`);
3068
3134
  const owners = await listedOwners(run);
3069
3135
  if (owners === null)
3070
3136
  return 1;
3071
3137
  for (const r of holders) {
3072
- const owner = ownerOf(r, owners);
3138
+ const owner = ownerOf2(r, owners);
3073
3139
  say(` ${describeHolder(r)}: ${owner ? publishCommand(owner) : "no registered map lists it; set that secret to the old value by hand"}`);
3074
3140
  }
3075
3141
  return 1;
@@ -3138,7 +3204,7 @@ function describeHolder(receipt) {
3138
3204
  return `${receipt.destinationId} (${receipt.keyId}, ${receipt.environment})`;
3139
3205
  }
3140
3206
  function publishCommand(owner) {
3141
- const env = owner.environment === "prod" ? "" : ` --env ${owner.environment}`;
3207
+ const env = envFlag(owner.environment, owner.publishDefault);
3142
3208
  const where = owner.project === null ? "" : `cd ${shellWord(owner.project)} && `;
3143
3209
  return `${where}keypin publish ${owner.keyId}${env}`;
3144
3210
  }
@@ -3148,11 +3214,17 @@ async function listedOwners(run) {
3148
3214
  const list = (map, project) => {
3149
3215
  for (const k of map.keys) {
3150
3216
  for (const [name, entry] of Object.entries(k.environments)) {
3151
- for (const target of entry.publish) {
3152
- const secret = secretKey(target, k.env);
3217
+ for (const target of entry?.publish ?? []) {
3218
+ const secret = secretKey(target, k.name);
3153
3219
  owners.set(secret, [
3154
3220
  ...owners.get(secret) ?? [],
3155
- { project, keyId: k.id, environment: name }
3221
+ {
3222
+ project,
3223
+ keyId: k.name,
3224
+ environment: name,
3225
+ mapFile: map.file,
3226
+ publishDefault: publishEnvironment(map)
3227
+ }
3156
3228
  ]);
3157
3229
  }
3158
3230
  }
@@ -3174,9 +3246,9 @@ async function listedOwners(run) {
3174
3246
  }
3175
3247
  return owners;
3176
3248
  }
3177
- function ownerOf(receipt, owners) {
3249
+ function ownerOf2(receipt, owners) {
3178
3250
  const found = owners.get(receiptSecretKey(receipt)) ?? [];
3179
- return found.find((o) => o.keyId === receipt.keyId && o.environment === receipt.environment) ?? found[0];
3251
+ return found.find((o) => ownedBy(receipt, o)) ?? found.find((o) => o.keyId === receipt.keyId && o.environment === receipt.environment) ?? found[0];
3180
3252
  }
3181
3253
  var UNLISTED = "no registered map lists it any more; revoking breaks it unless that secret is gone";
3182
3254
  async function otherHolders(run, receipts, generation, retired) {
@@ -3185,7 +3257,7 @@ async function otherHolders(run, receipts, generation, retired) {
3185
3257
  return null;
3186
3258
  const shown = new Set(retired.map((r) => r.destinationId));
3187
3259
  return holdersOf(receipts, generation).flatMap((receipt) => {
3188
- const owner = ownerOf(receipt, owners);
3260
+ const owner = ownerOf2(receipt, owners);
3189
3261
  if (owner)
3190
3262
  return [{ receipt, owner }];
3191
3263
  if (!shown.has(receipt.destinationId)) {
@@ -3195,7 +3267,7 @@ async function otherHolders(run, receipts, generation, retired) {
3195
3267
  });
3196
3268
  }
3197
3269
  function again(run) {
3198
- return rotateCommand(run.key.id, run.environment);
3270
+ return rotateCommand(run.key.name, run.environment, publishEnvironment(run.map));
3199
3271
  }
3200
3272
  async function checkNew(provider, id, value, old) {
3201
3273
  try {
@@ -3229,12 +3301,18 @@ async function confirmed2(run, needsApproval, what) {
3229
3301
  say(rerun(deps, "rotate", run.args));
3230
3302
  return false;
3231
3303
  }
3232
- function withoutFinished(data, keyId, environment) {
3304
+ function withoutFinished(data, owner) {
3233
3305
  return {
3234
3306
  ...data,
3235
- 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"))
3236
3308
  };
3237
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
+ }
3238
3316
  var DATED = /^(.*) (\d{4}-\d{2}-\d{2})(?: #(\d+))?$/;
3239
3317
  function nextName(old, today) {
3240
3318
  const match = DATED.exec(old);
@@ -3259,28 +3337,29 @@ function describeAccess(token) {
3259
3337
  // src/commands/run.ts
3260
3338
  import { parseArgs as parseArgs5 } from "util";
3261
3339
  async function run(args, deps) {
3262
- const { positionals } = parseArgs5({ args, options: {}, allowPositionals: true });
3340
+ const { values, positionals } = parseArgs5({
3341
+ args,
3342
+ options: { env: { type: "string" } },
3343
+ allowPositionals: true
3344
+ });
3263
3345
  if (!positionals.length)
3264
3346
  throw new UsageError("keypin run needs a command after --");
3265
3347
  const map = await findMap(deps.files, deps.cwd);
3348
+ const environment = pickEnvironment(map, values.env, runEnvironment(map));
3266
3349
  const keys = map.keys.flatMap((key) => {
3267
- const dev = key.environments.dev;
3268
- return dev ? [{ key, ref: dev.ref }] : [];
3350
+ const entry = key.environments[environment];
3351
+ return entry ? [{ key, ref: entry.ref }] : [];
3269
3352
  });
3270
- const skipped = map.keys.filter((key) => !key.environments.dev).map((key) => key.id);
3271
- if (skipped.length)
3272
- deps.stderr.write(`keypin: no dev entry, not added: ${skipped.join(", ")}
3273
- `);
3274
- const values = new Map;
3353
+ const found = new Map;
3275
3354
  if (keys.length) {
3276
- announce(deps.stderr, "dev values", keys.map((k) => k.ref));
3355
+ announce(deps.stderr, `${environment} values`, keys.map((k) => k.ref));
3277
3356
  const vault = deps.vault();
3278
3357
  const failures = [];
3279
3358
  for (const { key, ref } of keys) {
3280
3359
  try {
3281
- values.set(key.env, await vault.read(ref));
3360
+ found.set(key.name, await vault.read(ref));
3282
3361
  } catch (error) {
3283
- failures.push(`${key.id} (item "${ref.item}"): ${messageOf(error)}`);
3362
+ failures.push(`${key.name} (${formatReference(ref)}): ${messageOf(error)}`);
3284
3363
  }
3285
3364
  }
3286
3365
  if (failures.length) {
@@ -3295,7 +3374,7 @@ async function run(args, deps) {
3295
3374
  for (const [name, value] of Object.entries(deps.env))
3296
3375
  if (value !== undefined)
3297
3376
  env[name] = value;
3298
- for (const [name, secret] of values) {
3377
+ for (const [name, secret] of found) {
3299
3378
  if (env[name] !== undefined) {
3300
3379
  deps.stderr.write(`keypin: ${name} was already set; using the vault's value
3301
3380
  `);
@@ -3350,10 +3429,10 @@ async function status(args, deps) {
3350
3429
  `);
3351
3430
  }
3352
3431
  }
3353
- 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] : [])) : []));
3354
3433
  const metadata = new Map;
3355
3434
  if (refs.length) {
3356
- announce(deps.stderr, "rotation fields (no values)", refs);
3435
+ announce(deps.stderr, "rotated dates (no values)", refs);
3357
3436
  const vault = deps.vault();
3358
3437
  for (const ref of refs) {
3359
3438
  try {
@@ -3386,13 +3465,11 @@ function render2(result, projects) {
3386
3465
  return `No projects registered. Run "keypin init" in a project folder.
3387
3466
  `;
3388
3467
  const lines = [];
3389
- const header = ["KEY", "ENV", "VARIABLE", "OWNER", "ITEM", "ROTATED", "EVERY", "DUE"];
3468
+ const header = ["KEY", "ENV", "FROM", "ROTATED", "EVERY", "DUE"];
3390
3469
  const cells = (row) => [
3391
3470
  row.keyId,
3392
3471
  row.environment,
3393
- row.env,
3394
- row.owner,
3395
- row.ref.item,
3472
+ formatReference(row.ref),
3396
3473
  row.rotated ?? "-",
3397
3474
  row.rotateEvery ?? "-",
3398
3475
  row.due ?? (row.rotateEvery === "never" ? "never" : "unknown")
@@ -3470,7 +3547,7 @@ async function unregister2(args, deps) {
3470
3547
  return 0;
3471
3548
  }
3472
3549
  // ../../package.json
3473
- var version = "0.4.0";
3550
+ var version = "0.5.0";
3474
3551
 
3475
3552
  // src/cli.ts
3476
3553
  var USAGE = `Usage:
@@ -3480,10 +3557,12 @@ var USAGE = `Usage:
3480
3557
  keypin status [--json] every key in every registered project, with problems
3481
3558
  keypin discover [folder] [--json]
3482
3559
  every key name a project uses, local and in the cloud, and a draft map
3483
- keypin run -- <command> run a command with this project's dev keys in its environment
3484
- 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]
3485
3563
  check accounts, plan, confirm, then write the key to every destination
3486
- keypin rotate <key-id> [--env prod|dev] [--yes]
3564
+ (default environment: the last, prod)
3565
+ keypin rotate <VARIABLE> [--env <name>] [--yes]
3487
3566
  replace a token with a new one that has the same permissions, publish it,
3488
3567
  and revoke the old one on the next run
3489
3568
  keypin --version print the version