keypin 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -108,9 +108,13 @@ keypin import <env-file> --vault <vault>
108
108
  keypin run -- <command> # run a command with the project's dev keys (--env for another)
109
109
  keypin publish <VARIABLE> # check each destination's account, then write the key
110
110
  keypin publish --all # publish every key, with one plan and one approval
111
+ keypin publish --all --plan # show that plan without a terminal, and write nothing
111
112
  keypin rotate <VARIABLE> # replace a Cloudflare API token, then revoke the old one
112
113
  ```
113
114
 
115
+ Add `--plan` to `publish` or `rotate` to see the plan without a terminal. It changes nothing, and prints the
116
+ command that does.
117
+
114
118
  `import`, `publish` and `rotate` show a plan and wait for you to type `yes`. `--yes` approves `import`, which only
115
119
  creates new items. For `publish` and `rotate`, it skips that only for routine updates: it never approves a first
116
120
  write, a changed account or vault item, or a revoke. `keypin --help` lists the exit codes.
@@ -21,6 +21,15 @@ class Secret {
21
21
  reveal() {
22
22
  return this.#value;
23
23
  }
24
+ equals(other) {
25
+ return this.#value === other.#value;
26
+ }
27
+ isEmpty() {
28
+ return !this.#value;
29
+ }
30
+ includes(text) {
31
+ return this.#value.includes(text);
32
+ }
24
33
  toString() {
25
34
  return HIDDEN;
26
35
  }
@@ -2668,10 +2677,22 @@ function finishAll(state, owner) {
2668
2677
  return unfinishedOperations(state, owner).reduce((s, op) => finishOperation(s, op.id), state);
2669
2678
  }
2670
2679
  function rerun(deps, command, args) {
2671
- const words = [...deps.self, command, ...args].map(shellWord).join(" ");
2680
+ const end = args.includes("--") ? args.indexOf("--") : args.length;
2681
+ const approve = [...args.slice(0, end).filter((arg) => arg !== "--plan"), ...args.slice(end)];
2682
+ const words = [...deps.self, command, ...approve].map(shellWord).join(" ");
2672
2683
  return `To approve, run this in a terminal:
2673
2684
  cd ${shellWord(deps.cwd)} && ${words}`;
2674
2685
  }
2686
+ function planOnly(deps, command, args, needsApproval) {
2687
+ const say = (text) => deps.stderr.write(`${text}
2688
+ `);
2689
+ say(needsApproval ? `
2690
+ This plan needs yes typed in a terminal; --yes can't approve it.` : `
2691
+ This plan is routine: --yes can approve it.`);
2692
+ say("Nothing was written: --plan only shows the plan.");
2693
+ say(rerun(deps, command, args));
2694
+ return NEEDS_APPROVAL;
2695
+ }
2675
2696
  function shellWord(word) {
2676
2697
  return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
2677
2698
  }
@@ -2713,7 +2734,7 @@ async function importEnv(args, deps) {
2713
2734
  reason: "not a variable name (letters, digits and _, not a digit first)",
2714
2735
  onlyInFile: true
2715
2736
  });
2716
- else if (!value.reveal())
2737
+ else if (value.isEmpty())
2717
2738
  skips.push({ name, reason: "the value is empty", onlyInFile: false });
2718
2739
  else if (mapped?.environments[environment])
2719
2740
  skips.push({
@@ -2727,7 +2748,7 @@ async function importEnv(args, deps) {
2727
2748
  reason: `mapped in ${target.file} without ${environment}; left as it is, so add its ${environment} reference by hand`,
2728
2749
  onlyInFile: true
2729
2750
  });
2730
- else if (value.reveal().includes("$"))
2751
+ else if (value.includes("$"))
2731
2752
  skips.push({
2732
2753
  name,
2733
2754
  reason: "the value has a $, which some loaders expand to another variable's value",
@@ -2830,7 +2851,7 @@ async function importEnv(args, deps) {
2830
2851
  async function existingProblem(deps, entry) {
2831
2852
  try {
2832
2853
  const value = await deps.vault().read(entry.ref);
2833
- return value.reveal() === entry.value.reveal() ? null : "with another value";
2854
+ return value.equals(entry.value) ? null : "with another value";
2834
2855
  } catch (error) {
2835
2856
  return `and couldn't be read (${messageOf(error)})`;
2836
2857
  }
@@ -2971,10 +2992,10 @@ var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item
2971
2992
 
2972
2993
  // src/commands/publish.ts
