keypin 0.1.0 → 0.3.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.
@@ -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,
@@ -643,6 +736,407 @@ function rotationDue(input) {
643
736
  add("due-soon", `${label}: is due ${due} (rotated ${rotated}, every ${rotateEvery})`);
644
737
  return due;
645
738
  }
739
+ // ../../packages/core/src/discover.ts
740
+ var {TOML: TOML2 } = globalThis.Bun;
741
+ var SKIPPED_FOLDERS = new Set([
742
+ ".git",
743
+ "node_modules",
744
+ ".wrangler",
745
+ "dist",
746
+ "build",
747
+ "out",
748
+ ".output",
749
+ ".next",
750
+ ".nuxt",
751
+ ".svelte-kit",
752
+ ".astro",
753
+ ".turbo",
754
+ ".vercel",
755
+ ".netlify",
756
+ ".cache",
757
+ ".parcel-cache",
758
+ "coverage",
759
+ ".venv",
760
+ "venv",
761
+ "__pycache__",
762
+ "target",
763
+ "vendor",
764
+ "Pods",
765
+ "DerivedData"
766
+ ]);
767
+ var ENV_FILE = /^(\.env|\.dev\.vars)(\..+)?$/;
768
+ var EXPECTED_FILE = /\.(example|sample|template)$/;
769
+ function envFileKind(fileName) {
770
+ if (!ENV_FILE.test(fileName))
771
+ return null;
772
+ return EXPECTED_FILE.test(fileName) ? "expected" : "set";
773
+ }
774
+ var WRANGLER_FILES = [
775
+ "wrangler.toml",
776
+ "wrangler.json",
777
+ "wrangler.jsonc"
778
+ ];
779
+ var DOTENV_LINE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
780
+ function envNames(text) {
781
+ const names = new Set;
782
+ for (const match of text.replace(/\r\n?/g, `
783
+ `).matchAll(DOTENV_LINE)) {
784
+ if (match[1])
785
+ names.add(match[1]);
786
+ }
787
+ return [...names];
788
+ }
789
+ var CONTEXT_REF = /(?<![\w.])(secrets|vars)\s*(?:\.\s*([A-Za-z_][A-Za-z0-9_]*)|\[\s*'([A-Za-z_][A-Za-z0-9_]*)'\s*\])/g;
790
+ function workflowRefs(text) {
791
+ let data;
792
+ try {
793
+ data = Bun.YAML.parse(text);
794
+ } catch {
795
+ return null;
796
+ }
797
+ const refs = {
798
+ secrets: new Set,
799
+ vars: new Set,
800
+ environments: new Set,
801
+ hidesUses: false
802
+ };
803
+ const scan = (expression) => {
804
+ if (/toJSON\(\s*secrets\s*\)/.test(expression))
805
+ refs.hidesUses = true;
806
+ for (const match of expression.matchAll(CONTEXT_REF)) {
807
+ const name = (match[2] ?? match[3])?.toUpperCase();
808
+ if (!name)
809
+ continue;
810
+ (match[1] === "secrets" ? refs.secrets : refs.vars).add(name);
811
+ }
812
+ };
813
+ const visit = (value, key) => {
814
+ if (typeof value === "string") {
815
+ if (key === "if" && !value.includes("${{"))
816
+ scan(withoutStrings(value));
817
+ for (const expression of expressions(value))
818
+ scan(expression);
819
+ if (key === "secrets" && value.trim() === "inherit")
820
+ refs.hidesUses = true;
821
+ } else if (Array.isArray(value)) {
822
+ for (const item of value)
823
+ visit(item, null);
824
+ } else if (isRecord(value)) {
825
+ for (const [k, v] of Object.entries(value))
826
+ visit(v, k);
827
+ }
828
+ };
829
+ visit(data, null);
830
+ const jobs = isRecord(data) && isRecord(data.jobs) ? Object.values(data.jobs) : [];
831
+ for (const job of jobs) {
832
+ const environment = isRecord(job) ? job.environment : undefined;
833
+ const name = isRecord(environment) ? environment.name : environment;
834
+ if (typeof name === "string" && name.trim())
835
+ refs.environments.add(name);
836
+ }
837
+ return {
838
+ secrets: [...refs.secrets],
839
+ vars: [...refs.vars],
840
+ environments: [...refs.environments],
841
+ hidesUses: refs.hidesUses
842
+ };
843
+ }
844
+ function expressions(text) {
845
+ const found = [];
846
+ for (let start = text.indexOf("${{");start !== -1; start = text.indexOf("${{", start)) {
847
+ let i = start + 3;
848
+ while (i < text.length && !text.startsWith("}}", i))
849
+ i = text[i] === "'" ? endOfString(text, i) : i + 1;
850
+ found.push(withoutStrings(text.slice(start + 3, i)));
851
+ start = i + 2;
852
+ }
853
+ return found;
854
+ }
855
+ function withoutStrings(expression) {
856
+ let code = "";
857
+ for (let i = 0;i < expression.length; ) {
858
+ if (expression[i] !== "'") {
859
+ code += expression[i];
860
+ i++;
861
+ continue;
862
+ }
863
+ const end = endOfString(expression, i);
864
+ const literal = expression.slice(i, end);
865
+ code += /(?:secrets|vars)\s*\[\s*$/.test(code) ? literal : "''";
866
+ i = end;
867
+ }
868
+ return code;
869
+ }
870
+ function endOfString(text, open) {
871
+ let i = open + 1;
872
+ while (i < text.length) {
873
+ if (text[i] !== "'")
874
+ i++;
875
+ else if (text[i + 1] === "'")
876
+ i += 2;
877
+ else
878
+ return i + 1;
879
+ }
880
+ return i;
881
+ }
882
+ var ACCOUNT_ID2 = /^[0-9a-f]{32}$/;
883
+ function wranglerWorkers(text, config) {
884
+ let data;
885
+ try {
886
+ data = config.endsWith(".toml") ? TOML2.parse(text) : Bun.JSONC.parse(text);
887
+ } catch {
888
+ return { ok: false };
889
+ }
890
+ if (!isRecord(data))
891
+ return { ok: false };
892
+ const topName = stringOf(data.name);
893
+ const topAccount = stringOf(data.account_id);
894
+ const workers = [declaration(config, null, data, topName, topAccount)];
895
+ const envs = isRecord(data.env) ? data.env : {};
896
+ for (const [env, raw] of Object.entries(envs)) {
897
+ if (!isRecord(raw))
898
+ continue;
899
+ const name = stringOf(raw.name) ?? (topName ? `${topName}-${env}` : null);
900
+ workers.push(declaration(config, env, raw, name, stringOf(raw.account_id) ?? topAccount));
901
+ }
902
+ return { ok: true, workers };
903
+ }
904
+ function declaration(config, env, table, worker, account) {
905
+ const secrets = isRecord(table.secrets) ? table.secrets : null;
906
+ const required = Array.isArray(secrets?.required) ? secrets.required.filter((n) => typeof n === "string") : null;
907
+ return {
908
+ config,
909
+ env,
910
+ worker,
911
+ account: account && ACCOUNT_ID2.test(account) ? account : null,
912
+ required,
913
+ vars: isRecord(table.vars) ? Object.keys(table.vars) : []
914
+ };
915
+ }
916
+ function stringOf(value) {
917
+ return typeof value === "string" && value.trim() ? value : null;
918
+ }
919
+ var GITHUB_PROVIDED = "GITHUB_TOKEN";
920
+ var LOCAL_KINDS = ["env-file"];
921
+ var CLOUD_KINDS = ["github-secret", "worker-secret"];
922
+ var VARIABLE_KINDS = ["worker-var", "workflow-var"];
923
+ function buildDiscovery(input) {
924
+ const sources = new Map;
925
+ const add = (name, source) => {
926
+ const list = sources.get(name) ?? [];
927
+ list.push(source);
928
+ sources.set(name, list);
929
+ };
930
+ const problems = [];
931
+ const unknowns = [...input.unknowns];
932
+ for (const file of input.envFiles) {
933
+ for (const name of file.names) {
934
+ add(name, file.kind === "set" ? { kind: "env-file", path: file.path, tracked: file.tracked } : { kind: "example-file", path: file.path });
935
+ }
936
+ if (file.kind === "set" && file.tracked === true) {
937
+ problems.push({
938
+ kind: "tracked-env-file",
939
+ path: file.path,
940
+ message: `${file.path} is tracked by git, so its values may be committed`
941
+ });
942
+ }
943
+ }
944
+ const referenced = new Map;
945
+ let hidesUses = false;
946
+ for (const workflow of input.workflows) {
947
+ hidesUses ||= workflow.refs.hidesUses;
948
+ for (const name of workflow.refs.secrets) {
949
+ if (name === GITHUB_PROVIDED)
950
+ continue;
951
+ const environments = referenced.get(name) ?? new Set;
952
+ for (const environment of workflow.refs.environments)
953
+ environments.add(environment);
954
+ referenced.set(name, environments);
955
+ add(name, { kind: "workflow-secret", path: workflow.path });
956
+ }
957
+ for (const name of workflow.refs.vars)
958
+ add(name, { kind: "workflow-var", path: workflow.path });
959
+ }
960
+ const environments = new Set(input.workflows.flatMap((w) => w.refs.environments));
961
+ if (input.github && environments.size) {
962
+ unknowns.push({
963
+ what: `GitHub environment secrets (${[...environments].join(", ")})`,
964
+ reason: "discover reads repo secrets only",
965
+ cloud: true
966
+ });
967
+ }
968
+ if (input.github) {
969
+ const { repo, read } = input.github;
970
+ if (read.ok) {
971
+ const present = new Set(read.secrets.map((s) => s.name.toUpperCase()));
972
+ for (const secret of read.secrets) {
973
+ add(secret.name, { kind: "github-secret", repo, updatedAt: secret.updatedAt });
974
+ if (!referenced.has(secret.name.toUpperCase())) {
975
+ problems.push({
976
+ kind: "unreferenced-github-secret",
977
+ name: secret.name,
978
+ message: `no workflow here references this ${repo} secret${hidesUses ? " (a workflow passes secrets on, which can hide a use)" : ""}`
979
+ });
980
+ }
981
+ }
982
+ for (const [name, environments] of referenced) {
983
+ if (present.has(name))
984
+ continue;
985
+ const maybe = environments.size ? `; it may be a secret of the environment ${[...environments].join(" or ")}, which discover doesn't read` : "";
986
+ problems.push({
987
+ kind: "missing-github-secret",
988
+ name,
989
+ message: `a workflow references it, and ${repo} has no repo secret with this name${maybe}`
990
+ });
991
+ }
992
+ } else {
993
+ unknowns.push({
994
+ what: `GitHub Actions secrets of ${repo}`,
995
+ reason: read.reason,
996
+ cloud: true
997
+ });
998
+ }
999
+ }
1000
+ for (const worker of input.workers) {
1001
+ const label = workerLabel(worker);
1002
+ for (const name of worker.required ?? []) {
1003
+ add(name, { kind: "worker-required", path: worker.config, worker: worker.worker });
1004
+ }
1005
+ for (const name of worker.vars) {
1006
+ add(name, { kind: "worker-var", path: worker.config, worker: worker.worker });
1007
+ }
1008
+ if (!worker.worker || !worker.account) {
1009
+ unknowns.push({
1010
+ what: `Worker secrets of ${label}`,
1011
+ cloud: true,
1012
+ reason: worker.worker ? `${worker.config} has no account_id, and discover doesn't guess an account` : `${worker.config} names no Worker`
1013
+ });
1014
+ continue;
1015
+ }
1016
+ const read = worker.read;
1017
+ if (!read)
1018
+ continue;
1019
+ if (!read.ok) {
1020
+ unknowns.push({ what: `Worker secrets of ${label}`, reason: read.reason, cloud: true });
1021
+ continue;
1022
+ }
1023
+ const present = new Set(read.secrets.map((s) => s.name));
1024
+ for (const secret of read.secrets) {
1025
+ add(secret.name, { kind: "worker-secret", worker: worker.worker, account: worker.account });
1026
+ }
1027
+ for (const name of worker.required ?? []) {
1028
+ if (present.has(name))
1029
+ continue;
1030
+ problems.push({
1031
+ kind: "missing-worker-secret",
1032
+ name,
1033
+ message: `${worker.config} requires ${name}, and the Worker ${worker.worker} doesn't have it`
1034
+ });
1035
+ }
1036
+ }
1037
+ for (const key of input.map?.keys ?? []) {
1038
+ add(key.env, { kind: "map", path: input.map?.file ?? "keypin.toml", keyId: key.id });
1039
+ }
1040
+ const cloudUnknown = unknowns.some((u) => u.cloud);
1041
+ const names = [...sources.entries()].map(([name, list]) => {
1042
+ const local = list.some((s) => LOCAL_KINDS.includes(s.kind));
1043
+ const cloud = list.some((s) => CLOUD_KINDS.includes(s.kind));
1044
+ const configured = list.filter((s) => s.kind !== "map");
1045
+ const variable = configured.length > 0 && configured.every((s) => VARIABLE_KINDS.includes(s.kind));
1046
+ return {
1047
+ name,
1048
+ where: local && cloud ? "both" : local ? "local" : cloud ? "cloud" : variable ? "variable" : "declared",
1049
+ cloudUnknown: !cloud && cloudUnknown,
1050
+ mapped: list.flatMap((s) => s.kind === "map" ? [s.keyId] : []),
1051
+ sources: list,
1052
+ problems: problems.filter((p) => p.name?.toUpperCase() === name.toUpperCase()).map((p) => p.message)
1053
+ };
1054
+ }).sort((a, b) => a.name.localeCompare(b.name));
1055
+ return { names, problems, unknowns };
1056
+ }
1057
+ function workerLabel(worker) {
1058
+ const name = worker.worker ?? "(unnamed)";
1059
+ return worker.env ? `${name} (${worker.config}, env ${worker.env})` : `${name} (${worker.config})`;
1060
+ }
1061
+ function draftMap(names, options) {
1062
+ const lines = [];
1063
+ const taken = new Set(options.takenIds);
1064
+ const vault = options.vault ?? {
1065
+ name: "personal",
1066
+ account: "<your 1Password account>",
1067
+ vault: "<your vault>"
1068
+ };
1069
+ for (const row of names) {
1070
+ if (row.mapped.length)
1071
+ continue;
1072
+ const local = row.sources.some((s) => s.kind === "env-file");
1073
+ const seen = new Set;
1074
+ const publish = row.sources.flatMap((s) => {
1075
+ const place = s.kind === "worker-secret" ? `${s.account}/${s.worker}` : s.kind === "github-secret" ? s.repo.toLowerCase() : "";
1076
+ if (!place || seen.has(place))
1077
+ return [];
1078
+ seen.add(place);
1079
+ if (s.kind === "worker-secret")
1080
+ return [
1081
+ ['to = "cloudflare-worker"', `account = ${str(s.account)}`, `worker = ${str(s.worker)}`]
1082
+ ];
1083
+ if (s.kind === "github-secret") {
1084
+ const account = options.githubAccount;
1085
+ const owner = s.repo.split("/")[0]?.toLowerCase();
1086
+ return [
1087
+ [
1088
+ 'to = "github-actions"',
1089
+ `repo = ${str(s.repo)}`,
1090
+ ...account && account.toLowerCase() !== owner ? [`account = ${str(account)}`] : []
1091
+ ]
1092
+ ];
1093
+ }
1094
+ return [];
1095
+ });
1096
+ if (!local && !publish.length)
1097
+ continue;
1098
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(row.name))
1099
+ continue;
1100
+ const id = freeId(keyIdFor(row.name), taken);
1101
+ const what = row.name.toLowerCase().replaceAll("_", " ").trim();
1102
+ lines.push("", `[keys.${id}]`, `env = ${str(row.name)}`, `owner = ${str(options.owner)}`);
1103
+ if (local) {
1104
+ lines.push("", `[keys.${id}.dev]`, `vault = ${str(vault.name)}`, `item = ${str(`${options.owner} dev ${what}`)}`);
1105
+ }
1106
+ if (publish.length) {
1107
+ lines.push("", `[keys.${id}.prod]`, `vault = ${str(vault.name)}`, `item = ${str(`${options.owner} prod ${what}`)}`);
1108
+ for (const target of publish)
1109
+ lines.push("", `[[keys.${id}.prod.publish]]`, ...target);
1110
+ }
1111
+ }
1112
+ if (!lines.length)
1113
+ return null;
1114
+ const header = [
1115
+ "# Draft from keypin discover; nothing was written. Vault item names are placeholders.",
1116
+ options.vault ? "# The vault is the one in this project's keypin.toml; copy only the [keys.*] tables." : "# Fill in the vault, then save this as keypin.toml.",
1117
+ "",
1118
+ `[vaults.${/^[A-Za-z_][A-Za-z0-9_-]*$/.test(vault.name) ? vault.name : str(vault.name)}]`,
1119
+ 'kind = "1password"',
1120
+ `account = ${str(vault.account)}`,
1121
+ `vault = ${str(vault.vault)}`
1122
+ ];
1123
+ return `${[...header, ...lines].join(`
1124
+ `)}
1125
+ `;
1126
+ }
1127
+ function keyIdFor(name) {
1128
+ return name.toLowerCase().replaceAll("_", "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-") || "key";
1129
+ }
1130
+ function freeId(base, taken) {
1131
+ let id = base;
1132
+ for (let n = 2;taken.has(id); n++)
1133
+ id = `${base}-${n}`;
1134
+ taken.add(id);
1135
+ return id;
1136
+ }
1137
+ function str(value) {
1138
+ return JSON.stringify(value);
1139
+ }
646
1140
  // ../../packages/destination-cloudflare/src/token.ts
