keypin 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,9 @@
1
1
  // @bun
2
2
  import {
3
- __require,
3
+ messageOf,
4
4
  errorCode,
5
- installProblem,
6
- messageOf
7
- } from "./chunk-9dz90rbw.js";
5
+ installProblem
6
+ } from "./chunk-8agfxsqt.js";
8
7
 
9
8
  // src/start.ts
10
9
  import { homedir as homedir2 } from "os";
@@ -79,6 +78,7 @@ function addDays(day, days) {
79
78
 
80
79
  // ../../packages/core/src/map.ts
81
80
  var DESTINATION_KINDS = ["cloudflare-worker", "github-actions"];
81
+ var PROVIDER_KINDS = ["cloudflare-account-token"];
82
82
  function destinationId(target, secretName) {
83
83
  return `${placeId(target)}:${secretName}`;
84
84
  }
@@ -243,7 +243,7 @@ function validateEnv(raw, vaults, fail) {
243
243
  failed = true;
244
244
  fail(message);
245
245
  };
246
- unknownFields(raw, ["vault", "item", "publish"], (field) => err(`unknown field "${field}"`));
246
+ unknownFields(raw, ["vault", "item", "publish", "issue"], (field) => err(`unknown field "${field}"`));
247
247
  const vaultName = requiredString(raw, "vault", err);
248
248
  const item = requiredString(raw, "item", err);
249
249
  const vault = vaultName === undefined ? undefined : vaults.get(vaultName);
@@ -269,9 +269,36 @@ function validateEnv(raw, vaults, fail) {
269
269
  });
270
270
  }
271
271
  }
272
+ const issue = raw.issue === undefined || !vault || item === undefined ? undefined : validateIssue(raw.issue, vault, item, (m) => err(`issue: ${m}`));
272
273
  if (failed || !vault || item === undefined)
273
274
  return;
274
- return { ref: { ...vault, item }, publish };
275
+ return { ref: { ...vault, item }, publish, ...issue ? { issue } : {} };
276
+ }
277
+ var ACCOUNT_ID = /^[0-9a-f]{32}$/;
278
+ function validateIssue(raw, vault, item, fail) {
279
+ if (!isRecord(raw)) {
280
+ fail("must be a table");
281
+ return;
282
+ }
283
+ let failed = false;
284
+ const err = (message) => {
285
+ failed = true;
286
+ fail(message);
287
+ };
288
+ unknownFields(raw, ["provider", "account", "admin"], (field) => err(`unknown field "${field}"`));
289
+ const provider = requiredString(raw, "provider", err);
290
+ const account = requiredString(raw, "account", err);
291
+ const admin = requiredString(raw, "admin", err);
292
+ const kind = PROVIDER_KINDS.find((known) => known === provider);
293
+ if (provider !== undefined && !kind)
294
+ err(`field "provider" must be one of: ${PROVIDER_KINDS.join(", ")}`);
295
+ if (account !== undefined && !ACCOUNT_ID.test(account))
296
+ err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
297
+ if (admin !== undefined && admin === item)
298
+ err(`field "admin" names the key's own item; the admin token needs its own item`);
299
+ if (failed || !kind || account === undefined || admin === undefined)
300
+ return;
301
+ return { provider: kind, account, admin: { ...vault, item: admin } };
275
302
  }
276
303
  function validateTarget(raw, fail) {
277
304
  if (!isRecord(raw)) {
@@ -326,6 +353,26 @@ function requiredString(table, field, fail) {
326
353
  function optionalString(table, field, fail) {
327
354
  return table[field] === undefined ? undefined : requiredString(table, field, fail);
328
355
  }
356
+ // ../../packages/core/src/tokens.ts
357
+ function sameAccess(a, b) {
358
+ return canonical(a.policies.map(policyShape)) === canonical(b.policies.map(policyShape)) && canonical(a.condition ?? {}) === canonical(b.condition ?? {});
359
+ }
360
+ function policyShape(policy) {
361
+ return {
362
+ effect: policy.effect,
363
+ resources: policy.resources,
364
+ groups: policy.permissionGroups.map((group) => group.id)
365
+ };
366
+ }
367
+ function canonical(value) {
368
+ if (Array.isArray(value))
369
+ return `[${value.map(canonical).toSorted().join(",")}]`;
370
+ if (isRecord(value)) {
371
+ const entries = Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : 1).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item ?? null)}`);
372
+ return `{${entries.join(",")}}`;
373
+ }
374
+ return JSON.stringify(value);
375
+ }
329
376
  // ../../packages/core/src/files.ts
330
377
  async function writeJsonAtomic(files, path, data) {
331
378
  const temporary = `${path}.${crypto.randomUUID()}.tmp`;
@@ -531,7 +578,48 @@ function sameRef(a, b) {
531
578
  function describeRef(ref) {
532
579
  return `item "${ref.item}" (1Password account ${ref.account}, vault "${ref.vault}")`;
533
580
  }
581
+ // ../../packages/core/src/rotations.ts
582
+ var ROTATIONS_VERSION = 1;
583
+ var ROTATION_STAGES = ["issuing", "issued", "stored", "published", "revoked"];
584
+ var emptyRotations = () => ({ version: ROTATIONS_VERSION, rotations: [] });
585
+ async function loadRotations(files, path) {
586
+ const data = await readVersionedJson(files, path, [ROTATIONS_VERSION], "rotations file");
587
+ if (!data)
588
+ return emptyRotations();
589
+ const { rotations } = data;
590
+ if (!Array.isArray(rotations) || !rotations.every(isRotation)) {
591
+ throw new Error(`${path}: the rotations file's "rotations" must be a list of rotations`);
592
+ }
593
+ return { version: ROTATIONS_VERSION, rotations };
594
+ }
595
+ async function saveRotations(files, path, data) {
596
+ await writeJsonAtomic(files, path, data);
597
+ }
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");
600
+ }
601
+ function rotateCommand(keyId, environment) {
602
+ return `keypin rotate ${keyId}${environment === "prod" ? "" : ` --env ${environment}`}`;
603
+ }
604
+ function putRotation(data, rotation) {
605
+ return {
606
+ ...data,
607
+ rotations: [...data.rotations.filter((r) => r.id !== rotation.id), rotation]
608
+ };
609
+ }
610
+ function dropRotation(data, id) {
611
+ return { ...data, rotations: data.rotations.filter((r) => r.id !== id) };
612
+ }
613
+ var isText2 = (value) => typeof value === "string";
614
+ var isTextOrNull = (value) => value === null || typeof value === "string";
615
+ function isTokenRecord(t) {
616
+ return isRecord(t) && isText2(t.name) && [t.id, t.expiresOn, t.generation].every(isTextOrNull);
617
+ }
618
+ 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);
620
+ }
534
621
  // ../../packages/core/src/status.ts