2973
2994
  async function publish(args, deps) {
2974
- const { keyId, env, yes } = parseRequest2(args);
2995
+ const { keyId, env, yes, plan } = parseRequest2(args);
2975
2996
  const map = await findMap(deps.files, deps.cwd);
2976
2997
  const environment = pickEnvironment(map, env, publishEnvironment(map));
2977
- const request = { keyId, environment, yes, args };
2998
+ const request = { keyId, environment, yes, plan, args };
2978
2999
  return locked(deps, (path) => publishLocked(request, map, path, deps));
2979
3000
  }
2980
3001
  function parseRequest2(args) {
@@ -2983,7 +3004,8 @@ function parseRequest2(args) {
2983
3004
  options: {
2984
3005
  env: { type: "string" },
2985
3006
  yes: { type: "boolean", default: false },
2986
- all: { type: "boolean", default: false }
3007
+ all: { type: "boolean", default: false },
3008
+ plan: { type: "boolean", default: false }
2987
3009
  },
2988
3010
  allowPositionals: true
2989
3011
  });
@@ -2991,11 +3013,11 @@ function parseRequest2(args) {
2991
3013
  if (values.all) {
2992
3014
  if (positionals.length)
2993
3015
  throw new UsageError("keypin publish takes a variable name or --all, not both");
2994
- return { keyId: null, env: values.env, yes: values.yes };
3016
+ return { keyId: null, env: values.env, yes: values.yes, plan: values.plan };
2995
3017
  }
2996
3018
  if (keyId === undefined || extra.length)
2997
3019
  throw new UsageError("keypin publish takes one key: the variable name, or --all");
2998
- return { keyId, env: values.env, yes: values.yes };
3020
+ return { keyId, env: values.env, yes: values.yes, plan: values.plan };
2999
3021
  }
