keypin 0.1.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.
package/README.md CHANGED
@@ -75,6 +75,7 @@ keypin unregister [folder] # stop listing a project; its keypin.toml stays
75
75
  keypin status [--json] # every key, its rotation dates and receipts, then problems
76
76
  keypin run -- <command> # run a command with the project's dev keys in its environment
77
77
  keypin publish <key-id> # check accounts, show the plan, then write the key to every destination
78
+ keypin rotate <key-id> # replace a token with a new one, publish it, then revoke the old one
78
79
  ```
79
80
 
80
81
  `publish` writes `prod` by default (`--env dev` for dev). It checks each destination is the account the map pins,
@@ -83,13 +84,54 @@ change. `--yes` never gives that approval.
83
84
 
84
85
  Destinations: GitHub Actions secrets (with `gh`'s login) and Cloudflare Worker secrets (with wrangler's login).
85
86
 
87
+ ## Rotate
88
+
89
+ `rotate` replaces a Cloudflare account API token with a new one that has the same permissions. It needs an `issue`
90
+ section on the key's environment, at least one destination, and a `rotate_every` other than `never`:
91
+
92
+ ```toml
93
+ [keys.site-deploy.prod.issue]
94
+ provider = "cloudflare-account-token"
95
+ account = "<your Cloudflare account ID>"
96
+ admin = "shared cloudflare token admin" # an item in the same vault, read only by rotate
97
+ ```
98
+
99
+ The first run:
100
+
101
+ 1. reads the current value and asks Cloudflare which token it is;
102
+ 2. reads that token's policies with the admin token, and shows the plan: both tokens, the policies it copies, the
103
+ item and every destination. Type `yes`, or pass `--yes` when no destination needs approval;
104
+ 3. makes a new token with the same policies, named after the old one plus today's date. It expires after the
105
+ key's `rotate_every` plus 14 days, so `status` shows it due well before it stops working;
106
+ 4. checks the new token is active and has the same policies, or deletes it and stops;
107
+ 5. stores it in the item with `rotated` set to today, and publishes it like `publish`.
108
+
109
+ The old token stays active. Check that everything that uses the key works, then run `keypin rotate <key-id>`
110
+ again: it checks every destination has the new value, shows when the old token was last used, and revokes it after
111
+ you type `yes`. `--yes` never revokes.
112
+
113
+ If a run stops, the next one continues or cleans up. `status` shows an unfinished rotation as a notice.
114
+
115
+ ### The admin token
116
+
117
+ In the Cloudflare dashboard, go to **Manage account** → **Account API tokens** → **Create Token** → **Custom
118
+ token**:
119
+
120
+ - Permissions: **Account** → **Account API Tokens** → **Edit**, and nothing else;
121
+ - the account the keys live in;
122
+ - a short expiry, such as 30 days.
123
+
124
+ Store it in your vault as the `admin` item, with `rotated` and `rotate_every` like any other key. keypin never
125
+ publishes it, and `run` never injects it.
126
+
86
127
  ## Notes
87
128
 
88
129
  - **Cloudflare Workers:** `wrangler dev` passes environment variables to the Worker only for names in
89
130
  `secrets.required`, and a `.dev.vars` file overrides them. Delete `.dev.vars`, then `keypin run -- wrangler dev`.
90
131
  - **macOS only for now:** the Cloudflare destination reads wrangler's login from its macOS path.
91
- - **Files on your machine:** the project registry (`~/.config/keypin/registry.json`) and receipts
92
- (`~/.local/state/keypin/state.json`). Both honor `XDG_CONFIG_HOME` and `XDG_STATE_HOME`.
132
+ - **Files on your machine:** the project registry (`~/.config/keypin/registry.json`), receipts
133
+ (`~/.local/state/keypin/state.json`) and rotations (`~/.local/state/keypin/rotations.json`). They honor
134
+ `XDG_CONFIG_HOME` and `XDG_STATE_HOME`.
93
135
 
94
136
  ## Development
95
137
 
@@ -78,6 +78,7 @@ function addDays(day, days) {
78
78
 
79
79
  // ../../packages/core/src/map.ts
80
80
  var DESTINATION_KINDS = ["cloudflare-worker", "github-actions"];
81
+ var PROVIDER_KINDS = ["cloudflare-account-token"];
81
82
  function destinationId(target, secretName) {
82
83
  return `${placeId(target)}:${secretName}`;
83
84
  }
@@ -242,7 +243,7 @@ function validateEnv(raw, vaults, fail) {
242
243
  failed = true;
243
244
  fail(message);
244
245
  };
245
- unknownFields(raw, ["vault", "item", "publish"], (field) => err(`unknown field "${field}"`));
246
+ unknownFields(raw, ["vault", "item", "publish", "issue"], (field) => err(`unknown field "${field}"`));
246
247
  const vaultName = requiredString(raw, "vault", err);
247
248
  const item = requiredString(raw, "item", err);
248
249
  const vault = vaultName === undefined ? undefined : vaults.get(vaultName);
@@ -268,9 +269,36 @@ function validateEnv(raw, vaults, fail) {
268
269
  });
269
270
  }
270
271
  }
272
+ const issue = raw.issue === undefined || !vault || item === undefined ? undefined : validateIssue(raw.issue, vault, item, (m) => err(`issue: ${m}`));
271
273
  if (failed || !vault || item === undefined)
272
274
  return;
273
- 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 } };
274
302
  }
275
303
  function validateTarget(raw, fail) {
276
304
  if (!isRecord(raw)) {
@@ -325,6 +353,26 @@ function requiredString(table, field, fail) {
325
353
  function optionalString(table, field, fail) {
326
354
  return table[field] === undefined ? undefined : requiredString(table, field, fail);
327
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
+ }
328
376
  // ../../packages/core/src/files.ts
329
377
  async function writeJsonAtomic(files, path, data) {
330
378
  const temporary = `${path}.${crypto.randomUUID()}.tmp`;
@@ -530,7 +578,48 @@ function sameRef(a, b) {
530
578
  function describeRef(ref) {
531
579
  return `item "${ref.item}" (1Password account ${ref.account}, vault "${ref.vault}")`;
532
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
+ }
533
621
  // ../../packages/core/src/status.ts
622
+ var NOTICES = ["due-soon", "authority-unknown", "rotation-unfinished"];
534
623
  function buildStatus(input) {
535
624
  if (!isDay(input.today))
536
625
  throw new Error(`today must be YYYY-MM-DD, got "${input.today}"`);
@@ -567,7 +656,7 @@ function buildStatus(input) {
567
656
  const label = `${key.id} (${environment})`;
568
657
  const add = (kind, message, extra = {}) => problems.push({
569
658
  kind,
570
- severity: kind === "due-soon" || kind === "authority-unknown" ? "notice" : "problem",
659
+ severity: NOTICES.includes(kind) ? "notice" : "problem",
571
660
  ...where,
572
661
  ...extra,
573
662
  message
@@ -603,6 +692,10 @@ function buildStatus(input) {
603
692
  stale
604
693
  };
605
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
+ }
606
699
  rows.push({
607
700
  ...where,
608
701
  env: key.env,
@@ -694,7 +787,7 @@ function refresh() {
694
787
 
695
788
  // ../../packages/destination-cloudflare/src/cloudflare.ts
696
789
  var API = "https://api.cloudflare.com/client/v4";
697
- var ACCOUNT_ID = /^[0-9a-f]{32}$/;
790
+ var ACCOUNT_ID2 = /^[0-9a-f]{32}$/;
698
791
  var WORKER = /^[A-Za-z0-9_-]+$/;
699
792
 
700
793
  class WorkerSecretDestination {
@@ -706,7 +799,7 @@ class WorkerSecretDestination {
706
799
  #token;
707
800
  #passed = false;
708
801
  constructor(options) {
709
- if (!ACCOUNT_ID.test(options.account))
802
+ if (!ACCOUNT_ID2.test(options.account))
710
803
  throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
711
804
  if (!WORKER.test(options.worker))
712
805
  throw new Error(`"${options.worker}" isn't a Worker name`);