647
1141
  import { execFile } from "child_process";
648
1142
  import { readFile } from "fs/promises";
@@ -659,6 +1153,12 @@ async function wranglerToken(path = WRANGLER_CONFIG) {
659
1153
  }
660
1154
  return login.token;
661
1155
  }
1156
+ async function currentWranglerToken(path = WRANGLER_CONFIG) {
1157
+ const login = await readLogin(path);
1158
+ if (login.expired)
1159
+ throw new Error("the wrangler login has expired; run `wrangler whoami`");
1160
+ return login.token;
1161
+ }
662
1162
  async function readLogin(path) {
663
1163
  let text;
664
1164
  try {
@@ -694,7 +1194,7 @@ function refresh() {
694
1194
 
695
1195
  // ../../packages/destination-cloudflare/src/cloudflare.ts
696
1196
  var API = "https://api.cloudflare.com/client/v4";
697
- var ACCOUNT_ID = /^[0-9a-f]{32}$/;
1197
+ var ACCOUNT_ID3 = /^[0-9a-f]{32}$/;
698
1198
  var WORKER = /^[A-Za-z0-9_-]+$/;
699
1199
 
700
1200
  class WorkerSecretDestination {
@@ -706,7 +1206,7 @@ class WorkerSecretDestination {
706
1206
  #token;
707
1207
  #passed = false;
708
1208
  constructor(options) {
709
- if (!ACCOUNT_ID.test(options.account))
1209
+ if (!ACCOUNT_ID3.test(options.account))
710
1210
  throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
711
1211
  if (!WORKER.test(options.worker))
712
1212
  throw new Error(`"${options.worker}" isn't a Worker name`);
@@ -838,6 +1338,85 @@ function objectField(data, field) {
838
1338
  const value = data[field];
839
1339
  return isRecord(value) ? value : {};
840
1340
  }
1341
+ // ../../packages/destination-cloudflare/src/list.ts
1342
+ var API2 = "https://api.cloudflare.com/client/v4";
1343
+ var ACCOUNT_ID4 = /^[0-9a-f]{32}$/;
1344
+ var WORKER2 = /^[A-Za-z0-9_-]+$/;
1345
+
1346
+ class CloudflareReader {
1347
+ #tokenSource;
1348
+ #fetch;
1349
+ #token;
1350
+ #accounts;
1351
+ constructor(options) {
1352
+ this.#tokenSource = options.token;
1353
+ this.#fetch = options.fetch ?? globalThis.fetch;
1354
+ }
1355
+ async listWorkerSecrets(account, worker) {
1356
+ if (!ACCOUNT_ID4.test(account))
1357
+ return { ok: false, reason: `"${account}" isn't a Cloudflare account ID` };
1358
+ if (!WORKER2.test(worker))
1359
+ return { ok: false, reason: `"${worker}" isn't a Worker name` };
1360
+ const accounts = await (this.#accounts ??= this.#accountIds());
1361
+ if (!Array.isArray(accounts))
1362
+ return { ok: false, reason: accounts.reason };
1363
+ if (!accounts.includes(account)) {
1364
+ return {
1365
+ ok: false,
1366
+ reason: `the wrangler login reaches ${accounts.join(", ") || "no account"}, not ${account}`
1367
+ };
1368
+ }
1369
+ const response = await this.#get(`/accounts/${account}/workers/scripts/${worker}/secrets`);
1370
+ if ("reason" in response)
1371
+ return { ok: false, reason: response.reason };
1372
+ if (response.status === 404)
1373
+ return { ok: false, reason: `account ${account} has no Worker named ${worker}` };
1374
+ if (response.status !== 200)
1375
+ return { ok: false, reason: `Cloudflare returned HTTP ${response.status}` };
1376
+ const result = response.body.result;
1377
+ if (!Array.isArray(result))
1378
+ return { ok: false, reason: "Cloudflare's secrets response has no result list" };
1379
+ return {
1380
+ ok: true,
1381
+ secrets: result.flatMap((s) => isRecord(s) && typeof s.name === "string" ? [{ name: s.name, updatedAt: null }] : [])
1382
+ };
1383
+ }
1384
+ async#accountIds() {
1385
+ const ids = [];
1386
+ for (let page = 1;; page++) {
1387
+ const response = await this.#get(`/accounts?per_page=50&page=${page}`);
1388
+ if ("reason" in response)
1389
+ return response;
1390
+ if (response.status !== 200)
1391
+ return { reason: `Cloudflare GET /accounts returned HTTP ${response.status}` };
1392
+ const result = response.body.result;
1393
+ if (!Array.isArray(result))
1394
+ return { reason: "Cloudflare's /accounts response has no list" };
1395
+ for (const account of result) {
1396
+ if (isRecord(account) && typeof account.id === "string")
1397
+ ids.push(account.id);
1398
+ }
1399
+ const info = response.body.result_info;
1400
+ const pages = isRecord(info) ? info.total_pages : undefined;
1401
+ if (typeof pages !== "number" || page >= pages)
1402
+ return ids;
1403
+ }
1404
+ }
1405
+ async#get(path) {
1406
+ let token;
1407
+ try {
1408
+ token = await (this.#token ??= this.#tokenSource());
1409
+ } catch (error) {
1410
+ return { reason: error instanceof Error ? error.message : "no Cloudflare token" };
1411
+ }
1412
+ const response = await this.#fetch(`${API2}${path}`, {
1413
+ method: "GET",
1414
+ headers: { Authorization: `Bearer ${token}` }
1415
+ });
1416
+ const body = await response.json().catch(() => null);
1417
+ return { status: response.status, body: isRecord(body) ? body : {} };
1418
+ }
1419
+ }
841
1420
  // ../../packages/destination-github/src/github.ts
842
1421
  import sodium from "libsodium-wrappers";
843
1422
 
@@ -860,7 +1439,7 @@ function ghToken(login) {
860
1439
  }
861
1440
 
862
1441
  // ../../packages/destination-github/src/github.ts
863
- var API2 = "https://api.github.com";
1442
+ var API3 = "https://api.github.com";
864
1443
  var REPO2 = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
865
1444
  var SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
866
1445
 
@@ -952,7 +1531,7 @@ class GitHubSecretDestination {
952
1531
  }
953
1532
  async#request(method, path, body) {
954
1533
  this.#token ??= this.#tokenSource();
955
- const response = await this.#fetch(`${API2}${path}`, {
1534
+ const response = await this.#fetch(`${API3}${path}`, {
956
1535
  method,
957
1536
  headers: {
958
1537
  Authorization: `Bearer ${await this.#token}`,
@@ -992,6 +1571,229 @@ function stringField(data, field) {
992
1571
  throw new Error(`GitHub's response has no "${field}"`);
993
1572
  return value;
994
1573
  }
1574
+ // ../../packages/destination-github/src/list.ts
1575
+ var API4 = "https://api.github.com";
1576
+ var REPO3 = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
1577
+ async function listRepoSecrets(options) {
1578
+ if (!REPO3.test(options.repo))
1579
+ return {
1580
+ ok: false,
1581
+ reason: `"${options.repo}" isn't a GitHub repository in the form owner/name`
1582
+ };
1583
+ const fetch = options.fetch ?? globalThis.fetch;
1584
+ let token;
1585
+ try {
1586
+ token = await options.token();
1587
+ } catch (error) {
1588
+ return { ok: false, reason: error instanceof Error ? error.message : "no GitHub token" };
1589
+ }
1590
+ const secrets = [];
1591
+ for (let page = 1;; page++) {
1592
+ const path = `/repos/${options.repo}/actions/secrets?per_page=100&page=${page}`;
1593
+ const response = await fetch(`${API4}${path}`, {
1594
+ method: "GET",
1595
+ headers: {
1596
+ Authorization: `Bearer ${token}`,
1597
+ Accept: "application/vnd.github+json",
1598
+ "X-GitHub-Api-Version": "2022-11-28"
1599
+ }
1600
+ });
1601
+ if (response.status !== 200) {
1602
+ await response.body?.cancel();
1603
+ return { ok: false, reason: refusal(response.status, options.repo) };
1604
+ }
1605
+ const body = await response.json().catch(() => null);
1606
+ const list = isRecord(body) && Array.isArray(body.secrets) ? body.secrets : null;
1607
+ if (!list)
1608
+ return { ok: false, reason: "GitHub's secrets response has no secrets list" };
1609
+ for (const secret of list) {
1610
+ if (!isRecord(secret) || typeof secret.name !== "string")
1611
+ continue;
1612
+ secrets.push({
1613
+ name: secret.name,
1614
+ updatedAt: typeof secret.updated_at === "string" ? secret.updated_at : null
1615
+ });
1616
+ }
1617
+ const total = isRecord(body) && typeof body.total_count === "number" ? body.total_count : 0;
1618
+ if (list.length < 100 || secrets.length >= total)
1619
+ return { ok: true, secrets };
1620
+ }
1621
+ }
1622
+ function refusal(status, repo) {
1623
+ if (status === 404)
1624
+ return `HTTP 404: the login can't see ${repo}, or it isn't an admin of it`;
1625
+ if (status === 403)
1626
+ return `HTTP 403: the login isn't allowed to list ${repo}'s secrets`;
1627
+ if (status === 401)
1628
+ return "HTTP 401: the gh login's token was refused";
1629
+ return `GitHub returned HTTP ${status}`;
1630
+ }
1631
+ // ../../packages/provider-cloudflare/src/tokens.ts
1632
+ var API5 = "https://api.cloudflare.com/client/v4";
1633
+ var ACCOUNT_ID5 = /^[0-9a-f]{32}$/;
1634
+ var TOKEN_ID = /^[0-9a-f]{32}$/;
1635
+
1636
+ class CloudflareAccountTokens {
1637
+ #account;
1638
+ #admin;
1639
+ #fetch;
1640
+ constructor(options) {
1641
+ if (!ACCOUNT_ID5.test(options.account))
1642
+ throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
1643
+ this.#account = options.account;
1644
+ this.#admin = options.admin;
1645
+ this.#fetch = options.fetch ?? globalThis.fetch;
1646
+ }
1647
+ describe() {
1648
+ return `Cloudflare account API tokens in account ${this.#account}`;
1649
+ }
1650
+ async verify(secret) {
1651
+ const path = `${this.#base()}/verify`;
1652
+ const reply = await this.#request("GET", path, secret);
1653
+ if (reply.status !== 200)
1654
+ throw failure2("GET", path, reply);
1655
+ const result = objectField3(reply.body, "result");
1656
+ return {
1657
+ id: tokenId(result.id, "verify"),
1658
+ status: text(result.status, "status"),
1659
+ expiresOn: optionalText(result.expires_on)
1660
+ };
1661
+ }
1662
+ async details(id) {
1663
+ const path = `${this.#base()}/${tokenId(id, "details")}`;
1664
+ const reply = await this.#request("GET", path, this.#admin);
1665
+ if (reply.status === 404)
1666
+ return null;
1667
+ if (reply.status !== 200)
1668
+ throw failure2("GET", path, reply);
1669
+ return token(objectField3(reply.body, "result"));
1670
+ }
1671
+ async issue(request) {
1672
+ const path = this.#base();
1673
+ const body = {
1674
+ name: request.name,
1675
+ policies: request.like.policies.map((policy) => ({
1676
+ effect: policy.effect,
1677
+ resources: policy.resources,
1678
+ permission_groups: policy.permissionGroups.map((group) => ({ id: group.id }))
1679
+ })),
1680
+ expires_on: request.expiresOn
1681
+ };
1682
+ if (request.like.condition)
1683
+ body.condition = request.like.condition;
1684
+ const reply = await this.#request("POST", path, this.#admin, body);
1685
+ if (reply.status >= 400 && reply.status < 500)
1686
+ return { refused: failure2("POST", path, reply).message };
1687
+ if (reply.status !== 200)
1688
+ throw failure2("POST", path, reply);
1689
+ const result = objectField3(reply.body, "result");
1690
+ const value = result.value;
1691
+ if (typeof value !== "string" || !value)
1692
+ throw new Error("Cloudflare's create response has no token value");
1693
+ return { token: token(result), value: new Secret(value) };
1694
+ }
1695
+ async revoke(id) {
1696
+ const path = `${this.#base()}/${tokenId(id, "revoke")}`;
1697
+ const reply = await this.#request("DELETE", path, this.#admin);
1698
+ if (reply.status === 404)
1699
+ return "already gone";
1700
+ if (reply.status !== 200)
1701
+ throw failure2("DELETE", path, reply);
1702
+ return "revoked";
1703
+ }
1704
+ #base() {
1705
+ return `/accounts/${this.#account}/tokens`;
1706
+ }
1707
+ async#request(method, path, auth, body) {
1708
+ const response = await this.#fetch(`${API5}${path}`, {
1709
+ method,
1710
+ headers: {
1711
+ Authorization: `Bearer ${auth.reveal()}`,
1712
+ ...body === undefined ? {} : { "Content-Type": "application/json" }
1713
+ },
1714
+ body: body === undefined ? undefined : JSON.stringify(body)
1715
+ });
1716
+ return { status: response.status, body: parseObject3(await response.text()) };
1717
+ }
1718
+ }
1719
+ function token(result) {
1720
+ const policies = result.policies;
1721
+ if (!Array.isArray(policies))
1722
+ throw new Error("Cloudflare's token has no policies list");
1723
+ const condition = result.condition;
1724
+ return {
1725
+ id: tokenId(result.id, "token"),
1726
+ name: text(result.name, "name"),
1727
+ status: text(result.status, "status"),
1728
+ expiresOn: optionalText(result.expires_on),
1729
+ lastUsedOn: optionalText(result.last_used_on),
1730
+ policies: policies.map(policy),
1731
+ condition: isJsonObject(condition) && Object.keys(condition).length ? condition : null
1732
+ };
1733
+ }
1734
+ function policy(raw) {
1735
+ if (!isRecord(raw))
1736
+ throw new Error("a Cloudflare token policy isn't an object");
1737
+ const resources = raw.resources;
1738
+ const groups = raw.permission_groups;
1739
+ if (!isJsonObject(resources))
1740
+ throw new Error("a Cloudflare token policy has no resources");
1741
+ if (!Array.isArray(groups))
1742
+ throw new Error("a Cloudflare token policy has no permission groups");
1743
+ return {
1744
+ effect: text(raw.effect, "effect"),
1745
+ resources,
1746
+ permissionGroups: groups.map((group) => {
1747
+ if (!isRecord(group))
1748
+ throw new Error("a Cloudflare permission group isn't an object");
1749
+ return {
1750
+ id: text(group.id, "permission group id"),
1751
+ name: typeof group.name === "string" ? group.name : "(unnamed)"
1752
+ };
1753
+ })
1754
+ };
1755
+ }
1756
+ function isJson(value) {
1757
+ if (value === null || ["string", "number", "boolean"].includes(typeof value))
1758
+ return true;
1759
+ if (Array.isArray(value))
1760
+ return value.every(isJson);
1761
+ return isJsonObject(value);
1762
+ }
1763
+ function isJsonObject(value) {
1764
+ return isRecord(value) && Object.values(value).every(isJson);
1765
+ }
1766
+ function tokenId(value, where) {
1767
+ if (typeof value !== "string" || !TOKEN_ID.test(value))
1768
+ throw new Error(`Cloudflare's ${where} response has no valid token ID`);
1769
+ return value;
1770
+ }
1771
+ function text(value, field) {
1772
+ if (typeof value !== "string")
1773
+ throw new Error(`Cloudflare's token has no "${field}"`);
1774
+ return value;
1775
+ }
1776
+ function optionalText(value) {
1777
+ return typeof value === "string" && value ? value : null;
1778
+ }
1779
+ function failure2(method, path, reply) {
1780
+ const errors = reply.body.errors;
1781
+ const codes = Array.isArray(errors) ? errors.map((e) => isRecord(e) ? e.code : undefined).filter((c) => typeof c === "string" || typeof c === "number") : [];
1782
+ const detail = codes.length ? `, codes ${codes.join(", ")}` : "";
1783
+ return new Error(`Cloudflare ${method} ${path.split("?")[0]} returned HTTP ${reply.status}${detail}`);
1784
+ }
1785
+ function parseObject3(body) {
1786
+ try {
1787
+ const data = JSON.parse(body);
1788
+ return isRecord(data) ? data : {};
1789
+ } catch {
1790
+ return {};
1791
+ }
1792
+ }
1793
+ function objectField3(data, field) {
1794
+ const value = data[field];
1795
+ return isRecord(value) ? value : {};
1796
+ }
995
1797
  // ../../packages/vault-1password/src/sdk.ts
996
1798
  var desktopConnect = async (account) => {
997
1799
  const sdk = await import("@1password/sdk");
@@ -1170,9 +1972,10 @@ function toDay(value, ref) {
1170
1972
  function messageOf2(error) {
1171
1973
  return error instanceof Error ? error.message : String(error);
1172
1974
  }
1173
- // src/commands/init.ts
1174
- import { join as join4, resolve } from "path";
1975
+ // src/commands/discover.ts
1976
+ import { basename, join as join3, relative, resolve } from "path";
1175
1977
  import { parseArgs } from "util";
1978
+ var {TOML: TOML3 } = globalThis.Bun;
1176
1979
 
1177
1980
  // src/deps.ts
1178
1981
  class UsageError extends Error {
@@ -1182,28 +1985,12 @@ function localDay(date) {
1182
1985
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
1183
1986
  }
1184
1987
 
1185
- // src/paths.ts
1186
- import { join as join2 } from "path";
1187
- function registryPath(deps) {
1188
- return join2(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
1189
- }
1190
- function statePath(deps) {
1191
- return join2(base(deps.env.XDG_STATE_HOME, deps.home, ".local/state"), "keypin", "state.json");
1192
- }
1193
- function base(xdg, home, fallback) {
1194
- return xdg?.startsWith("/") ? xdg : join2(home, fallback);
1195
- }
1196
- function projectCount(registry, path) {
1197
- const count = registry.projects.length;
1198
- return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
1199
- }
1200
-
1201
1988
  // src/project.ts
1202
- import { dirname, join as join3 } from "path";
1989
+ import { dirname, join as join2 } from "path";
1203
1990
  var MAP_FILE = "keypin.toml";
1204
1991
  async function findMap(files, cwd) {
1205
1992
  for (let folder = cwd;; folder = dirname(folder)) {
1206
- const file = join3(folder, MAP_FILE);
1993
+ const file = join2(folder, MAP_FILE);
1207
1994
  const text = await files.read(file);
1208
1995
  if (text !== null) {
1209
1996
  const result = parseMap(text, file);
@@ -1218,24 +2005,365 @@ async function findMap(files, cwd) {
1218
2005
  }
1219
2006
  }
1220
2007
 
1221
- // src/commands/init.ts
1222
- var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
1223
- # Uncomment and edit. Every field is checked; an unknown one is an error.
1224
- #
1225
- # A vault the keys below read from. The name ("personal") is yours to choose.
1226
- # [vaults.personal]
1227
- # kind = "1password"
1228
- # account = "my.1password.com"
1229
- # vault = "Private"
1230
- #
1231
- # A key. Its ID ("example-api-key") stays the same when vault items are renamed.
1232
- # [keys.example-api-key]
1233
- # env = "EXAMPLE_API_KEY" # the variable your program reads
1234
- # owner = "my-project"
1235
- # rotate_every = "180d" # <n>d, <n>w, <n>m or never; leave out to use the vault item's rotate_every
1236
- #
1237
- # Where keypin run reads the value from.
1238
- # [keys.example-api-key.dev]
2008
+ // src/commands/discover.ts
2009
+ async function discover(args, deps) {
2010
+ const { values, positionals } = parseArgs({
2011
+ args,
2012
+ options: { json: { type: "boolean", default: false } },
2013
+ allowPositionals: true
2014
+ });
2015
+ if (positionals.length > 1)
2016
+ throw new UsageError("keypin discover takes at most one folder");
2017
+ const folder = resolve(deps.cwd, positionals[0] ?? ".");
2018
+ if (!await deps.isFolder(folder))
2019
+ throw new Error(`${folder} isn't a folder`);
2020
+ const unknowns = [];
2021
+ const scan = await walk(deps, folder);
2022
+ const tracked = await trackedFiles(deps, folder, scan.envFiles);
2023
+ const envFiles = [];
2024
+ for (const path of scan.envFiles) {
2025
+ const kind = envFileKind(basename(path));
2026
+ if (!kind)
2027
+ continue;
2028
+ const text = await deps.files.read(join3(folder, path));
2029
+ if (text === null)
2030
+ continue;
2031
+ envFiles.push({ path, kind, names: envNames(text), tracked: tracked?.has(path) ?? null });
2032
+ }
2033
+ if (tracked === null && envFiles.some((f) => f.kind === "set")) {
2034
+ unknowns.push({
2035
+ what: "whether env files are tracked by git",
2036
+ reason: "the folder isn't in a git repository",
2037
+ cloud: false
2038
+ });
2039
+ }
2040
+ const top = (await deps.git(folder, ["rev-parse", "--show-toplevel"]))?.trim() || null;
2041
+ const workflows = await readWorkflows(deps, folder, top, unknowns);
2042
+ const workers = [];
2043
+ for (const config of scan.wrangler) {
2044
+ const text = await deps.files.read(join3(folder, config));
2045
+ if (text === null)
2046
+ continue;
2047
+ const parsed = wranglerWorkers(text, config);
2048
+ if (!parsed.ok) {
2049
+ unknowns.push({
2050
+ what: `the Workers in ${config}`,
2051
+ reason: "it couldn't be parsed",
2052
+ cloud: true
2053
+ });
2054
+ continue;
2055
+ }
2056
+ for (const worker of parsed.workers) {
2057
+ const read = worker.worker && worker.account ? await deps.workerSecrets(worker.account, worker.worker).catch((error) => ({
2058
+ ok: false,
2059
+ reason: messageOf(error)
2060
+ })) : null;
2061
+ workers.push({ ...worker, read });
2062
+ }
2063
+ }
2064
+ const origin = top ? await githubOrigin(deps, folder) : null;
2065
+ let github = null;
2066
+ let login = null;
2067
+ if (!top) {
2068
+ unknowns.push({
2069
+ what: "GitHub Actions secrets",
2070
+ reason: "the folder isn't in a git repository",
2071
+ cloud: true
2072
+ });
2073
+ } else if (!origin || "reason" in origin) {
2074
+ unknowns.push({
2075
+ what: "GitHub Actions secrets",
2076
+ reason: origin?.reason ?? "the repository has no origin remote",
2077
+ cloud: true
2078
+ });
2079
+ } else {
2080
+ login = (await deps.git(folder, ["config", "--get", "github.account"]))?.trim() || origin.owner;
2081
+ const read = await deps.githubSecrets(origin.repo, login).catch((error) => ({ ok: false, reason: messageOf(error) }));
2082
+ github = {
2083
+ repo: origin.repo,
2084
+ read: read.ok ? read : { ok: false, reason: `as ${login}: ${read.reason}` }
2085
+ };
2086
+ }
2087
+ const mapText = await deps.files.read(join3(folder, MAP_FILE));
2088
+ let map = null;
2089
+ if (mapText !== null) {
2090
+ const parsed = parseMap(mapText, MAP_FILE);
2091
+ if (parsed.ok)
2092
+ map = parsed.map;
2093
+ else
2094
+ unknowns.push({
2095
+ what: `which names ${MAP_FILE} maps`,
2096
+ reason: parsed.errors.join("; "),
2097
+ cloud: false
2098
+ });
2099
+ }
2100
+ const discovery = buildDiscovery({ envFiles, workflows, workers, github, map, unknowns });
2101
+ const owner = map?.keys[0]?.owner ?? basename(folder);
2102
+ const draft = draftMap(discovery.names, {
2103
+ owner,
2104
+ githubAccount: login,
2105
+ vault: map && mapText !== null ? firstVault(mapText) : null,
2106
+ takenIds: map?.keys.map((k) => k.id) ?? []
2107
+ });
2108
+ if (draft !== null) {
2109
+ const check = parseMap(draft, "draft");
2110
+ if (!check.ok)
2111
+ throw new Error(`the draft doesn't parse: ${check.errors.join("; ")}`);
2112
+ }
2113
+ const report = {
2114
+ folder,
2115
+ repository: github?.repo ?? null,
2116
+ login,
2117
+ files: {
2118
+ env: envFiles.map(({ path, kind, tracked: t }) => ({ path, kind, tracked: t })),
2119
+ wrangler: scan.wrangler,
2120
+ workflows: workflows.map((w) => w.path)
2121
+ },
2122
+ nestedRepositories: scan.nested,
2123
+ ...discovery,
2124
+ draft
2125
+ };
2126
+ deps.stdout.write(values.json ? `${JSON.stringify(report, null, 2)}
2127
+ ` : render(report, discovery));
2128
+ return 0;
2129
+ }
2130
+ async function walk(deps, root) {
2131
+ const scan = { envFiles: [], wrangler: [], nested: [] };
2132
+ const visit = async (folder) => {
2133
+ const entries = (await deps.listFolder(folder)).toSorted((a, b) => a.name.localeCompare(b.name));
2134
+ if (folder !== root && entries.some((e) => e.name === ".git")) {
2135
+ scan.nested.push(relative(root, folder));
2136
+ return;
2137
+ }
2138
+ for (const entry of entries) {
2139
+ const path = join3(folder, entry.name);
2140
+ if (entry.kind === "folder") {
2141
+ if (!SKIPPED_FOLDERS.has(entry.name))
2142
+ await visit(path);
2143
+ } else if (entry.kind === "file") {
2144
+ if (envFileKind(entry.name))
2145
+ scan.envFiles.push(relative(root, path));
2146
+ else if (WRANGLER_FILES.includes(entry.name))
2147
+ scan.wrangler.push(relative(root, path));
2148
+ }
2149
+ }
2150
+ };
2151
+ await visit(root);
2152
+ return scan;
2153
+ }
2154
+ async function trackedFiles(deps, folder, paths) {
2155
+ if (!paths.length)
2156
+ return new Set;
2157
+ const out = await deps.git(folder, ["ls-files", "-z", "--", ...paths]);
2158
+ if (out === null)
2159
+ return null;
2160
+ return new Set(out.split("\x00").filter(Boolean));
2161
+ }
2162
+ async function readWorkflows(deps, folder, top, unknowns) {
2163
+ const dir = join3(top ?? folder, ".github", "workflows");
2164
+ let entries;
2165
+ try {
2166
+ entries = await deps.listFolder(dir);
2167
+ } catch (error) {
2168
+ if (errorCode(error) !== "ENOENT") {
2169
+ unknowns.push({
2170
+ what: "the secrets the workflows use",
2171
+ reason: `${relative(folder, dir)} couldn't be read: ${messageOf(error)}`,
2172
+ cloud: false
2173
+ });
2174
+ }
2175
+ return [];
2176
+ }
2177
+ const workflows = [];
2178
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
2179
+ if (entry.kind !== "file" || !/\.ya?ml$/.test(entry.name))
2180
+ continue;
2181
+ const text = await deps.files.read(join3(dir, entry.name));
2182
+ if (text === null)
2183
+ continue;
2184
+ const path = relative(folder, join3(dir, entry.name));
2185
+ const refs = workflowRefs(text);
2186
+ if (refs)
2187
+ workflows.push({ path, refs });
2188
+ else
2189
+ unknowns.push({
2190
+ what: `the secrets ${path} uses`,
2191
+ reason: "it isn't valid YAML",
2192
+ cloud: false
2193
+ });
2194
+ }
2195
+ return workflows;
2196
+ }
2197
+ var GITHUB_REMOTE = /^(?:https:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/;
2198
+ async function githubOrigin(deps, folder) {
2199
+ const url = (await deps.git(folder, ["remote", "get-url", "origin"]))?.trim();
2200
+ if (!url)
2201
+ return null;
2202
+ const match = GITHUB_REMOTE.exec(url);
2203
+ if (!match?.[1] || !match[2])
2204
+ return { reason: "the origin remote isn't on github.com" };
2205
+ return { repo: `${match[1]}/${match[2]}`, owner: match[1] };
2206
+ }
2207
+ function firstVault(text) {
2208
+ let data;
2209
+ try {
2210
+ data = TOML3.parse(text);
2211
+ } catch {
2212
+ return null;
2213
+ }
2214
+ const vaults = isRecord(data) && isRecord(data.vaults) ? data.vaults : {};
2215
+ for (const [name, raw] of Object.entries(vaults)) {
2216
+ if (!isRecord(raw))
2217
+ continue;
2218
+ const { account, vault } = raw;
2219
+ if (typeof account === "string" && typeof vault === "string")
2220
+ return { name, account, vault };
2221
+ }
2222
+ return null;
2223
+ }
2224
+ var WHERE = {
2225
+ both: "local and cloud",
2226
+ local: "local",
2227
+ cloud: "cloud",
2228
+ declared: "declared, not set",
2229
+ variable: "plain variable"
2230
+ };
2231
+ var LABELS = {
2232
+ "env-file": "local",
2233
+ "example-file": "expected",
2234
+ "github-secret": "cloud",
2235
+ "worker-secret": "cloud",
2236
+ "workflow-secret": "workflow",
2237
+ "workflow-var": "workflow var",
2238
+ "worker-required": "required by",
2239
+ "worker-var": "var in",
2240
+ map: "mapped"
2241
+ };
2242
+ function describe(source) {
2243
+ switch (source.kind) {
2244
+ case "env-file":
2245
+ return source.tracked ? `${source.path} (tracked by git)` : source.path;
2246
+ case "example-file":
2247
+ case "workflow-secret":
2248
+ case "workflow-var":
2249
+ return source.path;
2250
+ case "worker-required":
2251
+ case "worker-var":
2252
+ return source.worker ? `${source.path} (${source.worker})` : source.path;
2253
+ case "github-secret":
2254
+ return `GitHub ${source.repo}${source.updatedAt ? `, updated ${source.updatedAt.slice(0, 10)}` : ""}`;
2255
+ case "worker-secret":
2256
+ return `Worker ${source.worker} (account ${source.account.slice(0, 8)}\u2026)`;
2257
+ case "map":
2258
+ return `${source.path} key ${source.keyId}`;
2259
+ default: {
2260
+ const unknown = source;
2261
+ return JSON.stringify(unknown);
2262
+ }
2263
+ }
2264
+ }
2265
+ function render(report, discovery) {
2266
+ const lines = [`keypin discover ${report.folder}`];
2267
+ lines.push(` GitHub: ${report.repository ? `${report.repository} as ${report.login}` : "no GitHub origin"}`);
2268
+ lines.push(` read: ${count(report.files.env.length, "env file")}, ${count(report.files.wrangler.length, "wrangler config")}, ${count(report.files.workflows.length, "workflow")}`);
2269
+ if (report.nestedRepositories.length)
2270
+ lines.push(` not scanned (own git repository): ${report.nestedRepositories.join(", ")}`);
2271
+ const onlyMissing = (row) => row.sources.every((s) => s.kind === "workflow-secret") && discovery.problems.some((p) => p.kind === "missing-github-secret" && p.name === row.name);
2272
+ const missing = discovery.names.filter(onlyMissing);
2273
+ const shown = discovery.names.filter((row) => !onlyMissing(row));
2274
+ lines.push("", `Names (${discovery.names.length}):`);
2275
+ for (const row of shown) {
2276
+ const where = WHERE[row.where] + (row.cloudUnknown ? ", cloud unknown" : "");
2277
+ const mapped = row.mapped.length ? ", mapped" : "";
2278
+ lines.push(` ${row.name} [${where}${mapped}]`);
2279
+ const groups = new Map;
2280
+ for (const source of row.sources) {
2281
+ const label = LABELS[source.kind];
2282
+ groups.set(label, [...groups.get(label) ?? [], describe(source)]);
2283
+ }
2284
+ for (const [label, items] of groups)
2285
+ lines.push(` ${label}: ${[...new Set(items)].join(", ")}`);
2286
+ for (const problem of row.problems)
2287
+ lines.push(` ! ${problem}`);
2288
+ }
2289
+ if (missing.length) {
2290
+ const byWorkflow = new Map;
2291
+ for (const row of missing) {
2292
+ const files = row.sources.map(describe).join(", ");
2293
+ byWorkflow.set(files, [...byWorkflow.get(files) ?? [], row.name]);
2294
+ }
2295
+ const repo = report.repository ?? "the repository";
2296
+ lines.push("", `Referenced by a workflow, and not a repo secret of ${repo} (${missing.length}):`);
2297
+ for (const [files, names] of byWorkflow)
2298
+ lines.push(` ${files}: ${names.join(", ")}`);
2299
+ }
2300
+ if (!discovery.names.length)
2301
+ lines.push(" (none found)");
2302
+ const loose = discovery.problems.filter((p) => p.name === undefined);
2303
+ if (loose.length) {
2304
+ lines.push("", `Problems (${loose.length}):`);
2305
+ for (const p of loose)
2306
+ lines.push(` ${p.kind}: ${p.message}`);
2307
+ }
2308
+ if (discovery.unknowns.length) {
2309
+ lines.push("", `Unknown (${discovery.unknowns.length}):`);
2310
+ for (const u of discovery.unknowns)
2311
+ lines.push(` ${u.what}: ${u.reason}`);
2312
+ }
2313
+ lines.push("");
2314
+ if (report.draft === null)
2315
+ lines.push("No draft: every name set locally or in the cloud is already mapped.");
2316
+ else
2317
+ lines.push("Draft keypin.toml for the unmapped names (not written):", "", report.draft);
2318
+ return `${lines.join(`
2319
+ `).trimEnd()}
2320
+ `;
2321
+ }
2322
+ function count(n, noun) {
2323
+ return `${n} ${noun}${n === 1 ? "" : "s"}`;
2324
+ }
2325
+
2326
+ // src/commands/init.ts
2327
+ import { join as join5, resolve as resolve2 } from "path";
2328
+ import { parseArgs as parseArgs2 } from "util";
2329
+
2330
+ // src/paths.ts
2331
+ import { dirname as dirname2, join as join4 } from "path";
2332
+ function registryPath(deps) {
2333
+ return join4(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
2334
+ }
2335
+ function statePath(deps) {
2336
+ return join4(base(deps.env.XDG_STATE_HOME, deps.home, ".local/state"), "keypin", "state.json");
2337
+ }
2338
+ function base(xdg, home, fallback) {
2339
+ return xdg?.startsWith("/") ? xdg : join4(home, fallback);
2340
+ }
2341
+ function projectCount(registry, path) {
2342
+ const count = registry.projects.length;
2343
+ return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
2344
+ }
2345
+ function rotationsPath(deps) {
2346
+ return join4(dirname2(statePath(deps)), "rotations.json");
2347
+ }
2348
+
2349
+ // src/commands/init.ts
2350
+ var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
2351
+ # Uncomment and edit. Every field is checked; an unknown one is an error.
2352
+ #
2353
+ # A vault the keys below read from. The name ("personal") is yours to choose.
2354
+ # [vaults.personal]
2355
+ # kind = "1password"
2356
+ # account = "my.1password.com"
2357
+ # vault = "Private"
2358
+ #
2359
+ # A key. Its ID ("example-api-key") stays the same when vault items are renamed.
2360
+ # [keys.example-api-key]
2361
+ # env = "EXAMPLE_API_KEY" # the variable your program reads
2362
+ # owner = "my-project"
2363
+ # rotate_every = "180d" # <n>d, <n>w, <n>m or never; leave out to use the vault item's rotate_every
2364
+ #
2365
+ # Where keypin run reads the value from.
2366
+ # [keys.example-api-key.dev]
1239
2367
  # vault = "personal"
1240
2368
  # item = "my-project dev example api key"
1241
2369
  #
@@ -1254,13 +2382,13 @@ var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, n
1254
2382
  # repo = "owner/repo"
1255
2383
  `;
1256
2384
  async function init(args, deps) {
1257
- const { positionals } = parseArgs({ args, options: {}, allowPositionals: true });
2385
+ const { positionals } = parseArgs2({ args, options: {}, allowPositionals: true });
1258
2386
  if (positionals.length > 1)
1259
2387
  throw new UsageError("keypin init takes at most one folder");
1260
- const folder = resolve(deps.cwd, positionals[0] ?? ".");
2388
+ const folder = resolve2(deps.cwd, positionals[0] ?? ".");
1261
2389
  if (!await deps.isFolder(folder))
1262
2390
  throw new Error(`${folder} isn't a folder`);
1263
- const file = join4(folder, MAP_FILE);
2391
+ const file = join5(folder, MAP_FILE);
1264
2392
  const created = await deps.createFile(file, TEMPLATE);
1265
2393
  if (created === "link")
1266
2394
  throw new Error(`${file} is a symbolic link; keypin init doesn't follow one`);
@@ -1275,7 +2403,123 @@ async function init(args, deps) {
1275
2403
  }
1276
2404
 
1277
2405
  // src/commands/publish.ts
1278
- import { parseArgs as parseArgs2 } from "util";
2406
+ import { parseArgs as parseArgs3 } from "util";
2407
+
2408
+ // src/publishing.ts
2409
+ var NEEDS_APPROVAL = 2;
2410
+ async function locked(deps, body) {
2411
+ const path = statePath(deps);
2412
+ const lockFile = `${path}.lock`;
2413
+ const taken = await deps.lock(lockFile);
2414
+ if (!taken.held) {
2415
+ deps.stderr.write(`${lockedMessage(lockFile, taken.holder)}
2416
+ `);
2417
+ return 1;
2418
+ }
2419
+ try {
2420
+ return await body(path);
2421
+ } finally {
2422
+ await taken.lock.release();
2423
+ }
2424
+ }
2425
+ function lockedMessage(file, holder) {
2426
+ if (holder.pid === null) {
2427
+ return `keypin: ${file} exists but names no process. If no publish or rotate is running, delete that file and try again.`;
2428
+ }
2429
+ if (holder.running === false) {
2430
+ return `keypin: ${file} was left by process ${holder.pid}, which isn't running any more. Delete that file and try again.`;
2431
+ }
2432
+ return `keypin: another publish or rotate (process ${holder.pid}) holds ${file} and is still running. Wait for it to finish.`;
2433
+ }
2434
+ async function checkAccounts(key, entry, deps, say) {
2435
+ say(`
2436
+ Account checks:`);
2437
+ const checked = new Map;
2438
+ let failed = false;
2439
+ for (const target of entry.publish) {
2440
+ const label = describeTarget(target, key.env);
2441
+ try {
2442
+ const destination = deps.destination(target);
2443
+ const check = await destination.checkAccount();
2444
+ checked.set(destinationId(target, key.env), { target, destination, check });
2445
+ say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
2446
+ if (!check.ok)
2447
+ failed = true;
2448
+ } catch (error) {
2449
+ say(` FAILED ${label}: ${messageOf(error)}`);
2450
+ failed = true;
2451
+ }
2452
+ }
2453
+ return failed ? null : checked;
2454
+ }
2455
+ function writesFor(steps, checked) {
2456
+ return steps.flatMap((step) => {
2457
+ if (step.action !== "write")
2458
+ return [];
2459
+ const found = checked.get(step.destinationId);
2460
+ if (!found)
2461
+ throw new Error(`no account check for ${step.destinationId}`);
2462
+ return [{ destinationId: step.destinationId, found }];
2463
+ });
2464
+ }
2465
+ async function writeAll(input) {
2466
+ const { key, environment, entry, secret, generation, writes, path, deps, say } = input;
2467
+ const id = crypto.randomUUID();
2468
+ let state = startOperation(input.state, {
2469
+ id,
2470
+ keyId: key.id,
2471
+ environment,
2472
+ generation,
2473
+ startedAt: deps.now().toISOString(),
2474
+ planned: writes.map((w) => w.destinationId)
2475
+ });
2476
+ await saveState(deps.files, path, state);
2477
+ for (const { destinationId: written, found } of writes) {
2478
+ const label = describeTarget(found.target, key.env);
2479
+ try {
2480
+ const evidence = await found.destination.write(key.env, secret);
2481
+ state = recordReceipt(state, {
2482
+ keyId: key.id,
2483
+ environment,
2484
+ source: entry.ref,
2485
+ destinationId: written,
2486
+ generation,
2487
+ account: {
2488
+ pinned: found.target.account,
2489
+ publisher: found.check.publisher,
2490
+ destinationAccount: found.check.destinationAccount ?? found.target.account
2491
+ },
2492
+ at: deps.now().toISOString(),
2493
+ evidence
2494
+ }, id);
2495
+ await saveState(deps.files, path, state);
2496
+ say(` wrote ${label}`);
2497
+ } catch (error) {
2498
+ say(` FAILED ${label}: ${messageOf(error)}`);
2499
+ return { ok: false, state };
2500
+ }
2501
+ }
2502
+ state = finishAll(state, key.id, environment);
2503
+ await saveState(deps.files, path, state);
2504
+ return { ok: true, state };
2505
+ }
2506
+ function finishAll(state, keyId, environment) {
2507
+ return unfinishedOperations(state, keyId, environment).reduce((s, op) => finishOperation(s, op.id), state);
2508
+ }
2509
+ function rerun(deps, command, args) {
2510
+ const words = [...deps.self, command, ...args].map(shellWord).join(" ");
2511
+ return `To approve, run this in a terminal:
2512
+ cd ${shellWord(deps.cwd)} && ${words}`;
2513
+ }
2514
+ function shellWord(word) {
2515
+ return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
2516
+ }
2517
+ function accountFacts(check) {
2518
+ return `publisher ${check.publisher}, destination account ${check.destinationAccount ?? "unknown"}`;
2519
+ }
2520
+ function describeTarget(target, secretName) {
2521
+ return `${destinationId(target, secretName)} (account ${target.account})`;
2522
+ }
1279
2523
 
1280
2524
  // src/vault.ts
1281
2525
  function announce(stderr, what, refs) {
@@ -1300,35 +2544,13 @@ function distinctRefs(refs) {
1300
2544
  var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item]);
1301
2545
 
1302
2546
  // src/commands/publish.ts
1303
- var NEEDS_APPROVAL = 2;
1304
2547
  async function publish(args, deps) {
1305
2548
  const request = parseRequest(args);
1306
2549
  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.`;
2550
+ return locked(deps, (path) => publishLocked({ ...request, args }, map, path, deps));
1329
2551
  }
1330
2552
  function parseRequest(args) {
1331
- const { values, positionals } = parseArgs2({
2553
+ const { values, positionals } = parseArgs3({
1332
2554
  args,
1333
2555
  options: {
1334
2556
  env: { type: "string", default: "prod" },
@@ -1363,29 +2585,12 @@ async function publishLocked(request, map, path, deps) {
1363
2585
  say(`The map lists no destinations for ${keyId} (${environment}); nothing to publish.`);
1364
2586
  return 1;
1365
2587
  }
1366
- let state = await loadState(deps.files, path);
2588
+ const state = await loadState(deps.files, path);
1367
2589
  for (const op of unfinishedOperations(state, keyId, environment)) {
1368
2590
  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
2591
  }
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) {
2592
+ const checked = await checkAccounts(key, entry, deps, say);
2593
+ if (!checked) {
1389
2594
  say("Stopped: an account check failed. Nothing was read and nothing was written.");
1390
2595
  return 1;
1391
2596
  }
@@ -1396,7 +2601,7 @@ Needs approval:`);
1396
2601
  for (const approval of approvals)
1397
2602
  say(` ${approval.approval}`);
1398
2603
  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));
2604
+ say(rerun(deps, "publish", request.args));
1400
2605
  return NEEDS_APPROVAL;
1401
2606
  }
1402
2607
  announce(deps.stderr, "the value to publish", [entry.ref]);
@@ -1411,17 +2616,14 @@ Needs approval:`);
1411
2616
  const plan = planPublish({ key, environment, receipts: state.receipts, generation });
1412
2617
  say(`
1413
2618
  Plan for generation ${generation}:`);
1414
- const writes = [];
2619
+ const writes = writesFor(plan.steps, checked);
1415
2620
  for (const step of plan.steps) {
1416
2621
  const found = checked.get(step.destinationId);
1417
- if (!found)
1418
- throw new Error(`no account check for ${step.destinationId}`);
1419
2622
  say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
1420
- say(` ${accountFacts(found.check)}`);
2623
+ if (found)
2624
+ say(` ${accountFacts(found.check)}`);
1421
2625
  if (step.approval)
1422
2626
  say(` needs approval: ${step.approval}`);
1423
- if (step.action === "write")
1424
- writes.push({ destinationId: step.destinationId, found });
1425
2627
  }
1426
2628
  for (const removed of plan.removed) {
1427
2629
  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 +2637,22 @@ Plan for generation ${generation}:`);
1435
2637
  }
1436
2638
  if (!await confirmed(deps, plan.needsApproval, request))
1437
2639
  return NEEDS_APPROVAL;
1438
- const id = crypto.randomUUID();
1439
- state = startOperation(state, {
1440
- id,
1441
- keyId,
2640
+ const written = await writeAll({
2641
+ key,
1442
2642
  environment,
2643
+ entry,
2644
+ secret,
1443
2645
  generation,
1444
- startedAt: deps.now().toISOString(),
1445
- planned: writes.map((w) => w.destinationId)
2646
+ writes,
2647
+ state,
2648
+ path,
2649
+ deps,
2650
+ say
1446
2651
  });
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
- }
2652
+ if (!written.ok) {
2653
+ say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
2654
+ return 1;
1473
2655
  }
1474
- state = finishAll(state, keyId, environment);
1475
- await saveState(deps.files, path, state);
1476
2656
  say(`Published ${keyId} (${environment}) to ${writes.length} destination(s).`);
1477
2657
  return 0;
1478
2658
  }
@@ -1489,31 +2669,498 @@ async function confirmed(deps, needsApproval, request) {
1489
2669
  return false;
1490
2670
  }
1491
2671
  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));
2672
+ say(rerun(deps, "publish", request.args));
1493
2673
  return false;
1494
2674
  }
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}`;
2675
+
2676
+ // src/commands/rotate.ts
2677
+ import { parseArgs as parseArgs4 } from "util";
2678
+ var GRACE_DAYS = DUE_SOON_DAYS;
2679
+ async function rotate(args, deps) {
2680
+ const { values, positionals } = parseArgs4({
2681
+ args,
2682
+ options: {
2683
+ env: { type: "string", default: "prod" },
2684
+ yes: { type: "boolean", default: false }
2685
+ },
2686
+ allowPositionals: true
2687
+ });
2688
+ const [keyId, ...extra] = positionals;
2689
+ if (keyId === undefined || extra.length)
2690
+ throw new UsageError("keypin rotate takes one key ID");
2691
+ const environment = ENVIRONMENTS.find((name) => name === values.env);
2692
+ if (!environment) {
2693
+ throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
2694
+ }
2695
+ const map = await findMap(deps.files, deps.cwd);
2696
+ const key = map.keys.find((k) => k.id === keyId);
2697
+ if (!key)
2698
+ throw new Error(`${map.file} has no key "${keyId}"`);
2699
+ const entry = key.environments[environment];
2700
+ if (!entry)
2701
+ throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
2702
+ const issue = entry.issue;
2703
+ if (!issue) {
2704
+ throw new Error(`key "${keyId}" has no [keys.${keyId}.${environment}.issue] section in ${map.file}, so keypin can't make a new value`);
2705
+ }
2706
+ const say = (text) => deps.stderr.write(`${text}
2707
+ `);
2708
+ return locked(deps, async (statePath) => {
2709
+ const run = {
2710
+ key,
2711
+ entry,
2712
+ issue,
2713
+ environment,
2714
+ yes: values.yes,
2715
+ args,
2716
+ statePath,
2717
+ rotationsPath: rotationsPath(deps),
2718
+ deps,
2719
+ say
2720
+ };
2721
+ const data = await loadRotations(deps.files, run.rotationsPath);
2722
+ const open = unfinishedRotation(data, key.id, environment, entry.ref);
2723
+ if (!open)
2724
+ return start(run, data);
2725
+ say(`An unfinished rotation of ${key.id} (${environment}), started ${open.startedAt}, is at stage "${open.stage}".`);
2726
+ if (open.provider !== issue.provider || open.account !== issue.account) {
2727
+ say(`Stopped: that rotation made its token as ${open.provider} in account ${open.account}, and the map now says ${issue.provider} in account ${issue.account}. Put the map back to finish it. Nothing was changed.`);
2728
+ return 1;
2729
+ }
2730
+ switch (open.stage) {
2731
+ case "issuing":
2732
+ case "issued":
2733
+ return abandon(run, data, open);
2734
+ case "stored":
2735
+ return publishNew(run, data, open, null);
2736
+ case "published":
2737
+ return revokeOld(run, data, open);
2738
+ case "revoked":
2739
+ throw new Error(`rotation ${open.id} is finished`);
2740
+ }
2741
+ });
1499
2742
  }
