keypin 0.4.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.
- package/README.md +45 -22
- package/{chunk-dfr5e2r6.js → chunk-k52ykj6s.js} +1104 -537
- package/main.js +1 -1
- package/package.json +1 -1
|
@@ -39,13 +39,54 @@ async function generationOf(secret) {
|
|
|
39
39
|
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 16);
|
|
40
40
|
}
|
|
41
41
|
// ../../packages/core/src/contracts.ts
|
|
42
|
-
var
|
|
42
|
+
var DEFAULT_ENVIRONMENTS = ["dev", "prod"];
|
|
43
43
|
// ../../packages/core/src/map.ts
|
|
44
44
|
var {TOML } = globalThis.Bun;
|
|
45
45
|
|
|
46
46
|
// ../../packages/core/src/record.ts
|
|
47
47
|
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
48
48
|
|
|
49
|
+
// ../../packages/core/src/reference.ts
|
|
50
|
+
var SCHEME = "op://";
|
|
51
|
+
function parseReference(text) {
|
|
52
|
+
if (!text.startsWith(SCHEME))
|
|
53
|
+
return `must start with ${SCHEME}`;
|
|
54
|
+
if (/[?#]/.test(text))
|
|
55
|
+
return "can't have a query such as ?attribute=";
|
|
56
|
+
const parts = text.slice(SCHEME.length).split("/");
|
|
57
|
+
if (parts.length < 3 || parts.length > 4 || parts.some((part) => !part.trim())) {
|
|
58
|
+
return `must be ${SCHEME}<vault>/<item>/<field> or ${SCHEME}<vault>/<item>/<section>/<field>`;
|
|
59
|
+
}
|
|
60
|
+
const [vault = "", item = "", ...rest] = parts;
|
|
61
|
+
return {
|
|
62
|
+
vault,
|
|
63
|
+
item,
|
|
64
|
+
section: rest.length === 2 ? rest[0] ?? null : null,
|
|
65
|
+
field: rest.at(-1) ?? ""
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function formatReference(ref) {
|
|
69
|
+
const parts = [ref.vault, ref.item, ...ref.section === null ? [] : [ref.section], ref.field];
|
|
70
|
+
return `${SCHEME}${parts.join("/")}`;
|
|
71
|
+
}
|
|
72
|
+
var sameName = (a, b) => a === b || a !== null && b !== null && a.toLowerCase() === b.toLowerCase();
|
|
73
|
+
function sameItem(a, b) {
|
|
74
|
+
return a.kind === b.kind && a.account === b.account && sameName(a.vault, b.vault) && sameName(a.item, b.item);
|
|
75
|
+
}
|
|
76
|
+
function sameRef(a, b) {
|
|
77
|
+
return sameItem(a, b) && sameName(a.section, b.section) && sameName(a.field, b.field);
|
|
78
|
+
}
|
|
79
|
+
function storedRefWithPasswordDefault(value) {
|
|
80
|
+
if (!isRecord(value) || value.kind !== "1password")
|
|
81
|
+
return null;
|
|
82
|
+
const { account, vault, item, section = null, field = "password" } = value;
|
|
83
|
+
if (typeof account !== "string" || typeof vault !== "string" || typeof item !== "string")
|
|
84
|
+
return null;
|
|
85
|
+
if (typeof field !== "string" || section !== null && typeof section !== "string")
|
|
86
|
+
return null;
|
|
87
|
+
return { kind: "1password", account, vault, item, section, field };
|
|
88
|
+
}
|
|
89
|
+
|
|
49
90
|
// ../../packages/core/src/rotation.ts
|
|
50
91
|
var DUE_SOON_DAYS = 14;
|
|
51
92
|
var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
@@ -80,6 +121,15 @@ function addDays(day, days) {
|
|
|
80
121
|
// ../../packages/core/src/map.ts
|
|
81
122
|
var DESTINATION_KINDS = ["cloudflare-worker", "github-actions"];
|
|
82
123
|
var PROVIDER_KINDS = ["cloudflare-account-token"];
|
|
124
|
+
function runEnvironment(map) {
|
|
125
|
+
return map.environments[0] ?? "dev";
|
|
126
|
+
}
|
|
127
|
+
function publishEnvironment(map) {
|
|
128
|
+
return map.environments.at(-1) ?? "prod";
|
|
129
|
+
}
|
|
130
|
+
function envFlag(environment, fallback) {
|
|
131
|
+
return environment === fallback ? "" : ` --env ${environment}`;
|
|
132
|
+
}
|
|
83
133
|
function destinationId(target, secretName) {
|
|
84
134
|
return `${placeId(target)}:${secretName}`;
|
|
85
135
|
}
|
|
@@ -101,6 +151,9 @@ function receiptSecretKey(receipt) {
|
|
|
101
151
|
function placeId(target) {
|
|
102
152
|
return target.to === "cloudflare-worker" ? `cloudflare-worker:${target.worker}` : `github-actions:${target.repo}`;
|
|
103
153
|
}
|
|
154
|
+
function isVariableName(name) {
|
|
155
|
+
return VARIABLE_NAME.test(name);
|
|
156
|
+
}
|
|
104
157
|
function parseMap(text, file) {
|
|
105
158
|
let data;
|
|
106
159
|
try {
|
|
@@ -113,59 +166,112 @@ function parseMap(text, file) {
|
|
|
113
166
|
}
|
|
114
167
|
return validateMap(data, file);
|
|
115
168
|
}
|
|
116
|
-
var
|
|
117
|
-
var
|
|
169
|
+
var ENVIRONMENT_NAME = /^[a-z][a-z0-9-]*$/;
|
|
170
|
+
var TARGET_NAME = ENVIRONMENT_NAME;
|
|
171
|
+
var KEY_FIELDS = ["rotate_every"];
|
|
172
|
+
var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
118
173
|
var REPO = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
|
|
119
|
-
var
|
|
174
|
+
var REMOVED_KEY_FIELDS = ["owner", "consumers"];
|
|
175
|
+
var OLD_FORMAT = "see docs/configuration.md for the current format";
|
|
120
176
|
function validateMap(data, file) {
|
|
121
177
|
const errors = [];
|
|
122
178
|
const fail = (where, message) => errors.push(`${file}: ${where}${message}`);
|
|
123
179
|
if (!isRecord(data))
|
|
124
180
|
return { ok: false, errors: [`${file}: expected a table at the top level`] };
|
|
125
|
-
unknownFields(data, ["
|
|
126
|
-
const
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
fail("", `"vaults" must be a table`);
|
|
130
|
-
else {
|
|
131
|
-
for (const [name, raw] of Object.entries(rawVaults)) {
|
|
132
|
-
const at = `vault "${name}": `;
|
|
133
|
-
if (!isRecord(raw)) {
|
|
134
|
-
fail(at, "must be a table");
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
unknownFields(raw, ["kind", "account", "vault"], (field) => fail(at, `unknown field "${field}"`));
|
|
138
|
-
const kind = requiredString(raw, "kind", (m) => fail(at, m));
|
|
139
|
-
const account = requiredString(raw, "account", (m) => fail(at, m));
|
|
140
|
-
const vault = requiredString(raw, "vault", (m) => fail(at, m));
|
|
141
|
-
if (kind !== undefined && !VAULT_KINDS.includes(kind)) {
|
|
142
|
-
fail(at, `field "kind" must be one of: ${VAULT_KINDS.join(", ")}`);
|
|
143
|
-
} else if (kind !== undefined && account !== undefined && vault !== undefined) {
|
|
144
|
-
vaults.set(name, { kind: "1password", account, vault });
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
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}"`));
|
|
182
|
+
const environments = validateEnvironments(data.environments, (message) => fail("", message));
|
|
183
|
+
const account = validateAccount(data["1password"], (message) => fail("[1password]: ", message));
|
|
184
|
+
const targets = validateTargets(data.targets, (where, message) => fail(where, message));
|
|
148
185
|
const keys = [];
|
|
149
186
|
const rawKeys = data.keys ?? {};
|
|
150
187
|
if (!isRecord(rawKeys))
|
|
151
188
|
fail("", `"keys" must be a table`);
|
|
152
189
|
else {
|
|
153
|
-
|
|
154
|
-
const
|
|
190
|
+
Object.entries(rawKeys).forEach(([id, raw], index) => {
|
|
191
|
+
const label = VARIABLE_NAME.test(id) ? `key "${id}"` : `keys[${index}]`;
|
|
192
|
+
const entry = validateKey(id, raw, account, environments, targets, (where, message) => fail(`${label}${where}: `, message));
|
|
155
193
|
if (entry)
|
|
156
194
|
keys.push(entry);
|
|
157
|
-
}
|
|
195
|
+
});
|
|
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
|
+
}
|
|
201
|
+
sharedDestinations(keys, environments, (where, message) => fail(where, message));
|
|
202
|
+
return errors.length ? { ok: false, errors } : { ok: true, map: { file, account: account ?? null, environments, keys } };
|
|
203
|
+
}
|
|
204
|
+
function validateAccount(raw, fail) {
|
|
205
|
+
if (raw === undefined)
|
|
206
|
+
return;
|
|
207
|
+
if (!isRecord(raw)) {
|
|
208
|
+
fail("must be a table");
|
|
209
|
+
return;
|
|
158
210
|
}
|
|
159
|
-
|
|
160
|
-
return
|
|
211
|
+
unknownFields(raw, ["account"], (field) => fail(`unknown field "${field}"`));
|
|
212
|
+
return requiredString(raw, "account", fail);
|
|
161
213
|
}
|
|
162
|
-
function
|
|
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
|
+
}
|
|
250
|
+
function validateEnvironments(raw, fail) {
|
|
251
|
+
if (raw === undefined)
|
|
252
|
+
return DEFAULT_ENVIRONMENTS;
|
|
253
|
+
if (!Array.isArray(raw) || !raw.length || !raw.every((name) => typeof name === "string")) {
|
|
254
|
+
fail(`"environments" must be a list of names, such as ["dev", "staging", "prod"]`);
|
|
255
|
+
return DEFAULT_ENVIRONMENTS;
|
|
256
|
+
}
|
|
257
|
+
const names = [];
|
|
258
|
+
for (const name of raw) {
|
|
259
|
+
if (!ENVIRONMENT_NAME.test(name)) {
|
|
260
|
+
fail(`environment "${name}": a name starts with a lowercase letter and uses only lowercase letters, digits and dashes`);
|
|
261
|
+
} else if (names.includes(name)) {
|
|
262
|
+
fail(`environment "${name}" is listed twice`);
|
|
263
|
+
} else
|
|
264
|
+
names.push(name);
|
|
265
|
+
}
|
|
266
|
+
return names;
|
|
267
|
+
}
|
|
268
|
+
function sharedDestinations(keys, environments, fail) {
|
|
163
269
|
const owners = new Map;
|
|
164
270
|
for (const key of keys) {
|
|
165
|
-
for (const environment of
|
|
271
|
+
for (const environment of environments) {
|
|
166
272
|
key.environments[environment]?.publish.forEach((target, i) => {
|
|
167
|
-
const where = `key "${key.
|
|
168
|
-
const secret = secretKey(target, key.
|
|
273
|
+
const where = `key "${key.name}" ${environment} publish[${i}]`;
|
|
274
|
+
const secret = secretKey(target, key.name);
|
|
169
275
|
const owner = owners.get(secret);
|
|
170
276
|
if (owner === undefined)
|
|
171
277
|
owners.set(secret, where);
|
|
@@ -175,68 +281,47 @@ function sharedDestinations(keys, fail) {
|
|
|
175
281
|
}
|
|
176
282
|
}
|
|
177
283
|
}
|
|
178
|
-
function validateKey(id, raw,
|
|
284
|
+
function validateKey(id, raw, account, environmentNames, targets, fail) {
|
|
179
285
|
let failures = 0;
|
|
180
286
|
const err = (where, message) => {
|
|
181
287
|
failures++;
|
|
182
288
|
fail(where, message);
|
|
183
289
|
};
|
|
184
|
-
if (!
|
|
185
|
-
err("", "
|
|
290
|
+
if (!VARIABLE_NAME.test(id))
|
|
291
|
+
err("", "the table name is the variable your program reads: letters, digits and _, not starting with a digit");
|
|
186
292
|
if (!isRecord(raw)) {
|
|
187
293
|
err("", "must be a table");
|
|
188
294
|
return;
|
|
189
295
|
}
|
|
190
|
-
unknownFields(raw, [
|
|
191
|
-
const env = requiredString(raw, "env", (m) => err("", m));
|
|
192
|
-
if (env !== undefined && !ENV_NAME.test(env))
|
|
193
|
-
err("", `field "env" must be a variable name: letters, digits and _, not starting with a digit`);
|
|
194
|
-
const owner = requiredString(raw, "owner", (m) => err("", m));
|
|
296
|
+
unknownFields(raw, [...KEY_FIELDS, ...environmentNames], (field) => err("", field === "env" ? `field "env" is from keypin 0.4; name the table after the variable, such as [keys.API_TOKEN] (${OLD_FORMAT})` : REMOVED_KEY_FIELDS.includes(field) ? `field "${field}" is no longer used; delete it` : `unknown field "${field}"; environments are ${environmentNames.map((n) => `"${n}"`).join(", ")}`));
|
|
195
297
|
const rotateEvery = optionalString(raw, "rotate_every", (m) => err("", m));
|
|
196
298
|
if (rotateEvery !== undefined && periodDays(rotateEvery) === undefined) {
|
|
197
299
|
err("", `field "rotate_every" must be <n>d, <n>w, <n>m or never`);
|
|
198
300
|
}
|
|
199
|
-
const environments =
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const entry = validateEnv(raw[name], vaults, (m) => err(` ${name}`, m));
|
|
301
|
+
const environments = Object.create(null);
|
|
302
|
+
const declared = environmentNames.filter((name) => Object.hasOwn(raw, name));
|
|
303
|
+
for (const name of declared) {
|
|
304
|
+
const entry = validateEnv(raw[name], account, targets, (m) => err(` ${name}`, m));
|
|
204
305
|
if (entry)
|
|
205
306
|
environments[name] = entry;
|
|
206
307
|
}
|
|
207
308
|
for (const [name, entry] of Object.entries(environments)) {
|
|
208
309
|
const index = entry.publish.findIndex((target) => target.to === "github-actions");
|
|
209
|
-
if (
|
|
210
|
-
err(` ${name}`, `publish[${index}]: github-actions can't take this key, because GitHub reserves secret names that start with GITHUB_
|
|
310
|
+
if (index !== -1 && /^GITHUB_/i.test(id)) {
|
|
311
|
+
err(` ${name}`, `publish[${index}]: github-actions can't take this key, because GitHub reserves secret names that start with GITHUB_`);
|
|
211
312
|
}
|
|
212
313
|
}
|
|
213
|
-
if (!
|
|
214
|
-
err("", `needs at least one of ${
|
|
215
|
-
}
|
|
216
|
-
const consumers = [];
|
|
217
|
-
if (raw.consumers !== undefined) {
|
|
218
|
-
if (!Array.isArray(raw.consumers))
|
|
219
|
-
err("", `field "consumers" must be a list`);
|
|
220
|
-
else {
|
|
221
|
-
raw.consumers.forEach((c, i) => {
|
|
222
|
-
const at = ` consumers[${i}]`;
|
|
223
|
-
if (!isRecord(c))
|
|
224
|
-
return err(at, "must be a table");
|
|
225
|
-
unknownFields(c, ["name", "kind"], (field) => err(at, `unknown field "${field}"`));
|
|
226
|
-
const name = requiredString(c, "name", (m) => err(at, m));
|
|
227
|
-
const kind = requiredString(c, "kind", (m) => err(at, m));
|
|
228
|
-
if (name !== undefined && kind !== undefined)
|
|
229
|
-
consumers.push({ name, kind });
|
|
230
|
-
});
|
|
231
|
-
}
|
|
314
|
+
if (!declared.length) {
|
|
315
|
+
err("", `needs at least one of ${environmentNames.map((n) => `"${n}"`).join(", ")}`);
|
|
232
316
|
}
|
|
233
|
-
if (failures
|
|
317
|
+
if (failures)
|
|
234
318
|
return;
|
|
235
|
-
return { id,
|
|
319
|
+
return { name: id, rotateEvery: rotateEvery ?? null, environments };
|
|
236
320
|
}
|
|
237
|
-
function validateEnv(
|
|
321
|
+
function validateEnv(given, account, targets, fail) {
|
|
322
|
+
const raw = typeof given === "string" ? { from: given } : given;
|
|
238
323
|
if (!isRecord(raw)) {
|
|
239
|
-
fail(
|
|
324
|
+
fail(`must be an op:// reference, or a table with "from"`);
|
|
240
325
|
return;
|
|
241
326
|
}
|
|
242
327
|
let failed = false;
|
|
@@ -244,12 +329,8 @@ function validateEnv(raw, vaults, fail) {
|
|
|
244
329
|
failed = true;
|
|
245
330
|
fail(message);
|
|
246
331
|
};
|
|
247
|
-
unknownFields(raw, ["
|
|
248
|
-
const
|
|
249
|
-
const item = requiredString(raw, "item", err);
|
|
250
|
-
const vault = vaultName === undefined ? undefined : vaults.get(vaultName);
|
|
251
|
-
if (vaultName !== undefined && !vault)
|
|
252
|
-
err(`field "vault" names a vault that isn't under [vaults]`);
|
|
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}"`));
|
|
333
|
+
const ref = reference(raw, "from", account, err);
|
|
253
334
|
const publish = [];
|
|
254
335
|
const firstAt = new Map;
|
|
255
336
|
if (raw.publish !== undefined) {
|
|
@@ -257,7 +338,7 @@ function validateEnv(raw, vaults, fail) {
|
|
|
257
338
|
err(`field "publish" must be a list`);
|
|
258
339
|
else {
|
|
259
340
|
raw.publish.forEach((t, i) => {
|
|
260
|
-
const target =
|
|
341
|
+
const target = resolveTarget(t, targets, (m) => err(`publish[${i}]: ${m}`));
|
|
261
342
|
if (!target)
|
|
262
343
|
return;
|
|
263
344
|
const same = firstAt.get(placeId(target));
|
|
@@ -270,13 +351,28 @@ function validateEnv(raw, vaults, fail) {
|
|
|
270
351
|
});
|
|
271
352
|
}
|
|
272
353
|
}
|
|
273
|
-
const
|
|
274
|
-
if (failed || !
|
|
354
|
+
const rotate = raw.rotate === undefined || !ref ? undefined : validateRotate(raw.rotate, ref, account, (m) => err(`rotate: ${m}`));
|
|
355
|
+
if (failed || !ref)
|
|
356
|
+
return;
|
|
357
|
+
return { ref, publish, ...rotate ? { rotate } : {} };
|
|
358
|
+
}
|
|
359
|
+
function reference(table, field, account, fail) {
|
|
360
|
+
const text = requiredString(table, field, fail);
|
|
361
|
+
if (text === undefined)
|
|
362
|
+
return;
|
|
363
|
+
const parsed = parseReference(text);
|
|
364
|
+
if (typeof parsed === "string") {
|
|
365
|
+
fail(`field "${field}" ${parsed}`);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (account === undefined) {
|
|
369
|
+
fail(`field "${field}" needs your 1Password account: add [1password] with account = "..."`);
|
|
275
370
|
return;
|
|
276
|
-
|
|
371
|
+
}
|
|
372
|
+
return { kind: "1password", account, ...parsed };
|
|
277
373
|
}
|
|
278
374
|
var ACCOUNT_ID = /^[0-9a-f]{32}$/;
|
|
279
|
-
function
|
|
375
|
+
function validateRotate(raw, own, vaultAccount, fail) {
|
|
280
376
|
if (!isRecord(raw)) {
|
|
281
377
|
fail("must be a table");
|
|
282
378
|
return;
|
|
@@ -289,17 +385,17 @@ function validateIssue(raw, vault, item, fail) {
|
|
|
289
385
|
unknownFields(raw, ["provider", "account", "admin"], (field) => err(`unknown field "${field}"`));
|
|
290
386
|
const provider = requiredString(raw, "provider", err);
|
|
291
387
|
const account = requiredString(raw, "account", err);
|
|
292
|
-
const admin =
|
|
388
|
+
const admin = reference(raw, "admin", vaultAccount, err);
|
|
293
389
|
const kind = PROVIDER_KINDS.find((known) => known === provider);
|
|
294
390
|
if (provider !== undefined && !kind)
|
|
295
391
|
err(`field "provider" must be one of: ${PROVIDER_KINDS.join(", ")}`);
|
|
296
392
|
if (account !== undefined && !ACCOUNT_ID.test(account))
|
|
297
393
|
err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
|
|
298
|
-
if (admin
|
|
394
|
+
if (admin && sameItem(admin, own))
|
|
299
395
|
err(`field "admin" names the key's own item; the admin token needs its own item`);
|
|
300
396
|
if (failed || !kind || account === undefined || admin === undefined)
|
|
301
397
|
return;
|
|
302
|
-
return { provider: kind, account, admin
|
|
398
|
+
return { provider: kind, account, admin };
|
|
303
399
|
}
|
|
304
400
|
function validateTarget(raw, fail) {
|
|
305
401
|
if (!isRecord(raw)) {
|
|
@@ -318,6 +414,8 @@ function validateTarget(raw, fail) {
|
|
|
318
414
|
unknownFields(raw, ["to", "account", "worker"], (field) => err(`unknown field "${field}" for ${to}`));
|
|
319
415
|
const account = requiredString(raw, "account", err);
|
|
320
416
|
const worker = requiredString(raw, "worker", err);
|
|
417
|
+
if (account !== undefined && !ACCOUNT_ID.test(account))
|
|
418
|
+
err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
|
|
321
419
|
return failed || account === undefined || worker === undefined ? undefined : { to, account, worker };
|
|
322
420
|
}
|
|
323
421
|
if (to === "github-actions") {
|
|
@@ -443,14 +541,19 @@ function projectPath(project) {
|
|
|
443
541
|
return project.replace(/(.)\/+$/, "$1");
|
|
444
542
|
}
|
|
445
543
|
// ../../packages/core/src/state.ts
|
|
446
|
-
var STATE_VERSION =
|
|
544
|
+
var STATE_VERSION = 3;
|
|
447
545
|
var emptyState = () => ({ version: STATE_VERSION, receipts: [], operations: [] });
|
|
448
546
|
async function loadState(files, path) {
|
|
449
|
-
const data = await readVersionedJson(files, path, [1, STATE_VERSION], "state file");
|
|
547
|
+
const data = await readVersionedJson(files, path, [1, 2, STATE_VERSION], "state file");
|
|
450
548
|
if (!data)
|
|
451
549
|
return emptyState();
|
|
452
|
-
const
|
|
453
|
-
const receipts = Array.isArray(data.receipts) ? data.receipts.map((r) =>
|
|
550
|
+
const mapFile = (r) => data.version === STATE_VERSION ? r.mapFile : null;
|
|
551
|
+
const receipts = Array.isArray(data.receipts) ? data.receipts.map((r) => isRecord(r) ? {
|
|
552
|
+
...r,
|
|
553
|
+
mapFile: mapFile(r),
|
|
554
|
+
source: data.version === 1 ? null : storedSource(r.source)
|
|
555
|
+
} : r) : data.receipts;
|
|
556
|
+
const operations = Array.isArray(data.operations) ? data.operations.map((o) => isRecord(o) ? { ...o, mapFile: mapFile(o) } : o) : data.operations;
|
|
454
557
|
if (!Array.isArray(receipts) || !receipts.every(isReceipt)) {
|
|
455
558
|
throw new Error(`${path}: the state file's "receipts" must be a list of receipts`);
|
|
456
559
|
}
|
|
@@ -462,6 +565,9 @@ async function loadState(files, path) {
|
|
|
462
565
|
async function saveState(files, path, state) {
|
|
463
566
|
await writeJsonAtomic(files, path, state);
|
|
464
567
|
}
|
|
568
|
+
function ownedBy(entry, owner) {
|
|
569
|
+
return entry.mapFile === owner.mapFile && entry.keyId === owner.keyId && entry.environment === owner.environment;
|
|
570
|
+
}
|
|
465
571
|
function startOperation(state, operation) {
|
|
466
572
|
if (state.operations.some((o) => o.id === operation.id))
|
|
467
573
|
throw new Error(`operation ${operation.id} already exists`);
|
|
@@ -475,20 +581,26 @@ function recordReceipt(state, receipt, operationId) {
|
|
|
475
581
|
function finishOperation(state, operationId) {
|
|
476
582
|
return { ...state, operations: state.operations.filter((o) => o.id !== operationId) };
|
|
477
583
|
}
|
|
478
|
-
function unfinishedOperations(state,
|
|
479
|
-
return state.operations.filter((o) => o
|
|
584
|
+
function unfinishedOperations(state, owner) {
|
|
585
|
+
return state.operations.filter((o) => ownedBy(o, owner));
|
|
480
586
|
}
|
|
481
587
|
var isText = (value) => typeof value === "string";
|
|
588
|
+
var isTextOrNull = (value) => value === null || typeof value === "string";
|
|
482
589
|
function isReceipt(r) {
|
|
483
|
-
return isRecord(r) && [r.keyId, r.environment, r.destinationId, r.generation, r.at].every(isText) && isRecord(r.account) && isText(r.account.pinned) && isText(r.account.publisher) && isText(r.account.destinationAccount) && (r.source === null ||
|
|
590
|
+
return isRecord(r) && [r.keyId, r.environment, r.destinationId, r.generation, r.at].every(isText) && isTextOrNull(r.mapFile) && isRecord(r.account) && isText(r.account.pinned) && isText(r.account.publisher) && isText(r.account.destinationAccount) && (r.source === null || storedRefWithPasswordDefault(r.source) !== null) && typeof r.evidence === "object" && r.evidence !== null;
|
|
484
591
|
}
|
|
485
|
-
function
|
|
486
|
-
return
|
|
592
|
+
function storedSource(source) {
|
|
593
|
+
return source === null ? null : storedRefWithPasswordDefault(source) ?? source;
|
|
487
594
|
}
|
|
488
595
|
function isOperation(o) {
|
|
489
|
-
return isRecord(o) && [o.id, o.keyId, o.environment, o.generation, o.startedAt].every(isText) && Array.isArray(o.planned) && o.planned.every(isText) && Array.isArray(o.done) && o.done.every(isText);
|
|
596
|
+
return isRecord(o) && [o.id, o.keyId, o.environment, o.generation, o.startedAt].every(isText) && isTextOrNull(o.mapFile) && Array.isArray(o.planned) && o.planned.every(isText) && Array.isArray(o.done) && o.done.every(isText);
|
|
490
597
|
}
|
|
491
598
|
// ../../packages/core/src/plan.ts
|
|
599
|
+
var ownerOf = ({ key, environment, mapFile }) => ({
|
|
600
|
+
keyId: key.name,
|
|
601
|
+
environment,
|
|
602
|
+
mapFile
|
|
603
|
+
});
|
|
492
604
|
function approvalsFor(input) {
|
|
493
605
|
return judge(input).flatMap(({ id, approval }) => approval ? [{ destinationId: id, ...approval }] : []);
|
|
494
606
|
}
|
|
@@ -515,8 +627,8 @@ function planPublish(input) {
|
|
|
515
627
|
approval: null
|
|
516
628
|
};
|
|
517
629
|
});
|
|
518
|
-
const listed = new Set(steps.flatMap((s) => [secretKey(s.target, key.
|
|
519
|
-
const removed = latestPerSecret(input.receipts).filter((r) => r
|
|
630
|
+
const listed = new Set(steps.flatMap((s) => [secretKey(s.target, key.name), s.destinationId]));
|
|
631
|
+
const removed = latestPerSecret(input.receipts).filter((r) => ownedBy(r, ownerOf(input))).filter((r) => !listed.has(receiptSecretKey(r)) && !listed.has(r.destinationId)).map((r) => ({
|
|
520
632
|
destinationId: r.destinationId,
|
|
521
633
|
lastReceipt: {
|
|
522
634
|
generation: r.generation,
|
|
@@ -525,7 +637,7 @@ function planPublish(input) {
|
|
|
525
637
|
}
|
|
526
638
|
}));
|
|
527
639
|
return {
|
|
528
|
-
keyId: key.
|
|
640
|
+
keyId: key.name,
|
|
529
641
|
environment,
|
|
530
642
|
generation,
|
|
531
643
|
steps,
|
|
@@ -537,14 +649,15 @@ function judge(input) {
|
|
|
537
649
|
const { key, environment } = input;
|
|
538
650
|
const entry = key.environments[environment];
|
|
539
651
|
if (!entry)
|
|
540
|
-
throw new Error(`key "${key.
|
|
652
|
+
throw new Error(`key "${key.name}" has no ${environment} entry in the map`);
|
|
541
653
|
const newest = latestPerSecret(input.receipts);
|
|
542
654
|
const latest = new Map(newest.map((r) => [receiptSecretKey(r), r]));
|
|
543
|
-
const
|
|
544
|
-
const
|
|
655
|
+
const owner = ownerOf(input);
|
|
656
|
+
const ours = newest.filter((r) => ownedBy(r, owner));
|
|
657
|
+
const published = input.receipts.some((r) => ownedBy(r, owner));
|
|
545
658
|
return entry.publish.map((target) => {
|
|
546
|
-
const id = destinationId(target, key.
|
|
547
|
-
const receipt = latest.get(secretKey(target, key.
|
|
659
|
+
const id = destinationId(target, key.name);
|
|
660
|
+
const receipt = latest.get(secretKey(target, key.name)) ?? ours.find((r) => r.destinationId === id);
|
|
548
661
|
const needs = (reason, approval) => ({
|
|
549
662
|
id,
|
|
550
663
|
target,
|
|
@@ -573,21 +686,22 @@ function latestPerSecret(receipts) {
|
|
|
573
686
|
}
|
|
574
687
|
return [...latest.values()];
|
|
575
688
|
}
|
|
576
|
-
function sameRef(a, b) {
|
|
577
|
-
return a.kind === b.kind && a.account === b.account && a.vault === b.vault && a.item === b.item;
|
|
578
|
-
}
|
|
579
689
|
function describeRef(ref) {
|
|
580
|
-
return
|
|
690
|
+
return `${formatReference(ref)} (1Password account ${ref.account})`;
|
|
581
691
|
}
|
|
582
692
|
// ../../packages/core/src/rotations.ts
|
|
583
|
-
var ROTATIONS_VERSION =
|
|
693
|
+
var ROTATIONS_VERSION = 2;
|
|
584
694
|
var ROTATION_STAGES = ["issuing", "issued", "stored", "published", "revoked"];
|
|
585
695
|
var emptyRotations = () => ({ version: ROTATIONS_VERSION, rotations: [] });
|
|
586
696
|
async function loadRotations(files, path) {
|
|
587
|
-
const data = await readVersionedJson(files, path, [ROTATIONS_VERSION], "rotations file");
|
|
697
|
+
const data = await readVersionedJson(files, path, [1, ROTATIONS_VERSION], "rotations file");
|
|
588
698
|
if (!data)
|
|
589
699
|
return emptyRotations();
|
|
590
|
-
const
|
|
700
|
+
const rotations = Array.isArray(data.rotations) ? data.rotations.map((r) => isRecord(r) ? {
|
|
701
|
+
...r,
|
|
702
|
+
mapFile: data.version === ROTATIONS_VERSION ? r.mapFile : null,
|
|
703
|
+
item: storedRefWithPasswordDefault(r.item) ?? r.item
|
|
704
|
+
} : r) : data.rotations;
|
|
591
705
|
if (!Array.isArray(rotations) || !rotations.every(isRotation)) {
|
|
592
706
|
throw new Error(`${path}: the rotations file's "rotations" must be a list of rotations`);
|
|
593
707
|
}
|
|
@@ -596,11 +710,11 @@ async function loadRotations(files, path) {
|
|
|
596
710
|
async function saveRotations(files, path, data) {
|
|
597
711
|
await writeJsonAtomic(files, path, data);
|
|
598
712
|
}
|
|
599
|
-
function unfinishedRotation(data,
|
|
600
|
-
return data.rotations.find((r) => r
|
|
713
|
+
function unfinishedRotation(data, owner, item) {
|
|
714
|
+
return data.rotations.find((r) => ownedBy(r, owner) && sameRef(r.item, item) && r.stage !== "revoked");
|
|
601
715
|
}
|
|
602
|
-
function rotateCommand(keyId, environment) {
|
|
603
|
-
return `keypin rotate ${keyId}${environment
|
|
716
|
+
function rotateCommand(keyId, environment, fallback) {
|
|
717
|
+
return `keypin rotate ${keyId}${envFlag(environment, fallback)}`;
|
|
604
718
|
}
|
|
605
719
|
function putRotation(data, rotation) {
|
|
606
720
|
return {
|
|
@@ -612,15 +726,15 @@ function dropRotation(data, id) {
|
|
|
612
726
|
return { ...data, rotations: data.rotations.filter((r) => r.id !== id) };
|
|
613
727
|
}
|
|
614
728
|
var isText2 = (value) => typeof value === "string";
|
|
615
|
-
var
|
|
729
|
+
var isTextOrNull2 = (value) => value === null || typeof value === "string";
|
|
616
730
|
function isTokenRecord(t) {
|
|
617
|
-
return isRecord(t) && isText2(t.name) && [t.id, t.expiresOn, t.generation].every(
|
|
731
|
+
return isRecord(t) && isText2(t.name) && [t.id, t.expiresOn, t.generation].every(isTextOrNull2);
|
|
618
732
|
}
|
|
619
733
|
function isRotation(r) {
|
|
620
|
-
return isRecord(r) && [r.id, r.keyId, r.environment, r.provider, r.account, r.startedAt, r.updatedAt].every(isText2) && ROTATION_STAGES.some((stage) => stage === r.stage) &&
|
|
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);
|
|
621
735
|
}
|
|
622
736
|
// ../../packages/core/src/status.ts
|
|
623
|
-
var NOTICES = ["due-soon", "
|
|
737
|
+
var NOTICES = ["due-soon", "never-published", "rotation-unfinished"];
|
|
624
738
|
function buildStatus(input) {
|
|
625
739
|
if (!isDay(input.today))
|
|
626
740
|
throw new Error(`today must be YYYY-MM-DD, got "${input.today}"`);
|
|
@@ -649,12 +763,13 @@ function buildStatus(input) {
|
|
|
649
763
|
}
|
|
650
764
|
const latest = new Map(latestPerSecret(input.receipts).map((r) => [receiptSecretKey(r), r]));
|
|
651
765
|
for (const key of result.map.keys) {
|
|
652
|
-
for (const environment of
|
|
766
|
+
for (const environment of result.map.environments) {
|
|
653
767
|
const entry = key.environments[environment];
|
|
654
768
|
if (!entry)
|
|
655
769
|
continue;
|
|
656
|
-
const where = { project, keyId: key.
|
|
657
|
-
const
|
|
770
|
+
const where = { project, keyId: key.name, environment };
|
|
771
|
+
const owner = { keyId: key.name, environment, mapFile: result.map.file };
|
|
772
|
+
const label = `${key.name} (${environment})`;
|
|
658
773
|
const add = (kind, message, extra = {}) => problems.push({
|
|
659
774
|
kind,
|
|
660
775
|
severity: NOTICES.includes(kind) ? "notice" : "problem",
|
|
@@ -663,27 +778,31 @@ function buildStatus(input) {
|
|
|
663
778
|
message
|
|
664
779
|
});
|
|
665
780
|
const metadata = input.metadata(entry.ref);
|
|
666
|
-
const rotateEvery = key.rotateEvery
|
|
781
|
+
const rotateEvery = key.rotateEvery;
|
|
667
782
|
const rotated = metadata?.rotated ?? null;
|
|
668
783
|
const due = rotationDue({ label, metadata, rotated, rotateEvery, today: input.today, add });
|
|
669
|
-
|
|
670
|
-
const
|
|
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))}`;
|
|
671
788
|
const destinations = entry.publish.map((target) => {
|
|
672
|
-
const id = destinationId(target, key.
|
|
673
|
-
const last = latest.get(secretKey(target, key.
|
|
674
|
-
const ours = last && (last
|
|
789
|
+
const id = destinationId(target, key.name);
|
|
790
|
+
const last = latest.get(secretKey(target, key.name));
|
|
791
|
+
const ours = last && (ownedBy(last, owner) || last.source !== null && sameRef(last.source, entry.ref));
|
|
675
792
|
const receipt = ours ? last : undefined;
|
|
676
793
|
if (!receipt) {
|
|
677
|
-
|
|
678
|
-
destinationId: id
|
|
679
|
-
})
|
|
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
|
+
}
|
|
680
801
|
return { destinationId: id, account: target.account, receipt: null, stale: null };
|
|
681
802
|
}
|
|
682
803
|
const stale = current === undefined ? null : receipt.generation !== current;
|
|
683
804
|
if (stale) {
|
|
684
|
-
add("stale-receipt", `${label}: ${id} last got generation ${receipt.generation}, and the value is now ${current}`, {
|
|
685
|
-
destinationId: id
|
|
686
|
-
});
|
|
805
|
+
add("stale-receipt", `${label}: ${id} last got generation ${receipt.generation}, and the value is now ${current}`, { destinationId: id });
|
|
687
806
|
}
|
|
688
807
|
const { generation, at } = receipt;
|
|
689
808
|
return {
|
|
@@ -693,19 +812,19 @@ function buildStatus(input) {
|
|
|
693
812
|
stale
|
|
694
813
|
};
|
|
695
814
|
});
|
|
696
|
-
|
|
815
|
+
if (unpublished.length) {
|
|
816
|
+
add("never-published", `${label}: not published yet to ${unpublished.join(", ")}; run ${publish}`);
|
|
817
|
+
}
|
|
818
|
+
const rotation = unfinishedRotation({ version: ROTATIONS_VERSION, rotations: [...input.rotations ?? []] }, owner, entry.ref);
|
|
697
819
|
if (rotation) {
|
|
698
|
-
add("rotation-unfinished", `${label}: a rotation started ${rotation.startedAt} is at stage "${rotation.stage}"; run ${rotateCommand(key.
|
|
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`);
|
|
699
821
|
}
|
|
700
822
|
rows.push({
|
|
701
823
|
...where,
|
|
702
|
-
env: key.env,
|
|
703
|
-
owner: key.owner,
|
|
704
824
|
ref: entry.ref,
|
|
705
825
|
rotated,
|
|
706
826
|
rotateEvery,
|
|
707
827
|
due,
|
|
708
|
-
authority: "unknown",
|
|
709
828
|
destinations
|
|
710
829
|
});
|
|
711
830
|
}
|
|
@@ -716,7 +835,7 @@ function buildStatus(input) {
|
|
|
716
835
|
function rotationDue(input) {
|
|
717
836
|
const { label, metadata, rotated, rotateEvery, today, add } = input;
|
|
718
837
|
if (!metadata) {
|
|
719
|
-
add("rotation-unreadable", `${label}: the vault's
|
|
838
|
+
add("rotation-unreadable", `${label}: the vault item's rotated date couldn't be read, so whether it's due is unknown`);
|
|
720
839
|
return null;
|
|
721
840
|
}
|
|
722
841
|
if (!rotated || !isDay(rotated)) {
|
|
@@ -725,7 +844,7 @@ function rotationDue(input) {
|
|
|
725
844
|
}
|
|
726
845
|
const days = periodDays(rotateEvery);
|
|
727
846
|
if (days === undefined) {
|
|
728
|
-
add("bad-rotation-period", `${label}: rotate_every is
|
|
847
|
+
add("bad-rotation-period", rotateEvery ? `${label}: rotate_every is "${rotateEvery}"; use <n>d, <n>w, <n>m or never` : `${label}: keypin.toml has no rotate_every for this key; add one, such as "90d", or "never"`);
|
|
729
848
|
return null;
|
|
730
849
|
}
|
|
731
850
|
if (days === null)
|
|
@@ -779,13 +898,26 @@ var WRANGLER_FILES = [
|
|
|
779
898
|
];
|
|
780
899
|
var DOTENV_LINE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
|
|
781
900
|
function envNames(text) {
|
|
782
|
-
|
|
901
|
+
return [...envValues(text).keys()];
|
|
902
|
+
}
|
|
903
|
+
function envValues(text) {
|
|
904
|
+
const values = new Map;
|
|
783
905
|
for (const match of text.replace(/\r\n?/g, `
|
|
784
906
|
`).matchAll(DOTENV_LINE)) {
|
|
785
907
|
if (match[1])
|
|
786
|
-
|
|
908
|
+
values.set(match[1], new Secret(dotenvValue(match[2] ?? "")));
|
|
787
909
|
}
|
|
788
|
-
return
|
|
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()}`;
|
|
789
921
|
}
|
|
790
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;
|
|
791
923
|
function workflowRefs(text) {
|
|
@@ -1036,7 +1168,7 @@ function buildDiscovery(input) {
|
|
|
1036
1168
|
}
|
|
1037
1169
|
}
|
|
1038
1170
|
for (const key of input.map?.keys ?? []) {
|
|
1039
|
-
add(key.
|
|
1171
|
+
add(key.name, { kind: "map", path: input.map?.file ?? "keypin.toml", keyId: key.name });
|
|
1040
1172
|
}
|
|
1041
1173
|
const cloudUnknown = unknowns.some((u) => u.cloud);
|
|
1042
1174
|
const names = [...sources.entries()].map(([name, list]) => {
|
|
@@ -1061,12 +1193,15 @@ function workerLabel(worker) {
|
|
|
1061
1193
|
}
|
|
1062
1194
|
function draftMap(names, options) {
|
|
1063
1195
|
const lines = [];
|
|
1064
|
-
const
|
|
1065
|
-
const
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
vault
|
|
1069
|
-
|
|
1196
|
+
const runName = runEnvironment(options);
|
|
1197
|
+
const publishName = publishEnvironment(options);
|
|
1198
|
+
const vault = options.map?.vault ?? "<your vault>";
|
|
1199
|
+
const from = (environment, name) => str(formatReference({
|
|
1200
|
+
vault,
|
|
1201
|
+
item: draftItemName(options.project, environment, name),
|
|
1202
|
+
section: null,
|
|
1203
|
+
field: "password"
|
|
1204
|
+
}));
|
|
1070
1205
|
for (const row of names) {
|
|
1071
1206
|
if (row.mapped.length)
|
|
1072
1207
|
continue;
|
|
@@ -1096,45 +1231,35 @@ function draftMap(names, options) {
|
|
|
1096
1231
|
});
|
|
1097
1232
|
if (!local && !publish.length)
|
|
1098
1233
|
continue;
|
|
1099
|
-
if (
|
|
1234
|
+
if (!isVariableName(row.name))
|
|
1100
1235
|
continue;
|
|
1101
|
-
const
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
lines.push("", `[keys.${id}.dev]`, `vault = ${str(vault.name)}`, `item = ${str(`${options.owner} dev ${what}`)}`);
|
|
1236
|
+
const name = row.name;
|
|
1237
|
+
lines.push("", `[keys.${name}]`, `rotate_every = "90d"`);
|
|
1238
|
+
if (local && !(publish.length && runName === publishName)) {
|
|
1239
|
+
lines.push(`${runName} = ${from(runName, name)}`);
|
|
1106
1240
|
}
|
|
1107
1241
|
if (publish.length) {
|
|
1108
|
-
lines.push("", `[keys.${
|
|
1109
|
-
for (const target of publish)
|
|
1110
|
-
lines.push("", `[[keys.${
|
|
1242
|
+
lines.push("", `[keys.${name}.${publishName}]`, `from = ${from(publishName, name)}`);
|
|
1243
|
+
for (const target of publish) {
|
|
1244
|
+
lines.push("", `[[keys.${name}.${publishName}.publish]]`, ...target);
|
|
1245
|
+
}
|
|
1111
1246
|
}
|
|
1112
1247
|
}
|
|
1113
1248
|
if (!lines.length)
|
|
1114
1249
|
return null;
|
|
1250
|
+
const account = options.map?.account ?? "<your 1Password account>";
|
|
1115
1251
|
const header = [
|
|
1116
|
-
"# Draft from keypin discover; nothing was written.
|
|
1117
|
-
options.
|
|
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.",
|
|
1254
|
+
...options.environments.join() === DEFAULT_ENVIRONMENTS.join() ? [] : ["", `environments = [${options.environments.map(str).join(", ")}]`],
|
|
1118
1255
|
"",
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
`account = ${str(vault.account)}`,
|
|
1122
|
-
`vault = ${str(vault.vault)}`
|
|
1256
|
+
"[1password]",
|
|
1257
|
+
`account = ${str(account)}`
|
|
1123
1258
|
];
|
|
1124
1259
|
return `${[...header, ...lines].join(`
|
|
1125
1260
|
`)}
|
|
1126
1261
|
`;
|
|
1127
1262
|
}
|
|
1128
|
-
function keyIdFor(name) {
|
|
1129
|
-
return name.toLowerCase().replaceAll("_", "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-") || "key";
|
|
1130
|
-
}
|
|
1131
|
-
function freeId(base, taken) {
|
|
1132
|
-
let id = base;
|
|
1133
|
-
for (let n = 2;taken.has(id); n++)
|
|
1134
|
-
id = `${base}-${n}`;
|
|
1135
|
-
taken.add(id);
|
|
1136
|
-
return id;
|
|
1137
|
-
}
|
|
1138
1263
|
function str(value) {
|
|
1139
1264
|
return JSON.stringify(value);
|
|
1140
1265
|
}
|
|
@@ -1826,7 +1951,6 @@ var desktopConnect = async (account) => {
|
|
|
1826
1951
|
// ../../packages/vault-1password/src/backend.ts
|
|
1827
1952
|
var VALUE_FIELD = "password";
|
|
1828
1953
|
var ROTATED = "rotated";
|
|
1829
|
-
var ROTATE_EVERY = "rotate_every";
|
|
1830
1954
|
var DAY2 = /^\d{4}-\d{2}-\d{2}$/;
|
|
1831
1955
|
var UNIX_SECONDS = /^\d+$/;
|
|
1832
1956
|
function onePasswordBackend(connect = desktopConnect) {
|
|
@@ -1843,7 +1967,7 @@ function onePasswordBackend(connect = desktopConnect) {
|
|
|
1843
1967
|
return pending;
|
|
1844
1968
|
}
|
|
1845
1969
|
async function vaultId(sdk, scope) {
|
|
1846
|
-
const matches = (await sdk.vaults.list()
|
|
1970
|
+
const matches = named(await sdk.vaults.list(), scope.vault);
|
|
1847
1971
|
const [match] = matches;
|
|
1848
1972
|
if (!match) {
|
|
1849
1973
|
throw new Error(`1Password account "${scope.account}" has no vault "${scope.vault}"`);
|
|
@@ -1854,7 +1978,7 @@ function onePasswordBackend(connect = desktopConnect) {
|
|
|
1854
1978
|
return match.id;
|
|
1855
1979
|
}
|
|
1856
1980
|
async function find(sdk, id, ref) {
|
|
1857
|
-
const matches = (await sdk.items.list(id)
|
|
1981
|
+
const matches = named(await sdk.items.list(id), ref.item);
|
|
1858
1982
|
if (matches.length > 1)
|
|
1859
1983
|
throw new Error(`${where(ref)}: ${matches.length} items have this name`);
|
|
1860
1984
|
return matches[0] ?? null;
|
|
@@ -1871,10 +1995,7 @@ function onePasswordBackend(connect = desktopConnect) {
|
|
|
1871
1995
|
capabilities: { read: true, write: true, list: true, metadata: true },
|
|
1872
1996
|
async read(ref) {
|
|
1873
1997
|
const item = await get(ref);
|
|
1874
|
-
|
|
1875
|
-
if (!field)
|
|
1876
|
-
throw new Error(`${where(ref)}: no "${VALUE_FIELD}" field`);
|
|
1877
|
-
return new Secret(field.value);
|
|
1998
|
+
return new Secret(valueField(item, ref).value);
|
|
1878
1999
|
},
|
|
1879
2000
|
async write(ref, secret, options = {}) {
|
|
1880
2001
|
const rotated = options.rotated;
|
|
@@ -1884,7 +2005,13 @@ function onePasswordBackend(connect = desktopConnect) {
|
|
|
1884
2005
|
const sdk = await client(ref.account);
|
|
1885
2006
|
const id = await vaultId(sdk, ref);
|
|
1886
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
|
+
}
|
|
1887
2011
|
if (!found) {
|
|
2012
|
+
if (ref.field !== VALUE_FIELD || ref.section !== null) {
|
|
2013
|
+
throw new Error(`${where(ref)}: no such item; create it in 1Password first`);
|
|
2014
|
+
}
|
|
1888
2015
|
const fields = [passwordField(secret)];
|
|
1889
2016
|
if (rotated)
|
|
1890
2017
|
fields.push(rotatedField(rotated));
|
|
@@ -1898,11 +2025,8 @@ function onePasswordBackend(connect = desktopConnect) {
|
|
|
1898
2025
|
}
|
|
1899
2026
|
const item = await sdk.items.get(id, found.id);
|
|
1900
2027
|
const fields = [...item.fields];
|
|
1901
|
-
const value = valueField(
|
|
1902
|
-
|
|
1903
|
-
fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
|
|
1904
|
-
else
|
|
1905
|
-
fields.push(passwordField(secret));
|
|
2028
|
+
const value = valueField(item, ref);
|
|
2029
|
+
fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
|
|
1906
2030
|
if (rotated) {
|
|
1907
2031
|
const existing = fields.find((field) => field.title === ROTATED);
|
|
1908
2032
|
if (existing)
|
|
@@ -1929,16 +2053,32 @@ function onePasswordBackend(connect = desktopConnect) {
|
|
|
1929
2053
|
async metadata(ref) {
|
|
1930
2054
|
const item = await get(ref);
|
|
1931
2055
|
const rotated = plainField(item.fields, ROTATED, ref);
|
|
1932
|
-
|
|
1933
|
-
return { rotated: rotated === null ? null : toDay(rotated, ref), rotateEvery };
|
|
2056
|
+
return { rotated: rotated === null ? null : toDay(rotated, ref) };
|
|
1934
2057
|
}
|
|
1935
2058
|
};
|
|
1936
2059
|
}
|
|
1937
2060
|
function where(ref) {
|
|
1938
|
-
return
|
|
2061
|
+
return `${formatReference(ref)} (1Password account ${ref.account})`;
|
|
1939
2062
|
}
|
|
1940
|
-
function
|
|
1941
|
-
|
|
2063
|
+
function named(candidates, name) {
|
|
2064
|
+
const wanted = name.toLowerCase();
|
|
2065
|
+
return candidates.filter((candidate) => candidate.id.toLowerCase() === wanted || candidate.title.toLowerCase() === wanted);
|
|
2066
|
+
}
|
|
2067
|
+
function valueField(item, ref) {
|
|
2068
|
+
const sections = ref.section === null ? [] : named(item.sections, ref.section);
|
|
2069
|
+
if (ref.section !== null && !sections.length) {
|
|
2070
|
+
throw new Error(`${where(ref)}: the item has no section "${ref.section}"`);
|
|
2071
|
+
}
|
|
2072
|
+
const [field, ...more] = named(item.fields.filter((field) => ref.section === null || sections.some((section) => section.id === field.sectionId)), ref.field);
|
|
2073
|
+
if (!field)
|
|
2074
|
+
throw new Error(`${where(ref)}: the item has no field "${ref.field}"`);
|
|
2075
|
+
if (more.length) {
|
|
2076
|
+
throw new Error(`${where(ref)}: ${more.length + 1} fields are named "${ref.field}"; name a section`);
|
|
2077
|
+
}
|
|
2078
|
+
if (field.title === ROTATED) {
|
|
2079
|
+
throw new Error(`${where(ref)}: "${ROTATED}" holds the day the value last changed; put the value in another field`);
|
|
2080
|
+
}
|
|
2081
|
+
return field;
|
|
1942
2082
|
}
|
|
1943
2083
|
function passwordField(secret) {
|
|
1944
2084
|
return {
|
|
@@ -1974,9 +2114,8 @@ function messageOf2(error) {
|
|
|
1974
2114
|
return error instanceof Error ? error.message : String(error);
|
|
1975
2115
|
}
|
|
1976
2116
|
// src/commands/discover.ts
|
|
1977
|
-
import { basename, join as
|
|
1978
|
-
import { parseArgs } from "util";
|
|
1979
|
-
var {TOML: TOML3 } = globalThis.Bun;
|
|
2117
|
+
import { basename, join as join5, relative, resolve as resolve2 } from "path";
|
|
2118
|
+
import { parseArgs as parseArgs2 } from "util";
|
|
1980
2119
|
|
|
1981
2120
|
// src/deps.ts
|
|
1982
2121
|
class UsageError extends Error {
|
|
@@ -2005,19 +2144,108 @@ async function findMap(files, cwd) {
|
|
|
2005
2144
|
}
|
|
2006
2145
|
}
|
|
2007
2146
|
}
|
|
2147
|
+
function pickEnvironment(map, requested, fallback) {
|
|
2148
|
+
if (requested === undefined || map.environments.includes(requested))
|
|
2149
|
+
return requested ?? fallback;
|
|
2150
|
+
const names = map.environments.map((name) => `"${name}"`).join(", ");
|
|
2151
|
+
throw new UsageError(`--env is one of ${names} in ${map.file}, got "${requested}"`);
|
|
2152
|
+
}
|
|
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
|
+
}
|
|
2008
2226
|
|
|
2009
2227
|
// src/commands/discover.ts
|
|
2010
2228
|
async function discover(args, deps) {
|
|
2011
|
-
const { values, positionals } =
|
|
2229
|
+
const { values, positionals } = parseArgs2({
|
|
2012
2230
|
args,
|
|
2013
|
-
options: {
|
|
2231
|
+
options: {
|
|
2232
|
+
json: { type: "boolean", default: false },
|
|
2233
|
+
write: { type: "boolean", default: false }
|
|
2234
|
+
},
|
|
2014
2235
|
allowPositionals: true
|
|
2015
2236
|
});
|
|
2016
2237
|
if (positionals.length > 1)
|
|
2017
2238
|
throw new UsageError("keypin discover takes at most one folder");
|
|
2018
|
-
const folder =
|
|
2239
|
+
const folder = resolve2(deps.cwd, positionals[0] ?? ".");
|
|
2019
2240
|
if (!await deps.isFolder(folder))
|
|
2020
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
|
+
}
|
|
2021
2249
|
const unknowns = [];
|
|
2022
2250
|
const scan = await walk(deps, folder);
|
|
2023
2251
|
const tracked = await trackedFiles(deps, folder, scan.envFiles);
|
|
@@ -2026,7 +2254,7 @@ async function discover(args, deps) {
|
|
|
2026
2254
|
const kind = envFileKind(basename(path));
|
|
2027
2255
|
if (!kind)
|
|
2028
2256
|
continue;
|
|
2029
|
-
const text = await deps.files.read(
|
|
2257
|
+
const text = await deps.files.read(join5(folder, path));
|
|
2030
2258
|
if (text === null)
|
|
2031
2259
|
continue;
|
|
2032
2260
|
envFiles.push({ path, kind, names: envNames(text), tracked: tracked?.has(path) ?? null });
|
|
@@ -2042,7 +2270,7 @@ async function discover(args, deps) {
|
|
|
2042
2270
|
const workflows = await readWorkflows(deps, folder, top, unknowns);
|
|
2043
2271
|
const workers = [];
|
|
2044
2272
|
for (const config of scan.wrangler) {
|
|
2045
|
-
const text = await deps.files.read(
|
|
2273
|
+
const text = await deps.files.read(join5(folder, config));
|
|
2046
2274
|
if (text === null)
|
|
2047
2275
|
continue;
|
|
2048
2276
|
const parsed = wranglerWorkers(text, config);
|
|
@@ -2085,7 +2313,6 @@ async function discover(args, deps) {
|
|
|
2085
2313
|
read: read.ok ? read : { ok: false, reason: `as ${login}: ${read.reason}` }
|
|
2086
2314
|
};
|
|
2087
2315
|
}
|
|
2088
|
-
const mapText = await deps.files.read(join3(folder, MAP_FILE));
|
|
2089
2316
|
let map = null;
|
|
2090
2317
|
if (mapText !== null) {
|
|
2091
2318
|
const parsed = parseMap(mapText, MAP_FILE);
|
|
@@ -2099,18 +2326,24 @@ async function discover(args, deps) {
|
|
|
2099
2326
|
});
|
|
2100
2327
|
}
|
|
2101
2328
|
const discovery = buildDiscovery({ envFiles, workflows, workers, github, map, unknowns });
|
|
2102
|
-
const owner = map?.keys[0]?.owner ?? basename(folder);
|
|
2103
2329
|
const draft = draftMap(discovery.names, {
|
|
2104
|
-
|
|
2330
|
+
project: basename(folder),
|
|
2105
2331
|
githubAccount: login,
|
|
2106
|
-
|
|
2107
|
-
|
|
2332
|
+
map: map ? { account: map.account, vault: firstVault(map) } : null,
|
|
2333
|
+
environments: map?.environments ?? DEFAULT_ENVIRONMENTS,
|
|
2334
|
+
written: values.write
|
|
2108
2335
|
});
|
|
2109
2336
|
if (draft !== null) {
|
|
2110
2337
|
const check = parseMap(draft, "draft");
|
|
2111
2338
|
if (!check.ok)
|
|
2112
2339
|
throw new Error(`the draft doesn't parse: ${check.errors.join("; ")}`);
|
|
2113
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;
|
|
2114
2347
|
const report = {
|
|
2115
2348
|
folder,
|
|
2116
2349
|
repository: github?.repo ?? null,
|
|
@@ -2122,12 +2355,26 @@ async function discover(args, deps) {
|
|
|
2122
2355
|
},
|
|
2123
2356
|
nestedRepositories: scan.nested,
|
|
2124
2357
|
...discovery,
|
|
2125
|
-
draft
|
|
2358
|
+
draft,
|
|
2359
|
+
written
|
|
2126
2360
|
};
|
|
2127
2361
|
deps.stdout.write(values.json ? `${JSON.stringify(report, null, 2)}
|
|
2128
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
|
+
}
|
|
2129
2368
|
return 0;
|
|
2130
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
|
+
}
|
|
2131
2378
|
async function walk(deps, root) {
|
|
2132
2379
|
const scan = { envFiles: [], wrangler: [], nested: [] };
|
|
2133
2380
|
const visit = async (folder) => {
|
|
@@ -2137,7 +2384,7 @@ async function walk(deps, root) {
|
|
|
2137
2384
|
return;
|
|
2138
2385
|
}
|
|
2139
2386
|
for (const entry of entries) {
|
|
2140
|
-
const path =
|
|
2387
|
+
const path = join5(folder, entry.name);
|
|
2141
2388
|
if (entry.kind === "folder") {
|
|
2142
2389
|
if (!SKIPPED_FOLDERS.has(entry.name))
|
|
2143
2390
|
await visit(path);
|
|
@@ -2161,7 +2408,7 @@ async function trackedFiles(deps, folder, paths) {
|
|
|
2161
2408
|
return new Set(out.split("\x00").filter(Boolean));
|
|
2162
2409
|
}
|
|
2163
2410
|
async function readWorkflows(deps, folder, top, unknowns) {
|
|
2164
|
-
const dir =
|
|
2411
|
+
const dir = join5(top ?? folder, ".github", "workflows");
|
|
2165
2412
|
let entries;
|
|
2166
2413
|
try {
|
|
2167
2414
|
entries = await deps.listFolder(dir);
|
|
@@ -2179,10 +2426,10 @@ async function readWorkflows(deps, folder, top, unknowns) {
|
|
|
2179
2426
|
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
2180
2427
|
if (entry.kind !== "file" || !/\.ya?ml$/.test(entry.name))
|
|
2181
2428
|
continue;
|
|
2182
|
-
const text = await deps.files.read(
|
|
2429
|
+
const text = await deps.files.read(join5(dir, entry.name));
|
|
2183
2430
|
if (text === null)
|
|
2184
2431
|
continue;
|
|
2185
|
-
const path = relative(folder,
|
|
2432
|
+
const path = relative(folder, join5(dir, entry.name));
|
|
2186
2433
|
const refs = workflowRefs(text);
|
|
2187
2434
|
if (refs)
|
|
2188
2435
|
workflows.push({ path, refs });
|
|
@@ -2205,22 +2452,9 @@ async function githubOrigin(deps, folder) {
|
|
|
2205
2452
|
return { reason: "the origin remote isn't on github.com" };
|
|
2206
2453
|
return { repo: `${match[1]}/${match[2]}`, owner: match[1] };
|
|
2207
2454
|
}
|
|
2208
|
-
function firstVault(
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
data = TOML3.parse(text);
|
|
2212
|
-
} catch {
|
|
2213
|
-
return null;
|
|
2214
|
-
}
|
|
2215
|
-
const vaults = isRecord(data) && isRecord(data.vaults) ? data.vaults : {};
|
|
2216
|
-
for (const [name, raw] of Object.entries(vaults)) {
|
|
2217
|
-
if (!isRecord(raw))
|
|
2218
|
-
continue;
|
|
2219
|
-
const { account, vault } = raw;
|
|
2220
|
-
if (typeof account === "string" && typeof vault === "string")
|
|
2221
|
-
return { name, account, vault };
|
|
2222
|
-
}
|
|
2223
|
-
return null;
|
|
2455
|
+
function firstVault(map) {
|
|
2456
|
+
const [entry] = map.keys.flatMap((key) => Object.values(key.environments).filter((e) => e));
|
|
2457
|
+
return entry?.ref.vault ?? null;
|
|
2224
2458
|
}
|
|
2225
2459
|
var WHERE = {
|
|
2226
2460
|
both: "local and cloud",
|
|
@@ -2314,6 +2548,8 @@ function render(report, discovery) {
|
|
|
2314
2548
|
lines.push("");
|
|
2315
2549
|
if (report.draft === null)
|
|
2316
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);
|
|
2317
2553
|
else
|
|
2318
2554
|
lines.push("Draft keypin.toml for the unmapped names (not written):", "", report.draft);
|
|
2319
2555
|
return `${lines.join(`
|
|
@@ -2324,86 +2560,8 @@ function count(n, noun) {
|
|
|
2324
2560
|
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
2325
2561
|
}
|
|
2326
2562
|
|
|
2327
|
-
// src/commands/
|
|
2328
|
-
import { join as
|
|
2329
|
-
import { parseArgs as parseArgs2 } from "util";
|
|
2330
|
-
|
|
2331
|
-
// src/paths.ts
|
|
2332
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
2333
|
-
function registryPath(deps) {
|
|
2334
|
-
return join4(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
|
|
2335
|
-
}
|
|
2336
|
-
function statePath(deps) {
|
|
2337
|
-
return join4(base(deps.env.XDG_STATE_HOME, deps.home, ".local/state"), "keypin", "state.json");
|
|
2338
|
-
}
|
|
2339
|
-
function base(xdg, home, fallback) {
|
|
2340
|
-
return xdg?.startsWith("/") ? xdg : join4(home, fallback);
|
|
2341
|
-
}
|
|
2342
|
-
function projectCount(registry, path) {
|
|
2343
|
-
const count = registry.projects.length;
|
|
2344
|
-
return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
|
|
2345
|
-
}
|
|
2346
|
-
function rotationsPath(deps) {
|
|
2347
|
-
return join4(dirname2(statePath(deps)), "rotations.json");
|
|
2348
|
-
}
|
|
2349
|
-
|
|
2350
|
-
// src/commands/init.ts
|
|
2351
|
-
var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
|
|
2352
|
-
# Uncomment and edit. Every field is checked; an unknown one is an error.
|
|
2353
|
-
#
|
|
2354
|
-
# A vault the keys below read from. The name ("personal") is yours to choose.
|
|
2355
|
-
# [vaults.personal]
|
|
2356
|
-
# kind = "1password"
|
|
2357
|
-
# account = "my.1password.com"
|
|
2358
|
-
# vault = "Private"
|
|
2359
|
-
#
|
|
2360
|
-
# A key. Its ID ("example-api-key") stays the same when vault items are renamed.
|
|
2361
|
-
# [keys.example-api-key]
|
|
2362
|
-
# env = "EXAMPLE_API_KEY" # the variable your program reads
|
|
2363
|
-
# owner = "my-project"
|
|
2364
|
-
# rotate_every = "180d" # <n>d, <n>w, <n>m or never; leave out to use the vault item's rotate_every
|
|
2365
|
-
#
|
|
2366
|
-
# Where keypin run reads the value from.
|
|
2367
|
-
# [keys.example-api-key.dev]
|
|
2368
|
-
# vault = "personal"
|
|
2369
|
-
# item = "my-project dev example api key"
|
|
2370
|
-
#
|
|
2371
|
-
# Where keypin publish reads it from, and every place it writes it.
|
|
2372
|
-
# [keys.example-api-key.prod]
|
|
2373
|
-
# vault = "personal"
|
|
2374
|
-
# item = "my-project prod example api key"
|
|
2375
|
-
#
|
|
2376
|
-
# [[keys.example-api-key.prod.publish]]
|
|
2377
|
-
# to = "cloudflare-worker"
|
|
2378
|
-
# account = "<cloudflare account ID>"
|
|
2379
|
-
# worker = "my-worker"
|
|
2380
|
-
#
|
|
2381
|
-
# [[keys.example-api-key.prod.publish]]
|
|
2382
|
-
# to = "github-actions"
|
|
2383
|
-
# repo = "owner/repo"
|
|
2384
|
-
`;
|
|
2385
|
-
async function init(args, deps) {
|
|
2386
|
-
const { positionals } = parseArgs2({ args, options: {}, allowPositionals: true });
|
|
2387
|
-
if (positionals.length > 1)
|
|
2388
|
-
throw new UsageError("keypin init takes at most one folder");
|
|
2389
|
-
const folder = resolve2(deps.cwd, positionals[0] ?? ".");
|
|
2390
|
-
if (!await deps.isFolder(folder))
|
|
2391
|
-
throw new Error(`${folder} isn't a folder`);
|
|
2392
|
-
const file = join5(folder, MAP_FILE);
|
|
2393
|
-
const created = await deps.createFile(file, TEMPLATE);
|
|
2394
|
-
if (created === "link")
|
|
2395
|
-
throw new Error(`${file} is a symbolic link; keypin init doesn't follow one`);
|
|
2396
|
-
deps.stderr.write(created === "created" ? `keypin: wrote ${file}
|
|
2397
|
-
` : `keypin: ${file} exists; left it as it is
|
|
2398
|
-
`);
|
|
2399
|
-
const path = registryPath(deps);
|
|
2400
|
-
const registry = await register(deps.files, path, folder);
|
|
2401
|
-
deps.stderr.write(`keypin: ${folder} is registered (${projectCount(registry, path)})
|
|
2402
|
-
`);
|
|
2403
|
-
return 0;
|
|
2404
|
-
}
|
|
2405
|
-
|
|
2406
|
-
// src/commands/publish.ts
|
|
2563
|
+
// src/commands/import.ts
|
|
2564
|
+
import { basename as basename2, join as join6, resolve as resolve3 } from "path";
|
|
2407
2565
|
import { parseArgs as parseArgs3 } from "util";
|
|
2408
2566
|
|
|
2409
2567
|
// src/publishing.ts
|
|
@@ -2432,17 +2590,17 @@ function lockedMessage(file, holder) {
|
|
|
2432
2590
|
}
|
|
2433
2591
|
return `keypin: another publish or rotate (process ${holder.pid}) holds ${file} and is still running. Wait for it to finish.`;
|
|
2434
2592
|
}
|
|
2435
|
-
async function checkAccounts(key, entry, deps, say) {
|
|
2593
|
+
async function checkAccounts(key, entry, deps, say, heading = "Account checks") {
|
|
2436
2594
|
say(`
|
|
2437
|
-
|
|
2595
|
+
${heading}:`);
|
|
2438
2596
|
const checked = new Map;
|
|
2439
2597
|
let failed = false;
|
|
2440
2598
|
for (const target of entry.publish) {
|
|
2441
|
-
const label = describeTarget(target, key.
|
|
2599
|
+
const label = describeTarget(target, key.name);
|
|
2442
2600
|
try {
|
|
2443
2601
|
const destination = deps.destination(target);
|
|
2444
2602
|
const check = await destination.checkAccount();
|
|
2445
|
-
checked.set(destinationId(target, key.
|
|
2603
|
+
checked.set(destinationId(target, key.name), { target, destination, check });
|
|
2446
2604
|
say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
|
|
2447
2605
|
if (!check.ok)
|
|
2448
2606
|
failed = true;
|
|
@@ -2464,24 +2622,26 @@ function writesFor(steps, checked) {
|
|
|
2464
2622
|
});
|
|
2465
2623
|
}
|
|
2466
2624
|
async function writeAll(input) {
|
|
2467
|
-
const { key, environment, entry, secret, generation, writes, path, deps, say } = input;
|
|
2625
|
+
const { key, environment, mapFile, entry, secret, generation, writes, path, deps, say } = input;
|
|
2468
2626
|
const id = crypto.randomUUID();
|
|
2469
2627
|
let state = startOperation(input.state, {
|
|
2470
2628
|
id,
|
|
2471
|
-
keyId: key.
|
|
2629
|
+
keyId: key.name,
|
|
2472
2630
|
environment,
|
|
2631
|
+
mapFile,
|
|
2473
2632
|
generation,
|
|
2474
2633
|
startedAt: deps.now().toISOString(),
|
|
2475
2634
|
planned: writes.map((w) => w.destinationId)
|
|
2476
2635
|
});
|
|
2477
2636
|
await saveState(deps.files, path, state);
|
|
2478
2637
|
for (const { destinationId: written, found } of writes) {
|
|
2479
|
-
const label = describeTarget(found.target, key.
|
|
2638
|
+
const label = describeTarget(found.target, key.name);
|
|
2480
2639
|
try {
|
|
2481
|
-
const evidence = await found.destination.write(key.
|
|
2640
|
+
const evidence = await found.destination.write(key.name, secret);
|
|
2482
2641
|
state = recordReceipt(state, {
|
|
2483
|
-
keyId: key.
|
|
2642
|
+
keyId: key.name,
|
|
2484
2643
|
environment,
|
|
2644
|
+
mapFile,
|
|
2485
2645
|
source: entry.ref,
|
|
2486
2646
|
destinationId: written,
|
|
2487
2647
|
generation,
|
|
@@ -2500,12 +2660,12 @@ async function writeAll(input) {
|
|
|
2500
2660
|
return { ok: false, state };
|
|
2501
2661
|
}
|
|
2502
2662
|
}
|
|
2503
|
-
state = finishAll(state, key.
|
|
2663
|
+
state = finishAll(state, { keyId: key.name, environment, mapFile });
|
|
2504
2664
|
await saveState(deps.files, path, state);
|
|
2505
2665
|
return { ok: true, state };
|
|
2506
2666
|
}
|
|
2507
|
-
function finishAll(state,
|
|
2508
|
-
return unfinishedOperations(state,
|
|
2667
|
+
function finishAll(state, owner) {
|
|
2668
|
+
return unfinishedOperations(state, owner).reduce((s, op) => finishOperation(s, op.id), state);
|
|
2509
2669
|
}
|
|
2510
2670
|
function rerun(deps, command, args) {
|
|
2511
2671
|
const words = [...deps.self, command, ...args].map(shellWord).join(" ");
|
|
@@ -2522,16 +2682,281 @@ function describeTarget(target, secretName) {
|
|
|
2522
2682
|
return `${destinationId(target, secretName)} (account ${target.account})`;
|
|
2523
2683
|
}
|
|
2524
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
|
+
|
|
2525
2951
|
// src/vault.ts
|
|
2526
2952
|
function announce(stderr, what, refs) {
|
|
2527
2953
|
const groups = new Map;
|
|
2528
2954
|
for (const ref of refs) {
|
|
2529
|
-
const where = `1Password account ${ref.account}
|
|
2530
|
-
groups.set(where, (groups.get(where) ?? new Set).add(ref
|
|
2955
|
+
const where = `1Password account ${ref.account}`;
|
|
2956
|
+
groups.set(where, (groups.get(where) ?? new Set).add(formatReference(ref)));
|
|
2531
2957
|
}
|
|
2532
|
-
for (const [where,
|
|
2533
|
-
|
|
2534
|
-
stderr.write(`keypin: reading ${what} from ${where}: ${names}
|
|
2958
|
+
for (const [where, references] of groups) {
|
|
2959
|
+
stderr.write(`keypin: reading ${what} from ${where}: ${[...references].join(", ")}
|
|
2535
2960
|
`);
|
|
2536
2961
|
}
|
|
2537
2962
|
}
|
|
@@ -2542,122 +2967,186 @@ function distinctRefs(refs) {
|
|
|
2542
2967
|
seen.set(refKey(ref), ref);
|
|
2543
2968
|
return [...seen.values()];
|
|
2544
2969
|
}
|
|
2545
|
-
var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item]);
|
|
2970
|
+
var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item, ref.section, ref.field]);
|
|
2546
2971
|
|
|
2547
2972
|
// src/commands/publish.ts
|
|
2548
2973
|
async function publish(args, deps) {
|
|
2549
|
-
const
|
|
2974
|
+
const { keyId, env, yes } = parseRequest2(args);
|
|
2550
2975
|
const map = await findMap(deps.files, deps.cwd);
|
|
2551
|
-
|
|
2976
|
+
const environment = pickEnvironment(map, env, publishEnvironment(map));
|
|
2977
|
+
const request = { keyId, environment, yes, args };
|
|
2978
|
+
return locked(deps, (path) => publishLocked(request, map, path, deps));
|
|
2552
2979
|
}
|
|
2553
|
-
function
|
|
2554
|
-
const { values, positionals } =
|
|
2980
|
+
function parseRequest2(args) {
|
|
2981
|
+
const { values, positionals } = parseArgs4({
|
|
2555
2982
|
args,
|
|
2556
2983
|
options: {
|
|
2557
|
-
env: { type: "string"
|
|
2558
|
-
yes: { type: "boolean", default: false }
|
|
2984
|
+
env: { type: "string" },
|
|
2985
|
+
yes: { type: "boolean", default: false },
|
|
2986
|
+
all: { type: "boolean", default: false }
|
|
2559
2987
|
},
|
|
2560
2988
|
allowPositionals: true
|
|
2561
2989
|
});
|
|
2562
2990
|
const [keyId, ...extra] = positionals;
|
|
2563
|
-
if (
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
|
|
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 };
|
|
2568
2995
|
}
|
|
2569
|
-
|
|
2996
|
+
if (keyId === undefined || extra.length)
|
|
2997
|
+
throw new UsageError("keypin publish takes one key: the variable name, or --all");
|
|
2998
|
+
return { keyId, env: values.env, yes: values.yes };
|
|
2570
2999
|
}
|
|
2571
|
-
|
|
3000
|
+
function jobsFor(request, map, say) {
|
|
2572
3001
|
const { keyId, environment } = request;
|
|
2573
|
-
const
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
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;
|
|
2579
3028
|
const say = (text) => deps.stderr.write(`${text}
|
|
2580
3029
|
`);
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
say(` to: ${describeTarget(target, key.env)}`);
|
|
2585
|
-
if (!entry.publish.length) {
|
|
2586
|
-
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.`);
|
|
2587
3033
|
return 1;
|
|
2588
3034
|
}
|
|
2589
|
-
const
|
|
2590
|
-
|
|
2591
|
-
say(`
|
|
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
|
+
}
|
|
2592
3044
|
}
|
|
2593
|
-
|
|
2594
|
-
|
|
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) {
|
|
2595
3059
|
say("Stopped: an account check failed. Nothing was read and nothing was written.");
|
|
2596
3060
|
return 1;
|
|
2597
3061
|
}
|
|
2598
|
-
const approvals = approvalsFor({ key, environment, receipts: state.receipts });
|
|
3062
|
+
const approvals = jobs.flatMap(({ key, owner }) => approvalsFor({ key, environment, mapFile: owner.mapFile, receipts: state.receipts }));
|
|
2599
3063
|
if (approvals.length && !deps.isTerminal) {
|
|
2600
3064
|
say(`
|
|
2601
3065
|
Needs approval:`);
|
|
2602
3066
|
for (const approval of approvals)
|
|
2603
3067
|
say(` ${approval.approval}`);
|
|
2604
|
-
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.`);
|
|
2605
3069
|
say(rerun(deps, "publish", request.args));
|
|
2606
3070
|
return NEEDS_APPROVAL;
|
|
2607
3071
|
}
|
|
2608
|
-
announce(deps.stderr, "the value to publish",
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
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}:` : `
|
|
2619
3095
|
Plan for generation ${generation}:`);
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
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 });
|
|
2628
3109
|
}
|
|
2629
|
-
|
|
2630
|
-
|
|
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);
|
|
2631
3114
|
}
|
|
2632
|
-
|
|
3115
|
+
const pending = planned.filter((job) => job.writes.length);
|
|
3116
|
+
if (!pending.length) {
|
|
2633
3117
|
say("Nothing to write: every destination already has this generation.");
|
|
2634
|
-
if (unfinishedOperations(state, keyId, environment).length) {
|
|
2635
|
-
await saveState(deps.files, path, finishAll(state, keyId, environment));
|
|
2636
|
-
}
|
|
2637
3118
|
return 0;
|
|
2638
3119
|
}
|
|
2639
|
-
if (!await
|
|
3120
|
+
if (!await confirmed2(deps, needsApproval, request))
|
|
2640
3121
|
return NEEDS_APPROVAL;
|
|
2641
|
-
const
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
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).`);
|
|
2656
3146
|
}
|
|
2657
|
-
say(`Published ${keyId} (${environment}) to ${writes.length} destination(s).`);
|
|
2658
3147
|
return 0;
|
|
2659
3148
|
}
|
|
2660
|
-
async function
|
|
3149
|
+
async function confirmed2(deps, needsApproval, request) {
|
|
2661
3150
|
const say = (text) => deps.stderr.write(`${text}
|
|
2662
3151
|
`);
|
|
2663
3152
|
if (request.yes && !needsApproval)
|
|
@@ -2675,35 +3164,32 @@ async function confirmed(deps, needsApproval, request) {
|
|
|
2675
3164
|
}
|
|
2676
3165
|
|
|
2677
3166
|
// src/commands/rotate.ts
|
|
2678
|
-
import { join as
|
|
2679
|
-
import { parseArgs as
|
|
3167
|
+
import { join as join7 } from "path";
|
|
3168
|
+
import { parseArgs as parseArgs5 } from "util";
|
|
2680
3169
|
var GRACE_DAYS = DUE_SOON_DAYS;
|
|
2681
3170
|
async function rotate(args, deps) {
|
|
2682
|
-
const { values, positionals } =
|
|
3171
|
+
const { values, positionals } = parseArgs5({
|
|
2683
3172
|
args,
|
|
2684
3173
|
options: {
|
|
2685
|
-
env: { type: "string"
|
|
3174
|
+
env: { type: "string" },
|
|
2686
3175
|
yes: { type: "boolean", default: false }
|
|
2687
3176
|
},
|
|
2688
3177
|
allowPositionals: true
|
|
2689
3178
|
});
|
|
2690
3179
|
const [keyId, ...extra] = positionals;
|
|
2691
3180
|
if (keyId === undefined || extra.length)
|
|
2692
|
-
throw new UsageError("keypin rotate takes one key
|
|
2693
|
-
const environment = ENVIRONMENTS.find((name) => name === values.env);
|
|
2694
|
-
if (!environment) {
|
|
2695
|
-
throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
|
|
2696
|
-
}
|
|
3181
|
+
throw new UsageError("keypin rotate takes one key: the variable name");
|
|
2697
3182
|
const map = await findMap(deps.files, deps.cwd);
|
|
2698
|
-
const
|
|
3183
|
+
const environment = pickEnvironment(map, values.env, publishEnvironment(map));
|
|
3184
|
+
const key = map.keys.find((k) => k.name === keyId);
|
|
2699
3185
|
if (!key)
|
|
2700
3186
|
throw new Error(`${map.file} has no key "${keyId}"`);
|
|
2701
3187
|
const entry = key.environments[environment];
|
|
2702
3188
|
if (!entry)
|
|
2703
3189
|
throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
|
|
2704
|
-
const
|
|
2705
|
-
if (!
|
|
2706
|
-
throw new Error(`key "${keyId}" has no [keys.${keyId}.${environment}.
|
|
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`);
|
|
2707
3193
|
}
|
|
2708
3194
|
const say = (text) => deps.stderr.write(`${text}
|
|
2709
3195
|
`);
|
|
@@ -2712,7 +3198,7 @@ async function rotate(args, deps) {
|
|
|
2712
3198
|
map,
|
|
2713
3199
|
key,
|
|
2714
3200
|
entry,
|
|
2715
|
-
|
|
3201
|
+
spec,
|
|
2716
3202
|
environment,
|
|
2717
3203
|
yes: values.yes,
|
|
2718
3204
|
args,
|
|
@@ -2722,12 +3208,12 @@ async function rotate(args, deps) {
|
|
|
2722
3208
|
say
|
|
2723
3209
|
};
|
|
2724
3210
|
const data = await loadRotations(deps.files, run.rotationsPath);
|
|
2725
|
-
const open = unfinishedRotation(data,
|
|
3211
|
+
const open = unfinishedRotation(data, keyOwner(run), entry.ref);
|
|
2726
3212
|
if (!open)
|
|
2727
3213
|
return start(run, data);
|
|
2728
|
-
say(`An unfinished rotation of ${key.
|
|
2729
|
-
if (open.provider !==
|
|
2730
|
-
say(`Stopped: that rotation made its token as ${open.provider} in account ${open.account}, and the map now says ${
|
|
3214
|
+
say(`An unfinished rotation of ${key.name} (${environment}), started ${open.startedAt}, is at stage "${open.stage}".`);
|
|
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.`);
|
|
2731
3217
|
return 1;
|
|
2732
3218
|
}
|
|
2733
3219
|
switch (open.stage) {
|
|
@@ -2744,14 +3230,20 @@ async function rotate(args, deps) {
|
|
|
2744
3230
|
});
|
|
2745
3231
|
}
|
|
2746
3232
|
async function start(run, data) {
|
|
2747
|
-
const { key, entry,
|
|
2748
|
-
say(`Rotating ${key.
|
|
2749
|
-
say(`
|
|
2750
|
-
say(` new token: ${
|
|
3233
|
+
const { key, entry, spec, environment, deps, say } = run;
|
|
3234
|
+
say(`Rotating ${key.name} (${environment}) from ${formatReference(entry.ref)}`);
|
|
3235
|
+
say(` 1Password account: ${entry.ref.account}`);
|
|
3236
|
+
say(` new token: ${spec.provider} in account ${spec.account}, made with the admin token in ${formatReference(spec.admin)}`);
|
|
2751
3237
|
for (const target of entry.publish)
|
|
2752
|
-
say(` to: ${describeTarget(target, key.
|
|
3238
|
+
say(` to: ${describeTarget(target, key.name)}`);
|
|
2753
3239
|
if (!entry.publish.length) {
|
|
2754
|
-
say(`Stopped: the map lists no destinations for ${key.
|
|
3240
|
+
say(`Stopped: the map lists no destinations for ${key.name} (${environment}), so nothing would get the new token. Nothing was changed.`);
|
|
3241
|
+
return 1;
|
|
3242
|
+
}
|
|
3243
|
+
const every = key.rotateEvery;
|
|
3244
|
+
const days = periodDays(every);
|
|
3245
|
+
if (!days) {
|
|
3246
|
+
say(`Stopped: rotate needs a rotation period to set the new token's expiry, and ${every ? `rotate_every is "${every}"` : "keypin.toml has no rotate_every for this key"}. Nothing was changed.`);
|
|
2755
3247
|
return 1;
|
|
2756
3248
|
}
|
|
2757
3249
|
const state = await loadState(deps.files, run.statePath);
|
|
@@ -2760,7 +3252,7 @@ async function start(run, data) {
|
|
|
2760
3252
|
say("Stopped: an account check failed. Nothing was read and nothing was changed.");
|
|
2761
3253
|
return 1;
|
|
2762
3254
|
}
|
|
2763
|
-
const approvals = approvalsFor({
|
|
3255
|
+
const approvals = approvalsFor({ ...planFor(run), receipts: state.receipts });
|
|
2764
3256
|
if (!deps.isTerminal && (approvals.length || !run.yes)) {
|
|
2765
3257
|
for (const approval of approvals)
|
|
2766
3258
|
say(` needs approval: ${approval.approval}`);
|
|
@@ -2768,28 +3260,22 @@ async function start(run, data) {
|
|
|
2768
3260
|
say(rerun(deps, "rotate", run.args));
|
|
2769
3261
|
return NEEDS_APPROVAL;
|
|
2770
3262
|
}
|
|
2771
|
-
announce(deps.stderr, "the current value
|
|
2772
|
-
entry.ref,
|
|
2773
|
-
issue.admin
|
|
2774
|
-
]);
|
|
3263
|
+
announce(deps.stderr, "the current value and the admin token", [entry.ref, spec.admin]);
|
|
2775
3264
|
const vault = deps.vault();
|
|
2776
3265
|
let current;
|
|
2777
3266
|
let admin;
|
|
2778
|
-
let every;
|
|
2779
3267
|
try {
|
|
2780
3268
|
current = await vault.read(entry.ref);
|
|
2781
|
-
|
|
2782
|
-
admin = await vault.read(issue.admin);
|
|
3269
|
+
admin = await vault.read(spec.admin);
|
|
2783
3270
|
} catch (error) {
|
|
2784
3271
|
say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
|
|
2785
3272
|
return 1;
|
|
2786
3273
|
}
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
say(`Stopped: rotate needs a rotation period to set the new token's expiry, and rotate_every is ${every ? `"${every}"` : "missing"}. Nothing was changed.`);
|
|
3274
|
+
if (current.reveal() === admin.reveal()) {
|
|
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.`);
|
|
2790
3276
|
return 1;
|
|
2791
3277
|
}
|
|
2792
|
-
const provider = deps.provider(
|
|
3278
|
+
const provider = deps.provider(spec, admin);
|
|
2793
3279
|
const found = await provider.verify(current);
|
|
2794
3280
|
if (found.status !== "active") {
|
|
2795
3281
|
say(`Stopped: the current value is token ${found.id}, and it's ${found.status}. Nothing was changed.`);
|
|
@@ -2809,26 +3295,27 @@ Plan:`);
|
|
|
2809
3295
|
say(` new token: "${name}", expires ${expiresOn} (rotate_every ${every} plus ${GRACE_DAYS} days' grace)`);
|
|
2810
3296
|
for (const line of describeAccess(old))
|
|
2811
3297
|
say(` ${line}`);
|
|
2812
|
-
say(` store in:
|
|
3298
|
+
say(` store in: ${formatReference(entry.ref)}, with rotated ${today}`);
|
|
2813
3299
|
for (const target of entry.publish) {
|
|
2814
|
-
const found = checked.get(destinationId(target, key.
|
|
2815
|
-
say(` publish to: ${describeTarget(target, key.
|
|
3300
|
+
const found = checked.get(destinationId(target, key.name));
|
|
3301
|
+
say(` publish to: ${describeTarget(target, key.name)}`);
|
|
2816
3302
|
if (found)
|
|
2817
3303
|
say(` ${accountFacts(found.check)}`);
|
|
2818
3304
|
}
|
|
2819
3305
|
for (const approval of approvals)
|
|
2820
3306
|
say(` needs approval: ${approval.approval}`);
|
|
2821
3307
|
say(` then stop: the old token stays active until you run ${again(run)} again.`);
|
|
2822
|
-
if (!await
|
|
3308
|
+
if (!await confirmed3(run, approvals.length > 0, "make the new token"))
|
|
2823
3309
|
return NEEDS_APPROVAL;
|
|
2824
3310
|
const now = deps.now().toISOString();
|
|
2825
3311
|
let rotation = {
|
|
2826
3312
|
id: crypto.randomUUID(),
|
|
2827
|
-
keyId: key.
|
|
3313
|
+
keyId: key.name,
|
|
2828
3314
|
environment,
|
|
3315
|
+
mapFile: run.map.file,
|
|
2829
3316
|
item: entry.ref,
|
|
2830
|
-
provider:
|
|
2831
|
-
account:
|
|
3317
|
+
provider: spec.provider,
|
|
3318
|
+
account: spec.account,
|
|
2832
3319
|
stage: "issuing",
|
|
2833
3320
|
startedAt: now,
|
|
2834
3321
|
updatedAt: now,
|
|
@@ -2840,7 +3327,7 @@ Plan:`);
|
|
|
2840
3327
|
},
|
|
2841
3328
|
new: { id: null, name, expiresOn, generation: null }
|
|
2842
3329
|
};
|
|
2843
|
-
data = putRotation(withoutFinished(data,
|
|
3330
|
+
data = putRotation(withoutFinished(data, keyOwner(run)), rotation);
|
|
2844
3331
|
await saveRotations(deps.files, run.rotationsPath, data);
|
|
2845
3332
|
const made = await provider.issue({ name, like: old, expiresOn });
|
|
2846
3333
|
if ("refused" in made) {
|
|
@@ -2865,7 +3352,7 @@ Plan:`);
|
|
|
2865
3352
|
return deleteUnchecked(run, data, rotation, provider);
|
|
2866
3353
|
}
|
|
2867
3354
|
say(` checked: ${made.token.id} is active and has the same policies as ${old.id}`);
|
|
2868
|
-
say(`keypin: writing the new value to
|
|
3355
|
+
say(`keypin: writing the new value to ${formatReference(entry.ref)}, with rotated ${today}`);
|
|
2869
3356
|
try {
|
|
2870
3357
|
await vault.write(entry.ref, made.value, { rotated: today });
|
|
2871
3358
|
const stored = await generationOf(await vault.read(entry.ref));
|
|
@@ -2898,19 +3385,19 @@ async function publishNew(run, data, rotation, fresh) {
|
|
|
2898
3385
|
return 1;
|
|
2899
3386
|
}
|
|
2900
3387
|
checked = found;
|
|
2901
|
-
if (!deps.isTerminal && approvalsFor({
|
|
3388
|
+
if (!deps.isTerminal && approvalsFor({ ...planFor(run), receipts: state.receipts }).length) {
|
|
2902
3389
|
say("Stopped before reading the value: publishing needs approval, and --yes can't give it.");
|
|
2903
3390
|
say(rerun(deps, "rotate", run.args));
|
|
2904
3391
|
return NEEDS_APPROVAL;
|
|
2905
3392
|
}
|
|
2906
3393
|
announce(deps.stderr, "the value to publish and the admin token, to check the new token", [
|
|
2907
3394
|
entry.ref,
|
|
2908
|
-
run.
|
|
3395
|
+
run.spec.admin
|
|
2909
3396
|
]);
|
|
2910
3397
|
value = await deps.vault().read(entry.ref);
|
|
2911
3398
|
const generation = await generationOf(value);
|
|
2912
3399
|
if (generation !== rotation.new.generation) {
|
|
2913
|
-
say(`Stopped:
|
|
3400
|
+
say(`Stopped: ${formatReference(entry.ref)} holds generation ${generation}, not the rotation's ${rotation.new.generation}. Something else changed it. Nothing was written.`);
|
|
2914
3401
|
return 1;
|
|
2915
3402
|
}
|
|
2916
3403
|
const problem = await recheck(run, rotation, value);
|
|
@@ -2921,21 +3408,22 @@ async function publishNew(run, data, rotation, fresh) {
|
|
|
2921
3408
|
say(` checked: ${rotation.new.id} is active and has the same policies as ${rotation.old.id}`);
|
|
2922
3409
|
}
|
|
2923
3410
|
const generation = rotation.new.generation ?? await generationOf(value);
|
|
2924
|
-
const plan = planPublish({
|
|
3411
|
+
const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
|
|
2925
3412
|
say(`
|
|
2926
3413
|
Publishing generation ${generation}:`);
|
|
2927
3414
|
for (const step of plan.steps) {
|
|
2928
|
-
say(` ${step.action} ${describeTarget(step.target, key.
|
|
3415
|
+
say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
|
|
2929
3416
|
if (step.approval)
|
|
2930
3417
|
say(` needs approval: ${step.approval}`);
|
|
2931
3418
|
}
|
|
2932
3419
|
const writes = writesFor(plan.steps, checked);
|
|
2933
|
-
if (resuming && writes.length && !await
|
|
3420
|
+
if (resuming && writes.length && !await confirmed3(run, plan.needsApproval, "publish")) {
|
|
2934
3421
|
return NEEDS_APPROVAL;
|
|
2935
3422
|
}
|
|
2936
3423
|
const written = await writeAll({
|
|
2937
3424
|
key,
|
|
2938
3425
|
environment,
|
|
3426
|
+
mapFile: run.map.file,
|
|
2939
3427
|
entry,
|
|
2940
3428
|
secret: value,
|
|
2941
3429
|
generation,
|
|
@@ -2959,30 +3447,28 @@ Publishing generation ${generation}:`);
|
|
|
2959
3447
|
Published. The old token ${rotation.old.id} "${rotation.old.name}" is still active.`);
|
|
2960
3448
|
say("Next, check that every consumer works with the new value:");
|
|
2961
3449
|
for (const target of entry.publish)
|
|
2962
|
-
say(` ${describeTarget(target, key.
|
|
2963
|
-
for (const consumer of key.consumers)
|
|
2964
|
-
say(` ${consumer.name} (${consumer.kind})`);
|
|
3450
|
+
say(` ${describeTarget(target, key.name)}`);
|
|
2965
3451
|
say(`Then run ${again(run)} again to revoke the old token.`);
|
|
2966
3452
|
return 0;
|
|
2967
3453
|
}
|
|
2968
3454
|
async function revokeOld(run, data, rotation) {
|
|
2969
|
-
const { key,
|
|
3455
|
+
const { key, spec, environment, deps, say } = run;
|
|
2970
3456
|
const generation = rotation.new.generation;
|
|
2971
3457
|
if (!generation || !rotation.new.id || !rotation.old.id) {
|
|
2972
3458
|
throw new Error(`rotation ${rotation.id} has no new generation or token IDs`);
|
|
2973
3459
|
}
|
|
2974
3460
|
const state = await loadState(deps.files, run.statePath);
|
|
2975
|
-
const plan = planPublish({
|
|
3461
|
+
const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
|
|
2976
3462
|
const behind = plan.steps.filter((step) => step.action === "write");
|
|
2977
3463
|
for (const step of behind) {
|
|
2978
3464
|
say(` ${step.destinationId} doesn't have generation ${generation}: ${step.reason}`);
|
|
2979
3465
|
}
|
|
2980
3466
|
const retired = plan.removed.filter((removed) => removed.lastReceipt.generation === rotation.old.generation);
|
|
2981
3467
|
if (behind.length) {
|
|
2982
|
-
say(`Stopped: run keypin publish ${key.
|
|
3468
|
+
say(`Stopped: run keypin publish ${key.name}${envFlag(environment, publishEnvironment(run.map))} first. Nothing was revoked.`);
|
|
2983
3469
|
return 1;
|
|
2984
3470
|
}
|
|
2985
|
-
say(`Every destination of ${key.
|
|
3471
|
+
say(`Every destination of ${key.name} (${environment}) has generation ${generation}.`);
|
|
2986
3472
|
for (const removed of retired) {
|
|
2987
3473
|
say(` ${removed.destinationId} left the map and its receipt has the old token (generation ${removed.lastReceipt.generation}); revoking breaks it unless that secret is gone`);
|
|
2988
3474
|
}
|
|
@@ -3003,14 +3489,14 @@ async function revokeOld(run, data, rotation) {
|
|
|
3003
3489
|
}
|
|
3004
3490
|
announce(deps.stderr, "the current value, to check it's the new token, and the admin token", [
|
|
3005
3491
|
run.entry.ref,
|
|
3006
|
-
|
|
3492
|
+
spec.admin
|
|
3007
3493
|
]);
|
|
3008
3494
|
const holds = await generationOf(await deps.vault().read(run.entry.ref));
|
|
3009
3495
|
if (holds !== generation) {
|
|
3010
|
-
say(`Stopped:
|
|
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.`);
|
|
3011
3497
|
return 1;
|
|
3012
3498
|
}
|
|
3013
|
-
const provider = deps.provider(
|
|
3499
|
+
const provider = deps.provider(spec, await deps.vault().read(spec.admin));
|
|
3014
3500
|
const current = await provider.details(rotation.new.id);
|
|
3015
3501
|
if (current?.status !== "active") {
|
|
3016
3502
|
say(`Stopped: the new token ${rotation.new.id} is ${current ? current.status : "gone"}. Nothing was revoked.`);
|
|
@@ -3036,11 +3522,11 @@ Old token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "n
|
|
|
3036
3522
|
async function finish(run, data, rotation) {
|
|
3037
3523
|
const done = { ...rotation, stage: "revoked", updatedAt: run.deps.now().toISOString() };
|
|
3038
3524
|
await saveRotations(run.deps.files, run.rotationsPath, putRotation(data, done));
|
|
3039
|
-
run.say(`Rotated ${run.key.
|
|
3525
|
+
run.say(`Rotated ${run.key.name} (${run.environment}): ${rotation.new.id} replaced ${rotation.old.id}.`);
|
|
3040
3526
|
return 0;
|
|
3041
3527
|
}
|
|
3042
3528
|
async function abandon(run, data, rotation) {
|
|
3043
|
-
const { entry,
|
|
3529
|
+
const { entry, spec, deps, say } = run;
|
|
3044
3530
|
if (rotation.new.generation) {
|
|
3045
3531
|
announce(deps.stderr, "the current value, to see which token it holds", [entry.ref]);
|
|
3046
3532
|
const holds = await generationOf(await deps.vault().read(entry.ref));
|
|
@@ -3052,11 +3538,11 @@ async function abandon(run, data, rotation) {
|
|
|
3052
3538
|
};
|
|
3053
3539
|
const next = putRotation(data, stored);
|
|
3054
3540
|
await saveRotations(deps.files, run.rotationsPath, next);
|
|
3055
|
-
say(
|
|
3541
|
+
say(`${formatReference(entry.ref)} already holds the new value (generation ${holds}).`);
|
|
3056
3542
|
return publishNew(run, next, stored, null);
|
|
3057
3543
|
}
|
|
3058
3544
|
if (holds !== rotation.old.generation) {
|
|
3059
|
-
say(`Stopped:
|
|
3545
|
+
say(`Stopped: ${formatReference(entry.ref)} holds generation ${holds}, neither the old ${rotation.old.generation} nor the new ${rotation.new.generation}. Something else changed it. Nothing was changed.`);
|
|
3060
3546
|
return 1;
|
|
3061
3547
|
}
|
|
3062
3548
|
}
|
|
@@ -3064,12 +3550,12 @@ async function abandon(run, data, rotation) {
|
|
|
3064
3550
|
const state = await loadState(deps.files, run.statePath);
|
|
3065
3551
|
const holders = holdersOf(state.receipts, rotation.new.generation);
|
|
3066
3552
|
if (holders.length) {
|
|
3067
|
-
say(`Stopped: the new token ${rotation.new.id} was published, so keypin won't delete it. Nothing was changed. Either put the new value back in
|
|
3553
|
+
say(`Stopped: the new token ${rotation.new.id} was published, so keypin won't delete it. Nothing was changed. Either put the new value back in ${formatReference(entry.ref)} and run ${again(run)} again to finish, or publish the old value to each destination that has the new one:`);
|
|
3068
3554
|
const owners = await listedOwners(run);
|
|
3069
3555
|
if (owners === null)
|
|
3070
3556
|
return 1;
|
|
3071
3557
|
for (const r of holders) {
|
|
3072
|
-
const owner =
|
|
3558
|
+
const owner = ownerOf2(r, owners);
|
|
3073
3559
|
say(` ${describeHolder(r)}: ${owner ? publishCommand(owner) : "no registered map lists it; set that secret to the old value by hand"}`);
|
|
3074
3560
|
}
|
|
3075
3561
|
return 1;
|
|
@@ -3089,8 +3575,8 @@ async function abandon(run, data, rotation) {
|
|
|
3089
3575
|
return NEEDS_APPROVAL;
|
|
3090
3576
|
}
|
|
3091
3577
|
} else {
|
|
3092
|
-
announce(deps.stderr, "the admin token", [
|
|
3093
|
-
const provider = deps.provider(
|
|
3578
|
+
announce(deps.stderr, "the admin token", [spec.admin]);
|
|
3579
|
+
const provider = deps.provider(spec, await deps.vault().read(spec.admin));
|
|
3094
3580
|
const made = await provider.details(id);
|
|
3095
3581
|
if (made) {
|
|
3096
3582
|
say(`New token: ${made.id} "${made.name}", ${made.status}, its value was never stored`);
|
|
@@ -3125,7 +3611,7 @@ async function deleteUnchecked(run, data, rotation, provider) {
|
|
|
3125
3611
|
async function recheck(run, rotation, value) {
|
|
3126
3612
|
if (!rotation.new.id || !rotation.old.id)
|
|
3127
3613
|
return "the rotation has no token IDs";
|
|
3128
|
-
const provider = run.deps.provider(run.
|
|
3614
|
+
const provider = run.deps.provider(run.spec, await run.deps.vault().read(run.spec.admin));
|
|
3129
3615
|
const old = await provider.details(rotation.old.id);
|
|
3130
3616
|
if (!old)
|
|
3131
3617
|
return `the old token ${rotation.old.id} is gone, so its policies can't be compared`;
|
|
@@ -3138,7 +3624,7 @@ function describeHolder(receipt) {
|
|
|
3138
3624
|
return `${receipt.destinationId} (${receipt.keyId}, ${receipt.environment})`;
|
|
3139
3625
|
}
|
|
3140
3626
|
function publishCommand(owner) {
|
|
3141
|
-
const env = owner.environment
|
|
3627
|
+
const env = envFlag(owner.environment, owner.publishDefault);
|
|
3142
3628
|
const where = owner.project === null ? "" : `cd ${shellWord(owner.project)} && `;
|
|
3143
3629
|
return `${where}keypin publish ${owner.keyId}${env}`;
|
|
3144
3630
|
}
|
|
@@ -3148,11 +3634,17 @@ async function listedOwners(run) {
|
|
|
3148
3634
|
const list = (map, project) => {
|
|
3149
3635
|
for (const k of map.keys) {
|
|
3150
3636
|
for (const [name, entry] of Object.entries(k.environments)) {
|
|
3151
|
-
for (const target of entry
|
|
3152
|
-
const secret = secretKey(target, k.
|
|
3637
|
+
for (const target of entry?.publish ?? []) {
|
|
3638
|
+
const secret = secretKey(target, k.name);
|
|
3153
3639
|
owners.set(secret, [
|
|
3154
3640
|
...owners.get(secret) ?? [],
|
|
3155
|
-
{
|
|
3641
|
+
{
|
|
3642
|
+
project,
|
|
3643
|
+
keyId: k.name,
|
|
3644
|
+
environment: name,
|
|
3645
|
+
mapFile: map.file,
|
|
3646
|
+
publishDefault: publishEnvironment(map)
|
|
3647
|
+
}
|
|
3156
3648
|
]);
|
|
3157
3649
|
}
|
|
3158
3650
|
}
|
|
@@ -3161,7 +3653,7 @@ async function listedOwners(run) {
|
|
|
3161
3653
|
list(run.map, null);
|
|
3162
3654
|
const registry = await loadRegistry(deps.files, registryPath(deps));
|
|
3163
3655
|
for (const project of registry.projects) {
|
|
3164
|
-
const file =
|
|
3656
|
+
const file = join7(project, MAP_FILE);
|
|
3165
3657
|
if (file === run.map.file)
|
|
3166
3658
|
continue;
|
|
3167
3659
|
const text = await deps.files.read(file);
|
|
@@ -3174,9 +3666,9 @@ async function listedOwners(run) {
|
|
|
3174
3666
|
}
|
|
3175
3667
|
return owners;
|
|
3176
3668
|
}
|
|
3177
|
-
function
|
|
3669
|
+
function ownerOf2(receipt, owners) {
|
|
3178
3670
|
const found = owners.get(receiptSecretKey(receipt)) ?? [];
|
|
3179
|
-
return found.find((o) => o.keyId === receipt.keyId && o.environment === receipt.environment) ?? found[0];
|
|
3671
|
+
return found.find((o) => ownedBy(receipt, o)) ?? found.find((o) => o.keyId === receipt.keyId && o.environment === receipt.environment) ?? found[0];
|
|
3180
3672
|
}
|
|
3181
3673
|
var UNLISTED = "no registered map lists it any more; revoking breaks it unless that secret is gone";
|
|
3182
3674
|
async function otherHolders(run, receipts, generation, retired) {
|
|
@@ -3185,7 +3677,7 @@ async function otherHolders(run, receipts, generation, retired) {
|
|
|
3185
3677
|
return null;
|
|
3186
3678
|
const shown = new Set(retired.map((r) => r.destinationId));
|
|
3187
3679
|
return holdersOf(receipts, generation).flatMap((receipt) => {
|
|
3188
|
-
const owner =
|
|
3680
|
+
const owner = ownerOf2(receipt, owners);
|
|
3189
3681
|
if (owner)
|
|
3190
3682
|
return [{ receipt, owner }];
|
|
3191
3683
|
if (!shown.has(receipt.destinationId)) {
|
|
@@ -3195,7 +3687,7 @@ async function otherHolders(run, receipts, generation, retired) {
|
|
|
3195
3687
|
});
|
|
3196
3688
|
}
|
|
3197
3689
|
function again(run) {
|
|
3198
|
-
return rotateCommand(run.key.
|
|
3690
|
+
return rotateCommand(run.key.name, run.environment, publishEnvironment(run.map));
|
|
3199
3691
|
}
|
|
3200
3692
|
async function checkNew(provider, id, value, old) {
|
|
3201
3693
|
try {
|
|
@@ -3214,7 +3706,7 @@ async function checkNew(provider, id, value, old) {
|
|
|
3214
3706
|
return messageOf(error);
|
|
3215
3707
|
}
|
|
3216
3708
|
}
|
|
3217
|
-
async function
|
|
3709
|
+
async function confirmed3(run, needsApproval, what) {
|
|
3218
3710
|
const { deps, say } = run;
|
|
3219
3711
|
if (run.yes && !needsApproval)
|
|
3220
3712
|
return true;
|
|
@@ -3229,12 +3721,18 @@ async function confirmed2(run, needsApproval, what) {
|
|
|
3229
3721
|
say(rerun(deps, "rotate", run.args));
|
|
3230
3722
|
return false;
|
|
3231
3723
|
}
|
|
3232
|
-
function withoutFinished(data,
|
|
3724
|
+
function withoutFinished(data, owner) {
|
|
3233
3725
|
return {
|
|
3234
3726
|
...data,
|
|
3235
|
-
rotations: data.rotations.filter((r) => !(r
|
|
3727
|
+
rotations: data.rotations.filter((r) => !(ownedBy(r, owner) && r.stage === "revoked"))
|
|
3236
3728
|
};
|
|
3237
3729
|
}
|
|
3730
|
+
function keyOwner(run) {
|
|
3731
|
+
return { keyId: run.key.name, environment: run.environment, mapFile: run.map.file };
|
|
3732
|
+
}
|
|
3733
|
+
function planFor(run) {
|
|
3734
|
+
return { key: run.key, environment: run.environment, mapFile: run.map.file };
|
|
3735
|
+
}
|
|
3238
3736
|
var DATED = /^(.*) (\d{4}-\d{2}-\d{2})(?: #(\d+))?$/;
|
|
3239
3737
|
function nextName(old, today) {
|
|
3240
3738
|
const match = DATED.exec(old);
|
|
@@ -3257,30 +3755,31 @@ function describeAccess(token) {
|
|
|
3257
3755
|
}
|
|
3258
3756
|
|
|
3259
3757
|
// src/commands/run.ts
|
|
3260
|
-
import { parseArgs as
|
|
3758
|
+
import { parseArgs as parseArgs6 } from "util";
|
|
3261
3759
|
async function run(args, deps) {
|
|
3262
|
-
const { positionals } =
|
|
3760
|
+
const { values, positionals } = parseArgs6({
|
|
3761
|
+
args,
|
|
3762
|
+
options: { env: { type: "string" } },
|
|
3763
|
+
allowPositionals: true
|
|
3764
|
+
});
|
|
3263
3765
|
if (!positionals.length)
|
|
3264
3766
|
throw new UsageError("keypin run needs a command after --");
|
|
3265
3767
|
const map = await findMap(deps.files, deps.cwd);
|
|
3768
|
+
const environment = pickEnvironment(map, values.env, runEnvironment(map));
|
|
3266
3769
|
const keys = map.keys.flatMap((key) => {
|
|
3267
|
-
const
|
|
3268
|
-
return
|
|
3770
|
+
const entry = key.environments[environment];
|
|
3771
|
+
return entry ? [{ key, ref: entry.ref }] : [];
|
|
3269
3772
|
});
|
|
3270
|
-
const
|
|
3271
|
-
if (skipped.length)
|
|
3272
|
-
deps.stderr.write(`keypin: no dev entry, not added: ${skipped.join(", ")}
|
|
3273
|
-
`);
|
|
3274
|
-
const values = new Map;
|
|
3773
|
+
const found = new Map;
|
|
3275
3774
|
if (keys.length) {
|
|
3276
|
-
announce(deps.stderr,
|
|
3775
|
+
announce(deps.stderr, `${environment} values`, keys.map((k) => k.ref));
|
|
3277
3776
|
const vault = deps.vault();
|
|
3278
3777
|
const failures = [];
|
|
3279
3778
|
for (const { key, ref } of keys) {
|
|
3280
3779
|
try {
|
|
3281
|
-
|
|
3780
|
+
found.set(key.name, await vault.read(ref));
|
|
3282
3781
|
} catch (error) {
|
|
3283
|
-
failures.push(`${key.
|
|
3782
|
+
failures.push(`${key.name} (${formatReference(ref)}): ${messageOf(error)}`);
|
|
3284
3783
|
}
|
|
3285
3784
|
}
|
|
3286
3785
|
if (failures.length) {
|
|
@@ -3295,7 +3794,7 @@ async function run(args, deps) {
|
|
|
3295
3794
|
for (const [name, value] of Object.entries(deps.env))
|
|
3296
3795
|
if (value !== undefined)
|
|
3297
3796
|
env[name] = value;
|
|
3298
|
-
for (const [name, secret] of
|
|
3797
|
+
for (const [name, secret] of found) {
|
|
3299
3798
|
if (env[name] !== undefined) {
|
|
3300
3799
|
deps.stderr.write(`keypin: ${name} was already set; using the vault's value
|
|
3301
3800
|
`);
|
|
@@ -3325,10 +3824,10 @@ async function run(args, deps) {
|
|
|
3325
3824
|
}
|
|
3326
3825
|
|
|
3327
3826
|
// src/commands/status.ts
|
|
3328
|
-
import { join as
|
|
3329
|
-
import { parseArgs as
|
|
3827
|
+
import { join as join8 } from "path";
|
|
3828
|
+
import { parseArgs as parseArgs7 } from "util";
|
|
3330
3829
|
async function status(args, deps) {
|
|
3331
|
-
const { values, positionals } =
|
|
3830
|
+
const { values, positionals } = parseArgs7({
|
|
3332
3831
|
args,
|
|
3333
3832
|
options: { json: { type: "boolean", default: false } },
|
|
3334
3833
|
allowPositionals: true
|
|
@@ -3340,7 +3839,7 @@ async function status(args, deps) {
|
|
|
3340
3839
|
const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
|
|
3341
3840
|
const maps = new Map;
|
|
3342
3841
|
for (const project of registry.projects) {
|
|
3343
|
-
const file =
|
|
3842
|
+
const file = join8(project, MAP_FILE);
|
|
3344
3843
|
try {
|
|
3345
3844
|
const text = await deps.files.read(file);
|
|
3346
3845
|
if (text !== null)
|
|
@@ -3350,10 +3849,10 @@ async function status(args, deps) {
|
|
|
3350
3849
|
`);
|
|
3351
3850
|
}
|
|
3352
3851
|
}
|
|
3353
|
-
const refs = distinctRefs([...maps.values()].flatMap((result) => result.ok ? result.map.keys.flatMap((key) => Object.values(key.environments).
|
|
3852
|
+
const refs = distinctRefs([...maps.values()].flatMap((result) => result.ok ? result.map.keys.flatMap((key) => Object.values(key.environments).flatMap((e) => e ? [e.ref] : [])) : []));
|
|
3354
3853
|
const metadata = new Map;
|
|
3355
3854
|
if (refs.length) {
|
|
3356
|
-
announce(deps.stderr, "
|
|
3855
|
+
announce(deps.stderr, "rotated dates (no values)", refs);
|
|
3357
3856
|
const vault = deps.vault();
|
|
3358
3857
|
for (const ref of refs) {
|
|
3359
3858
|
try {
|
|
@@ -3386,13 +3885,11 @@ function render2(result, projects) {
|
|
|
3386
3885
|
return `No projects registered. Run "keypin init" in a project folder.
|
|
3387
3886
|
`;
|
|
3388
3887
|
const lines = [];
|
|
3389
|
-
const header = ["KEY", "ENV", "
|
|
3888
|
+
const header = ["KEY", "ENV", "FROM", "ROTATED", "EVERY", "DUE"];
|
|
3390
3889
|
const cells = (row) => [
|
|
3391
3890
|
row.keyId,
|
|
3392
3891
|
row.environment,
|
|
3393
|
-
row.
|
|
3394
|
-
row.owner,
|
|
3395
|
-
row.ref.item,
|
|
3892
|
+
formatReference(row.ref),
|
|
3396
3893
|
row.rotated ?? "-",
|
|
3397
3894
|
row.rotateEvery ?? "-",
|
|
3398
3895
|
row.due ?? (row.rotateEvery === "never" ? "never" : "unknown")
|
|
@@ -3418,7 +3915,7 @@ function render2(result, projects) {
|
|
|
3418
3915
|
["problem", "Problems"],
|
|
3419
3916
|
["notice", "Notices"]
|
|
3420
3917
|
]) {
|
|
3421
|
-
const found =
|
|
3918
|
+
const found = result.problems.filter((p) => p.severity === severity);
|
|
3422
3919
|
if (!found.length)
|
|
3423
3920
|
continue;
|
|
3424
3921
|
lines.push("", `${title} (${found.length}):`);
|
|
@@ -3431,30 +3928,15 @@ function render2(result, projects) {
|
|
|
3431
3928
|
`)}
|
|
3432
3929
|
`;
|
|
3433
3930
|
}
|
|
3434
|
-
function shown(problems) {
|
|
3435
|
-
const unknown = problems.filter((p) => p.kind === "authority-unknown");
|
|
3436
|
-
const rest = problems.filter((p) => p.kind !== "authority-unknown");
|
|
3437
|
-
if (!unknown.length)
|
|
3438
|
-
return rest;
|
|
3439
|
-
const keys = [...new Set(unknown.map((p) => p.keyId ?? p.project))];
|
|
3440
|
-
const subject = keys.length === 1 ? "1 key" : `${keys.length} keys`;
|
|
3441
|
-
return [
|
|
3442
|
-
...rest,
|
|
3443
|
-
{
|
|
3444
|
-
kind: "authority-unknown",
|
|
3445
|
-
message: `${subject} (${keys.join(", ")}): what each grants is unknown, because keypin didn't create it`
|
|
3446
|
-
}
|
|
3447
|
-
];
|
|
3448
|
-
}
|
|
3449
3931
|
|
|
3450
3932
|
// src/commands/unregister.ts
|
|
3451
|
-
import { resolve as
|
|
3452
|
-
import { parseArgs as
|
|
3933
|
+
import { resolve as resolve4 } from "path";
|
|
3934
|
+
import { parseArgs as parseArgs8 } from "util";
|
|
3453
3935
|
async function unregister2(args, deps) {
|
|
3454
|
-
const { positionals } =
|
|
3936
|
+
const { positionals } = parseArgs8({ args, options: {}, allowPositionals: true });
|
|
3455
3937
|
if (positionals.length > 1)
|
|
3456
3938
|
throw new UsageError("keypin unregister takes at most one folder");
|
|
3457
|
-
const folder =
|
|
3939
|
+
const folder = resolve4(deps.cwd, positionals[0] ?? ".");
|
|
3458
3940
|
const path = registryPath(deps);
|
|
3459
3941
|
const before = await loadRegistry(deps.files, path);
|
|
3460
3942
|
const registry = await unregister(deps.files, path, folder);
|
|
@@ -3470,7 +3952,7 @@ async function unregister2(args, deps) {
|
|
|
3470
3952
|
return 0;
|
|
3471
3953
|
}
|
|
3472
3954
|
// ../../package.json
|
|
3473
|
-
var version = "0.
|
|
3955
|
+
var version = "0.6.0";
|
|
3474
3956
|
|
|
3475
3957
|
// src/cli.ts
|
|
3476
3958
|
var USAGE = `Usage:
|
|
@@ -3478,12 +3960,22 @@ var USAGE = `Usage:
|
|
|
3478
3960
|
keypin unregister [folder]
|
|
3479
3961
|
stop listing a project; its keypin.toml stays
|
|
3480
3962
|
keypin status [--json] every key in every registered project, with problems
|
|
3481
|
-
keypin discover [folder] [--json]
|
|
3482
|
-
every key name a project uses, local and in the cloud, and a draft map
|
|
3483
|
-
|
|
3484
|
-
|
|
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.
|
|
3971
|
+
keypin run [--env <name>] -- <command>
|
|
3972
|
+
run a command with one environment's keys (default: the first, dev)
|
|
3973
|
+
keypin publish <VARIABLE> [--env <name>] [--yes]
|
|
3485
3974
|
check accounts, plan, confirm, then write the key to every destination
|
|
3486
|
-
|
|
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
|
|
3978
|
+
keypin rotate <VARIABLE> [--env <name>] [--yes]
|
|
3487
3979
|
replace a token with a new one that has the same permissions, publish it,
|
|
3488
3980
|
and revoke the old one on the next run
|
|
3489
3981
|
keypin --version print the version
|
|
@@ -3500,6 +3992,7 @@ var COMMANDS = new Map([
|
|
|
3500
3992
|
["unregister", unregister2],
|
|
3501
3993
|
["status", status],
|
|
3502
3994
|
["discover", discover],
|
|
3995
|
+
["import", importEnv],
|
|
3503
3996
|
["run", run],
|
|
3504
3997
|
["publish", publish],
|
|
3505
3998
|
["rotate", rotate]
|
|
@@ -3607,6 +4100,78 @@ var createFile = async (path, text) => {
|
|
|
3607
4100
|
return now === "missing" ? "exists" : now;
|
|
3608
4101
|
}
|
|
3609
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
|
+
}
|
|
3610
4175
|
async function kindOf(path) {
|
|
3611
4176
|
try {
|
|
3612
4177
|
const found = await lstat(path);
|
|
@@ -3704,12 +4269,12 @@ function destination(target) {
|
|
|
3704
4269
|
}
|
|
3705
4270
|
}
|
|
3706
4271
|
}
|
|
3707
|
-
function provider(
|
|
3708
|
-
switch (
|
|
4272
|
+
function provider(spec, admin) {
|
|
4273
|
+
switch (spec.provider) {
|
|
3709
4274
|
case "cloudflare-account-token":
|
|
3710
|
-
return new CloudflareAccountTokens({ account:
|
|
4275
|
+
return new CloudflareAccountTokens({ account: spec.account, admin });
|
|
3711
4276
|
default: {
|
|
3712
|
-
const unknown =
|
|
4277
|
+
const unknown = spec.provider;
|
|
3713
4278
|
throw new Error(`unknown provider ${JSON.stringify(unknown)}`);
|
|
3714
4279
|
}
|
|
3715
4280
|
}
|
|
@@ -3741,6 +4306,8 @@ function main() {
|
|
|
3741
4306
|
token: () => currentWranglerToken()
|
|
3742
4307
|
})).listWorkerSecrets(account, worker),
|
|
3743
4308
|
createFile,
|
|
4309
|
+
replaceFile,
|
|
4310
|
+
isLink,
|
|
3744
4311
|
vault: () => vault ??= onePasswordBackend(connect),
|
|
3745
4312
|
now: () => new Date,
|
|
3746
4313
|
stdout: process.stdout,
|