622
+ var NOTICES = ["due-soon", "authority-unknown", "rotation-unfinished"];
535
623
  function buildStatus(input) {
536
624
  if (!isDay(input.today))
537
625
  throw new Error(`today must be YYYY-MM-DD, got "${input.today}"`);
@@ -568,7 +656,7 @@ function buildStatus(input) {
568
656
  const label = `${key.id} (${environment})`;
569
657
  const add = (kind, message, extra = {}) => problems.push({
570
658
  kind,
571
- severity: kind === "due-soon" || kind === "authority-unknown" ? "notice" : "problem",
659
+ severity: NOTICES.includes(kind) ? "notice" : "problem",
572
660
  ...where,
573
661
  ...extra,
574
662
  message
@@ -604,6 +692,10 @@ function buildStatus(input) {
604
692
  stale
605
693
  };
606
694
  });
695
+ const rotation = unfinishedRotation({ version: 1, rotations: [...input.rotations ?? []] }, key.id, environment, entry.ref);
696
+ if (rotation) {
697
+ add("rotation-unfinished", `${label}: a rotation started ${rotation.startedAt} is at stage "${rotation.stage}"; run ${rotateCommand(key.id, environment)} to continue`);
698
+ }
607
699
  rows.push({
608
700
  ...where,
609
701
  env: key.env,
@@ -695,7 +787,7 @@ function refresh() {
695
787
 
696
788
  // ../../packages/destination-cloudflare/src/cloudflare.ts
697
789
  var API = "https://api.cloudflare.com/client/v4";
698
- var ACCOUNT_ID = /^[0-9a-f]{32}$/;
790
+ var ACCOUNT_ID2 = /^[0-9a-f]{32}$/;
699
791
  var WORKER = /^[A-Za-z0-9_-]+$/;
700
792
 
701
793
  class WorkerSecretDestination {
@@ -707,7 +799,7 @@ class WorkerSecretDestination {
707
799
  #token;
708
800
  #passed = false;
709
801
  constructor(options) {
710
- if (!ACCOUNT_ID.test(options.account))
802
+ if (!ACCOUNT_ID2.test(options.account))
711
803
  throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
712
804
  if (!WORKER.test(options.worker))
713
805
  throw new Error(`"${options.worker}" isn't a Worker name`);
@@ -993,6 +1085,172 @@ function stringField(data, field) {
993
1085
  throw new Error(`GitHub's response has no "${field}"`);
994
1086
  return value;
995
1087
  }
1088
+ // ../../packages/provider-cloudflare/src/tokens.ts
1089
+ var API3 = "https://api.cloudflare.com/client/v4";
1090
+ var ACCOUNT_ID3 = /^[0-9a-f]{32}$/;
1091
+ var TOKEN_ID = /^[0-9a-f]{32}$/;
1092
+
1093
+ class CloudflareAccountTokens {
1094
+ #account;
1095
+ #admin;
1096
+ #fetch;
1097
+ constructor(options) {
1098
+ if (!ACCOUNT_ID3.test(options.account))
1099
+ throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
1100
+ this.#account = options.account;
1101
+ this.#admin = options.admin;
1102
+ this.#fetch = options.fetch ?? globalThis.fetch;
1103
+ }
1104
+ describe() {
1105
+ return `Cloudflare account API tokens in account ${this.#account}`;
1106
+ }
1107
+ async verify(secret) {
1108
+ const path = `${this.#base()}/verify`;
1109
+ const reply = await this.#request("GET", path, secret);
1110
+ if (reply.status !== 200)
1111
+ throw failure2("GET", path, reply);
1112
+ const result = objectField3(reply.body, "result");
1113
+ return {
1114
+ id: tokenId(result.id, "verify"),
1115
+ status: text(result.status, "status"),
1116
+ expiresOn: optionalText(result.expires_on)
1117
+ };
1118
+ }
1119
+ async details(id) {
1120
+ const path = `${this.#base()}/${tokenId(id, "details")}`;
1121
+ const reply = await this.#request("GET", path, this.#admin);
1122
+ if (reply.status === 404)
1123
+ return null;
1124
+ if (reply.status !== 200)
1125
+ throw failure2("GET", path, reply);
1126
+ return token(objectField3(reply.body, "result"));
1127
+ }
1128
+ async issue(request) {
1129
+ const path = this.#base();
1130
+ const body = {
1131
+ name: request.name,
1132
+ policies: request.like.policies.map((policy) => ({
1133
+ effect: policy.effect,
1134
+ resources: policy.resources,
1135
+ permission_groups: policy.permissionGroups.map((group) => ({ id: group.id }))
1136
+ })),
1137
+ expires_on: request.expiresOn
1138
+ };
1139
+ if (request.like.condition)
1140
+ body.condition = request.like.condition;
1141
+ const reply = await this.#request("POST", path, this.#admin, body);
1142
+ if (reply.status >= 400 && reply.status < 500)
1143
+ return { refused: failure2("POST", path, reply).message };
1144
+ if (reply.status !== 200)
1145
+ throw failure2("POST", path, reply);
1146
+ const result = objectField3(reply.body, "result");
1147
+ const value = result.value;
1148
+ if (typeof value !== "string" || !value)
1149
+ throw new Error("Cloudflare's create response has no token value");
1150
+ return { token: token(result), value: new Secret(value) };
1151
+ }
1152
+ async revoke(id) {
1153
+ const path = `${this.#base()}/${tokenId(id, "revoke")}`;
1154
+ const reply = await this.#request("DELETE", path, this.#admin);
1155
+ if (reply.status === 404)
1156
+ return "already gone";
1157
+ if (reply.status !== 200)
1158
+ throw failure2("DELETE", path, reply);
1159
+ return "revoked";
1160
+ }
1161
+ #base() {
1162
+ return `/accounts/${this.#account}/tokens`;
1163
+ }
1164
+ async#request(method, path, auth, body) {
1165
+ const response = await this.#fetch(`${API3}${path}`, {
1166
+ method,
1167
+ headers: {
1168
+ Authorization: `Bearer ${auth.reveal()}`,
1169
+ ...body === undefined ? {} : { "Content-Type": "application/json" }
1170
+ },
1171
+ body: body === undefined ? undefined : JSON.stringify(body)
1172
+ });
1173
+ return { status: response.status, body: parseObject3(await response.text()) };
1174
+ }
1175
+ }
1176
+ function token(result) {
1177
+ const policies = result.policies;
1178
+ if (!Array.isArray(policies))
1179
+ throw new Error("Cloudflare's token has no policies list");
1180
+ const condition = result.condition;
1181
+ return {
1182
+ id: tokenId(result.id, "token"),
1183
+ name: text(result.name, "name"),
1184
+ status: text(result.status, "status"),
1185
+ expiresOn: optionalText(result.expires_on),
1186
+ lastUsedOn: optionalText(result.last_used_on),
1187
+ policies: policies.map(policy),
1188
+ condition: isJsonObject(condition) && Object.keys(condition).length ? condition : null
1189
+ };
1190
+ }
1191
+ function policy(raw) {
1192
+ if (!isRecord(raw))
1193
+ throw new Error("a Cloudflare token policy isn't an object");
1194
+ const resources = raw.resources;
1195
+ const groups = raw.permission_groups;
1196
+ if (!isJsonObject(resources))
1197
+ throw new Error("a Cloudflare token policy has no resources");
1198
+ if (!Array.isArray(groups))
1199
+ throw new Error("a Cloudflare token policy has no permission groups");
1200
+ return {
1201
+ effect: text(raw.effect, "effect"),
1202
+ resources,
1203
+ permissionGroups: groups.map((group) => {
1204
+ if (!isRecord(group))
1205
+ throw new Error("a Cloudflare permission group isn't an object");
1206
+ return {
1207
+ id: text(group.id, "permission group id"),
1208
+ name: typeof group.name === "string" ? group.name : "(unnamed)"
1209
+ };
1210
+ })
1211
+ };
1212
+ }
1213
+ function isJson(value) {
1214
+ if (value === null || ["string", "number", "boolean"].includes(typeof value))
1215
+ return true;
1216
+ if (Array.isArray(value))
1217
+ return value.every(isJson);
1218
+ return isJsonObject(value);
1219
+ }
1220
+ function isJsonObject(value) {
1221
+ return isRecord(value) && Object.values(value).every(isJson);
1222
+ }
1223
+ function tokenId(value, where) {
1224
+ if (typeof value !== "string" || !TOKEN_ID.test(value))
1225
+ throw new Error(`Cloudflare's ${where} response has no valid token ID`);
1226
+ return value;
1227
+ }
1228
+ function text(value, field) {
1229
+ if (typeof value !== "string")
1230
+ throw new Error(`Cloudflare's token has no "${field}"`);
1231
+ return value;
1232
+ }
1233
+ function optionalText(value) {
1234
+ return typeof value === "string" && value ? value : null;
1235
+ }
1236
+ function failure2(method, path, reply) {
1237
+ const errors = reply.body.errors;
1238
+ const codes = Array.isArray(errors) ? errors.map((e) => isRecord(e) ? e.code : undefined).filter((c) => typeof c === "string" || typeof c === "number") : [];
1239
+ const detail = codes.length ? `, codes ${codes.join(", ")}` : "";
1240
+ return new Error(`Cloudflare ${method} ${path.split("?")[0]} returned HTTP ${reply.status}${detail}`);
1241
+ }
1242
+ function parseObject3(body) {
1243
+ try {
1244
+ const data = JSON.parse(body);
1245
+ return isRecord(data) ? data : {};
1246
+ } catch {
1247
+ return {};
1248
+ }
1249
+ }
1250
+ function objectField3(data, field) {
1251
+ const value = data[field];
1252
+ return isRecord(value) ? value : {};
1253
+ }
996
1254
  // ../../packages/vault-1password/src/sdk.ts
997
1255
  var desktopConnect = async (account) => {
998
1256
  const sdk = await import("@1password/sdk");
@@ -1083,14 +1341,14 @@ function onePasswordBackend(connect = desktopConnect) {
1083
1341
  const id = await vaultId(sdk, ref);
1084
1342
  const found = await find(sdk, id, ref);
1085
1343
  if (!found) {
1086
- const fields2 = [passwordField(secret)];
1344
+ const fields = [passwordField(secret)];
1087
1345
  if (rotated)
1088
- fields2.push(rotatedField(rotated));
1346
+ fields.push(rotatedField(rotated));
1089
1347
  await sdk.items.create({
1090
1348
  category: "Password",
1091
1349
  vaultId: id,
1092
1350
  title: ref.item,
1093
- fields: fields2
1351
+ fields
1094
1352
  });
1095
1353
  return;
1096
1354
  }
@@ -1184,7 +1442,7 @@ function localDay(date) {
1184
1442
  }
1185
1443
 
1186
1444
  // src/paths.ts
1187
- import { join as join2 } from "path";
1445
+ import { dirname, join as join2 } from "path";
1188
1446
  function registryPath(deps) {
1189
1447
  return join2(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
1190
1448
  }
@@ -1198,12 +1456,15 @@ function projectCount(registry, path) {
1198
1456
  const count = registry.projects.length;
1199
1457
  return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
1200
1458
  }
1459
+ function rotationsPath(deps) {
1460
+ return join2(dirname(statePath(deps)), "rotations.json");
1461
+ }
1201
1462
 
1202
1463
  // src/project.ts
1203
- import { dirname, join as join3 } from "path";
1464
+ import { dirname as dirname2, join as join3 } from "path";
1204
1465
  var MAP_FILE = "keypin.toml";
1205
1466
  async function findMap(files, cwd) {
1206
- for (let folder = cwd;; folder = dirname(folder)) {
1467
+ for (let folder = cwd;; folder = dirname2(folder)) {
1207
1468
  const file = join3(folder, MAP_FILE);
1208
1469
  const text = await files.read(file);
1209
1470
  if (text !== null) {
@@ -1213,7 +1474,7 @@ async function findMap(files, cwd) {
1213
1474
  `));
1214
1475
  return result.map;
1215
1476
  }
1216
- if (dirname(folder) === folder) {
1477
+ if (dirname2(folder) === folder) {
1217
1478
  throw new Error(`no ${MAP_FILE} in ${cwd} or any folder above it; run "keypin init" first`);
1218
1479
  }
1219
1480
  }
@@ -1278,16 +1539,132 @@ async function init(args, deps) {
1278
1539
  // src/commands/publish.ts
1279
1540
  import { parseArgs as parseArgs2 } from "util";
1280
1541
 
1542
+ // src/publishing.ts
1543
+ var NEEDS_APPROVAL = 2;
1544
+ async function locked(deps, body) {
1545
+ const path = statePath(deps);
1546
+ const lockFile = `${path}.lock`;
1547
+ const taken = await deps.lock(lockFile);
1548
+ if (!taken.held) {
1549
+ deps.stderr.write(`${lockedMessage(lockFile, taken.holder)}
1550
+ `);
1551
+ return 1;
1552
+ }
1553
+ try {
1554
+ return await body(path);
1555
+ } finally {
1556
+ await taken.lock.release();
1557
+ }
1558
+ }
1559
+ function lockedMessage(file, holder) {
1560
+ if (holder.pid === null) {
1561
+ return `keypin: ${file} exists but names no process. If no publish or rotate is running, delete that file and try again.`;
1562
+ }
1563
+ if (holder.running === false) {
1564
+ return `keypin: ${file} was left by process ${holder.pid}, which isn't running any more. Delete that file and try again.`;
1565
+ }
1566
+ return `keypin: another publish or rotate (process ${holder.pid}) holds ${file} and is still running. Wait for it to finish.`;
1567
+ }
1568
+ async function checkAccounts(key, entry, deps, say) {
1569
+ say(`
1570
+ Account checks:`);
1571
+ const checked = new Map;
1572
+ let failed = false;
1573
+ for (const target of entry.publish) {
1574
+ const label = describeTarget(target, key.env);
1575
+ try {
1576
+ const destination = deps.destination(target);
1577
+ const check = await destination.checkAccount();
1578
+ checked.set(destinationId(target, key.env), { target, destination, check });
1579
+ say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
1580
+ if (!check.ok)
1581
+ failed = true;
1582
+ } catch (error) {
1583
+ say(` FAILED ${label}: ${messageOf(error)}`);
1584
+ failed = true;
1585
+ }
1586
+ }
1587
+ return failed ? null : checked;
1588
+ }
1589
+ function writesFor(steps, checked) {
1590
+ return steps.flatMap((step) => {
1591
+ if (step.action !== "write")
1592
+ return [];
1593
+ const found = checked.get(step.destinationId);
1594
+ if (!found)
1595
+ throw new Error(`no account check for ${step.destinationId}`);
1596
+ return [{ destinationId: step.destinationId, found }];
1597
+ });
1598
+ }
1599
+ async function writeAll(input) {
1600
+ const { key, environment, entry, secret, generation, writes, path, deps, say } = input;
1601
+ const id = crypto.randomUUID();
1602
+ let state = startOperation(input.state, {
1603
+ id,
1604
+ keyId: key.id,
1605
+ environment,
1606
+ generation,
1607
+ startedAt: deps.now().toISOString(),
1608
+ planned: writes.map((w) => w.destinationId)
1609
+ });
1610
+ await saveState(deps.files, path, state);
1611
+ for (const { destinationId: written, found } of writes) {
1612
+ const label = describeTarget(found.target, key.env);
1613
+ try {
1614
+ const evidence = await found.destination.write(key.env, secret);
1615
+ state = recordReceipt(state, {
1616
+ keyId: key.id,
1617
+ environment,
1618
+ source: entry.ref,
1619
+ destinationId: written,
1620
+ generation,
1621
+ account: {
1622
+ pinned: found.target.account,
1623
+ publisher: found.check.publisher,
1624
+ destinationAccount: found.check.destinationAccount ?? found.target.account
1625
+ },
1626
+ at: deps.now().toISOString(),
1627
+ evidence
1628
+ }, id);
1629
+ await saveState(deps.files, path, state);
1630
+ say(` wrote ${label}`);
1631
+ } catch (error) {
1632
+ say(` FAILED ${label}: ${messageOf(error)}`);
1633
+ return { ok: false, state };
1634
+ }
1635
+ }
1636
+ state = finishAll(state, key.id, environment);
1637
+ await saveState(deps.files, path, state);
1638
+ return { ok: true, state };
1639
+ }
1640
+ function finishAll(state, keyId, environment) {
1641
+ return unfinishedOperations(state, keyId, environment).reduce((s, op) => finishOperation(s, op.id), state);
1642
+ }
1643
+ function rerun(deps, command, args) {
1644
+ const words = [...deps.self, command, ...args].map(shellWord).join(" ");
1645
+ return `To approve, run this in a terminal:
1646
+ cd ${shellWord(deps.cwd)} && ${words}`;
1647
+ }
1648
+ function shellWord(word) {
1649
+ return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
1650
+ }
1651
+ function accountFacts(check) {
1652
+ return `publisher ${check.publisher}, destination account ${check.destinationAccount ?? "unknown"}`;
1653
+ }
1654
+ function describeTarget(target, secretName) {
1655
+ return `${destinationId(target, secretName)} (account ${target.account})`;
1656
+ }
1657
+
1281
1658
  // src/vault.ts
1282
1659
  function announce(stderr, what, refs) {
1283
1660
  const groups = new Map;
1284
1661
  for (const ref of refs) {
1285
- const where2 = `1Password account ${ref.account}, vault "${ref.vault}"`;
1286
- groups.set(where2, (groups.get(where2) ?? new Set).add(ref.item));
1662
+ const where = `1Password account ${ref.account}, vault "${ref.vault}"`;
1663
+ groups.set(where, (groups.get(where) ?? new Set).add(ref.item));
1287
1664
  }
1288
- for (const [where2, items] of groups) {
1665
+ for (const [where, items] of groups) {
1289
1666
  const names = [...items].map((item) => `"${item}"`).join(", ");
1290
- stderr.write(`keypin: reading ${what} from ${where2}: ${names}
1667
+ stderr.write(`keypin: reading ${what} from ${where}: ${names}
1291
1668
  `);
1292
1669
  }
1293
1670
  }
@@ -1301,32 +1678,10 @@ function distinctRefs(refs) {
1301
1678
  var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item]);
1302
1679
 
1303
1680
  // src/commands/publish.ts
1304
- var NEEDS_APPROVAL = 2;
1305
1681
  async function publish(args, deps) {
1306
1682
  const request = parseRequest(args);
1307
1683
  const map = await findMap(deps.files, deps.cwd);
1308
- const path = statePath(deps);
1309
- const lockFile = `${path}.lock`;
1310
- const taken = await deps.lock(lockFile);
1311
- if (!taken.held) {
1312
- deps.stderr.write(`${lockedMessage(lockFile, taken.holder)}
1313
- `);
1314
- return 1;
1315
- }
1316
- try {
1317
- return await publishLocked({ ...request, args }, map, path, deps);
1318
- } finally {
1319
- await taken.lock.release();
1320
- }
1321
- }
1322
- function lockedMessage(file, holder) {
1323
- if (holder.pid === null) {
1324
- return `keypin: ${file} exists but names no process. If no publish is running, delete that file and try again.`;
1325
- }
1326
- if (holder.running === false) {
1327
- return `keypin: ${file} was left by process ${holder.pid}, which isn't running any more. Delete that file and try again.`;
1328
- }
1329
- return `keypin: another publish (process ${holder.pid}) holds ${file} and is still running. Wait for it to finish.`;
1684
+ return locked(deps, (path) => publishLocked({ ...request, args }, map, path, deps));
1330
1685
  }
1331
1686
  function parseRequest(args) {
1332
1687
  const { values, positionals } = parseArgs2({
@@ -1364,29 +1719,12 @@ async function publishLocked(request, map, path, deps) {
1364
1719
  say(`The map lists no destinations for ${keyId} (${environment}); nothing to publish.`);
1365
1720
  return 1;
1366
1721
  }
1367
- let state = await loadState(deps.files, path);
1722
+ const state = await loadState(deps.files, path);
1368
1723
  for (const op of unfinishedOperations(state, keyId, environment)) {
1369
1724
  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.`);
1370
1725
  }
1371
- say(`
1372
- Account checks:`);
1373
- const checked = new Map;
1374
- let failed = false;
1375
- for (const target of entry.publish) {
1376
- const label = describeTarget(target, key.env);
1377
- try {
1378
- const destination = deps.destination(target);
1379
- const check = await destination.checkAccount();
1380
- checked.set(destinationId(target, key.env), { target, destination, check });
1381
- say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
1382
- if (!check.ok)
1383
- failed = true;
1384
- } catch (error) {
1385
- say(` FAILED ${label}: ${messageOf(error)}`);
1386
- failed = true;
1387
- }
1388
- }
1389
- if (failed) {
1726
+ const checked = await checkAccounts(key, entry, deps, say);
1727
+ if (!checked) {
1390
1728
  say("Stopped: an account check failed. Nothing was read and nothing was written.");
1391
1729
  return 1;
1392
1730
  }
@@ -1397,7 +1735,7 @@ Needs approval:`);
1397
1735
  for (const approval of approvals)
1398
1736
  say(` ${approval.approval}`);
1399
1737
  say(`Stopped before reading the value: this publish needs approval, and --yes can't give it. Nothing was read and nothing was written.`);
1400
- say(rerun(deps, request.args));
1738
+ say(rerun(deps, "publish", request.args));
1401
1739
  return NEEDS_APPROVAL;
1402
1740
  }
1403
1741
  announce(deps.stderr, "the value to publish", [entry.ref]);
@@ -1412,17 +1750,14 @@ Needs approval:`);
1412
1750
  const plan = planPublish({ key, environment, receipts: state.receipts, generation });
1413
1751
  say(`
1414
1752
  Plan for generation ${generation}:`);
1415
- const writes = [];
1753
+ const writes = writesFor(plan.steps, checked);
1416
1754
  for (const step of plan.steps) {
1417
1755
  const found = checked.get(step.destinationId);
1418
- if (!found)
1419
- throw new Error(`no account check for ${step.destinationId}`);
1420
1756
  say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
1421
- say(` ${accountFacts(found.check)}`);
1757
+ if (found)
1758
+ say(` ${accountFacts(found.check)}`);
1422
1759
  if (step.approval)
1423
1760
  say(` needs approval: ${step.approval}`);
1424
- if (step.action === "write")
1425
- writes.push({ destinationId: step.destinationId, found });
1426
1761
  }
1427
1762
  for (const removed of plan.removed) {
1428
1763
  say(` not in the map any more: ${removed.destinationId} (last got ${removed.lastReceipt.generation} at ${removed.lastReceipt.at}). keypin doesn't delete it.`);
@@ -1436,44 +1771,22 @@ Plan for generation ${generation}:`);
1436
1771
  }
1437
1772
  if (!await confirmed(deps, plan.needsApproval, request))
1438
1773
  return NEEDS_APPROVAL;
1439
- const id = crypto.randomUUID();
1440
- state = startOperation(state, {
1441
- id,
1442
- keyId,
1774
+ const written = await writeAll({
1775
+ key,
1443
1776
  environment,
1777
+ entry,
1778
+ secret,
1444
1779
  generation,
1445
- startedAt: deps.now().toISOString(),
1446
- planned: writes.map((w) => w.destinationId)
1780
+ writes,
1781
+ state,
1782
+ path,
1783
+ deps,
1784
+ say
1447
1785
  });
1448
- await saveState(deps.files, path, state);
1449
- for (const { destinationId: written, found } of writes) {
1450
- const label = describeTarget(found.target, key.env);
1451
- try {
1452
- const evidence = await found.destination.write(key.env, secret);
1453
- state = recordReceipt(state, {
1454
- keyId,
1455
- environment,
1456
- source: entry.ref,
1457
- destinationId: written,
1458
- generation,
1459
- account: {
1460
- pinned: found.target.account,
1461
- publisher: found.check.publisher,
1462
- destinationAccount: found.check.destinationAccount ?? found.target.account
1463
- },
1464
- at: deps.now().toISOString(),
1465
- evidence
1466
- }, id);
1467
- await saveState(deps.files, path, state);
1468
- say(` wrote ${label}`);
1469
- } catch (error) {
1470
- say(` FAILED ${label}: ${messageOf(error)}`);
1471
- say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
1472
- return 1;
1473
- }
1786
+ if (!written.ok) {
1787
+ say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
1788
+ return 1;
1474
1789
  }
1475
- state = finishAll(state, keyId, environment);
1476
- await saveState(deps.files, path, state);
1477
1790
  say(`Published ${keyId} (${environment}) to ${writes.length} destination(s).`);
1478
1791
  return 0;
1479
1792
  }
@@ -1490,31 +1803,498 @@ async function confirmed(deps, needsApproval, request) {
1490
1803
  return false;
1491
1804
  }
1492
1805
  say(needsApproval ? "Stopped: this plan needs approval, and --yes can't give it. Nothing was written." : "Stopped: no terminal to confirm on. Nothing was written. Add --yes, or confirm in a terminal.");
1493
- say(rerun(deps, request.args));
1806
+ say(rerun(deps, "publish", request.args));
1494
1807
  return false;
1495
1808
  }
1496
- function rerun(deps, args) {
1497
- const command = [...deps.self, "publish", ...args].map(shellWord).join(" ");
1498
- return `To approve, run this in a terminal:
1499
- cd ${shellWord(deps.cwd)} && ${command}`;
1809
+
1810
+ // src/commands/rotate.ts
1811
+ import { parseArgs as parseArgs3 } from "util";
1812
+ var GRACE_DAYS = DUE_SOON_DAYS;
1813
+ async function rotate(args, deps) {
1814
+ const { values, positionals } = parseArgs3({
1815
+ args,
1816
+ options: {
1817
+ env: { type: "string", default: "prod" },
1818
+ yes: { type: "boolean", default: false }
1819
+ },
1820
+ allowPositionals: true
1821
+ });
1822
+ const [keyId, ...extra] = positionals;
1823
+ if (keyId === undefined || extra.length)
1824
+ throw new UsageError("keypin rotate takes one key ID");
1825
+ const environment = ENVIRONMENTS.find((name) => name === values.env);
1826
+ if (!environment) {
1827
+ throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
1828
+ }
1829
+ const map = await findMap(deps.files, deps.cwd);
1830
+ const key = map.keys.find((k) => k.id === keyId);
1831
+ if (!key)
1832
+ throw new Error(`${map.file} has no key "${keyId}"`);
1833
+ const entry = key.environments[environment];
1834
+ if (!entry)
1835
+ throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
1836
+ const issue = entry.issue;
1837
+ if (!issue) {
1838
+ throw new Error(`key "${keyId}" has no [keys.${keyId}.${environment}.issue] section in ${map.file}, so keypin can't make a new value`);
1839
+ }
1840
+ const say = (text) => deps.stderr.write(`${text}
1841
+ `);
1842
+ return locked(deps, async (statePath) => {
1843
+ const run = {
1844
+ key,
1845
+ entry,
1846
+ issue,
1847
+ environment,
1848
+ yes: values.yes,
1849
+ args,
1850
+ statePath,
1851
+ rotationsPath: rotationsPath(deps),
1852
+ deps,
1853
+ say
1854
+ };
1855
+ const data = await loadRotations(deps.files, run.rotationsPath);
1856
+ const open = unfinishedRotation(data, key.id, environment, entry.ref);
1857
+ if (!open)
1858
+ return start(run, data);
1859
+ say(`An unfinished rotation of ${key.id} (${environment}), started ${open.startedAt}, is at stage "${open.stage}".`);
1860
+ if (open.provider !== issue.provider || open.account !== issue.account) {
1861
+ 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.`);
1862
+ return 1;
1863
+ }
1864
+ switch (open.stage) {
1865
+ case "issuing":
1866
+ case "issued":
1867
+ return abandon(run, data, open);
1868
+ case "stored":
1869
+ return publishNew(run, data, open, null);
1870
+ case "published":
1871
+ return revokeOld(run, data, open);
1872
+ case "revoked":
1873
+ throw new Error(`rotation ${open.id} is finished`);
1874
+ }
1875
+ });
1500
1876
  }
1501
- function shellWord(word) {
1502
- return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
1877
+ async function start(run, data) {
1878
+ const { key, entry, issue, environment, deps, say } = run;
1879
+ say(`Rotating ${key.id} (${environment}) as ${key.env}, item "${entry.ref.item}"`);
1880
+ say(` vault: 1Password account ${entry.ref.account}, vault "${entry.ref.vault}"`);
1881
+ say(` new token: ${issue.provider} in account ${issue.account}, made with the admin token in item "${issue.admin.item}"`);
1882
+ for (const target of entry.publish)
1883
+ say(` to: ${describeTarget(target, key.env)}`);
1884
+ if (!entry.publish.length) {
1885
+ say(`Stopped: the map lists no destinations for ${key.id} (${environment}), so nothing would get the new token. Nothing was changed.`);
1886
+ return 1;
1887
+ }
1888
+ const state = await loadState(deps.files, run.statePath);
1889
+ const checked = await checkAccounts(key, entry, deps, say);
1890
+ if (!checked) {
1891
+ say("Stopped: an account check failed. Nothing was read and nothing was changed.");
1892
+ return 1;
1893
+ }
1894
+ const approvals = approvalsFor({ key, environment, receipts: state.receipts });
1895
+ if (!deps.isTerminal && (approvals.length || !run.yes)) {
1896
+ for (const approval of approvals)
1897
+ say(` needs approval: ${approval.approval}`);
1898
+ say(approvals.length ? "Stopped before reading anything: this rotation needs approval, and --yes can't give it. Nothing was changed." : "Stopped before reading anything: no terminal to confirm on. Nothing was changed. Add --yes, or confirm in a terminal.");
1899
+ say(rerun(deps, "rotate", run.args));
1900
+ return NEEDS_APPROVAL;
1901
+ }
1902
+ announce(deps.stderr, "the current value, its rotation fields and the admin token", [
1903
+ entry.ref,
1904
+ issue.admin
1905
+ ]);
1906
+ const vault = deps.vault();
1907
+ let current;
1908
+ let admin;
1909
+ let every;
1910
+ try {
1911
+ current = await vault.read(entry.ref);
1912
+ every = key.rotateEvery ?? (await vault.metadata(entry.ref)).rotateEvery;
1913
+ admin = await vault.read(issue.admin);
1914
+ } catch (error) {
1915
+ say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
1916
+ return 1;
1917
+ }
1918
+ const days = periodDays(every);
1919
+ if (!days) {
1920
+ say(`Stopped: rotate needs a rotation period to set the new token's expiry, and rotate_every is ${every ? `"${every}"` : "missing"}. Nothing was changed.`);
1921
+ return 1;
1922
+ }
1923
+ const provider = deps.provider(issue, admin);
1924
+ const found = await provider.verify(current);
1925
+ if (found.status !== "active") {
1926
+ say(`Stopped: the current value is token ${found.id}, and it's ${found.status}. Nothing was changed.`);
1927
+ return 1;
1928
+ }
1929
+ const old = await provider.details(found.id);
1930
+ if (!old) {
1931
+ say(`Stopped: the admin token can't read token ${found.id}, the current value's token. Nothing was changed.`);
1932
+ return 1;
1933
+ }
1934
+ const today = localDay(deps.now());
1935
+ const name = nextName(old.name, today);
1936
+ const expiresOn = `${addDays(today, days + GRACE_DAYS)}T23:59:59Z`;
1937
+ say(`
1938
+ Plan:`);
1939
+ say(` current token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "never"}`);
1940
+ say(` new token: "${name}", expires ${expiresOn} (rotate_every ${every} plus ${GRACE_DAYS} days' grace)`);
1941
+ for (const line of describeAccess(old))
1942
+ say(` ${line}`);
1943
+ say(` store in: item "${entry.ref.item}", with rotated ${today}`);
1944
+ for (const target of entry.publish) {
1945
+ const found = checked.get(destinationId(target, key.env));
1946
+ say(` publish to: ${describeTarget(target, key.env)}`);
1947
+ if (found)
1948
+ say(` ${accountFacts(found.check)}`);
1949
+ }
1950
+ for (const approval of approvals)
1951
+ say(` needs approval: ${approval.approval}`);
1952
+ say(` then stop: the old token stays active until you run ${again(run)} again.`);
1953
+ if (!await confirmed2(run, approvals.length > 0, "make the new token"))
1954
+ return NEEDS_APPROVAL;
1955
+ const now = deps.now().toISOString();
1956
+ let rotation = {
1957
+ id: crypto.randomUUID(),
1958
+ keyId: key.id,
1959
+ environment,
1960
+ item: entry.ref,
1961
+ provider: issue.provider,
1962
+ account: issue.account,
1963
+ stage: "issuing",
1964
+ startedAt: now,
1965
+ updatedAt: now,
1966
+ old: {
1967
+ id: old.id,
1968
+ name: old.name,
1969
+ expiresOn: old.expiresOn,
1970
+ generation: await generationOf(current)
1971
+ },
1972
+ new: { id: null, name, expiresOn, generation: null }
1973
+ };
1974
+ data = putRotation(withoutFinished(data, key.id, environment), rotation);
1975
+ await saveRotations(deps.files, run.rotationsPath, data);
1976
+ const made = await provider.issue({ name, like: old, expiresOn });
1977
+ if ("refused" in made) {
1978
+ await saveRotations(deps.files, run.rotationsPath, dropRotation(data, rotation.id));
1979
+ say(`Stopped: ${made.refused}. No token was made, and nothing was changed.`);
1980
+ return 1;
1981
+ }
1982
+ const generation = await generationOf(made.value);
1983
+ rotation = {
1984
+ ...rotation,
1985
+ stage: "issued",
1986
+ updatedAt: deps.now().toISOString(),
1987
+ new: { id: made.token.id, name: made.token.name, expiresOn: made.token.expiresOn, generation }
1988
+ };
1989
+ data = putRotation(data, rotation);
1990
+ await saveRotations(deps.files, run.rotationsPath, data);
1991
+ say(`
1992
+ issued ${made.token.id} "${made.token.name}", expires ${made.token.expiresOn ?? "never"}`);
1993
+ const problem = await checkNew(provider, made.token.id, made.value, old);
1994
+ if (problem) {
1995
+ say(` FAILED the new token's check: ${problem}`);
1996
+ return deleteUnchecked(run, data, rotation, provider);
1997
+ }
1998
+ say(` checked: ${made.token.id} is active and has the same policies as ${old.id}`);
1999
+ say(`keypin: writing the new value to item "${entry.ref.item}", with rotated ${today}`);
2000
+ try {
2001
+ await vault.write(entry.ref, made.value, { rotated: today });
2002
+ const stored = await generationOf(await vault.read(entry.ref));
2003
+ if (stored !== generation)
2004
+ throw new Error(`the item reads back generation ${stored}, not ${generation}`);
2005
+ } catch (error) {
2006
+ say(`Stopped: couldn't store the new value: ${messageOf(error)}.`);
2007
+ say(`The new token ${made.token.id} exists, and the old token still works everywhere. Run ${again(run)} again to delete the new token and start over.`);
2008
+ return 1;
2009
+ }
2010
+ rotation = { ...rotation, stage: "stored", updatedAt: deps.now().toISOString() };
2011
+ data = putRotation(data, rotation);
2012
+ await saveRotations(deps.files, run.rotationsPath, data);
2013
+ say(` stored generation ${generation}`);
2014
+ return publishNew(run, data, rotation, { value: made.value, checked });
2015
+ }
2016
+ async function publishNew(run, data, rotation, fresh) {
2017
+ const { key, entry, environment, deps, say } = run;
2018
+ const state = await loadState(deps.files, run.statePath);
2019
+ let value;
2020
+ let checked;
2021
+ const resuming = fresh === null;
2022
+ if (fresh) {
2023
+ ({ value, checked } = fresh);
2024
+ } else {
2025
+ say(`It stored the new value (generation ${rotation.new.generation}); this run publishes it.`);
2026
+ const found = await checkAccounts(key, entry, deps, say);
2027
+ if (!found) {
2028
+ say("Stopped: an account check failed. Nothing was read and nothing was written.");
2029
+ return 1;
2030
+ }
2031
+ checked = found;
2032
+ if (!deps.isTerminal && approvalsFor({ key, environment, receipts: state.receipts }).length) {
2033
+ say("Stopped before reading the value: publishing needs approval, and --yes can't give it.");
2034
+ say(rerun(deps, "rotate", run.args));
2035
+ return NEEDS_APPROVAL;
2036
+ }
2037
+ announce(deps.stderr, "the value to publish and the admin token, to check the new token", [
2038
+ entry.ref,
2039
+ run.issue.admin
2040
+ ]);
2041
+ value = await deps.vault().read(entry.ref);
2042
+ const generation = await generationOf(value);
2043
+ if (generation !== rotation.new.generation) {
2044
+ say(`Stopped: item "${entry.ref.item}" holds generation ${generation}, not the rotation's ${rotation.new.generation}. Something else changed it. Nothing was written.`);
2045
+ return 1;
2046
+ }
2047
+ const problem = await recheck(run, rotation, value);
2048
+ if (problem) {
2049
+ say(`Stopped: ${problem}. Nothing was written, and the rotation stays at "${rotation.stage}". The old token still works where it was published.`);
2050
+ return 1;
2051
+ }
2052
+ say(` checked: ${rotation.new.id} is active and has the same policies as ${rotation.old.id}`);
2053
+ }
2054
+ const generation = rotation.new.generation ?? await generationOf(value);
2055
+ const plan = planPublish({ key, environment, receipts: state.receipts, generation });
2056
+ say(`
2057
+ Publishing generation ${generation}:`);
2058
+ for (const step of plan.steps) {
2059
+ say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
2060
+ if (step.approval)
2061
+ say(` needs approval: ${step.approval}`);
2062
+ }
2063
+ const writes = writesFor(plan.steps, checked);
2064
+ if (resuming && writes.length && !await confirmed2(run, plan.needsApproval, "publish")) {
2065
+ return NEEDS_APPROVAL;
2066
+ }
2067
+ const written = await writeAll({
2068
+ key,
2069
+ environment,
2070
+ entry,
2071
+ secret: value,
2072
+ generation,
2073
+ writes,
2074
+ state,
2075
+ path: run.statePath,
2076
+ deps,
2077
+ say
2078
+ });
2079
+ if (!written.ok) {
2080
+ say(`Stopped. The old token still works where the write failed. Run ${again(run)} again to finish publishing.`);
2081
+ return 1;
2082
+ }
2083
+ const published = {
2084
+ ...rotation,
2085
+ stage: "published",
2086
+ updatedAt: deps.now().toISOString()
2087
+ };
2088
+ await saveRotations(deps.files, run.rotationsPath, putRotation(data, published));
2089
+ say(`
2090
+ Published. The old token ${rotation.old.id} "${rotation.old.name}" is still active.`);
2091
+ say("Next, check that every consumer works with the new value:");
2092
+ for (const target of entry.publish)
2093
+ say(` ${describeTarget(target, key.env)}`);
2094
+ for (const consumer of key.consumers)
2095
+ say(` ${consumer.name} (${consumer.kind})`);
2096
+ say(`Then run ${again(run)} again to revoke the old token.`);
2097
+ return 0;
1503
2098
  }
1504
- function finishAll(state, keyId, environment) {
1505
- return unfinishedOperations(state, keyId, environment).reduce((s, op) => finishOperation(s, op.id), state);
2099
+ async function revokeOld(run, data, rotation) {
2100
+ const { key, issue, environment, deps, say } = run;
2101
+ const generation = rotation.new.generation;
2102
+ if (!generation || !rotation.new.id || !rotation.old.id) {
2103
+ throw new Error(`rotation ${rotation.id} has no new generation or token IDs`);
2104
+ }
2105
+ const state = await loadState(deps.files, run.statePath);
2106
+ const plan = planPublish({ key, environment, receipts: state.receipts, generation });
2107
+ const behind = plan.steps.filter((step) => step.action === "write");
2108
+ for (const step of behind) {
2109
+ say(` ${step.destinationId} doesn't have generation ${generation}: ${step.reason}`);
2110
+ }
2111
+ const retired = plan.removed.filter((removed) => removed.lastReceipt.generation === rotation.old.generation);
2112
+ if (behind.length) {
2113
+ say(`Stopped: run keypin publish ${key.id}${environment === "prod" ? "" : ` --env ${environment}`} first. Nothing was revoked.`);
2114
+ return 1;
2115
+ }
2116
+ say(`Every destination's receipt has generation ${generation}.`);
2117
+ for (const removed of retired) {
2118
+ 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`);
2119
+ }
2120
+ if (!deps.isTerminal) {
2121
+ say("Stopped: revoking needs yes typed in a terminal, and --yes can't give it. Nothing was revoked.");
2122
+ say(rerun(deps, "rotate", run.args));
2123
+ return NEEDS_APPROVAL;
2124
+ }
2125
+ announce(deps.stderr, "the admin token", [issue.admin]);
2126
+ const provider = deps.provider(issue, await deps.vault().read(issue.admin));
2127
+ const current = await provider.details(rotation.new.id);
2128
+ if (current?.status !== "active") {
2129
+ say(`Stopped: the new token ${rotation.new.id} is ${current ? current.status : "gone"}. Nothing was revoked.`);
2130
+ return 1;
2131
+ }
2132
+ const old = await provider.details(rotation.old.id);
2133
+ if (!old) {
2134
+ say(`The old token ${rotation.old.id} is already gone.`);
2135
+ return finish(run, data, rotation);
2136
+ }
2137
+ say(`
2138
+ Old token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "never"}`);
2139
+ say(` last used: ${old.lastUsedOn ?? "not reported"}`);
2140
+ say(`New token: ${current.id} "${current.name}", ${current.status}, expires ${current.expiresOn ?? "never"}`);
2141
+ const answer = await deps.ask(`Type yes to revoke the old token ${old.id}: `);
2142
+ if (answer.trim() !== "yes") {
2143
+ say("Not confirmed. Nothing was revoked.");
2144
+ return NEEDS_APPROVAL;
2145
+ }
2146
+ say(` ${await provider.revoke(old.id)} ${old.id}`);
2147
+ return finish(run, data, rotation);
1506
2148
  }
1507
- function accountFacts(check) {
1508
- return `publisher ${check.publisher}, destination account ${check.destinationAccount ?? "unknown"}`;
2149
+ async function finish(run, data, rotation) {
2150
+ const done = { ...rotation, stage: "revoked", updatedAt: run.deps.now().toISOString() };
2151
+ await saveRotations(run.deps.files, run.rotationsPath, putRotation(data, done));
2152
+ run.say(`Rotated ${run.key.id} (${run.environment}): ${rotation.new.id} replaced ${rotation.old.id}.`);
2153
+ return 0;
1509
2154
  }
1510
- function describeTarget(target, secretName) {
1511
- return `${destinationId(target, secretName)} (account ${target.account})`;
2155
+ async function abandon(run, data, rotation) {
2156
+ const { entry, issue, deps, say } = run;
2157
+ if (rotation.new.generation) {
2158
+ announce(deps.stderr, "the current value, to see which token it holds", [entry.ref]);
2159
+ const holds = await generationOf(await deps.vault().read(entry.ref));
2160
+ if (holds === rotation.new.generation) {
2161
+ const stored = {
2162
+ ...rotation,
2163
+ stage: "stored",
2164
+ updatedAt: deps.now().toISOString()
2165
+ };
2166
+ const next = putRotation(data, stored);
2167
+ await saveRotations(deps.files, run.rotationsPath, next);
2168
+ say(`Item "${entry.ref.item}" already holds the new value (generation ${holds}).`);
2169
+ return publishNew(run, next, stored, null);
2170
+ }
2171
+ if (holds !== rotation.old.generation) {
2172
+ 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.`);
2173
+ return 1;
2174
+ }
2175
+ }
2176
+ say(`It stopped before the new value was stored, so the old token ${rotation.old.id} still works everywhere.`);
2177
+ if (!deps.isTerminal) {
2178
+ say("Stopped: cleaning it up needs yes typed in a terminal. Nothing was changed.");
2179
+ say(rerun(deps, "rotate", run.args));
2180
+ return NEEDS_APPROVAL;
2181
+ }
2182
+ const id = rotation.new.id;
2183
+ if (!id) {
2184
+ say(`Cloudflare may have made a token named "${rotation.new.name}". Look for it under Account API tokens and delete it if it's there.`);
2185
+ if ((await deps.ask("Type yes to forget this rotation: ")).trim() !== "yes") {
2186
+ say("Not confirmed. Nothing was changed.");
2187
+ return NEEDS_APPROVAL;
2188
+ }
2189
+ } else {
2190
+ announce(deps.stderr, "the admin token", [issue.admin]);
2191
+ const provider = deps.provider(issue, await deps.vault().read(issue.admin));
2192
+ const made = await provider.details(id);
2193
+ if (made) {
2194
+ say(`New token: ${made.id} "${made.name}", ${made.status}, its value was never stored`);
2195
+ if ((await deps.ask(`Type yes to delete the new token ${made.id}: `)).trim() !== "yes") {
2196
+ say("Not confirmed. Nothing was changed.");
2197
+ return NEEDS_APPROVAL;
2198
+ }
2199
+ say(` ${await provider.revoke(made.id)} ${made.id}`);
2200
+ } else {
2201
+ say(`The new token ${id} is already gone.`);
2202
+ }
2203
+ }
2204
+ await saveRotations(deps.files, run.rotationsPath, dropRotation(data, rotation.id));
2205
+ say(`Cleared. Run ${again(run)} again to start over.`);
2206
+ return 1;
2207
+ }
2208
+ async function deleteUnchecked(run, data, rotation, provider) {
2209
+ const id = rotation.new.id;
2210
+ if (!id)
2211
+ throw new Error(`rotation ${rotation.id} has no new token ID`);
2212
+ try {
2213
+ run.say(` ${await provider.revoke(id)} ${id}, the token this run made`);
2214
+ } catch (error) {
2215
+ run.say(`Couldn't delete the new token ${id}: ${messageOf(error)}.`);
2216
+ run.say(`Nothing else was changed, and the old token still works everywhere. Run ${again(run)} again to delete it.`);
2217
+ return 1;
2218
+ }
2219
+ await saveRotations(run.deps.files, run.rotationsPath, dropRotation(data, rotation.id));
2220
+ run.say("Stopped. Nothing else was changed, and the old token still works everywhere.");
2221
+ return 1;
2222
+ }
2223
+ async function recheck(run, rotation, value) {
2224
+ if (!rotation.new.id || !rotation.old.id)
2225
+ return "the rotation has no token IDs";
2226
+ const provider = run.deps.provider(run.issue, await run.deps.vault().read(run.issue.admin));
2227
+ const old = await provider.details(rotation.old.id);
2228
+ if (!old)
2229
+ return `the old token ${rotation.old.id} is gone, so its policies can't be compared`;
2230
+ return checkNew(provider, rotation.new.id, value, old);
2231
+ }
2232
+ function again(run) {
2233
+ return rotateCommand(run.key.id, run.environment);
2234
+ }
2235
+ async function checkNew(provider, id, value, old) {
2236
+ try {
2237
+ const seen = await provider.verify(value);
2238
+ if (seen.id !== id)
2239
+ return `the new value verifies as token ${seen.id}, not ${id}`;
2240
+ if (seen.status !== "active")
2241
+ return `the new token is ${seen.status}`;
2242
+ const made = await provider.details(id);
2243
+ if (!made)
2244
+ return "the admin token can't read the new token";
2245
+ if (!sameAccess(made, old))
2246
+ return `its policies differ from ${old.id}'s`;
2247
+ return null;
2248
+ } catch (error) {
2249
+ return messageOf(error);
2250
+ }
2251
+ }
2252
+ async function confirmed2(run, needsApproval, what) {
2253
+ const { deps, say } = run;
2254
+ if (run.yes && !needsApproval)
2255
+ return true;
2256
+ if (deps.isTerminal) {
2257
+ const answer = await deps.ask(`Type yes to ${what}${needsApproval ? " (this plan needs approval)" : ""}: `);
2258
+ if (answer.trim() === "yes")
2259
+ return true;
2260
+ say("Not confirmed. Nothing was changed.");
2261
+ return false;
2262
+ }
2263
+ say("Stopped: this plan needs approval, and --yes can't give it. Nothing was changed.");
2264
+ say(rerun(deps, "rotate", run.args));
2265
+ return false;
2266
+ }
2267
+ function withoutFinished(data, keyId, environment) {
2268
+ return {
2269
+ ...data,
2270
+ rotations: data.rotations.filter((r) => !(r.keyId === keyId && r.environment === environment && r.stage === "revoked"))
2271
+ };
2272
+ }
2273
+ var DATED = /^(.*) (\d{4}-\d{2}-\d{2})(?: #(\d+))?$/;
2274
+ function nextName(old, today) {
2275
+ const match = DATED.exec(old);
2276
+ const base = match?.[1] ?? old;
2277
+ if (match?.[2] !== today)
2278
+ return `${base} ${today}`;
2279
+ return `${base} ${today} #${Number(match[3] ?? 1) + 1}`;
2280
+ }
2281
+ function describeAccess(token) {
2282
+ const lines = ["policies it copies:"];
2283
+ for (const policy of token.policies) {
2284
+ const groups = policy.permissionGroups.map((g) => g.name).join(", ");
2285
+ lines.push(` ${policy.effect} ${groups}`);
2286
+ for (const [resource, scope] of Object.entries(policy.resources)) {
2287
+ lines.push(` on ${resource}: ${JSON.stringify(scope)}`);
2288
+ }
2289
+ }
2290
+ lines.push(`condition: ${token.condition ? JSON.stringify(token.condition) : "none"}`);
2291
+ return lines;
1512
2292
  }
1513
2293
 
1514
2294
  // src/commands/run.ts
1515
- import { parseArgs as parseArgs3 } from "util";
2295
+ import { parseArgs as parseArgs4 } from "util";
1516
2296
  async function run(args, deps) {
1517
- const { positionals } = parseArgs3({ args, options: {}, allowPositionals: true });
2297
+ const { positionals } = parseArgs4({ args, options: {}, allowPositionals: true });
1518
2298
  if (!positionals.length)
1519
2299
  throw new UsageError("keypin run needs a command after --");
1520
2300
  const map = await findMap(deps.files, deps.cwd);
@@ -1581,9 +2361,9 @@ async function run(args, deps) {
1581
2361
 
1582
2362
  // src/commands/status.ts
1583
2363
  import { join as join5 } from "path";
1584
- import { parseArgs as parseArgs4 } from "util";
2364
+ import { parseArgs as parseArgs5 } from "util";
1585
2365
  async function status(args, deps) {
1586
- const { values, positionals } = parseArgs4({
2366
+ const { values, positionals } = parseArgs5({
1587
2367
  args,
1588
2368
  options: { json: { type: "boolean", default: false } },
1589
2369
  allowPositionals: true
@@ -1592,6 +2372,7 @@ async function status(args, deps) {
1592
2372
  throw new UsageError("keypin status takes no arguments");
1593
2373
  const registry = await loadRegistry(deps.files, registryPath(deps));
1594
2374
  const state = await loadState(deps.files, statePath(deps));
2375
+ const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
1595
2376
  const maps = new Map;
1596
2377
  for (const project of registry.projects) {
1597
2378
  const file = join5(project, MAP_FILE);
@@ -1604,7 +2385,7 @@ async function status(args, deps) {
1604
2385
  `);
1605
2386
  }
1606
2387
  }
1607
- const refs = distinctRefs([...maps.values()].flatMap((result2) => result2.ok ? result2.map.keys.flatMap((key) => Object.values(key.environments).map((e) => e.ref)) : []));
2388
+ const refs = distinctRefs([...maps.values()].flatMap((result) => result.ok ? result.map.keys.flatMap((key) => Object.values(key.environments).map((e) => e.ref)) : []));
1608
2389
  const metadata = new Map;
1609
2390
  if (refs.length) {
1610
2391
  announce(deps.stderr, "rotation fields (no values)", refs);
@@ -1623,6 +2404,7 @@ async function status(args, deps) {
1623
2404
  registry,
1624
2405
  maps,
1625
2406
  receipts: state.receipts,
2407
+ rotations,
1626
2408
  metadata: (ref) => metadata.get(refKey(ref)) ?? null,
1627
2409
  today: localDay(deps.now())
1628
2410
  });
@@ -1702,9 +2484,9 @@ function shown(problems) {
1702
2484
 
1703
2485
  // src/commands/unregister.ts
1704
2486
  import { resolve as resolve2 } from "path";
1705
- import { parseArgs as parseArgs5 } from "util";
2487
+ import { parseArgs as parseArgs6 } from "util";
1706
2488
  async function unregister2(args, deps) {
1707
- const { positionals } = parseArgs5({ args, options: {}, allowPositionals: true });
2489
+ const { positionals } = parseArgs6({ args, options: {}, allowPositionals: true });
1708
2490
  if (positionals.length > 1)
1709
2491
  throw new UsageError("keypin unregister takes at most one folder");
1710
2492
  const folder = resolve2(deps.cwd, positionals[0] ?? ".");
@@ -1723,7 +2505,7 @@ async function unregister2(args, deps) {
1723
2505
  return 0;
1724
2506
  }
1725
2507
  // ../../package.json
1726
- var version = "0.0.0";
2508
+ var version = "0.2.0";
1727
2509
 
1728
2510
  // src/cli.ts
1729
2511
  var USAGE = `Usage:
@@ -1734,6 +2516,9 @@ var USAGE = `Usage:
1734
2516
  keypin run -- <command> run a command with this project's dev keys in its environment
1735
2517
  keypin publish <key-id> [--env prod|dev] [--yes]
1736
2518
  check accounts, plan, confirm, then write the key to every destination
2519
+ keypin rotate <key-id> [--env prod|dev] [--yes]
2520
+ replace a token with a new one that has the same permissions, publish it,
2521
+ and revoke the old one on the next run
1737
2522
  keypin --version print the version
1738
2523
  `;
1739
2524
  var COMMANDS = new Map([
@@ -1741,7 +2526,8 @@ var COMMANDS = new Map([
1741
2526
  ["unregister", unregister2],
1742
2527
  ["status", status],
1743
2528
  ["run", run],
1744
- ["publish", publish]
2529
+ ["publish", publish],
2530
+ ["rotate", rotate]
1745
2531
  ]);
1746
2532
  async function cli(argv, deps) {
1747
2533
  const [name, ...args] = argv;
@@ -1777,7 +2563,7 @@ ${USAGE}`);
1777
2563
  // src/disk.ts
1778
2564
  import { constants, rmSync } from "fs";
1779
2565
  import { chmod, lstat, mkdir, open, readFile as readFile2, rename, rm, stat } from "fs/promises";
1780
- import { dirname as dirname2 } from "path";
2566
+ import { dirname as dirname3 } from "path";
1781
2567
 
1782
2568
  // src/launch.ts
1783
2569
  var launch = (command, env) => {
@@ -1806,7 +2592,7 @@ var diskFiles = {
1806
2592
  }
1807
2593
  },
1808
2594
  async write(path, text) {
1809
- await privateFolder(dirname2(path));
2595
+ await privateFolder(dirname3(path));
1810
2596
  const handle = await open(path, PRIVATE_WRITE, 384);
1811
2597
  try {
1812
2598
  await handle.chmod(384);
@@ -1862,7 +2648,7 @@ async function isFolder(path) {
1862
2648
  }
1863
2649
  }
1864
2650
  var diskLock = async (path) => {
1865
- await privateFolder(dirname2(path));
2651
+ await privateFolder(dirname3(path));
1866
2652
  if (await take(path))
1867
2653
  return { held: true, lock: held(path) };
1868
2654
  const pid = await holderOf(path);
@@ -1922,6 +2708,16 @@ function destination(target) {
1922
2708
  }
1923
2709
  }
1924
2710
  }
2711
+ function provider(issue, admin) {
2712
+ switch (issue.provider) {
2713
+ case "cloudflare-account-token":
2714
+ return new CloudflareAccountTokens({ account: issue.account, admin });
2715
+ default: {
2716
+ const unknown = issue.provider;
2717
+ throw new Error(`unknown provider ${JSON.stringify(unknown)}`);
2718
+ }
2719
+ }
2720
+ }
1925
2721
  var connect = (account) => desktopConnect(account).catch((error) => {
1926
2722
  const hint = installProblem(error);
1927
2723
  throw hint ? new Error(hint) : error;
@@ -1950,6 +2746,7 @@ function main() {
1950
2746
  launch,
1951
2747
  onSignals,
1952
2748
  destination,
2749
+ provider,
1953
2750
  lock: diskLock,
1954
2751
  isTerminal: Boolean(process.stdin.isTTY),
1955
2752
  ask