keypin 0.5.0 → 0.6.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.
@@ -151,6 +151,9 @@ function receiptSecretKey(receipt) {
151
151
  function placeId(target) {
152
152
  return target.to === "cloudflare-worker" ? `cloudflare-worker:${target.worker}` : `github-actions:${target.repo}`;
153
153
  }
154
+ function isVariableName(name) {
155
+ return VARIABLE_NAME.test(name);
156
+ }
154
157
  function parseMap(text, file) {
155
158
  let data;
156
159
  try {
@@ -164,6 +167,7 @@ function parseMap(text, file) {
164
167
  return validateMap(data, file);
165
168
  }
166
169
  var ENVIRONMENT_NAME = /^[a-z][a-z0-9-]*$/;
170
+ var TARGET_NAME = ENVIRONMENT_NAME;
167
171
  var KEY_FIELDS = ["rotate_every"];
168
172
  var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
169
173
  var REPO = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
@@ -174,9 +178,10 @@ function validateMap(data, file) {
174
178
  const fail = (where, message) => errors.push(`${file}: ${where}${message}`);
175
179
  if (!isRecord(data))
176
180
  return { ok: false, errors: [`${file}: expected a table at the top level`] };
177
- unknownFields(data, ["environments", "1password", "keys"], (field) => fail("", field === "vaults" ? `[vaults] is from keypin 0.4; use [1password] and op:// references (${OLD_FORMAT})` : `unknown top-level field "${field}"`));
181
+ unknownFields(data, ["environments", "1password", "targets", "keys"], (field) => fail("", field === "vaults" ? `[vaults] is from keypin 0.4; use [1password] and op:// references (${OLD_FORMAT})` : `unknown top-level field "${field}"`));
178
182
  const environments = validateEnvironments(data.environments, (message) => fail("", message));
179
183
  const account = validateAccount(data["1password"], (message) => fail("[1password]: ", message));
184
+ const targets = validateTargets(data.targets, (where, message) => fail(where, message));
180
185
  const keys = [];
181
186
  const rawKeys = data.keys ?? {};
182
187
  if (!isRecord(rawKeys))
@@ -184,11 +189,15 @@ function validateMap(data, file) {
184
189
  else {
185
190
  Object.entries(rawKeys).forEach(([id, raw], index) => {
186
191
  const label = VARIABLE_NAME.test(id) ? `key "${id}"` : `keys[${index}]`;
187
- const entry = validateKey(id, raw, account, environments, (where, message) => fail(`${label}${where}: `, message));
192
+ const entry = validateKey(id, raw, account, environments, targets, (where, message) => fail(`${label}${where}: `, message));
188
193
  if (entry)
189
194
  keys.push(entry);
190
195
  });
191
196
  }
197
+ for (const name of targets.defined) {
198
+ if (!targets.used.has(name))
199
+ fail(`target "${name}": `, "no key publishes to it; use it in a publish list or delete it");
200
+ }
192
201
  sharedDestinations(keys, environments, (where, message) => fail(where, message));
193
202
  return errors.length ? { ok: false, errors } : { ok: true, map: { file, account: account ?? null, environments, keys } };
194
203
  }
@@ -202,6 +211,42 @@ function validateAccount(raw, fail) {
202
211
  unknownFields(raw, ["account"], (field) => fail(`unknown field "${field}"`));
203
212
  return requiredString(raw, "account", fail);
204
213
  }
214
+ function validateTargets(raw, fail) {
215
+ const targets = { defined: [], valid: new Map, used: new Set };
216
+ if (raw === undefined)
217
+ return targets;
218
+ if (!isRecord(raw)) {
219
+ fail("", `"targets" must be a table of named destinations, such as [targets.ci]`);
220
+ return targets;
221
+ }
222
+ Object.entries(raw).forEach(([name, table], index) => {
223
+ if (!TARGET_NAME.test(name)) {
224
+ fail(`targets[${index}]: `, "a target name starts with a lowercase letter and uses only lowercase letters, digits and dashes");
225
+ return;
226
+ }
227
+ targets.defined.push(name);
228
+ const target = validateTarget(table, (m) => fail(`target "${name}": `, m));
229
+ if (target)
230
+ targets.valid.set(name, target);
231
+ });
232
+ return targets;
233
+ }
234
+ function resolveTarget(raw, targets, fail) {
235
+ if (isRecord(raw))
236
+ return validateTarget(raw, fail);
237
+ if (typeof raw !== "string") {
238
+ fail("must be a target name or a table");
239
+ return;
240
+ }
241
+ const name = targets.defined.find((defined) => defined === raw);
242
+ if (name === undefined) {
243
+ fail(targets.defined.length ? `names no target in [targets]; targets are ${targets.defined.map((n) => `"${n}"`).join(", ")}` : "names a target, but the map has no [targets]");
244
+ return;
245
+ }
246
+ targets.used.add(name);
247
+ const target = targets.valid.get(name);
248
+ return target ? { ...target } : undefined;
249
+ }
205
250
  function validateEnvironments(raw, fail) {
206
251
  if (raw === undefined)
207
252
  return DEFAULT_ENVIRONMENTS;
@@ -236,7 +281,7 @@ function sharedDestinations(keys, environments, fail) {
236
281
  }
237
282
  }
238
283
  }
239
- function validateKey(id, raw, account, environmentNames, fail) {
284
+ function validateKey(id, raw, account, environmentNames, targets, fail) {
240
285
  let failures = 0;
241
286
  const err = (where, message) => {
242
287
  failures++;
@@ -256,7 +301,7 @@ function validateKey(id, raw, account, environmentNames, fail) {
256
301
  const environments = Object.create(null);
257
302
  const declared = environmentNames.filter((name) => Object.hasOwn(raw, name));
258
303
  for (const name of declared) {
259
- const entry = validateEnv(raw[name], account, (m) => err(` ${name}`, m));
304
+ const entry = validateEnv(raw[name], account, targets, (m) => err(` ${name}`, m));
260
305
  if (entry)
261
306
  environments[name] = entry;
262
307
  }
@@ -273,7 +318,7 @@ function validateKey(id, raw, account, environmentNames, fail) {
273
318
  return;
274
319
  return { name: id, rotateEvery: rotateEvery ?? null, environments };
275
320
  }
276
- function validateEnv(given, account, fail) {
321
+ function validateEnv(given, account, targets, fail) {
277
322
  const raw = typeof given === "string" ? { from: given } : given;
278
323
  if (!isRecord(raw)) {
279
324
  fail(`must be an op:// reference, or a table with "from"`);
@@ -284,7 +329,7 @@ function validateEnv(given, account, fail) {
284
329
  failed = true;
285
330
  fail(message);
286
331
  };
287
- unknownFields(raw, ["from", "publish", "issue"], (field) => err(field === "vault" || field === "item" ? `"vault" and "item" are from keypin 0.4; use from = "op://<vault>/<item>/<field>" (${OLD_FORMAT})` : `unknown field "${field}"`));
332
+ unknownFields(raw, ["from", "publish", "rotate"], (field) => err(field === "vault" || field === "item" ? `"vault" and "item" are from keypin 0.4; use from = "op://<vault>/<item>/<field>" (${OLD_FORMAT})` : field === "issue" ? `the "issue" section is from keypin 0.5; rename it to "rotate" (${OLD_FORMAT})` : `unknown field "${field}"`));
288
333
  const ref = reference(raw, "from", account, err);
289
334
  const publish = [];
290
335
  const firstAt = new Map;
@@ -293,7 +338,7 @@ function validateEnv(given, account, fail) {
293
338
  err(`field "publish" must be a list`);
294
339
  else {
295
340
  raw.publish.forEach((t, i) => {
296
- const target = validateTarget(t, (m) => err(`publish[${i}]: ${m}`));
341
+ const target = resolveTarget(t, targets, (m) => err(`publish[${i}]: ${m}`));
297
342
  if (!target)
298
343
  return;
299
344
  const same = firstAt.get(placeId(target));
@@ -306,10 +351,10 @@ function validateEnv(given, account, fail) {
306
351
  });
307
352
  }
308
353
  }
309
- const issue = raw.issue === undefined || !ref ? undefined : validateIssue(raw.issue, ref, account, (m) => err(`issue: ${m}`));
354
+ const rotate = raw.rotate === undefined || !ref ? undefined : validateRotate(raw.rotate, ref, account, (m) => err(`rotate: ${m}`));
310
355
  if (failed || !ref)
311
356
  return;
312
- return { ref, publish, ...issue ? { issue } : {} };
357
+ return { ref, publish, ...rotate ? { rotate } : {} };
313
358
  }
314
359
  function reference(table, field, account, fail) {
315
360
  const text = requiredString(table, field, fail);
@@ -327,7 +372,7 @@ function reference(table, field, account, fail) {
327
372
  return { kind: "1password", account, ...parsed };
328
373
  }
329
374
  var ACCOUNT_ID = /^[0-9a-f]{32}$/;
330
- function validateIssue(raw, own, vaultAccount, fail) {
375
+ function validateRotate(raw, own, vaultAccount, fail) {
331
376
  if (!isRecord(raw)) {
332
377
  fail("must be a table");
333
378
  return;
@@ -689,7 +734,7 @@ function isRotation(r) {
689
734
  return isRecord(r) && [r.id, r.keyId, r.environment, r.provider, r.account, r.startedAt, r.updatedAt].every(isText2) && isTextOrNull2(r.mapFile) && ROTATION_STAGES.some((stage) => stage === r.stage) && storedRefWithPasswordDefault(r.item) !== null && isTokenRecord(r.old) && isTokenRecord(r.new);
690
735
  }
691
736
  // ../../packages/core/src/status.ts
692
- var NOTICES = ["due-soon", "authority-unknown", "rotation-unfinished"];
737
+ var NOTICES = ["due-soon", "never-published", "rotation-unfinished"];
693
738
  function buildStatus(input) {
694
739
  if (!isDay(input.today))
695
740
  throw new Error(`today must be YYYY-MM-DD, got "${input.today}"`);
@@ -736,24 +781,28 @@ function buildStatus(input) {
736
781
  const rotateEvery = key.rotateEvery;
737
782
  const rotated = metadata?.rotated ?? null;
738
783
  const due = rotationDue({ label, metadata, rotated, rotateEvery, today: input.today, add });
739
- add("authority-unknown", `${label}: what this key grants is unknown, because keypin didn't create it`);
740
784
  const current = input.generation?.(key.name, environment);
785
+ const published = input.receipts.some((r) => ownedBy(r, owner));
786
+ const unpublished = [];
787
+ const publish = `keypin publish ${key.name}${envFlag(environment, publishEnvironment(result.map))}`;
741
788
  const destinations = entry.publish.map((target) => {
742
789
  const id = destinationId(target, key.name);
743
790
  const last = latest.get(secretKey(target, key.name));
744
791
  const ours = last && (ownedBy(last, owner) || last.source !== null && sameRef(last.source, entry.ref));
745
792
  const receipt = ours ? last : undefined;
746
793
  if (!receipt) {
747
- add("missing-receipt", `${label}: no receipt for ${id}, so what it holds is unknown`, {
748
- destinationId: id
749
- });
794
+ if (last) {
795
+ add("missing-receipt", `${label}: ${id}'s last receipt isn't from this project or this key's item, so what it holds is unknown`, { destinationId: id });
796
+ } else if (published) {
797
+ add("missing-receipt", `${label}: no receipt for ${id}, though this project published this key before, so what it holds is unknown; ${publish} writes it again`, { destinationId: id });
798
+ } else {
799
+ unpublished.push(id);
800
+ }
750
801
  return { destinationId: id, account: target.account, receipt: null, stale: null };
751
802
  }
752
803
  const stale = current === undefined ? null : receipt.generation !== current;
753
804
  if (stale) {
754
- add("stale-receipt", `${label}: ${id} last got generation ${receipt.generation}, and the value is now ${current}`, {
755
- destinationId: id
756
- });
805
+ add("stale-receipt", `${label}: ${id} last got generation ${receipt.generation}, and the value is now ${current}`, { destinationId: id });
757
806
  }
758
807
  const { generation, at } = receipt;
759
808
  return {
@@ -763,6 +812,9 @@ function buildStatus(input) {
763
812
  stale
764
813
  };
765
814
  });
815
+ if (unpublished.length) {
816
+ add("never-published", `${label}: not published yet to ${unpublished.join(", ")}; run ${publish}`);
817
+ }
766
818
  const rotation = unfinishedRotation({ version: ROTATIONS_VERSION, rotations: [...input.rotations ?? []] }, owner, entry.ref);
767
819
  if (rotation) {
768
820
  add("rotation-unfinished", `${label}: a rotation started ${rotation.startedAt} is at stage "${rotation.stage}"; run ${rotateCommand(key.name, environment, publishEnvironment(result.map))} to continue`);
@@ -773,7 +825,6 @@ function buildStatus(input) {
773
825
  rotated,
774
826
  rotateEvery,
775
827
  due,
776
- authority: "unknown",
777
828
  destinations
778
829
  });
779
830
  }
@@ -847,13 +898,26 @@ var WRANGLER_FILES = [
847
898
  ];
848
899
  var DOTENV_LINE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
849
900
  function envNames(text) {
850
- const names = new Set;
901
+ return [...envValues(text).keys()];
902
+ }
903
+ function envValues(text) {
904
+ const values = new Map;
851
905
  for (const match of text.replace(/\r\n?/g, `
852
906
  `).matchAll(DOTENV_LINE)) {
853
907
  if (match[1])
854
- names.add(match[1]);
908
+ values.set(match[1], new Secret(dotenvValue(match[2] ?? "")));
855
909
  }
856
- return [...names];
910
+ return values;
911
+ }
912
+ function dotenvValue(raw) {
913
+ const value = raw.trim();
914
+ const unquoted = value.replace(/^(['"`])([\s\S]*)\1$/, "$2");
915
+ return value.startsWith('"') ? unquoted.replace(/\\n/g, `
916
+ `).replace(/\\r/g, "\r") : unquoted;
917
+ }
918
+ function draftItemName(project, environment, name) {
919
+ const folder = project.replace(/[^A-Za-z0-9 ._-]/g, "-");
920
+ return `${folder} ${environment} ${name.toLowerCase().replaceAll("_", " ").trim()}`;
857
921
  }
858
922
  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;
859
923
  function workflowRefs(text) {
@@ -1132,10 +1196,9 @@ function draftMap(names, options) {
1132
1196
  const runName = runEnvironment(options);
1133
1197
  const publishName = publishEnvironment(options);
1134
1198
  const vault = options.map?.vault ?? "<your vault>";
1135
- const project = options.project.replace(/[^A-Za-z0-9 ._-]/g, "-");
1136
- const from = (environment, what) => str(formatReference({
1199
+ const from = (environment, name) => str(formatReference({
1137
1200
  vault,
1138
- item: `${project} ${environment} ${what}`,
1201
+ item: draftItemName(options.project, environment, name),
1139
1202
  section: null,
1140
1203
  field: "password"
1141
1204
  }));
@@ -1168,16 +1231,15 @@ function draftMap(names, options) {
1168
1231
  });
1169
1232
  if (!local && !publish.length)
1170
1233
  continue;
1171
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(row.name))
1234
+ if (!isVariableName(row.name))
1172
1235
  continue;
1173
1236
  const name = row.name;
1174
- const what = name.toLowerCase().replaceAll("_", " ").trim();
1175
1237
  lines.push("", `[keys.${name}]`, `rotate_every = "90d"`);
1176
1238
  if (local && !(publish.length && runName === publishName)) {
1177
- lines.push(`${runName} = ${from(runName, what)}`);
1239
+ lines.push(`${runName} = ${from(runName, name)}`);
1178
1240
  }
1179
1241
  if (publish.length) {
1180
- lines.push("", `[keys.${name}.${publishName}]`, `from = ${from(publishName, what)}`);
1242
+ lines.push("", `[keys.${name}.${publishName}]`, `from = ${from(publishName, name)}`);
1181
1243
  for (const target of publish) {
1182
1244
  lines.push("", `[[keys.${name}.${publishName}.publish]]`, ...target);
1183
1245
  }
@@ -1187,8 +1249,8 @@ function draftMap(names, options) {
1187
1249
  return null;
1188
1250
  const account = options.map?.account ?? "<your 1Password account>";
1189
1251
  const header = [
1190
- "# Draft from keypin discover; nothing was written. The op:// references are placeholders.",
1191
- !options.map?.account ? "# Fill in your account and vault, then save this as keypin.toml." : options.map.vault === null ? "# Fill in the vault, then copy only the [keys.*] tables into this project's keypin.toml." : "# The vault is the one this project's keypin.toml uses; copy only the [keys.*] tables.",
1252
+ options.written ? "# Written by keypin discover. Each op:// reference is a placeholder: replace it with the field's secret reference." : "# Draft from keypin discover; nothing was written. The op:// references are placeholders.",
1253
+ options.written ? `# ${options.map?.account ? "Fill in the vault" : "Fill in your 1Password account and vault"}, then check each destination.` : !options.map?.account ? "# Fill in your account and vault, then save this as keypin.toml." : options.map.vault === null ? "# Fill in the vault, then copy only the [keys.*] tables into this project's keypin.toml." : "# The vault is the one this project's keypin.toml uses; copy only the [keys.*] tables.",
1192
1254
  ...options.environments.join() === DEFAULT_ENVIRONMENTS.join() ? [] : ["", `environments = [${options.environments.map(str).join(", ")}]`],
1193
1255
  "",
1194
1256
  "[1password]",
@@ -1943,6 +2005,9 @@ function onePasswordBackend(connect = desktopConnect) {
1943
2005
  const sdk = await client(ref.account);
1944
2006
  const id = await vaultId(sdk, ref);
1945
2007
  const found = await find(sdk, id, ref);
2008
+ if (found && options.newItem) {
2009
+ throw new Error(`${where(ref)}: the item already exists; keypin doesn't overwrite it`);
2010
+ }
1946
2011
  if (!found) {
1947
2012
  if (ref.field !== VALUE_FIELD || ref.section !== null) {
1948
2013
  throw new Error(`${where(ref)}: no such item; create it in 1Password first`);
@@ -2049,8 +2114,8 @@ function messageOf2(error) {
2049
2114
  return error instanceof Error ? error.message : String(error);
2050
2115
  }
2051
2116
  // src/commands/discover.ts
2052
- import { basename, join as join3, relative, resolve } from "path";
2053
- import { parseArgs } from "util";
2117
+ import { basename, join as join5, relative, resolve as resolve2 } from "path";
2118
+ import { parseArgs as parseArgs2 } from "util";
2054
2119
 
2055
2120
  // src/deps.ts
2056
2121
  class UsageError extends Error {
@@ -2086,18 +2151,101 @@ function pickEnvironment(map, requested, fallback) {
2086
2151
  throw new UsageError(`--env is one of ${names} in ${map.file}, got "${requested}"`);
2087
2152
  }
2088
2153
 
2154
+ // src/commands/init.ts
2155
+ import { join as join4, resolve } from "path";
2156
+ import { parseArgs } from "util";
2157
+
2158
+ // src/paths.ts
2159
+ import { dirname as dirname2, join as join3 } from "path";
2160
+ function registryPath(deps) {
2161
+ return join3(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
2162
+ }
2163
+ function statePath(deps) {
2164
+ return join3(base(deps.env.XDG_STATE_HOME, deps.home, ".local/state"), "keypin", "state.json");
2165
+ }
2166
+ function base(xdg, home, fallback) {
2167
+ return xdg?.startsWith("/") ? xdg : join3(home, fallback);
2168
+ }
2169
+ function projectCount(registry, path) {
2170
+ const count = registry.projects.length;
2171
+ return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
2172
+ }
2173
+ function rotationsPath(deps) {
2174
+ return join3(dirname2(statePath(deps)), "rotations.json");
2175
+ }
2176
+
2177
+ // src/commands/init.ts
2178
+ var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
2179
+ # Uncomment and edit. Every field is checked; an unknown one is an error.
2180
+ #
2181
+ # The 1Password account the keys below read from: its sign-in address or account ID.
2182
+ # [1password]
2183
+ # account = "my.1password.com"
2184
+ #
2185
+ # A key, named after the variable your program reads.
2186
+ # [keys.EXAMPLE_API_KEY]
2187
+ # rotate_every = "180d" # <n>d, <n>w, <n>m or never
2188
+ # dev = "op://Private/my-project dev example api key/password" # what keypin run reads
2189
+ #
2190
+ # What keypin publish reads, and every place it writes it.
2191
+ # [keys.EXAMPLE_API_KEY.prod]
2192
+ # from = "op://Private/my-project prod example api key/password"
2193
+ #
2194
+ # [[keys.EXAMPLE_API_KEY.prod.publish]]
2195
+ # to = "cloudflare-worker"
2196
+ # account = "<cloudflare account ID>"
2197
+ # worker = "my-worker"
2198
+ #
2199
+ # [[keys.EXAMPLE_API_KEY.prod.publish]]
2200
+ # to = "github-actions"
2201
+ # repo = "owner/repo"
2202
+ `;
2203
+ async function init(args, deps) {
2204
+ const { positionals } = parseArgs({ args, options: {}, allowPositionals: true });
2205
+ if (positionals.length > 1)
2206
+ throw new UsageError("keypin init takes at most one folder");
2207
+ const folder = resolve(deps.cwd, positionals[0] ?? ".");
2208
+ if (!await deps.isFolder(folder))
2209
+ throw new Error(`${folder} isn't a folder`);
2210
+ const file = join4(folder, MAP_FILE);
2211
+ const created = await deps.createFile(file, TEMPLATE);
2212
+ if (created === "link")
2213
+ throw new Error(`${file} is a symbolic link; keypin init doesn't follow one`);
2214
+ deps.stderr.write(created === "created" ? `keypin: wrote ${file}
2215
+ ` : `keypin: ${file} exists; left it as it is
2216
+ `);
2217
+ await registerProject(deps, folder);
2218
+ return 0;
2219
+ }
2220
+ async function registerProject(deps, folder) {
2221
+ const path = registryPath(deps);
2222
+ const registry = await register(deps.files, path, folder);
2223
+ deps.stderr.write(`keypin: ${folder} is registered (${projectCount(registry, path)})
2224
+ `);
2225
+ }
2226
+
2089
2227
  // src/commands/discover.ts
2090
2228
  async function discover(args, deps) {
2091
- const { values, positionals } = parseArgs({
2229
+ const { values, positionals } = parseArgs2({
2092
2230
  args,
2093
- options: { json: { type: "boolean", default: false } },
2231
+ options: {
2232
+ json: { type: "boolean", default: false },
2233
+ write: { type: "boolean", default: false }
2234
+ },
2094
2235
  allowPositionals: true
2095
2236
  });
2096
2237
  if (positionals.length > 1)
2097
2238
  throw new UsageError("keypin discover takes at most one folder");
2098
- const folder = resolve(deps.cwd, positionals[0] ?? ".");
2239
+ const folder = resolve2(deps.cwd, positionals[0] ?? ".");
2099
2240
  if (!await deps.isFolder(folder))
2100
2241
  throw new Error(`${folder} isn't a folder`);
2242
+ const mapFile = join5(folder, MAP_FILE);
2243
+ const mapText = await deps.files.read(mapFile);
2244
+ if (values.write && mapText !== null && mapText !== TEMPLATE) {
2245
+ deps.stderr.write(`keypin discover: ${mapFile} already has a map, and --write doesn't change one. Run keypin discover without --write and copy the [keys.*] tables from its draft by hand.
2246
+ `);
2247
+ return 1;
2248
+ }
2101
2249
  const unknowns = [];
2102
2250
  const scan = await walk(deps, folder);
2103
2251
  const tracked = await trackedFiles(deps, folder, scan.envFiles);
@@ -2106,7 +2254,7 @@ async function discover(args, deps) {
2106
2254
  const kind = envFileKind(basename(path));
2107
2255
  if (!kind)
2108
2256
  continue;
2109
- const text = await deps.files.read(join3(folder, path));
2257
+ const text = await deps.files.read(join5(folder, path));
2110
2258
  if (text === null)
2111
2259
  continue;
2112
2260
  envFiles.push({ path, kind, names: envNames(text), tracked: tracked?.has(path) ?? null });
@@ -2122,7 +2270,7 @@ async function discover(args, deps) {
2122
2270
  const workflows = await readWorkflows(deps, folder, top, unknowns);
2123
2271
  const workers = [];
2124
2272
  for (const config of scan.wrangler) {
2125
- const text = await deps.files.read(join3(folder, config));
2273
+ const text = await deps.files.read(join5(folder, config));
2126
2274
  if (text === null)
2127
2275
  continue;
2128
2276
  const parsed = wranglerWorkers(text, config);
@@ -2165,7 +2313,6 @@ async function discover(args, deps) {
2165
2313
  read: read.ok ? read : { ok: false, reason: `as ${login}: ${read.reason}` }
2166
2314
  };
2167
2315
  }
2168
- const mapText = await deps.files.read(join3(folder, MAP_FILE));
2169
2316
  let map = null;
2170
2317
  if (mapText !== null) {
2171
2318
  const parsed = parseMap(mapText, MAP_FILE);
@@ -2183,13 +2330,20 @@ async function discover(args, deps) {
2183
2330
  project: basename(folder),
2184
2331
  githubAccount: login,
2185
2332
  map: map ? { account: map.account, vault: firstVault(map) } : null,
2186
- environments: map?.environments ?? DEFAULT_ENVIRONMENTS
2333
+ environments: map?.environments ?? DEFAULT_ENVIRONMENTS,
2334
+ written: values.write
2187
2335
  });
2188
2336
  if (draft !== null) {
2189
2337
  const check = parseMap(draft, "draft");
2190
2338
  if (!check.ok)
2191
2339
  throw new Error(`the draft doesn't parse: ${check.errors.join("; ")}`);
2192
2340
  }
2341
+ if (values.write && draft === null) {
2342
+ deps.stderr.write(`keypin discover: found no unmapped name set locally or in the cloud, so there's no draft; nothing was written. Run keypin init for a template.
2343
+ `);
2344
+ return 1;
2345
+ }
2346
+ const written = values.write && draft !== null ? await writeDraft(deps, mapFile, mapText, draft) : null;
2193
2347
  const report = {
2194
2348
  folder,
2195
2349
  repository: github?.repo ?? null,
@@ -2201,12 +2355,26 @@ async function discover(args, deps) {
2201
2355
  },
2202
2356
  nestedRepositories: scan.nested,
2203
2357
  ...discovery,
2204
- draft
2358
+ draft,
2359
+ written
2205
2360
  };
2206
2361
  deps.stdout.write(values.json ? `${JSON.stringify(report, null, 2)}
2207
2362
  ` : render(report, discovery));
2363
+ if (written !== null) {
2364
+ deps.stderr.write(`keypin: wrote the draft to ${written}. Its op:// references are placeholders: replace each with the field's secret reference from 1Password before you run or publish.
2365
+ `);
2366
+ await registerProject(deps, folder);
2367
+ }
2208
2368
  return 0;
2209
2369
  }
2370
+ async function writeDraft(deps, file, found, draft) {
2371
+ const result = found === null ? await deps.createFile(file, draft) : await deps.replaceFile(file, TEMPLATE, draft);
2372
+ if (result === "link")
2373
+ throw new Error(`${file} is a symbolic link; keypin discover doesn't follow one`);
2374
+ if (result === "exists" || result === "changed")
2375
+ throw new Error(`${file} changed while discover ran; nothing was written. Run it again.`);
2376
+ return file;
2377
+ }
2210
2378
  async function walk(deps, root) {
2211
2379
  const scan = { envFiles: [], wrangler: [], nested: [] };
2212
2380
  const visit = async (folder) => {
@@ -2216,7 +2384,7 @@ async function walk(deps, root) {
2216
2384
  return;
2217
2385
  }
2218
2386
  for (const entry of entries) {
2219
- const path = join3(folder, entry.name);
2387
+ const path = join5(folder, entry.name);
2220
2388
  if (entry.kind === "folder") {
2221
2389
  if (!SKIPPED_FOLDERS.has(entry.name))
2222
2390
  await visit(path);
@@ -2240,7 +2408,7 @@ async function trackedFiles(deps, folder, paths) {
2240
2408
  return new Set(out.split("\x00").filter(Boolean));
2241
2409
  }
2242
2410
  async function readWorkflows(deps, folder, top, unknowns) {
2243
- const dir = join3(top ?? folder, ".github", "workflows");
2411
+ const dir = join5(top ?? folder, ".github", "workflows");
2244
2412
  let entries;
2245
2413
  try {
2246
2414
  entries = await deps.listFolder(dir);
@@ -2258,10 +2426,10 @@ async function readWorkflows(deps, folder, top, unknowns) {
2258
2426
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
2259
2427
  if (entry.kind !== "file" || !/\.ya?ml$/.test(entry.name))
2260
2428
  continue;
2261
- const text = await deps.files.read(join3(dir, entry.name));
2429
+ const text = await deps.files.read(join5(dir, entry.name));
2262
2430
  if (text === null)
2263
2431
  continue;
2264
- const path = relative(folder, join3(dir, entry.name));
2432
+ const path = relative(folder, join5(dir, entry.name));
2265
2433
  const refs = workflowRefs(text);
2266
2434
  if (refs)
2267
2435
  workflows.push({ path, refs });
@@ -2380,6 +2548,8 @@ function render(report, discovery) {
2380
2548
  lines.push("");
2381
2549
  if (report.draft === null)
2382
2550
  lines.push("No draft: every name set locally or in the cloud is already mapped.");
2551
+ else if (report.written !== null)
2552
+ lines.push(`Draft keypin.toml for the unmapped names, written to ${report.written}:`, "", report.draft);
2383
2553
  else
2384
2554
  lines.push("Draft keypin.toml for the unmapped names (not written):", "", report.draft);
2385
2555
  return `${lines.join(`
@@ -2390,77 +2560,8 @@ function count(n, noun) {
2390
2560
  return `${n} ${noun}${n === 1 ? "" : "s"}`;
2391
2561
  }
2392
2562
 
2393
- // src/commands/init.ts
2394
- import { join as join5, resolve as resolve2 } from "path";
2395
- import { parseArgs as parseArgs2 } from "util";
2396
-
2397
- // src/paths.ts
2398
- import { dirname as dirname2, join as join4 } from "path";
2399
- function registryPath(deps) {
2400
- return join4(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
2401
- }
2402
- function statePath(deps) {
2403
- return join4(base(deps.env.XDG_STATE_HOME, deps.home, ".local/state"), "keypin", "state.json");
2404
- }
2405
- function base(xdg, home, fallback) {
2406
- return xdg?.startsWith("/") ? xdg : join4(home, fallback);
2407
- }
2408
- function projectCount(registry, path) {
2409
- const count = registry.projects.length;
2410
- return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
2411
- }
2412
- function rotationsPath(deps) {
2413
- return join4(dirname2(statePath(deps)), "rotations.json");
2414
- }
2415
-
2416
- // src/commands/init.ts
2417
- var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
2418
- # Uncomment and edit. Every field is checked; an unknown one is an error.
2419
- #
2420
- # The 1Password account the keys below read from: its sign-in address or account ID.
2421
- # [1password]
2422
- # account = "my.1password.com"
2423
- #
2424
- # A key, named after the variable your program reads.
2425
- # [keys.EXAMPLE_API_KEY]
2426
- # rotate_every = "180d" # <n>d, <n>w, <n>m or never
2427
- # dev = "op://Private/my-project dev example api key/password" # what keypin run reads
2428
- #
2429
- # What keypin publish reads, and every place it writes it.
2430
- # [keys.EXAMPLE_API_KEY.prod]
2431
- # from = "op://Private/my-project prod example api key/password"
2432
- #
2433
- # [[keys.EXAMPLE_API_KEY.prod.publish]]
2434
- # to = "cloudflare-worker"
2435
- # account = "<cloudflare account ID>"
2436
- # worker = "my-worker"
2437
- #
2438
- # [[keys.EXAMPLE_API_KEY.prod.publish]]
2439
- # to = "github-actions"
2440
- # repo = "owner/repo"
2441
- `;
2442
- async function init(args, deps) {
2443
- const { positionals } = parseArgs2({ args, options: {}, allowPositionals: true });
2444
- if (positionals.length > 1)
2445
- throw new UsageError("keypin init takes at most one folder");
2446
- const folder = resolve2(deps.cwd, positionals[0] ?? ".");
2447
- if (!await deps.isFolder(folder))
2448
- throw new Error(`${folder} isn't a folder`);
2449
- const file = join5(folder, MAP_FILE);
2450
- const created = await deps.createFile(file, TEMPLATE);
2451
- if (created === "link")
2452
- throw new Error(`${file} is a symbolic link; keypin init doesn't follow one`);
2453
- deps.stderr.write(created === "created" ? `keypin: wrote ${file}
2454
- ` : `keypin: ${file} exists; left it as it is
2455
- `);
2456
- const path = registryPath(deps);
2457
- const registry = await register(deps.files, path, folder);
2458
- deps.stderr.write(`keypin: ${folder} is registered (${projectCount(registry, path)})
2459
- `);
2460
- return 0;
2461
- }
2462
-
2463
- // src/commands/publish.ts
2563
+ // src/commands/import.ts
2564
+ import { basename as basename2, join as join6, resolve as resolve3 } from "path";
2464
2565
  import { parseArgs as parseArgs3 } from "util";
2465
2566
 
2466
2567
  // src/publishing.ts
@@ -2489,9 +2590,9 @@ function lockedMessage(file, holder) {
2489
2590
  }
2490
2591
  return `keypin: another publish or rotate (process ${holder.pid}) holds ${file} and is still running. Wait for it to finish.`;
2491
2592
  }
2492
- async function checkAccounts(key, entry, deps, say) {
2593
+ async function checkAccounts(key, entry, deps, say, heading = "Account checks") {
2493
2594
  say(`
2494
- Account checks:`);
2595
+ ${heading}:`);
2495
2596
  const checked = new Map;
2496
2597
  let failed = false;
2497
2598
  for (const target of entry.publish) {
@@ -2581,6 +2682,272 @@ function describeTarget(target, secretName) {
2581
2682
  return `${destinationId(target, secretName)} (account ${target.account})`;
2582
2683
  }
2583
2684
 
2685
+ // src/commands/import.ts
2686
+ var ROTATE_EVERY = "90d";
2687
+ async function importEnv(args, deps) {
2688
+ const request = parseRequest(args);
2689
+ const say = (text) => deps.stderr.write(`${text}
2690
+ `);
2691
+ const envPath = resolve3(deps.cwd, request.envFile);
2692
+ if (envFileKind(basename2(envPath)) === "expected")
2693
+ throw new UsageError(`${envPath} is an example file; import the file that sets the values`);
2694
+ const text = await deps.files.read(envPath);
2695
+ if (text === null)
2696
+ throw new Error(`${envPath} doesn't exist`);
2697
+ const target = await readTarget(deps, request);
2698
+ const environment = runEnvironment(target.map ?? { environments: DEFAULT_ENVIRONMENTS });
2699
+ const project = basename2(deps.cwd);
2700
+ const values = envValues(text);
2701
+ if (!values.size)
2702
+ throw new Error(`${envPath} sets no variables; nothing to import`);
2703
+ const planned = [];
2704
+ const skips = [];
2705
+ const items = new Map;
2706
+ for (const [name, value] of values) {
2707
+ const item = draftItemName(project, environment, name);
2708
+ const sameItem = items.get(item.toLowerCase());
2709
+ const mapped = target.map?.keys.find((key) => key.name === name);
2710
+ if (!isVariableName(name))
2711
+ skips.push({
2712
+ name,
2713
+ reason: "not a variable name (letters, digits and _, not a digit first)",
2714
+ onlyInFile: true
2715
+ });
2716
+ else if (!value.reveal())
2717
+ skips.push({ name, reason: "the value is empty", onlyInFile: false });
2718
+ else if (mapped?.environments[environment])
2719
+ skips.push({
2720
+ name,
2721
+ reason: `already mapped in ${target.file}; left as it is`,
2722
+ onlyInFile: false
2723
+ });
2724
+ else if (mapped)
2725
+ skips.push({
2726
+ name,
2727
+ reason: `mapped in ${target.file} without ${environment}; left as it is, so add its ${environment} reference by hand`,
2728
+ onlyInFile: true
2729
+ });
2730
+ else if (value.reveal().includes("$"))
2731
+ skips.push({
2732
+ name,
2733
+ reason: "the value has a $, which some loaders expand to another variable's value",
2734
+ onlyInFile: true
2735
+ });
2736
+ else if (sameItem !== undefined)
2737
+ skips.push({
2738
+ name,
2739
+ reason: `its item would be "${item}", the same as ${sameItem}'s`,
2740
+ onlyInFile: true
2741
+ });
2742
+ else {
2743
+ items.set(item.toLowerCase(), name);
2744
+ planned.push({ name, value, ref: refFor(target.account, request.vault, item) });
2745
+ }
2746
+ }
2747
+ let imports = planned;
2748
+ const stored = [];
2749
+ if (planned.length) {
2750
+ if (await deps.isLink(target.file))
2751
+ throw new Error(`${target.file} is a symbolic link; keypin import doesn't follow one`);
2752
+ const check = parseMap(mapText(target, planned, environment), target.file);
2753
+ if (!check.ok)
2754
+ throw new Error(`adding the keys to ${target.file} wouldn't parse, so nothing was created: ${check.errors.join("; ")}`);
2755
+ const scope = { kind: "1password", account: target.account, vault: request.vault };
2756
+ say(`keypin: listing the items in vault ${request.vault} of 1Password account ${target.account}`);
2757
+ const titles = new Set((await deps.vault().list(scope)).map((i) => i.title.toLowerCase()));
2758
+ imports = [];
2759
+ for (const entry of planned) {
2760
+ if (!titles.has(entry.ref.item.toLowerCase())) {
2761
+ imports.push(entry);
2762
+ continue;
2763
+ }
2764
+ const problem = await existingProblem(deps, entry);
2765
+ if (problem === null)
2766
+ stored.push(entry);
2767
+ else
2768
+ skips.push({
2769
+ name: entry.name,
2770
+ reason: `"${entry.ref.item}" already exists in vault ${request.vault} ${problem}; keypin doesn't overwrite it`,
2771
+ onlyInFile: true,
2772
+ exists: true
2773
+ });
2774
+ }
2775
+ }
2776
+ const today = localDay(deps.now());
2777
+ say(`Import ${envPath} into 1Password account ${target.account}, vault ${request.vault}:`);
2778
+ for (const { name, ref } of imports)
2779
+ say(` create "${ref.item}" (password, rotated ${today}), and map ${name} to ${formatReference(ref)}`);
2780
+ if (!imports.length)
2781
+ say(" nothing to create");
2782
+ for (const { name, ref } of stored)
2783
+ say(` map ${name} to ${formatReference(ref)}, an item that exists with the same value`);
2784
+ if (skips.length) {
2785
+ say("Skipped:");
2786
+ for (const skip of skips)
2787
+ say(` ${skip.name}: ${skip.reason}`);
2788
+ }
2789
+ const existed = skips.some((skip) => skip.exists);
2790
+ if (!imports.length && !stored.length)
2791
+ return existed ? 1 : 0;
2792
+ say(target.map ? `Map: add ${count2(imports.length + stored.length, "key")} at the end of ${target.file}` : `Map: write ${target.file} and register ${deps.cwd}`);
2793
+ if (imports.length && !await confirmed(deps, request, imports.length))
2794
+ return NEEDS_APPROVAL;
2795
+ const created = [];
2796
+ for (const entry of imports) {
2797
+ try {
2798
+ await deps.vault().write(entry.ref, entry.value, { rotated: today, newItem: true });
2799
+ created.push(entry);
2800
+ say(` created "${entry.ref.item}"`);
2801
+ } catch (error) {
2802
+ say(` FAILED "${entry.ref.item}": ${messageOf(error)}`);
2803
+ break;
2804
+ }
2805
+ }
2806
+ const failed = imports.filter((entry) => !created.includes(entry)).map((i) => i.name);
2807
+ if (failed.length)
2808
+ say(`Stopped. Created ${names(created.map((i) => i.name))}; not created: ${names(failed)}.`);
2809
+ const mapped = planned.filter((entry) => stored.includes(entry) || created.includes(entry));
2810
+ if (!mapped.length)
2811
+ return 1;
2812
+ try {
2813
+ await writeMap(deps, target, mapped, environment);
2814
+ } catch (error) {
2815
+ say(`keypin: ${messageOf(error)}`);
2816
+ say(target.map ? `The items are in 1Password. Add this at the end of ${target.file} by hand:` : `The items are in 1Password. Save this as ${target.file} by hand:`);
2817
+ deps.stdout.write(mapAddition(target, mapped, environment));
2818
+ return 1;
2819
+ }
2820
+ say(`keypin: mapped ${names(mapped.map((i) => i.name))} in ${target.file}`);
2821
+ if (!target.map)
2822
+ await registerProject(deps, deps.cwd);
2823
+ const left = [...skips.filter((skip) => skip.onlyInFile).map((skip) => skip.name), ...failed];
2824
+ say(`The imported values are now in 1Password, and keypin run -- <command> provides them. keypin left ${envPath} as it is.`);
2825
+ say(left.length ? `${names(left)} ${left.length === 1 ? "is" : "are"} still only in that file. Move ${left.length === 1 ? "it" : "them"}, then delete the file and stop loading it (for example, wrangler dev reads .dev.vars).` : "Delete it and stop loading it (for example, wrangler dev reads .dev.vars).");
2826
+ if (failed.length)
2827
+ say("Run keypin import again to create the rest. It maps an item it already stored, since that item holds the same value.");
2828
+ return failed.length || existed ? 1 : 0;
2829
+ }
2830
+ async function existingProblem(deps, entry) {
2831
+ try {
2832
+ const value = await deps.vault().read(entry.ref);
2833
+ return value.reveal() === entry.value.reveal() ? null : "with another value";
2834
+ } catch (error) {
2835
+ return `and couldn't be read (${messageOf(error)})`;
2836
+ }
2837
+ }
2838
+ function names(list) {
2839
+ return list.length ? list.join(", ") : "none";
2840
+ }
2841
+ function parseRequest(args) {
2842
+ const { values, positionals } = parseArgs3({
2843
+ args,
2844
+ options: {
2845
+ vault: { type: "string" },
2846
+ account: { type: "string" },
2847
+ yes: { type: "boolean", default: false }
2848
+ },
2849
+ allowPositionals: true
2850
+ });
2851
+ const [envFile, ...extra] = positionals;
2852
+ if (envFile === undefined || extra.length)
2853
+ throw new UsageError("keypin import takes one env file, such as .env or .dev.vars");
2854
+ const vault = values.vault?.trim();
2855
+ if (!vault)
2856
+ throw new UsageError("--vault is required: the 1Password vault to create the items in");
2857
+ if (vault.includes("/"))
2858
+ throw new UsageError("--vault is a vault name, without /");
2859
+ const account = values.account?.trim();
2860
+ if (values.account !== undefined && !account)
2861
+ throw new UsageError("--account is your 1Password sign-in address, such as my.1password.com");
2862
+ return { envFile, vault, account, yes: values.yes, args };
2863
+ }
2864
+ async function readTarget(deps, request) {
2865
+ const file = join6(deps.cwd, MAP_FILE);
2866
+ const found = await deps.files.read(file);
2867
+ if (found === null || found === TEMPLATE) {
2868
+ if (!request.account)
2869
+ throw new UsageError(`--account is required: ${file} doesn't name a 1Password account yet, so give its sign-in address, such as my.1password.com`);
2870
+ return { file, found, map: null, account: request.account };
2871
+ }
2872
+ const parsed = parseMap(found, file);
2873
+ if (!parsed.ok)
2874
+ throw new Error(`fix ${file} first: ${parsed.errors.join("; ")}`);
2875
+ const account = parsed.map.account ?? request.account;
2876
+ if (!account)
2877
+ throw new UsageError(`--account is required: ${file} has no [1password] account, so give its sign-in address, such as my.1password.com`);
2878
+ if (request.account && request.account !== account)
2879
+ throw new UsageError(`${file} uses 1Password account ${account}, not ${request.account}; drop --account`);
2880
+ return { file, found, map: parsed.map, account };
2881
+ }
2882
+ function refFor(account, vault, item) {
2883
+ return { kind: "1password", account, vault, item, section: null, field: "password" };
2884
+ }
2885
+ function keyTables(imports, environment) {
2886
+ return imports.map(({ name, ref }) => `
2887
+ [keys.${name}]
2888
+ rotate_every = ${str2(ROTATE_EVERY)}
2889
+ ${environment} = ${str2(formatReference(ref))}
2890
+ `).join("");
2891
+ }
2892
+ function mapBase(target) {
2893
+ if (!target.map || target.found === null)
2894
+ return "";
2895
+ return target.found.endsWith(`
2896
+ `) || !target.found ? target.found : `${target.found}
2897
+ `;
2898
+ }
2899
+ function mapAddition(target, imports, environment) {
2900
+ const account = `[1password]
2901
+ account = ${str2(target.account)}
2902
+ `;
2903
+ const tables = keyTables(imports, environment);
2904
+ if (!target.map)
2905
+ return `# Written by keypin import. The values are in 1Password; this file holds only references.
2906
+
2907
+ ${account}${tables}`;
2908
+ return `${target.map.account ? "" : `
2909
+ ${account}`}${tables}`;
2910
+ }
2911
+ function mapText(target, imports, environment) {
2912
+ return `${mapBase(target)}${mapAddition(target, imports, environment)}`;
2913
+ }
2914
+ async function writeMap(deps, target, imports, environment) {
2915
+ const text = mapText(target, imports, environment);
2916
+ const check = parseMap(text, target.file);
2917
+ if (!check.ok)
2918
+ throw new Error(`the new ${target.file} doesn't parse: ${check.errors.join("; ")}`);
2919
+ const result = target.found === null ? await deps.createFile(target.file, text) : await deps.replaceFile(target.file, target.found, text);
2920
+ if (result === "link")
2921
+ throw new Error(`${target.file} is a symbolic link; keypin import doesn't follow one`);
2922
+ if (result === "exists" || result === "changed")
2923
+ throw new Error(`${target.file} changed while import ran, so it wasn't written`);
2924
+ }
2925
+ async function confirmed(deps, request, items) {
2926
+ const say = (text) => deps.stderr.write(`${text}
2927
+ `);
2928
+ if (request.yes)
2929
+ return true;
2930
+ if (deps.isTerminal) {
2931
+ const answer = await deps.ask(`Type yes to create ${count2(items, "item")} in 1Password: `);
2932
+ if (answer.trim() === "yes")
2933
+ return true;
2934
+ say("Not confirmed. Nothing was created.");
2935
+ return false;
2936
+ }
2937
+ say("Stopped: no terminal to confirm on. Nothing was created. Confirm in a terminal, or add --yes.");
2938
+ say(rerun(deps, "import", request.args));
2939
+ return false;
2940
+ }
2941
+ function count2(n, noun) {
2942
+ return `${n} ${noun}${n === 1 ? "" : "s"}`;
2943
+ }
2944
+ function str2(value) {
2945
+ return JSON.stringify(value);
2946
+ }
2947
+
2948
+ // src/commands/publish.ts
2949
+ import { parseArgs as parseArgs4 } from "util";
2950
+
2584
2951
  // src/vault.ts
2585
2952
  function announce(stderr, what, refs) {
2586
2953
  const groups = new Map;
@@ -2604,129 +2971,182 @@ var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item
2604
2971
 
2605
2972
  // src/commands/publish.ts
2606
2973
  async function publish(args, deps) {
2607
- const { keyId, env, yes } = parseRequest(args);
2974
+ const { keyId, env, yes } = parseRequest2(args);
2608
2975
  const map = await findMap(deps.files, deps.cwd);
2609
2976
  const environment = pickEnvironment(map, env, publishEnvironment(map));
2610
2977
  const request = { keyId, environment, yes, args };
2611
2978
  return locked(deps, (path) => publishLocked(request, map, path, deps));
2612
2979
  }
2613
- function parseRequest(args) {
2614
- const { values, positionals } = parseArgs3({
2980
+ function parseRequest2(args) {
2981
+ const { values, positionals } = parseArgs4({
2615
2982
  args,
2616
2983
  options: {
2617
2984
  env: { type: "string" },
2618
- yes: { type: "boolean", default: false }
2985
+ yes: { type: "boolean", default: false },
2986
+ all: { type: "boolean", default: false }
2619
2987
  },
2620
2988
  allowPositionals: true
2621
2989
  });
2622
2990
  const [keyId, ...extra] = positionals;
2991
+ if (values.all) {
2992
+ if (positionals.length)
2993
+ throw new UsageError("keypin publish takes a variable name or --all, not both");
2994
+ return { keyId: null, env: values.env, yes: values.yes };
2995
+ }
2623
2996
  if (keyId === undefined || extra.length)
2624
- throw new UsageError("keypin publish takes one key: the variable name");
2997
+ throw new UsageError("keypin publish takes one key: the variable name, or --all");
2625
2998
  return { keyId, env: values.env, yes: values.yes };
2626
2999
  }
2627
- async function publishLocked(request, map, path, deps) {
3000
+ function jobsFor(request, map, say) {
2628
3001
  const { keyId, environment } = request;
2629
- const key = map.keys.find((k) => k.name === keyId);
2630
- if (!key)
2631
- throw new Error(`${map.file} has no key "${keyId}"`);
2632
- const entry = key.environments[environment];
2633
- if (!entry)
2634
- throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
3002
+ const job = (key, entry) => ({
3003
+ key,
3004
+ entry,
3005
+ owner: { keyId: key.name, environment, mapFile: map.file }
3006
+ });
3007
+ if (keyId !== null) {
3008
+ const key = map.keys.find((k) => k.name === keyId);
3009
+ if (!key)
3010
+ throw new Error(`${map.file} has no key "${keyId}"`);
3011
+ const entry = key.environments[environment];
3012
+ if (!entry)
3013
+ throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
3014
+ return [job(key, entry)];
3015
+ }
3016
+ const jobs = map.keys.flatMap((key) => {
3017
+ const entry = key.environments[environment];
3018
+ return entry?.publish.length ? [job(key, entry)] : [];
3019
+ });
3020
+ const skipped = map.keys.filter((key) => !jobs.some((j) => j.key === key));
3021
+ if (skipped.length)
3022
+ say(`Not published, no ${environment} destinations: ${skipped.map((k) => k.name).join(", ")}`);
3023
+ return jobs;
3024
+ }
3025
+ async function publishLocked(request, map, path, deps) {
3026
+ const { environment } = request;
3027
+ const many = request.keyId === null;
2635
3028
  const say = (text) => deps.stderr.write(`${text}
2636
3029
  `);
2637
- say(`Publishing ${keyId} (${environment}) from ${formatReference(entry.ref)}`);
2638
- say(` 1Password account: ${entry.ref.account}`);
2639
- for (const target of entry.publish)
2640
- say(` to: ${describeTarget(target, key.name)}`);
2641
- if (!entry.publish.length) {
2642
- say(`The map lists no destinations for ${keyId} (${environment}); nothing to publish.`);
3030
+ const jobs = jobsFor(request, map, say);
3031
+ if (many && !jobs.length) {
3032
+ say(`No key in ${map.file} has ${environment} destinations; nothing to publish.`);
2643
3033
  return 1;
2644
3034
  }
2645
- const state = await loadState(deps.files, path);
2646
- const owner = { keyId, environment, mapFile: map.file };
2647
- for (const op of unfinishedOperations(state, owner)) {
2648
- say(`An earlier publish (started ${op.startedAt}, generation ${op.generation}) didn't finish: wrote ${op.done.length} of ${op.planned.length} (${op.done.join(", ") || "none"}). This run plans again from the receipts.`);
3035
+ for (const { key, entry } of jobs) {
3036
+ say(`Publishing ${key.name} (${environment}) from ${formatReference(entry.ref)}`);
3037
+ say(` 1Password account: ${entry.ref.account}`);
3038
+ for (const target of entry.publish)
3039
+ say(` to: ${describeTarget(target, key.name)}`);
3040
+ if (!entry.publish.length) {
3041
+ say(`The map lists no destinations for ${key.name} (${environment}); nothing to publish.`);
3042
+ return 1;
3043
+ }
2649
3044
  }
2650
- const checked = await checkAccounts(key, entry, deps, say);
2651
- if (!checked) {
3045
+ let state = await loadState(deps.files, path);
3046
+ for (const { owner } of jobs) {
3047
+ for (const op of unfinishedOperations(state, owner)) {
3048
+ 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.`);
3049
+ }
3050
+ }
3051
+ const checks = [];
3052
+ for (const job of jobs) {
3053
+ const heading = many ? `Account checks for ${job.key.name}` : "Account checks";
3054
+ const checked = await checkAccounts(job.key, job.entry, deps, say, heading);
3055
+ if (checked)
3056
+ checks.push({ ...job, checked });
3057
+ }
3058
+ if (checks.length < jobs.length) {
2652
3059
  say("Stopped: an account check failed. Nothing was read and nothing was written.");
2653
3060
  return 1;
2654
3061
  }
2655
- const approvals = approvalsFor({
2656
- key,
2657
- environment,
2658
- mapFile: map.file,
2659
- receipts: state.receipts
2660
- });
3062
+ const approvals = jobs.flatMap(({ key, owner }) => approvalsFor({ key, environment, mapFile: owner.mapFile, receipts: state.receipts }));
2661
3063
  if (approvals.length && !deps.isTerminal) {
2662
3064
  say(`
2663
3065
  Needs approval:`);
2664
3066
  for (const approval of approvals)
2665
3067
  say(` ${approval.approval}`);
2666
- say(`Stopped before reading the value: this publish needs approval, and --yes can't give it. Nothing was read and nothing was written.`);
3068
+ say(`Stopped before reading ${many ? "any value" : "the value"}: this publish needs approval, and --yes can't give it. Nothing was read and nothing was written.`);
2667
3069
  say(rerun(deps, "publish", request.args));
2668
3070
  return NEEDS_APPROVAL;
2669
3071
  }
2670
- announce(deps.stderr, "the value to publish", [entry.ref]);
2671
- let secret;
2672
- try {
2673
- secret = await deps.vault().read(entry.ref);
2674
- } catch (error) {
2675
- say(`Stopped: couldn't read ${keyId} (${formatReference(entry.ref)}): ${messageOf(error)}`);
2676
- return 1;
2677
- }
2678
- const generation = await generationOf(secret);
2679
- const plan = planPublish({
2680
- key,
2681
- environment,
2682
- mapFile: map.file,
2683
- receipts: state.receipts,
2684
- generation
2685
- });
2686
- say(`
3072
+ announce(deps.stderr, many ? "the values to publish" : "the value to publish", jobs.map((job) => job.entry.ref));
3073
+ const planned = [];
3074
+ let needsApproval = false;
3075
+ for (const job of checks) {
3076
+ const { key, entry, owner, checked } = job;
3077
+ let secret;
3078
+ try {
3079
+ secret = await deps.vault().read(entry.ref);
3080
+ } catch (error) {
3081
+ say(`Stopped: couldn't read ${key.name} (${formatReference(entry.ref)}): ${messageOf(error)}`);
3082
+ return 1;
3083
+ }
3084
+ const generation = await generationOf(secret);
3085
+ const plan = planPublish({
3086
+ key,
3087
+ environment,
3088
+ mapFile: owner.mapFile,
3089
+ receipts: state.receipts,
3090
+ generation
3091
+ });
3092
+ const writes = writesFor(plan.steps, checked);
3093
+ say(many ? `
3094
+ Plan for ${key.name}, generation ${generation}:` : `
2687
3095
  Plan for generation ${generation}:`);
2688
- const writes = writesFor(plan.steps, checked);
2689
- for (const step of plan.steps) {
2690
- const found = checked.get(step.destinationId);
2691
- say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
2692
- if (found)
2693
- say(` ${accountFacts(found.check)}`);
2694
- if (step.approval)
2695
- say(` needs approval: ${step.approval}`);
3096
+ for (const step of plan.steps) {
3097
+ const found = checked.get(step.destinationId);
3098
+ say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
3099
+ if (found)
3100
+ say(` ${accountFacts(found.check)}`);
3101
+ if (step.approval)
3102
+ say(` needs approval: ${step.approval}`);
3103
+ }
3104
+ for (const removed of plan.removed) {
3105
+ say(` not in the map any more: ${removed.destinationId} (last got ${removed.lastReceipt.generation} at ${removed.lastReceipt.at}). keypin doesn't delete it.`);
3106
+ }
3107
+ needsApproval ||= plan.needsApproval;
3108
+ planned.push({ ...job, secret, generation, writes });
2696
3109
  }
2697
- for (const removed of plan.removed) {
2698
- say(` not in the map any more: ${removed.destinationId} (last got ${removed.lastReceipt.generation} at ${removed.lastReceipt.at}). keypin doesn't delete it.`);
3110
+ const finished = planned.filter((job) => !job.writes.length && unfinishedOperations(state, job.owner).length).reduce((s, job) => finishAll(s, job.owner), state);
3111
+ if (finished !== state) {
3112
+ state = finished;
3113
+ await saveState(deps.files, path, state);
2699
3114
  }
2700
- if (!writes.length) {
3115
+ const pending = planned.filter((job) => job.writes.length);
3116
+ if (!pending.length) {
2701
3117
  say("Nothing to write: every destination already has this generation.");
2702
- if (unfinishedOperations(state, owner).length) {
2703
- await saveState(deps.files, path, finishAll(state, owner));
2704
- }
2705
3118
  return 0;
2706
3119
  }
2707
- if (!await confirmed(deps, plan.needsApproval, request))
3120
+ if (!await confirmed2(deps, needsApproval, request))
2708
3121
  return NEEDS_APPROVAL;
2709
- const written = await writeAll({
2710
- key,
2711
- environment,
2712
- mapFile: map.file,
2713
- entry,
2714
- secret,
2715
- generation,
2716
- writes,
2717
- state,
2718
- path,
2719
- deps,
2720
- say
2721
- });
2722
- if (!written.ok) {
2723
- say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
2724
- return 1;
3122
+ for (const [index, job] of pending.entries()) {
3123
+ const written = await writeAll({
3124
+ key: job.key,
3125
+ environment,
3126
+ mapFile: job.owner.mapFile,
3127
+ entry: job.entry,
3128
+ secret: job.secret,
3129
+ generation: job.generation,
3130
+ writes: job.writes,
3131
+ state,
3132
+ path,
3133
+ deps,
3134
+ say
3135
+ });
3136
+ state = written.state;
3137
+ if (!written.ok) {
3138
+ if (many) {
3139
+ const left = pending.slice(index).map((j) => j.key.name);
3140
+ say(`Not finished: ${left.join(", ")}.`);
3141
+ }
3142
+ say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
3143
+ return 1;
3144
+ }
3145
+ say(`Published ${job.key.name} (${environment}) to ${job.writes.length} destination(s).`);
2725
3146
  }
2726
- say(`Published ${keyId} (${environment}) to ${writes.length} destination(s).`);
2727
3147
  return 0;
2728
3148
  }
2729
- async function confirmed(deps, needsApproval, request) {
3149
+ async function confirmed2(deps, needsApproval, request) {
2730
3150
  const say = (text) => deps.stderr.write(`${text}
2731
3151
  `);
2732
3152
  if (request.yes && !needsApproval)
@@ -2744,11 +3164,11 @@ async function confirmed(deps, needsApproval, request) {
2744
3164
  }
2745
3165
 
2746
3166
  // src/commands/rotate.ts
2747
- import { join as join6 } from "path";
2748
- import { parseArgs as parseArgs4 } from "util";
3167
+ import { join as join7 } from "path";
3168
+ import { parseArgs as parseArgs5 } from "util";
2749
3169
  var GRACE_DAYS = DUE_SOON_DAYS;
2750
3170
  async function rotate(args, deps) {
2751
- const { values, positionals } = parseArgs4({
3171
+ const { values, positionals } = parseArgs5({
2752
3172
  args,
2753
3173
  options: {
2754
3174
  env: { type: "string" },
@@ -2767,9 +3187,9 @@ async function rotate(args, deps) {
2767
3187
  const entry = key.environments[environment];
2768
3188
  if (!entry)
2769
3189
  throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
2770
- const issue = entry.issue;
2771
- if (!issue) {
2772
- throw new Error(`key "${keyId}" has no [keys.${keyId}.${environment}.issue] section in ${map.file}, so keypin can't make a new value`);
3190
+ const spec = entry.rotate;
3191
+ if (!spec) {
3192
+ throw new Error(`key "${keyId}" has no [keys.${keyId}.${environment}.rotate] section in ${map.file}, so keypin can't make a new value`);
2773
3193
  }
2774
3194
  const say = (text) => deps.stderr.write(`${text}
2775
3195
  `);
@@ -2778,7 +3198,7 @@ async function rotate(args, deps) {
2778
3198
  map,
2779
3199
  key,
2780
3200
  entry,
2781
- issue,
3201
+ spec,
2782
3202
  environment,
2783
3203
  yes: values.yes,
2784
3204
  args,
@@ -2792,8 +3212,8 @@ async function rotate(args, deps) {
2792
3212
  if (!open)
2793
3213
  return start(run, data);
2794
3214
  say(`An unfinished rotation of ${key.name} (${environment}), started ${open.startedAt}, is at stage "${open.stage}".`);
2795
- if (open.provider !== issue.provider || open.account !== issue.account) {
2796
- say(`Stopped: that rotation made its token as ${open.provider} in account ${open.account}, and the map now says ${issue.provider} in account ${issue.account}. Put the map back to finish it. Nothing was changed.`);
3215
+ if (open.provider !== spec.provider || open.account !== spec.account) {
3216
+ say(`Stopped: that rotation made its token as ${open.provider} in account ${open.account}, and the map now says ${spec.provider} in account ${spec.account}. Put the map back to finish it. Nothing was changed.`);
2797
3217
  return 1;
2798
3218
  }
2799
3219
  switch (open.stage) {
@@ -2810,10 +3230,10 @@ async function rotate(args, deps) {
2810
3230
  });
2811
3231
  }
2812
3232
  async function start(run, data) {
2813
- const { key, entry, issue, environment, deps, say } = run;
3233
+ const { key, entry, spec, environment, deps, say } = run;
2814
3234
  say(`Rotating ${key.name} (${environment}) from ${formatReference(entry.ref)}`);
2815
3235
  say(` 1Password account: ${entry.ref.account}`);
2816
- say(` new token: ${issue.provider} in account ${issue.account}, made with the admin token in ${formatReference(issue.admin)}`);
3236
+ say(` new token: ${spec.provider} in account ${spec.account}, made with the admin token in ${formatReference(spec.admin)}`);
2817
3237
  for (const target of entry.publish)
2818
3238
  say(` to: ${describeTarget(target, key.name)}`);
2819
3239
  if (!entry.publish.length) {
@@ -2840,22 +3260,22 @@ async function start(run, data) {
2840
3260
  say(rerun(deps, "rotate", run.args));
2841
3261
  return NEEDS_APPROVAL;
2842
3262
  }
2843
- announce(deps.stderr, "the current value and the admin token", [entry.ref, issue.admin]);
3263
+ announce(deps.stderr, "the current value and the admin token", [entry.ref, spec.admin]);
2844
3264
  const vault = deps.vault();
2845
3265
  let current;
2846
3266
  let admin;
2847
3267
  try {
2848
3268
  current = await vault.read(entry.ref);
2849
- admin = await vault.read(issue.admin);
3269
+ admin = await vault.read(spec.admin);
2850
3270
  } catch (error) {
2851
3271
  say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
2852
3272
  return 1;
2853
3273
  }
2854
3274
  if (current.reveal() === admin.reveal()) {
2855
- say(`Stopped: ${formatReference(issue.admin)} holds the same value as ${formatReference(entry.ref)}. The admin token needs its own field, or rotating would overwrite it. Nothing was changed.`);
3275
+ say(`Stopped: ${formatReference(spec.admin)} holds the same value as ${formatReference(entry.ref)}. The admin token needs its own field, or rotating would overwrite it. Nothing was changed.`);
2856
3276
  return 1;
2857
3277
  }
2858
- const provider = deps.provider(issue, admin);
3278
+ const provider = deps.provider(spec, admin);
2859
3279
  const found = await provider.verify(current);
2860
3280
  if (found.status !== "active") {
2861
3281
  say(`Stopped: the current value is token ${found.id}, and it's ${found.status}. Nothing was changed.`);
@@ -2885,7 +3305,7 @@ Plan:`);
2885
3305
  for (const approval of approvals)
2886
3306
  say(` needs approval: ${approval.approval}`);
2887
3307
  say(` then stop: the old token stays active until you run ${again(run)} again.`);
2888
- if (!await confirmed2(run, approvals.length > 0, "make the new token"))
3308
+ if (!await confirmed3(run, approvals.length > 0, "make the new token"))
2889
3309
  return NEEDS_APPROVAL;
2890
3310
  const now = deps.now().toISOString();
2891
3311
  let rotation = {
@@ -2894,8 +3314,8 @@ Plan:`);
2894
3314
  environment,
2895
3315
  mapFile: run.map.file,
2896
3316
  item: entry.ref,
2897
- provider: issue.provider,
2898
- account: issue.account,
3317
+ provider: spec.provider,
3318
+ account: spec.account,
2899
3319
  stage: "issuing",
2900
3320
  startedAt: now,
2901
3321
  updatedAt: now,
@@ -2972,7 +3392,7 @@ async function publishNew(run, data, rotation, fresh) {
2972
3392
  }
2973
3393
  announce(deps.stderr, "the value to publish and the admin token, to check the new token", [
2974
3394
  entry.ref,
2975
- run.issue.admin
3395
+ run.spec.admin
2976
3396
  ]);
2977
3397
  value = await deps.vault().read(entry.ref);
2978
3398
  const generation = await generationOf(value);
@@ -2997,7 +3417,7 @@ Publishing generation ${generation}:`);
2997
3417
  say(` needs approval: ${step.approval}`);
2998
3418
  }
2999
3419
  const writes = writesFor(plan.steps, checked);
3000
- if (resuming && writes.length && !await confirmed2(run, plan.needsApproval, "publish")) {
3420
+ if (resuming && writes.length && !await confirmed3(run, plan.needsApproval, "publish")) {
3001
3421
  return NEEDS_APPROVAL;
3002
3422
  }
3003
3423
  const written = await writeAll({
@@ -3032,7 +3452,7 @@ Published. The old token ${rotation.old.id} "${rotation.old.name}" is still acti
3032
3452
  return 0;
3033
3453
  }
3034
3454
  async function revokeOld(run, data, rotation) {
3035
- const { key, issue, environment, deps, say } = run;
3455
+ const { key, spec, environment, deps, say } = run;
3036
3456
  const generation = rotation.new.generation;
3037
3457
  if (!generation || !rotation.new.id || !rotation.old.id) {
3038
3458
  throw new Error(`rotation ${rotation.id} has no new generation or token IDs`);
@@ -3069,14 +3489,14 @@ async function revokeOld(run, data, rotation) {
3069
3489
  }
3070
3490
  announce(deps.stderr, "the current value, to check it's the new token, and the admin token", [
3071
3491
  run.entry.ref,
3072
- issue.admin
3492
+ spec.admin
3073
3493
  ]);
3074
3494
  const holds = await generationOf(await deps.vault().read(run.entry.ref));
3075
3495
  if (holds !== generation) {
3076
3496
  say(`Stopped: ${formatReference(run.entry.ref)} holds generation ${holds}, not the new ${generation}. Something else changed it, and revoking would leave it with a dead token. Nothing was revoked.`);
3077
3497
  return 1;
3078
3498
  }
3079
- const provider = deps.provider(issue, await deps.vault().read(issue.admin));
3499
+ const provider = deps.provider(spec, await deps.vault().read(spec.admin));
3080
3500
  const current = await provider.details(rotation.new.id);
3081
3501
  if (current?.status !== "active") {
3082
3502
  say(`Stopped: the new token ${rotation.new.id} is ${current ? current.status : "gone"}. Nothing was revoked.`);
@@ -3106,7 +3526,7 @@ async function finish(run, data, rotation) {
3106
3526
  return 0;
3107
3527
  }
3108
3528
  async function abandon(run, data, rotation) {
3109
- const { entry, issue, deps, say } = run;
3529
+ const { entry, spec, deps, say } = run;
3110
3530
  if (rotation.new.generation) {
3111
3531
  announce(deps.stderr, "the current value, to see which token it holds", [entry.ref]);
3112
3532
  const holds = await generationOf(await deps.vault().read(entry.ref));
@@ -3155,8 +3575,8 @@ async function abandon(run, data, rotation) {
3155
3575
  return NEEDS_APPROVAL;
3156
3576
  }
3157
3577
  } else {
3158
- announce(deps.stderr, "the admin token", [issue.admin]);
3159
- const provider = deps.provider(issue, await deps.vault().read(issue.admin));
3578
+ announce(deps.stderr, "the admin token", [spec.admin]);
3579
+ const provider = deps.provider(spec, await deps.vault().read(spec.admin));
3160
3580
  const made = await provider.details(id);
3161
3581
  if (made) {
3162
3582
  say(`New token: ${made.id} "${made.name}", ${made.status}, its value was never stored`);
@@ -3191,7 +3611,7 @@ async function deleteUnchecked(run, data, rotation, provider) {
3191
3611
  async function recheck(run, rotation, value) {
3192
3612
  if (!rotation.new.id || !rotation.old.id)
3193
3613
  return "the rotation has no token IDs";
3194
- const provider = run.deps.provider(run.issue, await run.deps.vault().read(run.issue.admin));
3614
+ const provider = run.deps.provider(run.spec, await run.deps.vault().read(run.spec.admin));
3195
3615
  const old = await provider.details(rotation.old.id);
3196
3616
  if (!old)
3197
3617
  return `the old token ${rotation.old.id} is gone, so its policies can't be compared`;
@@ -3233,7 +3653,7 @@ async function listedOwners(run) {
3233
3653
  list(run.map, null);
3234
3654
  const registry = await loadRegistry(deps.files, registryPath(deps));
3235
3655
  for (const project of registry.projects) {
3236
- const file = join6(project, MAP_FILE);
3656
+ const file = join7(project, MAP_FILE);
3237
3657
  if (file === run.map.file)
3238
3658
  continue;
3239
3659
  const text = await deps.files.read(file);
@@ -3286,7 +3706,7 @@ async function checkNew(provider, id, value, old) {
3286
3706
  return messageOf(error);
3287
3707
  }
3288
3708
  }
3289
- async function confirmed2(run, needsApproval, what) {
3709
+ async function confirmed3(run, needsApproval, what) {
3290
3710
  const { deps, say } = run;
3291
3711
  if (run.yes && !needsApproval)
3292
3712
  return true;
@@ -3335,9 +3755,9 @@ function describeAccess(token) {
3335
3755
  }
3336
3756
 
3337
3757
  // src/commands/run.ts
3338
- import { parseArgs as parseArgs5 } from "util";
3758
+ import { parseArgs as parseArgs6 } from "util";
3339
3759
  async function run(args, deps) {
3340
- const { values, positionals } = parseArgs5({
3760
+ const { values, positionals } = parseArgs6({
3341
3761
  args,
3342
3762
  options: { env: { type: "string" } },
3343
3763
  allowPositionals: true
@@ -3404,10 +3824,10 @@ async function run(args, deps) {
3404
3824
  }
3405
3825
 
3406
3826
  // src/commands/status.ts
3407
- import { join as join7 } from "path";
3408
- import { parseArgs as parseArgs6 } from "util";
3827
+ import { join as join8 } from "path";
3828
+ import { parseArgs as parseArgs7 } from "util";
3409
3829
  async function status(args, deps) {
3410
- const { values, positionals } = parseArgs6({
3830
+ const { values, positionals } = parseArgs7({
3411
3831
  args,
3412
3832
  options: { json: { type: "boolean", default: false } },
3413
3833
  allowPositionals: true
@@ -3419,7 +3839,7 @@ async function status(args, deps) {
3419
3839
  const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
3420
3840
  const maps = new Map;
3421
3841
  for (const project of registry.projects) {
3422
- const file = join7(project, MAP_FILE);
3842
+ const file = join8(project, MAP_FILE);
3423
3843
  try {
3424
3844
  const text = await deps.files.read(file);
3425
3845
  if (text !== null)
@@ -3495,7 +3915,7 @@ function render2(result, projects) {
3495
3915
  ["problem", "Problems"],
3496
3916
  ["notice", "Notices"]
3497
3917
  ]) {
3498
- const found = shown(result.problems.filter((p) => p.severity === severity));
3918
+ const found = result.problems.filter((p) => p.severity === severity);
3499
3919
  if (!found.length)
3500
3920
  continue;
3501
3921
  lines.push("", `${title} (${found.length}):`);
@@ -3508,30 +3928,15 @@ function render2(result, projects) {
3508
3928
  `)}
3509
3929
  `;
3510
3930
  }
3511
- function shown(problems) {
3512
- const unknown = problems.filter((p) => p.kind === "authority-unknown");
3513
- const rest = problems.filter((p) => p.kind !== "authority-unknown");
3514
- if (!unknown.length)
3515
- return rest;
3516
- const keys = [...new Set(unknown.map((p) => p.keyId ?? p.project))];
3517
- const subject = keys.length === 1 ? "1 key" : `${keys.length} keys`;
3518
- return [
3519
- ...rest,
3520
- {
3521
- kind: "authority-unknown",
3522
- message: `${subject} (${keys.join(", ")}): what each grants is unknown, because keypin didn't create it`
3523
- }
3524
- ];
3525
- }
3526
3931
 
3527
3932
  // src/commands/unregister.ts
3528
- import { resolve as resolve3 } from "path";
3529
- import { parseArgs as parseArgs7 } from "util";
3933
+ import { resolve as resolve4 } from "path";
3934
+ import { parseArgs as parseArgs8 } from "util";
3530
3935
  async function unregister2(args, deps) {
3531
- const { positionals } = parseArgs7({ args, options: {}, allowPositionals: true });
3936
+ const { positionals } = parseArgs8({ args, options: {}, allowPositionals: true });
3532
3937
  if (positionals.length > 1)
3533
3938
  throw new UsageError("keypin unregister takes at most one folder");
3534
- const folder = resolve3(deps.cwd, positionals[0] ?? ".");
3939
+ const folder = resolve4(deps.cwd, positionals[0] ?? ".");
3535
3940
  const path = registryPath(deps);
3536
3941
  const before = await loadRegistry(deps.files, path);
3537
3942
  const registry = await unregister(deps.files, path, folder);
@@ -3547,7 +3952,7 @@ async function unregister2(args, deps) {
3547
3952
  return 0;
3548
3953
  }
3549
3954
  // ../../package.json
3550
- var version = "0.5.0";
3955
+ var version = "0.6.0";
3551
3956
 
3552
3957
  // src/cli.ts
3553
3958
  var USAGE = `Usage:
@@ -3555,13 +3960,21 @@ var USAGE = `Usage:
3555
3960
  keypin unregister [folder]
3556
3961
  stop listing a project; its keypin.toml stays
3557
3962
  keypin status [--json] every key in every registered project, with problems
3558
- keypin discover [folder] [--json]
3559
- every key name a project uses, local and in the cloud, and a draft map
3963
+ keypin discover [folder] [--json] [--write]
3964
+ every key name a project uses, local and in the cloud, and a draft map;
3965
+ --write saves the draft as keypin.toml (only when there's none, or the
3966
+ untouched init template) and registers the project
3967
+ keypin import <env-file> --vault <vault> [--account <sign-in address>] [--yes]
3968
+ move an env file's values into new 1Password items and map them; the
3969
+ account is the map's, or --account when there's no map yet. It never
3970
+ overwrites an item, so --yes is enough to approve it. The file stays.
3560
3971
  keypin run [--env <name>] -- <command>
3561
3972
  run a command with one environment's keys (default: the first, dev)
3562
3973
  keypin publish <VARIABLE> [--env <name>] [--yes]
3563
3974
  check accounts, plan, confirm, then write the key to every destination
3564
3975
  (default environment: the last, prod)
3976
+ keypin publish --all [--env <name>] [--yes]
3977
+ the same for every key with destinations, with one plan and one approval
3565
3978
  keypin rotate <VARIABLE> [--env <name>] [--yes]
3566
3979
  replace a token with a new one that has the same permissions, publish it,
3567
3980
  and revoke the old one on the next run
@@ -3579,6 +3992,7 @@ var COMMANDS = new Map([
3579
3992
  ["unregister", unregister2],
3580
3993
  ["status", status],
3581
3994
  ["discover", discover],
3995
+ ["import", importEnv],
3582
3996
  ["run", run],
3583
3997
  ["publish", publish],
3584
3998
  ["rotate", rotate]
@@ -3686,6 +4100,78 @@ var createFile = async (path, text) => {
3686
4100
  return now === "missing" ? "exists" : now;
3687
4101
  }
3688
4102
  };
4103
+ function replaceFileWith(beforeRecheck) {
4104
+ return async (path, expected, text) => {
4105
+ const first = await readExpected(path, expected);
4106
+ if (typeof first === "string")
4107
+ return first;
4108
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
4109
+ try {
4110
+ const handle = await open(temporary, "wx", 384);
4111
+ try {
4112
+ await handle.chmod(Number(first.mode) & 4095);
4113
+ await handle.writeFile(text);
4114
+ await handle.sync();
4115
+ } finally {
4116
+ await handle.close();
4117
+ }
4118
+ await beforeRecheck();
4119
+ const now = await readExpected(path, expected);
4120
+ if (typeof now === "string")
4121
+ return now;
4122
+ if (!sameFile(first, now))
4123
+ return "changed";
4124
+ await rename(temporary, path);
4125
+ return "replaced";
4126
+ } finally {
4127
+ await rm(temporary, { force: true });
4128
+ }
4129
+ };
4130
+ }
4131
+ var replaceFile = replaceFileWith(async () => {});
4132
+ function sameFile(a, b) {
4133
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs;
4134
+ }
4135
+ async function readExpected(path, expected) {
4136
+ if (await kindOf(path) === "link")
4137
+ return "link";
4138
+ let handle;
4139
+ try {
4140
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
4141
+ } catch (error) {
4142
+ if (errorCode(error) === "ELOOP")
4143
+ return "link";
4144
+ if (errorCode(error) === "ENOENT")
4145
+ return "changed";
4146
+ throw error;
4147
+ }
4148
+ try {
4149
+ const opened = await handle.stat({ bigint: true });
4150
+ if (await handle.readFile("utf8") !== expected)
4151
+ return "changed";
4152
+ const found = await lstat(path, { bigint: true }).catch((error) => {
4153
+ if (errorCode(error) === "ENOENT")
4154
+ return null;
4155
+ throw error;
4156
+ });
4157
+ if (found === null)
4158
+ return "changed";
4159
+ if (found.isSymbolicLink())
4160
+ return "link";
4161
+ return sameFile(opened, found) ? opened : "changed";
4162
+ } finally {
4163
+ await handle.close();
4164
+ }
4165
+ }
4166
+ async function isLink(path) {
4167
+ try {
4168
+ return (await lstat(path)).isSymbolicLink();
4169
+ } catch (error) {
4170
+ if (errorCode(error) === "ENOENT")
4171
+ return false;
4172
+ throw error;
4173
+ }
4174
+ }
3689
4175
  async function kindOf(path) {
3690
4176
  try {
3691
4177
  const found = await lstat(path);
@@ -3783,12 +4269,12 @@ function destination(target) {
3783
4269
  }
3784
4270
  }
3785
4271
  }
3786
- function provider(issue, admin) {
3787
- switch (issue.provider) {
4272
+ function provider(spec, admin) {
4273
+ switch (spec.provider) {
3788
4274
  case "cloudflare-account-token":
3789
- return new CloudflareAccountTokens({ account: issue.account, admin });
4275
+ return new CloudflareAccountTokens({ account: spec.account, admin });
3790
4276
  default: {
3791
- const unknown = issue.provider;
4277
+ const unknown = spec.provider;
3792
4278
  throw new Error(`unknown provider ${JSON.stringify(unknown)}`);
3793
4279
  }
3794
4280
  }
@@ -3820,6 +4306,8 @@ function main() {
3820
4306
  token: () => currentWranglerToken()
3821
4307
  })).listWorkerSecrets(account, worker),
3822
4308
  createFile,
4309
+ replaceFile,
4310
+ isLink,
3823
4311
  vault: () => vault ??= onePasswordBackend(connect),
3824
4312
  now: () => new Date,
3825
4313
  stdout: process.stdout,