1500
- function shellWord(word) {
1501
- return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
2743
+ async function start(run, data) {
2744
+ const { key, entry, issue, environment, deps, say } = run;
2745
+ say(`Rotating ${key.id} (${environment}) as ${key.env}, item "${entry.ref.item}"`);
2746
+ say(` vault: 1Password account ${entry.ref.account}, vault "${entry.ref.vault}"`);
2747
+ say(` new token: ${issue.provider} in account ${issue.account}, made with the admin token in item "${issue.admin.item}"`);
2748
+ for (const target of entry.publish)
2749
+ say(` to: ${describeTarget(target, key.env)}`);
2750
+ if (!entry.publish.length) {
2751
+ say(`Stopped: the map lists no destinations for ${key.id} (${environment}), so nothing would get the new token. Nothing was changed.`);
2752
+ return 1;
2753
+ }
2754
+ const state = await loadState(deps.files, run.statePath);
2755
+ const checked = await checkAccounts(key, entry, deps, say);
2756
+ if (!checked) {
2757
+ say("Stopped: an account check failed. Nothing was read and nothing was changed.");
2758
+ return 1;
2759
+ }
2760
+ const approvals = approvalsFor({ key, environment, receipts: state.receipts });
2761
+ if (!deps.isTerminal && (approvals.length || !run.yes)) {
2762
+ for (const approval of approvals)
2763
+ say(` needs approval: ${approval.approval}`);
2764
+ 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.");
2765
+ say(rerun(deps, "rotate", run.args));
2766
+ return NEEDS_APPROVAL;
2767
+ }
2768
+ announce(deps.stderr, "the current value, its rotation fields and the admin token", [
2769
+ entry.ref,
2770
+ issue.admin
2771
+ ]);
2772
+ const vault = deps.vault();
2773
+ let current;
2774
+ let admin;
2775
+ let every;
2776
+ try {
2777
+ current = await vault.read(entry.ref);
2778
+ every = key.rotateEvery ?? (await vault.metadata(entry.ref)).rotateEvery;
2779
+ admin = await vault.read(issue.admin);
2780
+ } catch (error) {
2781
+ say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
2782
+ return 1;
2783
+ }
2784
+ const days = periodDays(every);
2785
+ if (!days) {
2786
+ say(`Stopped: rotate needs a rotation period to set the new token's expiry, and rotate_every is ${every ? `"${every}"` : "missing"}. Nothing was changed.`);
2787
+ return 1;
2788
+ }
2789
+ const provider = deps.provider(issue, admin);
2790
+ const found = await provider.verify(current);
2791
+ if (found.status !== "active") {
2792
+ say(`Stopped: the current value is token ${found.id}, and it's ${found.status}. Nothing was changed.`);
2793
+ return 1;
2794
+ }
2795
+ const old = await provider.details(found.id);
2796
+ if (!old) {
2797
+ say(`Stopped: the admin token can't read token ${found.id}, the current value's token. Nothing was changed.`);
2798
+ return 1;
2799
+ }
2800
+ const today = localDay(deps.now());
2801
+ const name = nextName(old.name, today);
2802
+ const expiresOn = `${addDays(today, days + GRACE_DAYS)}T23:59:59Z`;
2803
+ say(`
2804
+ Plan:`);
2805
+ say(` current token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "never"}`);
2806
+ say(` new token: "${name}", expires ${expiresOn} (rotate_every ${every} plus ${GRACE_DAYS} days' grace)`);
2807
+ for (const line of describeAccess(old))
2808
+ say(` ${line}`);
2809
+ say(` store in: item "${entry.ref.item}", with rotated ${today}`);
2810
+ for (const target of entry.publish) {
2811
+ const found = checked.get(destinationId(target, key.env));
2812
+ say(` publish to: ${describeTarget(target, key.env)}`);
2813
+ if (found)
2814
+ say(` ${accountFacts(found.check)}`);
2815
+ }
2816
+ for (const approval of approvals)
2817
+ say(` needs approval: ${approval.approval}`);
2818
+ say(` then stop: the old token stays active until you run ${again(run)} again.`);
2819
+ if (!await confirmed2(run, approvals.length > 0, "make the new token"))
2820
+ return NEEDS_APPROVAL;
2821
+ const now = deps.now().toISOString();
2822
+ let rotation = {
2823
+ id: crypto.randomUUID(),
2824
+ keyId: key.id,
2825
+ environment,
2826
+ item: entry.ref,
2827
+ provider: issue.provider,
2828
+ account: issue.account,
2829
+ stage: "issuing",
2830
+ startedAt: now,
2831
+ updatedAt: now,
2832
+ old: {
2833
+ id: old.id,
2834
+ name: old.name,
2835
+ expiresOn: old.expiresOn,
2836
+ generation: await generationOf(current)
2837
+ },
2838
+ new: { id: null, name, expiresOn, generation: null }
2839
+ };
2840
+ data = putRotation(withoutFinished(data, key.id, environment), rotation);
2841
+ await saveRotations(deps.files, run.rotationsPath, data);
2842
+ const made = await provider.issue({ name, like: old, expiresOn });
2843
+ if ("refused" in made) {
2844
+ await saveRotations(deps.files, run.rotationsPath, dropRotation(data, rotation.id));
2845
+ say(`Stopped: ${made.refused}. No token was made, and nothing was changed.`);
2846
+ return 1;
2847
+ }
2848
+ const generation = await generationOf(made.value);
2849
+ rotation = {
2850
+ ...rotation,
2851
+ stage: "issued",
2852
+ updatedAt: deps.now().toISOString(),
2853
+ new: { id: made.token.id, name: made.token.name, expiresOn: made.token.expiresOn, generation }
2854
+ };
2855
+ data = putRotation(data, rotation);
2856
+ await saveRotations(deps.files, run.rotationsPath, data);
2857
+ say(`
2858
+ issued ${made.token.id} "${made.token.name}", expires ${made.token.expiresOn ?? "never"}`);
2859
+ const problem = await checkNew(provider, made.token.id, made.value, old);
2860
+ if (problem) {
2861
+ say(` FAILED the new token's check: ${problem}`);
2862
+ return deleteUnchecked(run, data, rotation, provider);
2863
+ }
2864
+ say(` checked: ${made.token.id} is active and has the same policies as ${old.id}`);
2865
+ say(`keypin: writing the new value to item "${entry.ref.item}", with rotated ${today}`);
2866
+ try {
2867
+ await vault.write(entry.ref, made.value, { rotated: today });
2868
+ const stored = await generationOf(await vault.read(entry.ref));
2869
+ if (stored !== generation)
2870
+ throw new Error(`the item reads back generation ${stored}, not ${generation}`);
2871
+ } catch (error) {
2872
+ say(`Stopped: couldn't store the new value: ${messageOf(error)}.`);
2873
+ 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.`);
2874
+ return 1;
2875
+ }
2876
+ rotation = { ...rotation, stage: "stored", updatedAt: deps.now().toISOString() };
2877
+ data = putRotation(data, rotation);
2878
+ await saveRotations(deps.files, run.rotationsPath, data);
2879
+ say(` stored generation ${generation}`);
2880
+ return publishNew(run, data, rotation, { value: made.value, checked });
2881
+ }
2882
+ async function publishNew(run, data, rotation, fresh) {
2883
+ const { key, entry, environment, deps, say } = run;
2884
+ const state = await loadState(deps.files, run.statePath);
2885
+ let value;
2886
+ let checked;
2887
+ const resuming = fresh === null;
2888
+ if (fresh) {
2889
+ ({ value, checked } = fresh);
2890
+ } else {
2891
+ say(`It stored the new value (generation ${rotation.new.generation}); this run publishes it.`);
2892
+ const found = await checkAccounts(key, entry, deps, say);
2893
+ if (!found) {
2894
+ say("Stopped: an account check failed. Nothing was read and nothing was written.");
2895
+ return 1;
2896
+ }
2897
+ checked = found;
2898
+ if (!deps.isTerminal && approvalsFor({ key, environment, receipts: state.receipts }).length) {
2899
+ say("Stopped before reading the value: publishing needs approval, and --yes can't give it.");
2900
+ say(rerun(deps, "rotate", run.args));
2901
+ return NEEDS_APPROVAL;
2902
+ }
2903
+ announce(deps.stderr, "the value to publish and the admin token, to check the new token", [
2904
+ entry.ref,
2905
+ run.issue.admin
2906
+ ]);
2907
+ value = await deps.vault().read(entry.ref);
2908
+ const generation = await generationOf(value);
2909
+ if (generation !== rotation.new.generation) {
2910
+ say(`Stopped: item "${entry.ref.item}" holds generation ${generation}, not the rotation's ${rotation.new.generation}. Something else changed it. Nothing was written.`);
2911
+ return 1;
2912
+ }
2913
+ const problem = await recheck(run, rotation, value);
2914
+ if (problem) {
2915
+ say(`Stopped: ${problem}. Nothing was written, and the rotation stays at "${rotation.stage}". The old token still works where it was published.`);
2916
+ return 1;
2917
+ }
2918
+ say(` checked: ${rotation.new.id} is active and has the same policies as ${rotation.old.id}`);
2919
+ }
2920
+ const generation = rotation.new.generation ?? await generationOf(value);
2921
+ const plan = planPublish({ key, environment, receipts: state.receipts, generation });
2922
+ say(`
2923
+ Publishing generation ${generation}:`);
2924
+ for (const step of plan.steps) {
2925
+ say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
2926
+ if (step.approval)
2927
+ say(` needs approval: ${step.approval}`);
2928
+ }
2929
+ const writes = writesFor(plan.steps, checked);
2930
+ if (resuming && writes.length && !await confirmed2(run, plan.needsApproval, "publish")) {
2931
+ return NEEDS_APPROVAL;
2932
+ }
2933
+ const written = await writeAll({
2934
+ key,
2935
+ environment,
2936
+ entry,
2937
+ secret: value,
2938
+ generation,
2939
+ writes,
2940
+ state,
2941
+ path: run.statePath,
2942
+ deps,
2943
+ say
2944
+ });
2945
+ if (!written.ok) {
2946
+ say(`Stopped. The old token still works where the write failed. Run ${again(run)} again to finish publishing.`);
2947
+ return 1;
2948
+ }
2949
+ const published = {
2950
+ ...rotation,
2951
+ stage: "published",
2952
+ updatedAt: deps.now().toISOString()
2953
+ };
2954
+ await saveRotations(deps.files, run.rotationsPath, putRotation(data, published));
2955
+ say(`
2956
+ Published. The old token ${rotation.old.id} "${rotation.old.name}" is still active.`);
2957
+ say("Next, check that every consumer works with the new value:");
2958
+ for (const target of entry.publish)
2959
+ say(` ${describeTarget(target, key.env)}`);
2960
+ for (const consumer of key.consumers)
2961
+ say(` ${consumer.name} (${consumer.kind})`);
2962
+ say(`Then run ${again(run)} again to revoke the old token.`);
2963
+ return 0;
1502
2964
  }