3000
3022
  function jobsFor(request, map, say) {
3001
3023
  const { keyId, environment } = request;
@@ -3060,7 +3082,7 @@ async function publishLocked(request, map, path, deps) {
3060
3082
  return 1;
3061
3083
  }
3062
3084
  const approvals = jobs.flatMap(({ key, owner }) => approvalsFor({ key, environment, mapFile: owner.mapFile, receipts: state.receipts }));
3063
- if (approvals.length && !deps.isTerminal) {
3085
+ if (approvals.length && !deps.isTerminal && !request.plan) {
3064
3086
  say(`
3065
3087
  Needs approval:`);
3066
3088
  for (const approval of approvals)
@@ -3108,7 +3130,7 @@ Plan for generation ${generation}:`);
3108
3130
  planned.push({ ...job, secret, generation, writes });
3109
3131
  }
3110
3132
  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) {
3133
+ if (finished !== state && !request.plan) {
3112
3134
  state = finished;
3113
3135
  await saveState(deps.files, path, state);
3114
3136
  }
@@ -3117,6 +3139,8 @@ Plan for generation ${generation}:`);
3117
3139
  say("Nothing to write: every destination already has this generation.");
3118
3140
  return 0;
3119
3141
  }
3142
+ if (request.plan)
3143
+ return planOnly(deps, "publish", request.args, needsApproval);
3120
3144
  if (!await confirmed2(deps, needsApproval, request))
3121
3145
  return NEEDS_APPROVAL;
3122
3146
  for (const [index, job] of pending.entries()) {
@@ -3172,7 +3196,8 @@ async function rotate(args, deps) {
3172
3196
  args,
3173
3197
  options: {
3174
3198
  env: { type: "string" },
3175
- yes: { type: "boolean", default: false }
3199
+ yes: { type: "boolean", default: false },
3200
+ plan: { type: "boolean", default: false }
3176
3201
  },
3177
3202
  allowPositionals: true
3178
3203
  });
@@ -3201,6 +3226,7 @@ async function rotate(args, deps) {
3201
3226
  spec,
3202
3227
  environment,
3203
3228
  yes: values.yes,
3229
+ plan: values.plan,
3204
3230
  args,
3205
3231
  statePath,
3206
3232
  rotationsPath: rotationsPath(deps),
@@ -3253,7 +3279,7 @@ async function start(run, data) {
3253
3279
  return 1;
3254
3280
  }
3255
3281
  const approvals = approvalsFor({ ...planFor(run), receipts: state.receipts });
3256
- if (!deps.isTerminal && (approvals.length || !run.yes)) {
3282
+ if (!deps.isTerminal && !run.plan && (approvals.length || !run.yes)) {
3257
3283
  for (const approval of approvals)
3258
3284
  say(` needs approval: ${approval.approval}`);
3259
3285
  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.");
@@ -3271,7 +3297,7 @@ async function start(run, data) {
3271
3297
  say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
3272
3298
  return 1;
3273
3299
  }
3274
- if (current.reveal() === admin.reveal()) {
3300
+ if (current.equals(admin)) {
3275
3301
  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.`);
3276
3302
  return 1;
3277
3303
  }
@@ -3305,6 +3331,8 @@ Plan:`);
3305
3331
  for (const approval of approvals)
3306
3332
  say(` needs approval: ${approval.approval}`);
3307
3333
  say(` then stop: the old token stays active until you run ${again(run)} again.`);
3334
+ if (run.plan)
3335
+ return planOnly(deps, "rotate", run.args, approvals.length > 0);
3308
3336
  if (!await confirmed3(run, approvals.length > 0, "make the new token"))
3309
3337
  return NEEDS_APPROVAL;
3310
3338
  const now = deps.now().toISOString();
@@ -3385,7 +3413,8 @@ async function publishNew(run, data, rotation, fresh) {
3385
3413
  return 1;
3386
3414
  }
3387
3415
  checked = found;
3388
- if (!deps.isTerminal && approvalsFor({ ...planFor(run), receipts: state.receipts }).length) {
3416
+ const approvals = approvalsFor({ ...planFor(run), receipts: state.receipts });
3417
+ if (!deps.isTerminal && !run.plan && approvals.length) {
3389
3418
  say("Stopped before reading the value: publishing needs approval, and --yes can't give it.");
3390
3419
  say(rerun(deps, "rotate", run.args));
3391
3420
  return NEEDS_APPROVAL;
@@ -3417,6 +3446,8 @@ Publishing generation ${generation}:`);
3417
3446
  say(` needs approval: ${step.approval}`);
3418
3447
  }
3419
3448
  const writes = writesFor(plan.steps, checked);
3449
+ if (run.plan)
3450
+ return planOnly(deps, "rotate", run.args, plan.needsApproval);
3420
3451
  if (resuming && writes.length && !await confirmed3(run, plan.needsApproval, "publish")) {
3421
3452
  return NEEDS_APPROVAL;
3422
3453
  }
@@ -3482,7 +3513,7 @@ async function revokeOld(run, data, rotation) {
3482
3513
  }
3483
3514
  return 1;
3484
3515
  }
3485
- if (!deps.isTerminal) {
3516
+ if (!deps.isTerminal && !run.plan) {
3486
3517
  say("Stopped: revoking needs yes typed in a terminal, and --yes can't give it. Nothing was revoked.");
3487
3518
  say(rerun(deps, "rotate", run.args));
3488
3519
  return NEEDS_APPROVAL;
@@ -3505,12 +3536,17 @@ async function revokeOld(run, data, rotation) {
3505
3536
  const old = await provider.details(rotation.old.id);
3506
3537
  if (!old) {
3507
3538
  say(`The old token ${rotation.old.id} is already gone.`);
3508
- return finish(run, data, rotation);
3539
+ if (!run.plan)
3540
+ return finish(run, data, rotation);
3541
+ say("The next run records this rotation as finished, and asks nothing.");
3542
+ return planOnly(deps, "rotate", run.args, true);
3509
3543
  }
3510
3544
  say(`
3511
3545
  Old token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "never"}`);
3512
3546
  say(` last used: ${old.lastUsedOn ?? "not reported"}`);
3513
3547
  say(`New token: ${current.id} "${current.name}", ${current.status}, expires ${current.expiresOn ?? "never"}`);
3548
+ if (run.plan)
3549
+ return planOnly(deps, "rotate", run.args, true);
3514
3550
  const answer = await deps.ask(`Type yes to revoke the old token ${old.id}: `);
3515
3551
  if (answer.trim() !== "yes") {
3516
3552
  say("Not confirmed. Nothing was revoked.");
@@ -3537,7 +3573,8 @@ async function abandon(run, data, rotation) {
3537
3573
  updatedAt: deps.now().toISOString()
3538
3574
  };
3539
3575
  const next = putRotation(data, stored);
3540
- await saveRotations(deps.files, run.rotationsPath, next);
3576
+ if (!run.plan)
3577
+ await saveRotations(deps.files, run.rotationsPath, next);
3541
3578
  say(`${formatReference(entry.ref)} already holds the new value (generation ${holds}).`);
3542
3579
  return publishNew(run, next, stored, null);
3543
3580
  }
@@ -3562,6 +3599,10 @@ async function abandon(run, data, rotation) {
3562
3599
  }
3563
3600
  }
3564
3601
  say(`It stopped before the new value was stored, so the old token ${rotation.old.id} still works everywhere.`);
3602
+ if (run.plan) {
3603
+ say(rotation.new.id ? `The next run deletes the new token ${rotation.new.id} and forgets this rotation.` : `Cloudflare may have made a token named "${rotation.new.name}". The next run can't delete it: find it under Account API tokens and delete it, then the next run forgets this rotation.`);
3604
+ return planOnly(deps, "rotate", run.args, true);
3605
+ }
3565
3606
  if (!deps.isTerminal) {
3566
3607
  say("Stopped: cleaning it up needs yes typed in a terminal. Nothing was changed.");
3567
3608
  say(rerun(deps, "rotate", run.args));
@@ -3755,6 +3796,7 @@ function describeAccess(token) {
3755
3796
  }
3756
3797
 
3757
3798
  // src/commands/run.ts
3799
+ import { dirname as dirname3, join as join8, relative as relative2 } from "path";
3758
3800
  import { parseArgs as parseArgs6 } from "util";
3759
3801
  async function run(args, deps) {
3760
3802
  const { values, positionals } = parseArgs6({
@@ -3807,6 +3849,7 @@ async function run(args, deps) {
3807
3849
  `);
3808
3850
  return 1;
3809
3851
  }
3852
+ await warnAboutEnvFiles(deps, [...new Set([dirname3(map.file), deps.cwd])], keys.map((k) => k.key.name));
3810
3853
  let child;
3811
3854
  try {
3812
3855
  child = deps.launch(positionals, env);
@@ -3822,9 +3865,35 @@ async function run(args, deps) {
3822
3865
  stop();
3823
3866
  }
3824
3867
  }
3868
+ async function warnAboutEnvFiles(deps, folders, mapped) {
3869
+ if (!mapped.length)
3870
+ return;
3871
+ for (const folder of folders) {
3872
+ const entries = await deps.listFolder(folder).catch(() => []);
3873
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
3874
+ if (entry.kind !== "file" || envFileKind(entry.name) !== "set")
3875
+ continue;
3876
+ const path = join8(folder, entry.name);
3877
+ const text = await deps.files.read(path).catch(() => null);
3878
+ if (text === null)
3879
+ continue;
3880
+ const names = new Set(envNames(text));
3881
+ const held = mapped.filter((name) => names.has(name));
3882
+ if (held.length)
3883
+ deps.stderr.write(envFileWarning(entry.name, relative2(deps.cwd, path), held));
3884
+ }
3885
+ }
3886
+ }
3887
+ function envFileWarning(name, file, keys) {
3888
+ const list = keys.join(", ");
3889
+ const it = keys.length === 1 ? "it" : "them";
3890
+ const effect = name.startsWith(".dev.vars") ? `still sets ${list}; wrangler dev uses the file's value over keypin's` : `still holds a plaintext copy of ${list}; tools differ on which value wins`;
3891
+ return `keypin: ${file} ${effect}. Move ${it} out of the file.
3892
+ `;
3893
+ }
3825
3894
 
3826
3895
  // src/commands/status.ts
3827
- import { join as join8 } from "path";
3896
+ import { join as join9 } from "path";
3828
3897
  import { parseArgs as parseArgs7 } from "util";
3829
3898
  async function status(args, deps) {
3830
3899
  const { values, positionals } = parseArgs7({
@@ -3839,7 +3908,7 @@ async function status(args, deps) {
3839
3908
  const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
3840
3909
  const maps = new Map;
3841
3910
  for (const project of registry.projects) {
3842
- const file = join8(project, MAP_FILE);
3911
+ const file = join9(project, MAP_FILE);
3843
3912
  try {
3844
3913
  const text = await deps.files.read(file);
3845
3914
  if (text !== null)
@@ -3952,7 +4021,7 @@ async function unregister2(args, deps) {
3952
4021
  return 0;
3953
4022
  }
3954
4023
  // ../../package.json
3955
- var version = "0.6.0";
4024
+ var version = "0.7.0";
3956
4025
 
3957
4026
  // src/cli.ts
3958
4027
  var USAGE = `Usage:
@@ -3970,21 +4039,24 @@ var USAGE = `Usage:
3970
4039
  overwrites an item, so --yes is enough to approve it. The file stays.
3971
4040
  keypin run [--env <name>] -- <command>
3972
4041
  run a command with one environment's keys (default: the first, dev)
3973
- keypin publish <VARIABLE> [--env <name>] [--yes]
4042
+ keypin publish <VARIABLE> [--env <name>] [--yes | --plan]
3974
4043
  check accounts, plan, confirm, then write the key to every destination
3975
- (default environment: the last, prod)
3976
- keypin publish --all [--env <name>] [--yes]
4044
+ (default environment: the last, prod); --plan reads the value, prints
4045
+ the plan and the command to approve it, and writes nothing
4046
+ keypin publish --all [--env <name>] [--yes | --plan]
3977
4047
  the same for every key with destinations, with one plan and one approval
3978
- keypin rotate <VARIABLE> [--env <name>] [--yes]
4048
+ keypin rotate <VARIABLE> [--env <name>] [--yes | --plan]
3979
4049
  replace a token with a new one that has the same permissions, publish it,
3980
- and revoke the old one on the next run
4050
+ and revoke the old one on the next run; --plan reads and checks the tokens,
4051
+ prints this run's plan and the command to approve it, and changes nothing
3981
4052
  keypin --version print the version
3982
4053
 
3983
4054
  Exit codes:
3984
4055
  0 done
3985
4056
  1 failed, or status found a problem
3986
4057
  2 usage error
3987
- 3 stopped for approval: run the printed command in a terminal and type yes
4058
+ 3 stopped for approval: run the printed command in a terminal and type yes;
4059
+ --plan exits 3 whenever the plan would write (routine or not), 0 when there's nothing to write
3988
4060
  keypin run exits 1 if it can't start the command, then with the command's own code.
3989
4061
  `;
3990
4062
  var COMMANDS = new Map([
@@ -4036,8 +4108,8 @@ ${USAGE}`);
4036
4108
  // src/disk.ts
4037
4109
  import { constants, rmSync } from "fs";
4038
4110
  import { execFile as execFile3 } from "child_process";
4039
- import { chmod, lstat, mkdir, open, readdir, readFile as readFile2, rename, rm, stat } from "fs/promises";
4040
- import { dirname as dirname3 } from "path";
4111
+ import { chmod, lstat, mkdir, open, readdir, rename, rm, stat } from "fs/promises";
4112
+ import { dirname as dirname4 } from "path";
4041
4113
 
4042
4114
  // src/launch.ts
4043
4115
  var launch = (command, env) => {
@@ -4057,16 +4129,24 @@ var onSignals = (handler) => {
4057
4129
  // src/disk.ts
4058
4130
  var diskFiles = {
4059
4131
  async read(path) {
4132
+ let handle;
4060
4133
  try {
4061
- return await readFile2(path, "utf8");
4134
+ handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
4062
4135
  } catch (error) {
4063
4136
  if (errorCode(error) === "ENOENT")
4064
4137
  return null;
4065
4138
  throw error;
4066
4139
  }
4140
+ try {
4141
+ if (!(await handle.stat()).isFile())
4142
+ throw new Error(`${path} isn't a regular file`);
4143
+ return await handle.readFile("utf8");
4144
+ } finally {
4145
+ await handle.close();
4146
+ }
4067
4147
  },
4068
4148
  async write(path, text) {
4069
- await privateFolder(dirname3(path));
4149
+ await privateFolder(dirname4(path));
4070
4150
  const handle = await open(path, PRIVATE_WRITE, 384);
4071
4151
  try {
4072
4152
  await handle.chmod(384);
@@ -4208,7 +4288,7 @@ function git(folder, args) {
4208
4288
  });
4209
4289
  }
4210
4290
  var diskLock = async (path) => {
4211
- await privateFolder(dirname3(path));
4291
+ await privateFolder(dirname4(path));
4212
4292
  if (await take(path))
4213
4293
  return { held: true, lock: held(path) };
4214
4294
  const pid = await holderOf(path);
package/main.js CHANGED
@@ -14,7 +14,7 @@ if (problem) {
14
14
  }
15
15
  var start;
16
16
  try {
17
- start = await import("./chunk-k52ykj6s.js");
17
+ start = await import("./chunk-1rrcgz3h.js");
18
18
  } catch (error) {
19
19
  const hint = installProblem(error);
20
20
  if (!hint)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keypin",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "A map of every app key across your projects, published to the account it's pinned to. Values stay in your vault.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/caiopizzol/keypin#readme",