@@ -992,6 +1085,172 @@ function stringField(data, field) {
992
1085
  throw new Error(`GitHub's response has no "${field}"`);
993
1086
  return value;
994
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
+ }
995
1254
  // ../../packages/vault-1password/src/sdk.ts
996
1255
  var desktopConnect = async (account) => {
997
1256
  const sdk = await import("@1password/sdk");
@@ -1183,7 +1442,7 @@ function localDay(date) {
1183
1442
  }
1184
1443
 
1185
1444
  // src/paths.ts
1186
- import { join as join2 } from "path";
1445
+ import { dirname, join as join2 } from "path";
1187
1446
  function registryPath(deps) {
1188
1447
  return join2(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
1189
1448
  }
@@ -1197,12 +1456,15 @@ function projectCount(registry, path) {
1197
1456
  const count = registry.projects.length;
1198
1457
  return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
1199
1458
  }
1459
+ function rotationsPath(deps) {
1460
+ return join2(dirname(statePath(deps)), "rotations.json");
1461
+ }
1200
1462
 
1201
1463
  // src/project.ts
1202
- import { dirname, join as join3 } from "path";
1464
+ import { dirname as dirname2, join as join3 } from "path";
1203
1465
  var MAP_FILE = "keypin.toml";
1204
1466
  async function findMap(files, cwd) {
1205
- for (let folder = cwd;; folder = dirname(folder)) {
1467
+ for (let folder = cwd;; folder = dirname2(folder)) {
1206
1468
  const file = join3(folder, MAP_FILE);
1207
1469
  const text = await files.read(file);
1208
1470
  if (text !== null) {
@@ -1212,7 +1474,7 @@ async function findMap(files, cwd) {
1212
1474
  `));
1213
1475
  return result.map;
1214
1476
  }
1215
- if (dirname(folder) === folder) {
1477
+ if (dirname2(folder) === folder) {
1216
1478
  throw new Error(`no ${MAP_FILE} in ${cwd} or any folder above it; run "keypin init" first`);
1217
1479
  }
1218
1480
  }
@@ -1277,6 +1539,122 @@ async function init(args, deps) {
1277
1539
  // src/commands/publish.ts
1278
1540
  import { parseArgs as parseArgs2 } from "util";
1279
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
+
1280
1658
  // src/vault.ts
1281
1659
  function announce(stderr, what, refs) {
1282
1660
  const groups = new Map;
@@ -1300,32 +1678,10 @@ function distinctRefs(refs) {
1300
1678
  var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item]);
1301
1679
 
1302
1680
  // src/commands/publish.ts
1303
- var NEEDS_APPROVAL = 2;
1304
1681
  async function publish(args, deps) {
1305
1682
  const request = parseRequest(args);
1306
1683
  const map = await findMap(deps.files, deps.cwd);
1307
- const path = statePath(deps);
1308
- const lockFile = `${path}.lock`;
1309
- const taken = await deps.lock(lockFile);
1310
- if (!taken.held) {
1311
- deps.stderr.write(`${lockedMessage(lockFile, taken.holder)}
1312
- `);
1313
- return 1;
1314
- }
1315
- try {
1316
- return await publishLocked({ ...request, args }, map, path, deps);
1317
- } finally {
1318
- await taken.lock.release();
1319
- }
1320
- }
1321
- function lockedMessage(file, holder) {
1322
- if (holder.pid === null) {
1323
- return `keypin: ${file} exists but names no process. If no publish is running, delete that file and try again.`;
1324
- }
1325
- if (holder.running === false) {
1326
- return `keypin: ${file} was left by process ${holder.pid}, which isn't running any more. Delete that file and try again.`;
1327
- }
1328
- 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));
1329
1685
  }
1330
1686
  function parseRequest(args) {
1331
1687
  const { values, positionals } = parseArgs2({
@@ -1363,29 +1719,12 @@ async function publishLocked(request, map, path, deps) {
1363
1719
  say(`The map lists no destinations for ${keyId} (${environment}); nothing to publish.`);
1364
1720
  return 1;
1365
1721
  }
1366
- let state = await loadState(deps.files, path);
1722
+ const state = await loadState(deps.files, path);
1367
1723
  for (const op of unfinishedOperations(state, keyId, environment)) {
1368
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.`);
1369
1725
  }
1370
- say(`
1371
- Account checks:`);
1372
- const checked = new Map;
1373
- let failed = false;
1374
- for (const target of entry.publish) {
1375
- const label = describeTarget(target, key.env);
1376
- try {
1377
- const destination = deps.destination(target);
1378
- const check = await destination.checkAccount();
1379
- checked.set(destinationId(target, key.env), { target, destination, check });
1380
- say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
1381
- if (!check.ok)
1382
- failed = true;
1383
- } catch (error) {
1384
- say(` FAILED ${label}: ${messageOf(error)}`);
1385
- failed = true;
1386
- }
1387
- }
1388
- if (failed) {
1726
+ const checked = await checkAccounts(key, entry, deps, say);
1727
+ if (!checked) {
1389
1728
  say("Stopped: an account check failed. Nothing was read and nothing was written.");
1390
1729
  return 1;
1391
1730
  }
@@ -1396,7 +1735,7 @@ Needs approval:`);
1396
1735
  for (const approval of approvals)
1397
1736
  say(` ${approval.approval}`);
1398
1737
  say(`Stopped before reading the value: this publish needs approval, and --yes can't give it. Nothing was read and nothing was written.`);
1399
- say(rerun(deps, request.args));
1738
+ say(rerun(deps, "publish", request.args));
1400
1739
  return NEEDS_APPROVAL;
1401
1740
  }
1402
1741
  announce(deps.stderr, "the value to publish", [entry.ref]);
@@ -1411,17 +1750,14 @@ Needs approval:`);
1411
1750
  const plan = planPublish({ key, environment, receipts: state.receipts, generation });
1412
1751
  say(`
1413
1752
  Plan for generation ${generation}:`);
1414
- const writes = [];
1753
+ const writes = writesFor(plan.steps, checked);
1415
1754
  for (const step of plan.steps) {
1416
1755
  const found = checked.get(step.destinationId);
1417
- if (!found)
1418
- throw new Error(`no account check for ${step.destinationId}`);
1419
1756
  say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
1420
- say(` ${accountFacts(found.check)}`);
1757
+ if (found)
1758
+ say(` ${accountFacts(found.check)}`);
1421
1759
  if (step.approval)
1422
1760
  say(` needs approval: ${step.approval}`);
1423
- if (step.action === "write")
1424
- writes.push({ destinationId: step.destinationId, found });
1425
1761
  }
1426
1762
  for (const removed of plan.removed) {
1427
1763
  say(` not in the map any more: ${removed.destinationId} (last got ${removed.lastReceipt.generation} at ${removed.lastReceipt.at}). keypin doesn't delete it.`);
@@ -1435,44 +1771,22 @@ Plan for generation ${generation}:`);
1435
1771
  }
1436
1772
  if (!await confirmed(deps, plan.needsApproval, request))
1437
1773
  return NEEDS_APPROVAL;
1438
- const id = crypto.randomUUID();
1439
- state = startOperation(state, {
1440
- id,
1441
- keyId,
1774
+ const written = await writeAll({
1775
+ key,
1442
1776
  environment,
1777
+ entry,
1778
+ secret,
1443
1779
  generation,
1444
- startedAt: deps.now().toISOString(),
1445
- planned: writes.map((w) => w.destinationId)
1780
+ writes,
1781
+ state,
1782
+ path,
1783
+ deps,
1784
+ say
1446
1785
  });
1447
- await saveState(deps.files, path, state);
1448
- for (const { destinationId: written, found } of writes) {
1449
- const label = describeTarget(found.target, key.env);
1450
- try {
1451
- const evidence = await found.destination.write(key.env, secret);
1452
- state = recordReceipt(state, {
1453
- keyId,
1454
- environment,
1455
- source: entry.ref,
1456
- destinationId: written,
1457
- generation,
1458
- account: {
1459
- pinned: found.target.account,
1460
- publisher: found.check.publisher,
1461
- destinationAccount: found.check.destinationAccount ?? found.target.account
1462
- },
1463
- at: deps.now().toISOString(),
1464
- evidence
1465
- }, id);
1466
- await saveState(deps.files, path, state);
1467
- say(` wrote ${label}`);
1468
- } catch (error) {
1469
- say(` FAILED ${label}: ${messageOf(error)}`);
1470
- say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
1471
- return 1;
1472
- }
1786
+ if (!written.ok) {
1787
+ say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
1788
+ return 1;
1473
1789
  }
1474
- state = finishAll(state, keyId, environment);
1475
- await saveState(deps.files, path, state);
1476
1790
  say(`Published ${keyId} (${environment}) to ${writes.length} destination(s).`);
1477
1791
  return 0;
1478
1792
  }
@@ -1489,31 +1803,498 @@ async function confirmed(deps, needsApproval, request) {
1489
1803
  return false;
1490
1804
  }
1491
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.");
1492
- say(rerun(deps, request.args));
1806
+ say(rerun(deps, "publish", request.args));
1493
1807
  return false;
1494
1808
  }
1495
- function rerun(deps, args) {
1496
- const command = [...deps.self, "publish", ...args].map(shellWord).join(" ");
1497
- return `To approve, run this in a terminal:
1498
- 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
+ });
1499
1876
  }
1500
- function shellWord(word) {
1501
- 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;
1502
2098
  }
1503
- function finishAll(state, keyId, environment) {
1504
- 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);
1505
2148
  }
1506
- function accountFacts(check) {
1507
- 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;
1508
2154
  }
1509
- function describeTarget(target, secretName) {
1510
- 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;
1511
2292
  }
1512
2293
 
1513
2294
  // src/commands/run.ts
1514
- import { parseArgs as parseArgs3 } from "util";
2295
+ import { parseArgs as parseArgs4 } from "util";
1515
2296
  async function run(args, deps) {
1516
- const { positionals } = parseArgs3({ args, options: {}, allowPositionals: true });
2297
+ const { positionals } = parseArgs4({ args, options: {}, allowPositionals: true });
1517
2298
  if (!positionals.length)
1518
2299
  throw new UsageError("keypin run needs a command after --");
1519
2300
  const map = await findMap(deps.files, deps.cwd);
@@ -1580,9 +2361,9 @@ async function run(args, deps) {
1580
2361
 
1581
2362
  // src/commands/status.ts
1582
2363
  import { join as join5 } from "path";
1583
- import { parseArgs as parseArgs4 } from "util";
2364
+ import { parseArgs as parseArgs5 } from "util";
1584
2365
  async function status(args, deps) {
1585
- const { values, positionals } = parseArgs4({
2366
+ const { values, positionals } = parseArgs5({
1586
2367
  args,
1587
2368
  options: { json: { type: "boolean", default: false } },
1588
2369
  allowPositionals: true
@@ -1591,6 +2372,7 @@ async function status(args, deps) {
1591
2372
  throw new UsageError("keypin status takes no arguments");
1592
2373
  const registry = await loadRegistry(deps.files, registryPath(deps));
1593
2374
  const state = await loadState(deps.files, statePath(deps));
2375
+ const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
1594
2376
  const maps = new Map;
1595
2377
  for (const project of registry.projects) {
1596
2378
  const file = join5(project, MAP_FILE);
@@ -1622,6 +2404,7 @@ async function status(args, deps) {
1622
2404
  registry,
1623
2405
  maps,
1624
2406
  receipts: state.receipts,
2407
+ rotations,
1625
2408
  metadata: (ref) => metadata.get(refKey(ref)) ?? null,
1626
2409
  today: localDay(deps.now())
1627
2410
  });
@@ -1701,9 +2484,9 @@ function shown(problems) {
1701
2484
 
1702
2485
  // src/commands/unregister.ts
1703
2486
  import { resolve as resolve2 } from "path";
1704
- import { parseArgs as parseArgs5 } from "util";
2487
+ import { parseArgs as parseArgs6 } from "util";
1705
2488
  async function unregister2(args, deps) {
1706
- const { positionals } = parseArgs5({ args, options: {}, allowPositionals: true });
2489
+ const { positionals } = parseArgs6({ args, options: {}, allowPositionals: true });
1707
2490
  if (positionals.length > 1)
1708
2491
  throw new UsageError("keypin unregister takes at most one folder");
1709
2492
  const folder = resolve2(deps.cwd, positionals[0] ?? ".");
@@ -1722,7 +2505,7 @@ async function unregister2(args, deps) {
1722
2505
  return 0;
1723
2506
  }
1724
2507
  // ../../package.json
1725
- var version = "0.1.0";
2508
+ var version = "0.2.0";
1726
2509
 
1727
2510
  // src/cli.ts
1728
2511
  var USAGE = `Usage:
@@ -1733,6 +2516,9 @@ var USAGE = `Usage:
1733
2516
  keypin run -- <command> run a command with this project's dev keys in its environment
1734
2517
  keypin publish <key-id> [--env prod|dev] [--yes]
1735
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
1736
2522
  keypin --version print the version
1737
2523
  `;
1738
2524
  var COMMANDS = new Map([
@@ -1740,7 +2526,8 @@ var COMMANDS = new Map([
1740
2526
  ["unregister", unregister2],
1741
2527
  ["status", status],
1742
2528
  ["run", run],
1743
- ["publish", publish]
2529
+ ["publish", publish],
2530
+ ["rotate", rotate]
1744
2531
  ]);
1745
2532
  async function cli(argv, deps) {
1746
2533
  const [name, ...args] = argv;
@@ -1776,7 +2563,7 @@ ${USAGE}`);
1776
2563
  // src/disk.ts
1777
2564
  import { constants, rmSync } from "fs";
1778
2565
  import { chmod, lstat, mkdir, open, readFile as readFile2, rename, rm, stat } from "fs/promises";
1779
- import { dirname as dirname2 } from "path";
2566
+ import { dirname as dirname3 } from "path";
1780
2567
 
1781
2568
  // src/launch.ts
1782
2569
  var launch = (command, env) => {
@@ -1805,7 +2592,7 @@ var diskFiles = {
1805
2592
  }
1806
2593
  },
1807
2594
  async write(path, text) {
1808
- await privateFolder(dirname2(path));
2595
+ await privateFolder(dirname3(path));
1809
2596
  const handle = await open(path, PRIVATE_WRITE, 384);
1810
2597
  try {
1811
2598
  await handle.chmod(384);
@@ -1861,7 +2648,7 @@ async function isFolder(path) {
1861
2648
  }
1862
2649
  }
1863
2650
  var diskLock = async (path) => {
1864
- await privateFolder(dirname2(path));
2651
+ await privateFolder(dirname3(path));
1865
2652
  if (await take(path))
1866
2653
  return { held: true, lock: held(path) };
1867
2654
  const pid = await holderOf(path);
@@ -1921,6 +2708,16 @@ function destination(target) {
1921
2708
  }
1922
2709
  }
1923
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
+ }
1924
2721
  var connect = (account) => desktopConnect(account).catch((error) => {
1925
2722
  const hint = installProblem(error);
1926
2723
  throw hint ? new Error(hint) : error;
@@ -1949,6 +2746,7 @@ function main() {
1949
2746
  launch,
1950
2747
  onSignals,
1951
2748
  destination,
2749
+ provider,
1952
2750
  lock: diskLock,
1953
2751
  isTerminal: Boolean(process.stdin.isTTY),
1954
2752
  ask
package/main.js CHANGED
@@ -36,7 +36,7 @@ if (problem) {
36
36
  }
37
37
  var start;
38
38
  try {
39
- start = await import("./chunk-03233dfg.js");
39
+ start = await import("./chunk-mjxb8yj8.js");
40
40
  } catch (error) {
41
41
  const hint = installProblem(error);
42
42
  if (!hint)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keypin",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A map of every app key across your projects, published to the account it's pinned to. Values stay in your vault.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/caiopizzol/keypin#readme",