1503
- function finishAll(state, keyId, environment) {
1504
- return unfinishedOperations(state, keyId, environment).reduce((s, op) => finishOperation(s, op.id), state);
2965
+ async function revokeOld(run, data, rotation) {
2966
+ const { key, issue, environment, deps, say } = run;
2967
+ const generation = rotation.new.generation;
2968
+ if (!generation || !rotation.new.id || !rotation.old.id) {
2969
+ throw new Error(`rotation ${rotation.id} has no new generation or token IDs`);
2970
+ }
2971
+ const state = await loadState(deps.files, run.statePath);
2972
+ const plan = planPublish({ key, environment, receipts: state.receipts, generation });
2973
+ const behind = plan.steps.filter((step) => step.action === "write");
2974
+ for (const step of behind) {
2975
+ say(` ${step.destinationId} doesn't have generation ${generation}: ${step.reason}`);
2976
+ }
2977
+ const retired = plan.removed.filter((removed) => removed.lastReceipt.generation === rotation.old.generation);
2978
+ if (behind.length) {
2979
+ say(`Stopped: run keypin publish ${key.id}${environment === "prod" ? "" : ` --env ${environment}`} first. Nothing was revoked.`);
2980
+ return 1;
2981
+ }
2982
+ say(`Every destination's receipt has generation ${generation}.`);
2983
+ for (const removed of retired) {
2984
+ say(` ${removed.destinationId} left the map and its receipt has the old token (generation ${removed.lastReceipt.generation}); revoking breaks it unless that secret is gone`);
2985
+ }
2986
+ if (!deps.isTerminal) {
2987
+ say("Stopped: revoking needs yes typed in a terminal, and --yes can't give it. Nothing was revoked.");
2988
+ say(rerun(deps, "rotate", run.args));
2989
+ return NEEDS_APPROVAL;
2990
+ }
2991
+ announce(deps.stderr, "the admin token", [issue.admin]);
2992
+ const provider = deps.provider(issue, await deps.vault().read(issue.admin));
2993
+ const current = await provider.details(rotation.new.id);
2994
+ if (current?.status !== "active") {
2995
+ say(`Stopped: the new token ${rotation.new.id} is ${current ? current.status : "gone"}. Nothing was revoked.`);
2996
+ return 1;
2997
+ }
2998
+ const old = await provider.details(rotation.old.id);
2999
+ if (!old) {
3000
+ say(`The old token ${rotation.old.id} is already gone.`);
3001
+ return finish(run, data, rotation);
3002
+ }
3003
+ say(`
3004
+ Old token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "never"}`);
3005
+ say(` last used: ${old.lastUsedOn ?? "not reported"}`);
3006
+ say(`New token: ${current.id} "${current.name}", ${current.status}, expires ${current.expiresOn ?? "never"}`);
3007
+ const answer = await deps.ask(`Type yes to revoke the old token ${old.id}: `);
3008
+ if (answer.trim() !== "yes") {
3009
+ say("Not confirmed. Nothing was revoked.");
3010
+ return NEEDS_APPROVAL;
3011
+ }
3012
+ say(` ${await provider.revoke(old.id)} ${old.id}`);
3013
+ return finish(run, data, rotation);
1505
3014
  }
1506
- function accountFacts(check) {
1507
- return `publisher ${check.publisher}, destination account ${check.destinationAccount ?? "unknown"}`;
3015
+ async function finish(run, data, rotation) {
3016
+ const done = { ...rotation, stage: "revoked", updatedAt: run.deps.now().toISOString() };
3017
+ await saveRotations(run.deps.files, run.rotationsPath, putRotation(data, done));
3018
+ run.say(`Rotated ${run.key.id} (${run.environment}): ${rotation.new.id} replaced ${rotation.old.id}.`);
3019
+ return 0;
1508
3020
  }
1509
- function describeTarget(target, secretName) {
1510
- return `${destinationId(target, secretName)} (account ${target.account})`;
3021
+ async function abandon(run, data, rotation) {
3022
+ const { entry, issue, deps, say } = run;
3023
+ if (rotation.new.generation) {
3024
+ announce(deps.stderr, "the current value, to see which token it holds", [entry.ref]);
3025
+ const holds = await generationOf(await deps.vault().read(entry.ref));
3026
+ if (holds === rotation.new.generation) {
3027
+ const stored = {
3028
+ ...rotation,
3029
+ stage: "stored",
3030
+ updatedAt: deps.now().toISOString()
3031
+ };
3032
+ const next = putRotation(data, stored);
3033
+ await saveRotations(deps.files, run.rotationsPath, next);
3034
+ say(`Item "${entry.ref.item}" already holds the new value (generation ${holds}).`);
3035
+ return publishNew(run, next, stored, null);
3036
+ }
3037
+ if (holds !== rotation.old.generation) {
3038
+ say(`Stopped: item "${entry.ref.item}" holds generation ${holds}, neither the old ${rotation.old.generation} nor the new ${rotation.new.generation}. Something else changed it. Nothing was changed.`);
3039
+ return 1;
3040
+ }
3041
+ }
3042
+ say(`It stopped before the new value was stored, so the old token ${rotation.old.id} still works everywhere.`);
3043
+ if (!deps.isTerminal) {
3044
+ say("Stopped: cleaning it up needs yes typed in a terminal. Nothing was changed.");
3045
+ say(rerun(deps, "rotate", run.args));
3046
+ return NEEDS_APPROVAL;
3047
+ }
3048
+ const id = rotation.new.id;
3049
+ if (!id) {
3050
+ 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.`);
3051
+ if ((await deps.ask("Type yes to forget this rotation: ")).trim() !== "yes") {
3052
+ say("Not confirmed. Nothing was changed.");
3053
+ return NEEDS_APPROVAL;
3054
+ }
3055
+ } else {
3056
+ announce(deps.stderr, "the admin token", [issue.admin]);
3057
+ const provider = deps.provider(issue, await deps.vault().read(issue.admin));
3058
+ const made = await provider.details(id);
3059
+ if (made) {
3060
+ say(`New token: ${made.id} "${made.name}", ${made.status}, its value was never stored`);
3061
+ if ((await deps.ask(`Type yes to delete the new token ${made.id}: `)).trim() !== "yes") {
3062
+ say("Not confirmed. Nothing was changed.");
3063
+ return NEEDS_APPROVAL;
3064
+ }
3065
+ say(` ${await provider.revoke(made.id)} ${made.id}`);
3066
+ } else {
3067
+ say(`The new token ${id} is already gone.`);
3068
+ }
3069
+ }
3070
+ await saveRotations(deps.files, run.rotationsPath, dropRotation(data, rotation.id));
3071
+ say(`Cleared. Run ${again(run)} again to start over.`);
3072
+ return 1;
3073
+ }
3074
+ async function deleteUnchecked(run, data, rotation, provider) {
3075
+ const id = rotation.new.id;
3076
+ if (!id)
3077
+ throw new Error(`rotation ${rotation.id} has no new token ID`);
3078
+ try {
3079
+ run.say(` ${await provider.revoke(id)} ${id}, the token this run made`);
3080
+ } catch (error) {
3081
+ run.say(`Couldn't delete the new token ${id}: ${messageOf(error)}.`);
3082
+ run.say(`Nothing else was changed, and the old token still works everywhere. Run ${again(run)} again to delete it.`);
3083
+ return 1;
3084
+ }
3085
+ await saveRotations(run.deps.files, run.rotationsPath, dropRotation(data, rotation.id));
3086
+ run.say("Stopped. Nothing else was changed, and the old token still works everywhere.");
3087
+ return 1;
3088
+ }
3089
+ async function recheck(run, rotation, value) {
3090
+ if (!rotation.new.id || !rotation.old.id)
3091
+ return "the rotation has no token IDs";
3092
+ const provider = run.deps.provider(run.issue, await run.deps.vault().read(run.issue.admin));
3093
+ const old = await provider.details(rotation.old.id);
3094
+ if (!old)
3095
+ return `the old token ${rotation.old.id} is gone, so its policies can't be compared`;
3096
+ return checkNew(provider, rotation.new.id, value, old);
3097
+ }
3098
+ function again(run) {
3099
+ return rotateCommand(run.key.id, run.environment);
3100
+ }
3101
+ async function checkNew(provider, id, value, old) {
3102
+ try {
3103
+ const seen = await provider.verify(value);
3104
+ if (seen.id !== id)
3105
+ return `the new value verifies as token ${seen.id}, not ${id}`;
3106
+ if (seen.status !== "active")
3107
+ return `the new token is ${seen.status}`;
3108
+ const made = await provider.details(id);
3109
+ if (!made)
3110
+ return "the admin token can't read the new token";
3111
+ if (!sameAccess(made, old))
3112
+ return `its policies differ from ${old.id}'s`;
3113
+ return null;
3114
+ } catch (error) {
3115
+ return messageOf(error);
3116
+ }
3117
+ }
3118
+ async function confirmed2(run, needsApproval, what) {
3119
+ const { deps, say } = run;
3120
+ if (run.yes && !needsApproval)
3121
+ return true;
3122
+ if (deps.isTerminal) {
3123
+ const answer = await deps.ask(`Type yes to ${what}${needsApproval ? " (this plan needs approval)" : ""}: `);
3124
+ if (answer.trim() === "yes")
3125
+ return true;
3126
+ say("Not confirmed. Nothing was changed.");
3127
+ return false;
3128
+ }
3129
+ say("Stopped: this plan needs approval, and --yes can't give it. Nothing was changed.");
3130
+ say(rerun(deps, "rotate", run.args));
3131
+ return false;
3132
+ }
3133
+ function withoutFinished(data, keyId, environment) {
3134
+ return {
3135
+ ...data,
3136
+ rotations: data.rotations.filter((r) => !(r.keyId === keyId && r.environment === environment && r.stage === "revoked"))
3137
+ };
3138
+ }
3139
+ var DATED = /^(.*) (\d{4}-\d{2}-\d{2})(?: #(\d+))?$/;
3140
+ function nextName(old, today) {
3141
+ const match = DATED.exec(old);
3142
+ const base = match?.[1] ?? old;
3143
+ if (match?.[2] !== today)
3144
+ return `${base} ${today}`;
3145
+ return `${base} ${today} #${Number(match[3] ?? 1) + 1}`;
3146
+ }
3147
+ function describeAccess(token) {
3148
+ const lines = ["policies it copies:"];
3149
+ for (const policy of token.policies) {
3150
+ const groups = policy.permissionGroups.map((g) => g.name).join(", ");
3151
+ lines.push(` ${policy.effect} ${groups}`);
3152
+ for (const [resource, scope] of Object.entries(policy.resources)) {
3153
+ lines.push(` on ${resource}: ${JSON.stringify(scope)}`);
3154
+ }
3155
+ }
3156
+ lines.push(`condition: ${token.condition ? JSON.stringify(token.condition) : "none"}`);
3157
+ return lines;
1511
3158
  }
1512
3159
 
1513
3160
  // src/commands/run.ts
1514
- import { parseArgs as parseArgs3 } from "util";
3161
+ import { parseArgs as parseArgs5 } from "util";
1515
3162
  async function run(args, deps) {
1516
- const { positionals } = parseArgs3({ args, options: {}, allowPositionals: true });
3163
+ const { positionals } = parseArgs5({ args, options: {}, allowPositionals: true });
1517
3164
  if (!positionals.length)
1518
3165
  throw new UsageError("keypin run needs a command after --");
1519
3166
  const map = await findMap(deps.files, deps.cwd);
@@ -1579,10 +3226,10 @@ async function run(args, deps) {
1579
3226
  }
1580
3227
 
1581
3228
  // src/commands/status.ts
1582
- import { join as join5 } from "path";
1583
- import { parseArgs as parseArgs4 } from "util";
3229
+ import { join as join6 } from "path";
3230
+ import { parseArgs as parseArgs6 } from "util";
1584
3231
  async function status(args, deps) {
1585
- const { values, positionals } = parseArgs4({
3232
+ const { values, positionals } = parseArgs6({
1586
3233
  args,
1587
3234
  options: { json: { type: "boolean", default: false } },
1588
3235
  allowPositionals: true
@@ -1591,9 +3238,10 @@ async function status(args, deps) {
1591
3238
  throw new UsageError("keypin status takes no arguments");
1592
3239
  const registry = await loadRegistry(deps.files, registryPath(deps));
1593
3240
  const state = await loadState(deps.files, statePath(deps));
3241
+ const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
1594
3242
  const maps = new Map;
1595
3243
  for (const project of registry.projects) {
1596
- const file = join5(project, MAP_FILE);
3244
+ const file = join6(project, MAP_FILE);
1597
3245
  try {
1598
3246
  const text = await deps.files.read(file);
1599
3247
  if (text !== null)
@@ -1622,6 +3270,7 @@ async function status(args, deps) {
1622
3270
  registry,
1623
3271
  maps,
1624
3272
  receipts: state.receipts,
3273
+ rotations,
1625
3274
  metadata: (ref) => metadata.get(refKey(ref)) ?? null,
1626
3275
  today: localDay(deps.now())
1627
3276
  });
@@ -1629,11 +3278,11 @@ async function status(args, deps) {
1629
3278
  deps.stdout.write(`${JSON.stringify({ today: localDay(deps.now()), ...result }, null, 2)}
1630
3279
  `);
1631
3280
  } else {
1632
- deps.stdout.write(render(result, registry.projects.length));
3281
+ deps.stdout.write(render2(result, registry.projects.length));
1633
3282
  }
1634
3283
  return result.problems.some((p) => p.severity === "problem") ? 1 : 0;
1635
3284
  }
1636
- function render(result, projects) {
3285
+ function render2(result, projects) {
1637
3286
  if (!projects)
1638
3287
  return `No projects registered. Run "keypin init" in a project folder.
1639
3288
  `;
@@ -1700,13 +3349,13 @@ function shown(problems) {
1700
3349
  }
1701
3350
 
1702
3351
  // src/commands/unregister.ts
1703
- import { resolve as resolve2 } from "path";
1704
- import { parseArgs as parseArgs5 } from "util";
3352
+ import { resolve as resolve3 } from "path";
3353
+ import { parseArgs as parseArgs7 } from "util";
1705
3354
  async function unregister2(args, deps) {
1706
- const { positionals } = parseArgs5({ args, options: {}, allowPositionals: true });
3355
+ const { positionals } = parseArgs7({ args, options: {}, allowPositionals: true });
1707
3356
  if (positionals.length > 1)
1708
3357
  throw new UsageError("keypin unregister takes at most one folder");
1709
- const folder = resolve2(deps.cwd, positionals[0] ?? ".");
3358
+ const folder = resolve3(deps.cwd, positionals[0] ?? ".");
1710
3359
  const path = registryPath(deps);
1711
3360
  const before = await loadRegistry(deps.files, path);
1712
3361
  const registry = await unregister(deps.files, path, folder);
@@ -1722,7 +3371,7 @@ async function unregister2(args, deps) {
1722
3371
  return 0;
1723
3372
  }
1724
3373
  // ../../package.json
1725
- var version = "0.1.0";
3374
+ var version = "0.3.0";
1726
3375
 
1727
3376
  // src/cli.ts
1728
3377
  var USAGE = `Usage:
@@ -1730,17 +3379,24 @@ var USAGE = `Usage:
1730
3379
  keypin unregister [folder]
1731
3380
  stop listing a project; its keypin.toml stays
1732
3381
  keypin status [--json] every key in every registered project, with problems
3382
+ keypin discover [folder] [--json]
3383
+ every key name a project uses, local and in the cloud, and a draft map
1733
3384
  keypin run -- <command> run a command with this project's dev keys in its environment
1734
3385
  keypin publish <key-id> [--env prod|dev] [--yes]
1735
3386
  check accounts, plan, confirm, then write the key to every destination
3387
+ keypin rotate <key-id> [--env prod|dev] [--yes]
3388
+ replace a token with a new one that has the same permissions, publish it,
3389
+ and revoke the old one on the next run
1736
3390
  keypin --version print the version
1737
3391
  `;
1738
3392
  var COMMANDS = new Map([
1739
3393
  ["init", init],
1740
3394
  ["unregister", unregister2],
1741
3395
  ["status", status],
3396
+ ["discover", discover],
1742
3397
  ["run", run],
1743
- ["publish", publish]
3398
+ ["publish", publish],
3399
+ ["rotate", rotate]
1744
3400
  ]);
1745
3401
  async function cli(argv, deps) {
1746
3402
  const [name, ...args] = argv;
@@ -1775,8 +3431,9 @@ ${USAGE}`);
1775
3431
 
1776
3432
  // src/disk.ts
1777
3433
  import { constants, rmSync } from "fs";
1778
- import { chmod, lstat, mkdir, open, readFile as readFile2, rename, rm, stat } from "fs/promises";
1779
- import { dirname as dirname2 } from "path";
3434
+ import { execFile as execFile3 } from "child_process";
3435
+ import { chmod, lstat, mkdir, open, readdir, readFile as readFile2, rename, rm, stat } from "fs/promises";
3436
+ import { dirname as dirname3 } from "path";
1780
3437
 
1781
3438
  // src/launch.ts
1782
3439
  var launch = (command, env) => {
@@ -1805,7 +3462,7 @@ var diskFiles = {
1805
3462
  }
1806
3463
  },
1807
3464
  async write(path, text) {
1808
- await privateFolder(dirname2(path));
3465
+ await privateFolder(dirname3(path));
1809
3466
  const handle = await open(path, PRIVATE_WRITE, 384);
1810
3467
  try {
1811
3468
  await handle.chmod(384);
@@ -1860,8 +3517,22 @@ async function isFolder(path) {
1860
3517
  return false;
1861
3518
  }
1862
3519
  }
3520
+ async function listFolder(path) {
3521
+ const entries = await readdir(path, { withFileTypes: true });
3522
+ return entries.map((entry) => ({
3523
+ name: entry.name,
3524
+ kind: entry.isFile() ? "file" : entry.isDirectory() ? "folder" : "other"
3525
+ }));
3526
+ }
3527
+ function git(folder, args) {
3528
+ return new Promise((resolve) => {
3529
+ execFile3("git", ["-C", folder, ...args], { maxBuffer: 64 * 1024 * 1024 }, (error, stdout) => {
3530
+ resolve(error ? null : String(stdout));
3531
+ });
3532
+ });
3533
+ }
1863
3534
  var diskLock = async (path) => {
1864
- await privateFolder(dirname2(path));
3535
+ await privateFolder(dirname3(path));
1865
3536
  if (await take(path))
1866
3537
  return { held: true, lock: held(path) };
1867
3538
  const pid = await holderOf(path);
@@ -1909,6 +3580,7 @@ function held(path) {
1909
3580
 
1910
3581
  // src/start.ts
1911
3582
  var vault;
3583
+ var cloudflare;
1912
3584
  function destination(target) {
1913
3585
  switch (target.to) {
1914
3586
  case "cloudflare-worker":
@@ -1921,6 +3593,16 @@ function destination(target) {
1921
3593
  }
1922
3594
  }
1923
3595
  }
3596
+ function provider(issue, admin) {
3597
+ switch (issue.provider) {
3598
+ case "cloudflare-account-token":
3599
+ return new CloudflareAccountTokens({ account: issue.account, admin });
3600
+ default: {
3601
+ const unknown = issue.provider;
3602
+ throw new Error(`unknown provider ${JSON.stringify(unknown)}`);
3603
+ }
3604
+ }
3605
+ }
1924
3606
  var connect = (account) => desktopConnect(account).catch((error) => {
1925
3607
  const hint = installProblem(error);
1926
3608
  throw hint ? new Error(hint) : error;
@@ -1941,6 +3623,12 @@ function main() {
1941
3623
  home: homedir2(),
1942
3624
  files: diskFiles,
1943
3625
  isFolder,
3626
+ listFolder,
3627
+ git,
3628
+ githubSecrets: (repo, login) => listRepoSecrets({ repo, token: () => ghToken(login) }),
3629
+ workerSecrets: (account, worker) => (cloudflare ??= new CloudflareReader({
3630
+ token: () => currentWranglerToken()
3631
+ })).listWorkerSecrets(account, worker),
1944
3632
  createFile,
1945
3633
  vault: () => vault ??= onePasswordBackend(connect),
1946
3634
  now: () => new Date,
@@ -1949,6 +3637,7 @@ function main() {
1949
3637
  launch,
1950
3638
  onSignals,
1951
3639
  destination,
3640
+ provider,
1952
3641
  lock: diskLock,
1953
3642
  isTerminal: Boolean(process.stdin.isTTY),
1954
3643
  ask