keypin 0.7.0 → 0.9.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 +36 -17
- package/chunk-8jhj2smy.js +12632 -0
- package/{chunk-j6kpw8ge.js → chunk-t31ce2x2.js} +16 -1
- package/main.js +7 -3
- package/package.json +1 -1
- package/chunk-1rrcgz3h.js +0 -4406
package/chunk-1rrcgz3h.js
DELETED
|
@@ -1,4406 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import {
|
|
3
|
-
messageOf,
|
|
4
|
-
errorCode,
|
|
5
|
-
installProblem,
|
|
6
|
-
selfCommand
|
|
7
|
-
} from "./chunk-j6kpw8ge.js";
|
|
8
|
-
|
|
9
|
-
// src/start.ts
|
|
10
|
-
import { homedir as homedir2 } from "os";
|
|
11
|
-
import { createInterface } from "readline/promises";
|
|
12
|
-
|
|
13
|
-
// ../../packages/core/src/secret.ts
|
|
14
|
-
var HIDDEN = "[secret]";
|
|
15
|
-
|
|
16
|
-
class Secret {
|
|
17
|
-
#value;
|
|
18
|
-
constructor(value) {
|
|
19
|
-
this.#value = value;
|
|
20
|
-
}
|
|
21
|
-
reveal() {
|
|
22
|
-
return this.#value;
|
|
23
|
-
}
|
|
24
|
-
equals(other) {
|
|
25
|
-
return this.#value === other.#value;
|
|
26
|
-
}
|
|
27
|
-
isEmpty() {
|
|
28
|
-
return !this.#value;
|
|
29
|
-
}
|
|
30
|
-
includes(text) {
|
|
31
|
-
return this.#value.includes(text);
|
|
32
|
-
}
|
|
33
|
-
toString() {
|
|
34
|
-
return HIDDEN;
|
|
35
|
-
}
|
|
36
|
-
toJSON() {
|
|
37
|
-
return HIDDEN;
|
|
38
|
-
}
|
|
39
|
-
[Symbol.toPrimitive]() {
|
|
40
|
-
return HIDDEN;
|
|
41
|
-
}
|
|
42
|
-
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
43
|
-
return HIDDEN;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
async function generationOf(secret) {
|
|
47
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret.reveal()));
|
|
48
|
-
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 16);
|
|
49
|
-
}
|
|
50
|
-
// ../../packages/core/src/contracts.ts
|
|
51
|
-
var DEFAULT_ENVIRONMENTS = ["dev", "prod"];
|
|
52
|
-
// ../../packages/core/src/map.ts
|
|
53
|
-
var {TOML } = globalThis.Bun;
|
|
54
|
-
|
|
55
|
-
// ../../packages/core/src/record.ts
|
|
56
|
-
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
57
|
-
|
|
58
|
-
// ../../packages/core/src/reference.ts
|
|
59
|
-
var SCHEME = "op://";
|
|
60
|
-
function parseReference(text) {
|
|
61
|
-
if (!text.startsWith(SCHEME))
|
|
62
|
-
return `must start with ${SCHEME}`;
|
|
63
|
-
if (/[?#]/.test(text))
|
|
64
|
-
return "can't have a query such as ?attribute=";
|
|
65
|
-
const parts = text.slice(SCHEME.length).split("/");
|
|
66
|
-
if (parts.length < 3 || parts.length > 4 || parts.some((part) => !part.trim())) {
|
|
67
|
-
return `must be ${SCHEME}<vault>/<item>/<field> or ${SCHEME}<vault>/<item>/<section>/<field>`;
|
|
68
|
-
}
|
|
69
|
-
const [vault = "", item = "", ...rest] = parts;
|
|
70
|
-
return {
|
|
71
|
-
vault,
|
|
72
|
-
item,
|
|
73
|
-
section: rest.length === 2 ? rest[0] ?? null : null,
|
|
74
|
-
field: rest.at(-1) ?? ""
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
function formatReference(ref) {
|
|
78
|
-
const parts = [ref.vault, ref.item, ...ref.section === null ? [] : [ref.section], ref.field];
|
|
79
|
-
return `${SCHEME}${parts.join("/")}`;
|
|
80
|
-
}
|
|
81
|
-
var sameName = (a, b) => a === b || a !== null && b !== null && a.toLowerCase() === b.toLowerCase();
|
|
82
|
-
function sameItem(a, b) {
|
|
83
|
-
return a.kind === b.kind && a.account === b.account && sameName(a.vault, b.vault) && sameName(a.item, b.item);
|
|
84
|
-
}
|
|
85
|
-
function sameRef(a, b) {
|
|
86
|
-
return sameItem(a, b) && sameName(a.section, b.section) && sameName(a.field, b.field);
|
|
87
|
-
}
|
|
88
|
-
function storedRefWithPasswordDefault(value) {
|
|
89
|
-
if (!isRecord(value) || value.kind !== "1password")
|
|
90
|
-
return null;
|
|
91
|
-
const { account, vault, item, section = null, field = "password" } = value;
|
|
92
|
-
if (typeof account !== "string" || typeof vault !== "string" || typeof item !== "string")
|
|
93
|
-
return null;
|
|
94
|
-
if (typeof field !== "string" || section !== null && typeof section !== "string")
|
|
95
|
-
return null;
|
|
96
|
-
return { kind: "1password", account, vault, item, section, field };
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// ../../packages/core/src/rotation.ts
|
|
100
|
-
var DUE_SOON_DAYS = 14;
|
|
101
|
-
var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
102
|
-
var UNIT_DAYS = new Map([
|
|
103
|
-
["d", 1],
|
|
104
|
-
["w", 7],
|
|
105
|
-
["m", 30]
|
|
106
|
-
]);
|
|
107
|
-
function periodDays(period) {
|
|
108
|
-
if (period === "never")
|
|
109
|
-
return null;
|
|
110
|
-
const match = /^(\d+)([dwm])$/.exec(period ?? "");
|
|
111
|
-
const count = Number(match?.[1]);
|
|
112
|
-
const unit = UNIT_DAYS.get(match?.[2] ?? "");
|
|
113
|
-
if (!count || unit === undefined)
|
|
114
|
-
return;
|
|
115
|
-
return count * unit;
|
|
116
|
-
}
|
|
117
|
-
function isDay(value) {
|
|
118
|
-
const match = DAY.exec(value);
|
|
119
|
-
if (!match)
|
|
120
|
-
return false;
|
|
121
|
-
const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
|
|
122
|
-
return date.toISOString().slice(0, 10) === value;
|
|
123
|
-
}
|
|
124
|
-
function addDays(day, days) {
|
|
125
|
-
const date = new Date(`${day}T00:00:00Z`);
|
|
126
|
-
date.setUTCDate(date.getUTCDate() + days);
|
|
127
|
-
return date.toISOString().slice(0, 10);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// ../../packages/core/src/map.ts
|
|
131
|
-
var DESTINATION_KINDS = ["cloudflare-worker", "github-actions"];
|
|
132
|
-
var PROVIDER_KINDS = ["cloudflare-account-token"];
|
|
133
|
-
function runEnvironment(map) {
|
|
134
|
-
return map.environments[0] ?? "dev";
|
|
135
|
-
}
|
|
136
|
-
function publishEnvironment(map) {
|
|
137
|
-
return map.environments.at(-1) ?? "prod";
|
|
138
|
-
}
|
|
139
|
-
function envFlag(environment, fallback) {
|
|
140
|
-
return environment === fallback ? "" : ` --env ${environment}`;
|
|
141
|
-
}
|
|
142
|
-
function destinationId(target, secretName) {
|
|
143
|
-
return `${placeId(target)}:${secretName}`;
|
|
144
|
-
}
|
|
145
|
-
function secretKey(target, secretName) {
|
|
146
|
-
return target.to === "cloudflare-worker" ? `cloudflare-worker:${target.account}:${target.worker}:${secretName}` : `github-actions:${target.repo.toLowerCase()}:${secretName.toUpperCase()}`;
|
|
147
|
-
}
|
|
148
|
-
function receiptSecretKey(receipt) {
|
|
149
|
-
const [to, place, name, ...rest] = receipt.destinationId.split(":");
|
|
150
|
-
if (rest.length || place === undefined || name === undefined)
|
|
151
|
-
return receipt.destinationId;
|
|
152
|
-
if (to === "cloudflare-worker") {
|
|
153
|
-
return secretKey({ to, account: receipt.account.pinned, worker: place }, name);
|
|
154
|
-
}
|
|
155
|
-
if (to === "github-actions") {
|
|
156
|
-
return secretKey({ to, repo: place, account: receipt.account.pinned }, name);
|
|
157
|
-
}
|
|
158
|
-
return receipt.destinationId;
|
|
159
|
-
}
|
|
160
|
-
function placeId(target) {
|
|
161
|
-
return target.to === "cloudflare-worker" ? `cloudflare-worker:${target.worker}` : `github-actions:${target.repo}`;
|
|
162
|
-
}
|
|
163
|
-
function isVariableName(name) {
|
|
164
|
-
return VARIABLE_NAME.test(name);
|
|
165
|
-
}
|
|
166
|
-
function parseMap(text, file) {
|
|
167
|
-
let data;
|
|
168
|
-
try {
|
|
169
|
-
data = TOML.parse(text);
|
|
170
|
-
} catch (error) {
|
|
171
|
-
return {
|
|
172
|
-
ok: false,
|
|
173
|
-
errors: [`${file}: not valid TOML: ${tomlProblem(error)}`]
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
return validateMap(data, file);
|
|
177
|
-
}
|
|
178
|
-
var ENVIRONMENT_NAME = /^[a-z][a-z0-9-]*$/;
|
|
179
|
-
var TARGET_NAME = ENVIRONMENT_NAME;
|
|
180
|
-
var KEY_FIELDS = ["rotate_every"];
|
|
181
|
-
var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
182
|
-
var REPO = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
|
|
183
|
-
var REMOVED_KEY_FIELDS = ["owner", "consumers"];
|
|
184
|
-
var OLD_FORMAT = "see docs/configuration.md for the current format";
|
|
185
|
-
function validateMap(data, file) {
|
|
186
|
-
const errors = [];
|
|
187
|
-
const fail = (where, message) => errors.push(`${file}: ${where}${message}`);
|
|
188
|
-
if (!isRecord(data))
|
|
189
|
-
return { ok: false, errors: [`${file}: expected a table at the top level`] };
|
|
190
|
-
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}"`));
|
|
191
|
-
const environments = validateEnvironments(data.environments, (message) => fail("", message));
|
|
192
|
-
const account = validateAccount(data["1password"], (message) => fail("[1password]: ", message));
|
|
193
|
-
const targets = validateTargets(data.targets, (where, message) => fail(where, message));
|
|
194
|
-
const keys = [];
|
|
195
|
-
const rawKeys = data.keys ?? {};
|
|
196
|
-
if (!isRecord(rawKeys))
|
|
197
|
-
fail("", `"keys" must be a table`);
|
|
198
|
-
else {
|
|
199
|
-
Object.entries(rawKeys).forEach(([id, raw], index) => {
|
|
200
|
-
const label = VARIABLE_NAME.test(id) ? `key "${id}"` : `keys[${index}]`;
|
|
201
|
-
const entry = validateKey(id, raw, account, environments, targets, (where, message) => fail(`${label}${where}: `, message));
|
|
202
|
-
if (entry)
|
|
203
|
-
keys.push(entry);
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
|
-
for (const name of targets.defined) {
|
|
207
|
-
if (!targets.used.has(name))
|
|
208
|
-
fail(`target "${name}": `, "no key publishes to it; use it in a publish list or delete it");
|
|
209
|
-
}
|
|
210
|
-
sharedDestinations(keys, environments, (where, message) => fail(where, message));
|
|
211
|
-
return errors.length ? { ok: false, errors } : { ok: true, map: { file, account: account ?? null, environments, keys } };
|
|
212
|
-
}
|
|
213
|
-
function validateAccount(raw, fail) {
|
|
214
|
-
if (raw === undefined)
|
|
215
|
-
return;
|
|
216
|
-
if (!isRecord(raw)) {
|
|
217
|
-
fail("must be a table");
|
|
218
|
-
return;
|
|
219
|
-
}
|
|
220
|
-
unknownFields(raw, ["account"], (field) => fail(`unknown field "${field}"`));
|
|
221
|
-
return requiredString(raw, "account", fail);
|
|
222
|
-
}
|
|
223
|
-
function validateTargets(raw, fail) {
|
|
224
|
-
const targets = { defined: [], valid: new Map, used: new Set };
|
|
225
|
-
if (raw === undefined)
|
|
226
|
-
return targets;
|
|
227
|
-
if (!isRecord(raw)) {
|
|
228
|
-
fail("", `"targets" must be a table of named destinations, such as [targets.ci]`);
|
|
229
|
-
return targets;
|
|
230
|
-
}
|
|
231
|
-
Object.entries(raw).forEach(([name, table], index) => {
|
|
232
|
-
if (!TARGET_NAME.test(name)) {
|
|
233
|
-
fail(`targets[${index}]: `, "a target name starts with a lowercase letter and uses only lowercase letters, digits and dashes");
|
|
234
|
-
return;
|
|
235
|
-
}
|
|
236
|
-
targets.defined.push(name);
|
|
237
|
-
const target = validateTarget(table, (m) => fail(`target "${name}": `, m));
|
|
238
|
-
if (target)
|
|
239
|
-
targets.valid.set(name, target);
|
|
240
|
-
});
|
|
241
|
-
return targets;
|
|
242
|
-
}
|
|
243
|
-
function resolveTarget(raw, targets, fail) {
|
|
244
|
-
if (isRecord(raw))
|
|
245
|
-
return validateTarget(raw, fail);
|
|
246
|
-
if (typeof raw !== "string") {
|
|
247
|
-
fail("must be a target name or a table");
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
const name = targets.defined.find((defined) => defined === raw);
|
|
251
|
-
if (name === undefined) {
|
|
252
|
-
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]");
|
|
253
|
-
return;
|
|
254
|
-
}
|
|
255
|
-
targets.used.add(name);
|
|
256
|
-
const target = targets.valid.get(name);
|
|
257
|
-
return target ? { ...target } : undefined;
|
|
258
|
-
}
|
|
259
|
-
function validateEnvironments(raw, fail) {
|
|
260
|
-
if (raw === undefined)
|
|
261
|
-
return DEFAULT_ENVIRONMENTS;
|
|
262
|
-
if (!Array.isArray(raw) || !raw.length || !raw.every((name) => typeof name === "string")) {
|
|
263
|
-
fail(`"environments" must be a list of names, such as ["dev", "staging", "prod"]`);
|
|
264
|
-
return DEFAULT_ENVIRONMENTS;
|
|
265
|
-
}
|
|
266
|
-
const names = [];
|
|
267
|
-
for (const name of raw) {
|
|
268
|
-
if (!ENVIRONMENT_NAME.test(name)) {
|
|
269
|
-
fail(`environment "${name}": a name starts with a lowercase letter and uses only lowercase letters, digits and dashes`);
|
|
270
|
-
} else if (names.includes(name)) {
|
|
271
|
-
fail(`environment "${name}" is listed twice`);
|
|
272
|
-
} else
|
|
273
|
-
names.push(name);
|
|
274
|
-
}
|
|
275
|
-
return names;
|
|
276
|
-
}
|
|
277
|
-
function sharedDestinations(keys, environments, fail) {
|
|
278
|
-
const owners = new Map;
|
|
279
|
-
for (const key of keys) {
|
|
280
|
-
for (const environment of environments) {
|
|
281
|
-
key.environments[environment]?.publish.forEach((target, i) => {
|
|
282
|
-
const where = `key "${key.name}" ${environment} publish[${i}]`;
|
|
283
|
-
const secret = secretKey(target, key.name);
|
|
284
|
-
const owner = owners.get(secret);
|
|
285
|
-
if (owner === undefined)
|
|
286
|
-
owners.set(secret, where);
|
|
287
|
-
else
|
|
288
|
-
fail(`${where}: `, `writes the same destination secret as ${owner}`);
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
function validateKey(id, raw, account, environmentNames, targets, fail) {
|
|
294
|
-
let failures = 0;
|
|
295
|
-
const err = (where, message) => {
|
|
296
|
-
failures++;
|
|
297
|
-
fail(where, message);
|
|
298
|
-
};
|
|
299
|
-
if (!VARIABLE_NAME.test(id))
|
|
300
|
-
err("", "the table name is the variable your program reads: letters, digits and _, not starting with a digit");
|
|
301
|
-
if (!isRecord(raw)) {
|
|
302
|
-
err("", "must be a table");
|
|
303
|
-
return;
|
|
304
|
-
}
|
|
305
|
-
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(", ")}`));
|
|
306
|
-
const rotateEvery = optionalString(raw, "rotate_every", (m) => err("", m));
|
|
307
|
-
if (rotateEvery !== undefined && periodDays(rotateEvery) === undefined) {
|
|
308
|
-
err("", `field "rotate_every" must be <n>d, <n>w, <n>m or never`);
|
|
309
|
-
}
|
|
310
|
-
const environments = Object.create(null);
|
|
311
|
-
const declared = environmentNames.filter((name) => Object.hasOwn(raw, name));
|
|
312
|
-
for (const name of declared) {
|
|
313
|
-
const entry = validateEnv(raw[name], account, targets, (m) => err(` ${name}`, m));
|
|
314
|
-
if (entry)
|
|
315
|
-
environments[name] = entry;
|
|
316
|
-
}
|
|
317
|
-
for (const [name, entry] of Object.entries(environments)) {
|
|
318
|
-
const index = entry.publish.findIndex((target) => target.to === "github-actions");
|
|
319
|
-
if (index !== -1 && /^GITHUB_/i.test(id)) {
|
|
320
|
-
err(` ${name}`, `publish[${index}]: github-actions can't take this key, because GitHub reserves secret names that start with GITHUB_`);
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
if (!declared.length) {
|
|
324
|
-
err("", `needs at least one of ${environmentNames.map((n) => `"${n}"`).join(", ")}`);
|
|
325
|
-
}
|
|
326
|
-
if (failures)
|
|
327
|
-
return;
|
|
328
|
-
return { name: id, rotateEvery: rotateEvery ?? null, environments };
|
|
329
|
-
}
|
|
330
|
-
function validateEnv(given, account, targets, fail) {
|
|
331
|
-
const raw = typeof given === "string" ? { from: given } : given;
|
|
332
|
-
if (!isRecord(raw)) {
|
|
333
|
-
fail(`must be an op:// reference, or a table with "from"`);
|
|
334
|
-
return;
|
|
335
|
-
}
|
|
336
|
-
let failed = false;
|
|
337
|
-
const err = (message) => {
|
|
338
|
-
failed = true;
|
|
339
|
-
fail(message);
|
|
340
|
-
};
|
|
341
|
-
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}"`));
|
|
342
|
-
const ref = reference(raw, "from", account, err);
|
|
343
|
-
const publish = [];
|
|
344
|
-
const firstAt = new Map;
|
|
345
|
-
if (raw.publish !== undefined) {
|
|
346
|
-
if (!Array.isArray(raw.publish))
|
|
347
|
-
err(`field "publish" must be a list`);
|
|
348
|
-
else {
|
|
349
|
-
raw.publish.forEach((t, i) => {
|
|
350
|
-
const target = resolveTarget(t, targets, (m) => err(`publish[${i}]: ${m}`));
|
|
351
|
-
if (!target)
|
|
352
|
-
return;
|
|
353
|
-
const same = firstAt.get(placeId(target));
|
|
354
|
-
if (same !== undefined)
|
|
355
|
-
err(`publish[${i}]: the same destination as publish[${same}]`);
|
|
356
|
-
else {
|
|
357
|
-
firstAt.set(placeId(target), i);
|
|
358
|
-
publish.push(target);
|
|
359
|
-
}
|
|
360
|
-
});
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
const rotate = raw.rotate === undefined || !ref ? undefined : validateRotate(raw.rotate, ref, account, (m) => err(`rotate: ${m}`));
|
|
364
|
-
if (failed || !ref)
|
|
365
|
-
return;
|
|
366
|
-
return { ref, publish, ...rotate ? { rotate } : {} };
|
|
367
|
-
}
|
|
368
|
-
function reference(table, field, account, fail) {
|
|
369
|
-
const text = requiredString(table, field, fail);
|
|
370
|
-
if (text === undefined)
|
|
371
|
-
return;
|
|
372
|
-
const parsed = parseReference(text);
|
|
373
|
-
if (typeof parsed === "string") {
|
|
374
|
-
fail(`field "${field}" ${parsed}`);
|
|
375
|
-
return;
|
|
376
|
-
}
|
|
377
|
-
if (account === undefined) {
|
|
378
|
-
fail(`field "${field}" needs your 1Password account: add [1password] with account = "..."`);
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
381
|
-
return { kind: "1password", account, ...parsed };
|
|
382
|
-
}
|
|
383
|
-
var ACCOUNT_ID = /^[0-9a-f]{32}$/;
|
|
384
|
-
function validateRotate(raw, own, vaultAccount, fail) {
|
|
385
|
-
if (!isRecord(raw)) {
|
|
386
|
-
fail("must be a table");
|
|
387
|
-
return;
|
|
388
|
-
}
|
|
389
|
-
let failed = false;
|
|
390
|
-
const err = (message) => {
|
|
391
|
-
failed = true;
|
|
392
|
-
fail(message);
|
|
393
|
-
};
|
|
394
|
-
unknownFields(raw, ["provider", "account", "admin"], (field) => err(`unknown field "${field}"`));
|
|
395
|
-
const provider = requiredString(raw, "provider", err);
|
|
396
|
-
const account = requiredString(raw, "account", err);
|
|
397
|
-
const admin = reference(raw, "admin", vaultAccount, err);
|
|
398
|
-
const kind = PROVIDER_KINDS.find((known) => known === provider);
|
|
399
|
-
if (provider !== undefined && !kind)
|
|
400
|
-
err(`field "provider" must be one of: ${PROVIDER_KINDS.join(", ")}`);
|
|
401
|
-
if (account !== undefined && !ACCOUNT_ID.test(account))
|
|
402
|
-
err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
|
|
403
|
-
if (admin && sameItem(admin, own))
|
|
404
|
-
err(`field "admin" names the key's own item; the admin token needs its own item`);
|
|
405
|
-
if (failed || !kind || account === undefined || admin === undefined)
|
|
406
|
-
return;
|
|
407
|
-
return { provider: kind, account, admin };
|
|
408
|
-
}
|
|
409
|
-
function validateTarget(raw, fail) {
|
|
410
|
-
if (!isRecord(raw)) {
|
|
411
|
-
fail("must be a table");
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
const to = requiredString(raw, "to", fail);
|
|
415
|
-
if (to === undefined)
|
|
416
|
-
return;
|
|
417
|
-
let failed = false;
|
|
418
|
-
const err = (message) => {
|
|
419
|
-
failed = true;
|
|
420
|
-
fail(message);
|
|
421
|
-
};
|
|
422
|
-
if (to === "cloudflare-worker") {
|
|
423
|
-
unknownFields(raw, ["to", "account", "worker"], (field) => err(`unknown field "${field}" for ${to}`));
|
|
424
|
-
const account = requiredString(raw, "account", err);
|
|
425
|
-
const worker = requiredString(raw, "worker", err);
|
|
426
|
-
if (account !== undefined && !ACCOUNT_ID.test(account))
|
|
427
|
-
err(`field "account" must be a Cloudflare account ID (32 hex characters)`);
|
|
428
|
-
return failed || account === undefined || worker === undefined ? undefined : { to, account, worker };
|
|
429
|
-
}
|
|
430
|
-
if (to === "github-actions") {
|
|
431
|
-
unknownFields(raw, ["to", "repo", "account"], (field) => err(`unknown field "${field}" for ${to}`));
|
|
432
|
-
const repo = requiredString(raw, "repo", err);
|
|
433
|
-
const account = optionalString(raw, "account", err);
|
|
434
|
-
if (repo !== undefined && !REPO.test(repo))
|
|
435
|
-
err(`field "repo" must be "owner/name"`);
|
|
436
|
-
return failed || repo === undefined ? undefined : { to, repo, account: account ?? repo.split("/")[0] };
|
|
437
|
-
}
|
|
438
|
-
err(`field "to" must be one of: ${DESTINATION_KINDS.join(", ")}`);
|
|
439
|
-
return;
|
|
440
|
-
}
|
|
441
|
-
function tomlProblem(error) {
|
|
442
|
-
const message = error instanceof Error ? error.message : "unknown parse error";
|
|
443
|
-
const problem = message.replace(/^TOML Parse error: /, "").split(/["']|\(0x/)[0] ?? "";
|
|
444
|
-
return problem.replace(/(\s+but)?\s+found\s*$/, "").replace(/[\s:]+$/, "");
|
|
445
|
-
}
|
|
446
|
-
function unknownFields(table, known, report) {
|
|
447
|
-
for (const field of Object.keys(table))
|
|
448
|
-
if (!known.includes(field))
|
|
449
|
-
report(field);
|
|
450
|
-
}
|
|
451
|
-
function requiredString(table, field, fail) {
|
|
452
|
-
const value = table[field];
|
|
453
|
-
if (value === undefined)
|
|
454
|
-
fail(`missing field "${field}"`);
|
|
455
|
-
else if (typeof value !== "string" || !value.trim())
|
|
456
|
-
fail(`field "${field}" must be a non-empty string`);
|
|
457
|
-
else
|
|
458
|
-
return value;
|
|
459
|
-
return;
|
|
460
|
-
}
|
|
461
|
-
function optionalString(table, field, fail) {
|
|
462
|
-
return table[field] === undefined ? undefined : requiredString(table, field, fail);
|
|
463
|
-
}
|
|
464
|
-
// ../../packages/core/src/tokens.ts
|
|
465
|
-
function sameAccess(a, b) {
|
|
466
|
-
return canonical(a.policies.map(policyShape)) === canonical(b.policies.map(policyShape)) && canonical(a.condition ?? {}) === canonical(b.condition ?? {});
|
|
467
|
-
}
|
|
468
|
-
function policyShape(policy) {
|
|
469
|
-
return {
|
|
470
|
-
effect: policy.effect,
|
|
471
|
-
resources: policy.resources,
|
|
472
|
-
groups: policy.permissionGroups.map((group) => group.id)
|
|
473
|
-
};
|
|
474
|
-
}
|
|
475
|
-
function canonical(value) {
|
|
476
|
-
if (Array.isArray(value))
|
|
477
|
-
return `[${value.map(canonical).toSorted().join(",")}]`;
|
|
478
|
-
if (isRecord(value)) {
|
|
479
|
-
const entries = Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : 1).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item ?? null)}`);
|
|
480
|
-
return `{${entries.join(",")}}`;
|
|
481
|
-
}
|
|
482
|
-
return JSON.stringify(value);
|
|
483
|
-
}
|
|
484
|
-
// ../../packages/core/src/files.ts
|
|
485
|
-
async function writeJsonAtomic(files, path, data) {
|
|
486
|
-
const temporary = `${path}.${crypto.randomUUID()}.tmp`;
|
|
487
|
-
await files.write(temporary, `${JSON.stringify(data, null, 2)}
|
|
488
|
-
`);
|
|
489
|
-
await files.rename(temporary, path);
|
|
490
|
-
}
|
|
491
|
-
async function readVersionedJson(files, path, versions, what) {
|
|
492
|
-
const text = await files.read(path);
|
|
493
|
-
if (text === null)
|
|
494
|
-
return null;
|
|
495
|
-
let data;
|
|
496
|
-
try {
|
|
497
|
-
data = JSON.parse(text);
|
|
498
|
-
} catch {
|
|
499
|
-
throw new Error(`${path}: the ${what} isn't valid JSON`);
|
|
500
|
-
}
|
|
501
|
-
if (!isRecord(data))
|
|
502
|
-
throw new Error(`${path}: the ${what} must be a JSON object`);
|
|
503
|
-
if (!versions.some((version) => version === data.version)) {
|
|
504
|
-
throw new Error(`${path}: the ${what} has schema version ${JSON.stringify(data.version ?? null)}, and this keypin reads version ${versions.join(" or ")}`);
|
|
505
|
-
}
|
|
506
|
-
return data;
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
// ../../packages/core/src/registry.ts
|
|
510
|
-
var REGISTRY_VERSION = 1;
|
|
511
|
-
var emptyRegistry = () => ({
|
|
512
|
-
version: REGISTRY_VERSION,
|
|
513
|
-
projects: [],
|
|
514
|
-
shared: []
|
|
515
|
-
});
|
|
516
|
-
async function loadRegistry(files, path) {
|
|
517
|
-
const data = await readVersionedJson(files, path, [REGISTRY_VERSION], "registry");
|
|
518
|
-
if (!data)
|
|
519
|
-
return emptyRegistry();
|
|
520
|
-
const { projects, shared } = data;
|
|
521
|
-
if (!Array.isArray(projects) || !projects.every((p) => typeof p === "string")) {
|
|
522
|
-
throw new Error(`${path}: the registry's "projects" must be a list of paths`);
|
|
523
|
-
}
|
|
524
|
-
if (!Array.isArray(shared) || !shared.every((s) => typeof s?.id === "string")) {
|
|
525
|
-
throw new Error(`${path}: the registry's "shared" must be a list of { id }`);
|
|
526
|
-
}
|
|
527
|
-
return { version: REGISTRY_VERSION, projects, shared };
|
|
528
|
-
}
|
|
529
|
-
async function register(files, path, project) {
|
|
530
|
-
const folder = projectPath(project);
|
|
531
|
-
const registry = await loadRegistry(files, path);
|
|
532
|
-
if (registry.projects.includes(folder))
|
|
533
|
-
return registry;
|
|
534
|
-
const next = { ...registry, projects: [...registry.projects, folder].sort() };
|
|
535
|
-
await writeJsonAtomic(files, path, next);
|
|
536
|
-
return next;
|
|
537
|
-
}
|
|
538
|
-
async function unregister(files, path, project) {
|
|
539
|
-
const folder = projectPath(project);
|
|
540
|
-
const registry = await loadRegistry(files, path);
|
|
541
|
-
if (!registry.projects.includes(folder))
|
|
542
|
-
return registry;
|
|
543
|
-
const next = { ...registry, projects: registry.projects.filter((p) => p !== folder) };
|
|
544
|
-
await writeJsonAtomic(files, path, next);
|
|
545
|
-
return next;
|
|
546
|
-
}
|
|
547
|
-
function projectPath(project) {
|
|
548
|
-
if (!project.startsWith("/"))
|
|
549
|
-
throw new Error(`a project path must be absolute, got "${project}"`);
|
|
550
|
-
return project.replace(/(.)\/+$/, "$1");
|
|
551
|
-
}
|
|
552
|
-
// ../../packages/core/src/state.ts
|
|
553
|
-
var STATE_VERSION = 3;
|
|
554
|
-
var emptyState = () => ({ version: STATE_VERSION, receipts: [], operations: [] });
|
|
555
|
-
async function loadState(files, path) {
|
|
556
|
-
const data = await readVersionedJson(files, path, [1, 2, STATE_VERSION], "state file");
|
|
557
|
-
if (!data)
|
|
558
|
-
return emptyState();
|
|
559
|
-
const mapFile = (r) => data.version === STATE_VERSION ? r.mapFile : null;
|
|
560
|
-
const receipts = Array.isArray(data.receipts) ? data.receipts.map((r) => isRecord(r) ? {
|
|
561
|
-
...r,
|
|
562
|
-
mapFile: mapFile(r),
|
|
563
|
-
source: data.version === 1 ? null : storedSource(r.source)
|
|
564
|
-
} : r) : data.receipts;
|
|
565
|
-
const operations = Array.isArray(data.operations) ? data.operations.map((o) => isRecord(o) ? { ...o, mapFile: mapFile(o) } : o) : data.operations;
|
|
566
|
-
if (!Array.isArray(receipts) || !receipts.every(isReceipt)) {
|
|
567
|
-
throw new Error(`${path}: the state file's "receipts" must be a list of receipts`);
|
|
568
|
-
}
|
|
569
|
-
if (!Array.isArray(operations) || !operations.every(isOperation)) {
|
|
570
|
-
throw new Error(`${path}: the state file's "operations" must be a list of operations`);
|
|
571
|
-
}
|
|
572
|
-
return { version: STATE_VERSION, receipts, operations };
|
|
573
|
-
}
|
|
574
|
-
async function saveState(files, path, state) {
|
|
575
|
-
await writeJsonAtomic(files, path, state);
|
|
576
|
-
}
|
|
577
|
-
function ownedBy(entry, owner) {
|
|
578
|
-
return entry.mapFile === owner.mapFile && entry.keyId === owner.keyId && entry.environment === owner.environment;
|
|
579
|
-
}
|
|
580
|
-
function startOperation(state, operation) {
|
|
581
|
-
if (state.operations.some((o) => o.id === operation.id))
|
|
582
|
-
throw new Error(`operation ${operation.id} already exists`);
|
|
583
|
-
return { ...state, operations: [...state.operations, { ...operation, done: [] }] };
|
|
584
|
-
}
|
|
585
|
-
function recordReceipt(state, receipt, operationId) {
|
|
586
|
-
const same = (r) => receiptSecretKey(r) === receiptSecretKey(receipt);
|
|
587
|
-
const operations = state.operations.map((o) => o.id === operationId && !o.done.includes(receipt.destinationId) ? { ...o, done: [...o.done, receipt.destinationId] } : o);
|
|
588
|
-
return { ...state, receipts: [...state.receipts.filter((r) => !same(r)), receipt], operations };
|
|
589
|
-
}
|
|
590
|
-
function finishOperation(state, operationId) {
|
|
591
|
-
return { ...state, operations: state.operations.filter((o) => o.id !== operationId) };
|
|
592
|
-
}
|
|
593
|
-
function unfinishedOperations(state, owner) {
|
|
594
|
-
return state.operations.filter((o) => ownedBy(o, owner));
|
|
595
|
-
}
|
|
596
|
-
var isText = (value) => typeof value === "string";
|
|
597
|
-
var isTextOrNull = (value) => value === null || typeof value === "string";
|
|
598
|
-
function isReceipt(r) {
|
|
599
|
-
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;
|
|
600
|
-
}
|
|
601
|
-
function storedSource(source) {
|
|
602
|
-
return source === null ? null : storedRefWithPasswordDefault(source) ?? source;
|
|
603
|
-
}
|
|
604
|
-
function isOperation(o) {
|
|
605
|
-
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);
|
|
606
|
-
}
|
|
607
|
-
// ../../packages/core/src/plan.ts
|
|
608
|
-
var ownerOf = ({ key, environment, mapFile }) => ({
|
|
609
|
-
keyId: key.name,
|
|
610
|
-
environment,
|
|
611
|
-
mapFile
|
|
612
|
-
});
|
|
613
|
-
function approvalsFor(input) {
|
|
614
|
-
return judge(input).flatMap(({ id, approval }) => approval ? [{ destinationId: id, ...approval }] : []);
|
|
615
|
-
}
|
|
616
|
-
function planPublish(input) {
|
|
617
|
-
const { key, environment, generation } = input;
|
|
618
|
-
const steps = judge(input).map(({ id, target, receipt, approval }) => {
|
|
619
|
-
if (approval) {
|
|
620
|
-
return { action: "write", destinationId: id, target, ...approval };
|
|
621
|
-
}
|
|
622
|
-
if (receipt?.generation === generation) {
|
|
623
|
-
return {
|
|
624
|
-
action: "skip",
|
|
625
|
-
destinationId: id,
|
|
626
|
-
target,
|
|
627
|
-
reason: "receipt already has this generation",
|
|
628
|
-
approval: null
|
|
629
|
-
};
|
|
630
|
-
}
|
|
631
|
-
return {
|
|
632
|
-
action: "write",
|
|
633
|
-
destinationId: id,
|
|
634
|
-
target,
|
|
635
|
-
reason: "different generation",
|
|
636
|
-
approval: null
|
|
637
|
-
};
|
|
638
|
-
});
|
|
639
|
-
const listed = new Set(steps.flatMap((s) => [secretKey(s.target, key.name), s.destinationId]));
|
|
640
|
-
const removed = latestPerSecret(input.receipts).filter((r) => ownedBy(r, ownerOf(input))).filter((r) => !listed.has(receiptSecretKey(r)) && !listed.has(r.destinationId)).map((r) => ({
|
|
641
|
-
destinationId: r.destinationId,
|
|
642
|
-
lastReceipt: {
|
|
643
|
-
generation: r.generation,
|
|
644
|
-
at: r.at,
|
|
645
|
-
destinationAccount: r.account.destinationAccount
|
|
646
|
-
}
|
|
647
|
-
}));
|
|
648
|
-
return {
|
|
649
|
-
keyId: key.name,
|
|
650
|
-
environment,
|
|
651
|
-
generation,
|
|
652
|
-
steps,
|
|
653
|
-
removed,
|
|
654
|
-
needsApproval: steps.some((s) => s.approval !== null)
|
|
655
|
-
};
|
|
656
|
-
}
|
|
657
|
-
function judge(input) {
|
|
658
|
-
const { key, environment } = input;
|
|
659
|
-
const entry = key.environments[environment];
|
|
660
|
-
if (!entry)
|
|
661
|
-
throw new Error(`key "${key.name}" has no ${environment} entry in the map`);
|
|
662
|
-
const newest = latestPerSecret(input.receipts);
|
|
663
|
-
const latest = new Map(newest.map((r) => [receiptSecretKey(r), r]));
|
|
664
|
-
const owner = ownerOf(input);
|
|
665
|
-
const ours = newest.filter((r) => ownedBy(r, owner));
|
|
666
|
-
const published = input.receipts.some((r) => ownedBy(r, owner));
|
|
667
|
-
return entry.publish.map((target) => {
|
|
668
|
-
const id = destinationId(target, key.name);
|
|
669
|
-
const receipt = latest.get(secretKey(target, key.name)) ?? ours.find((r) => r.destinationId === id);
|
|
670
|
-
const needs = (reason, approval) => ({
|
|
671
|
-
id,
|
|
672
|
-
target,
|
|
673
|
-
receipt,
|
|
674
|
-
approval: { reason, approval }
|
|
675
|
-
});
|
|
676
|
-
if (!receipt) {
|
|
677
|
-
return needs(published ? "new destination" : "no receipt", `first write to ${id} (account ${target.account})`);
|
|
678
|
-
}
|
|
679
|
-
if (receipt.account.pinned !== target.account) {
|
|
680
|
-
return needs("account changed", `${id} account changed from ${receipt.account.pinned} to ${target.account}`);
|
|
681
|
-
}
|
|
682
|
-
if (!receipt.source || !sameRef(receipt.source, entry.ref)) {
|
|
683
|
-
const before = receipt.source ? describeRef(receipt.source) : "an item its receipt doesn't record";
|
|
684
|
-
return needs("item changed", `${id} was last published from ${before}, and now from ${describeRef(entry.ref)}`);
|
|
685
|
-
}
|
|
686
|
-
return { id, target, receipt, approval: null };
|
|
687
|
-
});
|
|
688
|
-
}
|
|
689
|
-
function latestPerSecret(receipts) {
|
|
690
|
-
const latest = new Map;
|
|
691
|
-
for (const receipt of receipts) {
|
|
692
|
-
const seen = latest.get(receiptSecretKey(receipt));
|
|
693
|
-
if (!seen || seen.at < receipt.at)
|
|
694
|
-
latest.set(receiptSecretKey(receipt), receipt);
|
|
695
|
-
}
|
|
696
|
-
return [...latest.values()];
|
|
697
|
-
}
|
|
698
|
-
function describeRef(ref) {
|
|
699
|
-
return `${formatReference(ref)} (1Password account ${ref.account})`;
|
|
700
|
-
}
|
|
701
|
-
// ../../packages/core/src/rotations.ts
|
|
702
|
-
var ROTATIONS_VERSION = 2;
|
|
703
|
-
var ROTATION_STAGES = ["issuing", "issued", "stored", "published", "revoked"];
|
|
704
|
-
var emptyRotations = () => ({ version: ROTATIONS_VERSION, rotations: [] });
|
|
705
|
-
async function loadRotations(files, path) {
|
|
706
|
-
const data = await readVersionedJson(files, path, [1, ROTATIONS_VERSION], "rotations file");
|
|
707
|
-
if (!data)
|
|
708
|
-
return emptyRotations();
|
|
709
|
-
const rotations = Array.isArray(data.rotations) ? data.rotations.map((r) => isRecord(r) ? {
|
|
710
|
-
...r,
|
|
711
|
-
mapFile: data.version === ROTATIONS_VERSION ? r.mapFile : null,
|
|
712
|
-
item: storedRefWithPasswordDefault(r.item) ?? r.item
|
|
713
|
-
} : r) : data.rotations;
|
|
714
|
-
if (!Array.isArray(rotations) || !rotations.every(isRotation)) {
|
|
715
|
-
throw new Error(`${path}: the rotations file's "rotations" must be a list of rotations`);
|
|
716
|
-
}
|
|
717
|
-
return { version: ROTATIONS_VERSION, rotations };
|
|
718
|
-
}
|
|
719
|
-
async function saveRotations(files, path, data) {
|
|
720
|
-
await writeJsonAtomic(files, path, data);
|
|
721
|
-
}
|
|
722
|
-
function unfinishedRotation(data, owner, item) {
|
|
723
|
-
return data.rotations.find((r) => ownedBy(r, owner) && sameRef(r.item, item) && r.stage !== "revoked");
|
|
724
|
-
}
|
|
725
|
-
function rotateCommand(keyId, environment, fallback) {
|
|
726
|
-
return `keypin rotate ${keyId}${envFlag(environment, fallback)}`;
|
|
727
|
-
}
|
|
728
|
-
function putRotation(data, rotation) {
|
|
729
|
-
return {
|
|
730
|
-
...data,
|
|
731
|
-
rotations: [...data.rotations.filter((r) => r.id !== rotation.id), rotation]
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
function dropRotation(data, id) {
|
|
735
|
-
return { ...data, rotations: data.rotations.filter((r) => r.id !== id) };
|
|
736
|
-
}
|
|
737
|
-
var isText2 = (value) => typeof value === "string";
|
|
738
|
-
var isTextOrNull2 = (value) => value === null || typeof value === "string";
|
|
739
|
-
function isTokenRecord(t) {
|
|
740
|
-
return isRecord(t) && isText2(t.name) && [t.id, t.expiresOn, t.generation].every(isTextOrNull2);
|
|
741
|
-
}
|
|
742
|
-
function isRotation(r) {
|
|
743
|
-
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);
|
|
744
|
-
}
|
|
745
|
-
// ../../packages/core/src/status.ts
|
|
746
|
-
var NOTICES = ["due-soon", "never-published", "rotation-unfinished"];
|
|
747
|
-
function buildStatus(input) {
|
|
748
|
-
if (!isDay(input.today))
|
|
749
|
-
throw new Error(`today must be YYYY-MM-DD, got "${input.today}"`);
|
|
750
|
-
const rows = [];
|
|
751
|
-
const problems = [];
|
|
752
|
-
for (const project of input.registry.projects) {
|
|
753
|
-
const result = input.maps.get(project);
|
|
754
|
-
if (!result) {
|
|
755
|
-
problems.push({
|
|
756
|
-
kind: "no-map",
|
|
757
|
-
severity: "problem",
|
|
758
|
-
project,
|
|
759
|
-
message: `${project} has no readable keypin.toml`
|
|
760
|
-
});
|
|
761
|
-
continue;
|
|
762
|
-
}
|
|
763
|
-
if (!result.ok) {
|
|
764
|
-
problems.push({
|
|
765
|
-
kind: "bad-map",
|
|
766
|
-
severity: "problem",
|
|
767
|
-
project,
|
|
768
|
-
message: result.errors.join(`
|
|
769
|
-
`)
|
|
770
|
-
});
|
|
771
|
-
continue;
|
|
772
|
-
}
|
|
773
|
-
const latest = new Map(latestPerSecret(input.receipts).map((r) => [receiptSecretKey(r), r]));
|
|
774
|
-
for (const key of result.map.keys) {
|
|
775
|
-
for (const environment of result.map.environments) {
|
|
776
|
-
const entry = key.environments[environment];
|
|
777
|
-
if (!entry)
|
|
778
|
-
continue;
|
|
779
|
-
const where = { project, keyId: key.name, environment };
|
|
780
|
-
const owner = { keyId: key.name, environment, mapFile: result.map.file };
|
|
781
|
-
const label = `${key.name} (${environment})`;
|
|
782
|
-
const add = (kind, message, extra = {}) => problems.push({
|
|
783
|
-
kind,
|
|
784
|
-
severity: NOTICES.includes(kind) ? "notice" : "problem",
|
|
785
|
-
...where,
|
|
786
|
-
...extra,
|
|
787
|
-
message
|
|
788
|
-
});
|
|
789
|
-
const metadata = input.metadata(entry.ref);
|
|
790
|
-
const rotateEvery = key.rotateEvery;
|
|
791
|
-
const rotated = metadata?.rotated ?? null;
|
|
792
|
-
const due = rotationDue({ label, metadata, rotated, rotateEvery, today: input.today, add });
|
|
793
|
-
const current = input.generation?.(key.name, environment);
|
|
794
|
-
const published = input.receipts.some((r) => ownedBy(r, owner));
|
|
795
|
-
const unpublished = [];
|
|
796
|
-
const publish = `keypin publish ${key.name}${envFlag(environment, publishEnvironment(result.map))}`;
|
|
797
|
-
const destinations = entry.publish.map((target) => {
|
|
798
|
-
const id = destinationId(target, key.name);
|
|
799
|
-
const last = latest.get(secretKey(target, key.name));
|
|
800
|
-
const ours = last && (ownedBy(last, owner) || last.source !== null && sameRef(last.source, entry.ref));
|
|
801
|
-
const receipt = ours ? last : undefined;
|
|
802
|
-
if (!receipt) {
|
|
803
|
-
if (last) {
|
|
804
|
-
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 });
|
|
805
|
-
} else if (published) {
|
|
806
|
-
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 });
|
|
807
|
-
} else {
|
|
808
|
-
unpublished.push(id);
|
|
809
|
-
}
|
|
810
|
-
return { destinationId: id, account: target.account, receipt: null, stale: null };
|
|
811
|
-
}
|
|
812
|
-
const stale = current === undefined ? null : receipt.generation !== current;
|
|
813
|
-
if (stale) {
|
|
814
|
-
add("stale-receipt", `${label}: ${id} last got generation ${receipt.generation}, and the value is now ${current}`, { destinationId: id });
|
|
815
|
-
}
|
|
816
|
-
const { generation, at } = receipt;
|
|
817
|
-
return {
|
|
818
|
-
destinationId: id,
|
|
819
|
-
account: target.account,
|
|
820
|
-
receipt: { generation, at, publisher: receipt.account.publisher },
|
|
821
|
-
stale
|
|
822
|
-
};
|
|
823
|
-
});
|
|
824
|
-
if (unpublished.length) {
|
|
825
|
-
add("never-published", `${label}: not published yet to ${unpublished.join(", ")}; run ${publish}`);
|
|
826
|
-
}
|
|
827
|
-
const rotation = unfinishedRotation({ version: ROTATIONS_VERSION, rotations: [...input.rotations ?? []] }, owner, entry.ref);
|
|
828
|
-
if (rotation) {
|
|
829
|
-
add("rotation-unfinished", `${label}: a rotation started ${rotation.startedAt} is at stage "${rotation.stage}"; run ${rotateCommand(key.name, environment, publishEnvironment(result.map))} to continue`);
|
|
830
|
-
}
|
|
831
|
-
rows.push({
|
|
832
|
-
...where,
|
|
833
|
-
ref: entry.ref,
|
|
834
|
-
rotated,
|
|
835
|
-
rotateEvery,
|
|
836
|
-
due,
|
|
837
|
-
destinations
|
|
838
|
-
});
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
return { rows, problems };
|
|
843
|
-
}
|
|
844
|
-
function rotationDue(input) {
|
|
845
|
-
const { label, metadata, rotated, rotateEvery, today, add } = input;
|
|
846
|
-
if (!metadata) {
|
|
847
|
-
add("rotation-unreadable", `${label}: the vault item's rotated date couldn't be read, so whether it's due is unknown`);
|
|
848
|
-
return null;
|
|
849
|
-
}
|
|
850
|
-
if (!rotated || !isDay(rotated)) {
|
|
851
|
-
add("no-rotation-date", `${label}: ${rotated ? `rotated "${rotated}" isn't YYYY-MM-DD` : "no rotated date"}`);
|
|
852
|
-
return null;
|
|
853
|
-
}
|
|
854
|
-
const days = periodDays(rotateEvery);
|
|
855
|
-
if (days === undefined) {
|
|
856
|
-
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"`);
|
|
857
|
-
return null;
|
|
858
|
-
}
|
|
859
|
-
if (days === null)
|
|
860
|
-
return null;
|
|
861
|
-
const due = addDays(rotated, days);
|
|
862
|
-
if (due < today)
|
|
863
|
-
add("overdue", `${label}: was due ${due} (rotated ${rotated}, every ${rotateEvery})`);
|
|
864
|
-
else if (due <= addDays(today, DUE_SOON_DAYS))
|
|
865
|
-
add("due-soon", `${label}: is due ${due} (rotated ${rotated}, every ${rotateEvery})`);
|
|
866
|
-
return due;
|
|
867
|
-
}
|
|
868
|
-
// ../../packages/core/src/discover.ts
|
|
869
|
-
var {TOML: TOML2 } = globalThis.Bun;
|
|
870
|
-
var SKIPPED_FOLDERS = new Set([
|
|
871
|
-
".git",
|
|
872
|
-
"node_modules",
|
|
873
|
-
".wrangler",
|
|
874
|
-
"dist",
|
|
875
|
-
"build",
|
|
876
|
-
"out",
|
|
877
|
-
".output",
|
|
878
|
-
".next",
|
|
879
|
-
".nuxt",
|
|
880
|
-
".svelte-kit",
|
|
881
|
-
".astro",
|
|
882
|
-
".turbo",
|
|
883
|
-
".vercel",
|
|
884
|
-
".netlify",
|
|
885
|
-
".cache",
|
|
886
|
-
".parcel-cache",
|
|
887
|
-
"coverage",
|
|
888
|
-
".venv",
|
|
889
|
-
"venv",
|
|
890
|
-
"__pycache__",
|
|
891
|
-
"target",
|
|
892
|
-
"vendor",
|
|
893
|
-
"Pods",
|
|
894
|
-
"DerivedData"
|
|
895
|
-
]);
|
|
896
|
-
var ENV_FILE = /^(\.env|\.dev\.vars)(\..+)?$/;
|
|
897
|
-
var EXPECTED_FILE = /\.(example|sample|template)$/;
|
|
898
|
-
function envFileKind(fileName) {
|
|
899
|
-
if (!ENV_FILE.test(fileName))
|
|
900
|
-
return null;
|
|
901
|
-
return EXPECTED_FILE.test(fileName) ? "expected" : "set";
|
|
902
|
-
}
|
|
903
|
-
var WRANGLER_FILES = [
|
|
904
|
-
"wrangler.toml",
|
|
905
|
-
"wrangler.json",
|
|
906
|
-
"wrangler.jsonc"
|
|
907
|
-
];
|
|
908
|
-
var DOTENV_LINE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
|
|
909
|
-
function envNames(text) {
|
|
910
|
-
return [...envValues(text).keys()];
|
|
911
|
-
}
|
|
912
|
-
function envValues(text) {
|
|
913
|
-
const values = new Map;
|
|
914
|
-
for (const match of text.replace(/\r\n?/g, `
|
|
915
|
-
`).matchAll(DOTENV_LINE)) {
|
|
916
|
-
if (match[1])
|
|
917
|
-
values.set(match[1], new Secret(dotenvValue(match[2] ?? "")));
|
|
918
|
-
}
|
|
919
|
-
return values;
|
|
920
|
-
}
|
|
921
|
-
function dotenvValue(raw) {
|
|
922
|
-
const value = raw.trim();
|
|
923
|
-
const unquoted = value.replace(/^(['"`])([\s\S]*)\1$/, "$2");
|
|
924
|
-
return value.startsWith('"') ? unquoted.replace(/\\n/g, `
|
|
925
|
-
`).replace(/\\r/g, "\r") : unquoted;
|
|
926
|
-
}
|
|
927
|
-
function draftItemName(project, environment, name) {
|
|
928
|
-
const folder = project.replace(/[^A-Za-z0-9 ._-]/g, "-");
|
|
929
|
-
return `${folder} ${environment} ${name.toLowerCase().replaceAll("_", " ").trim()}`;
|
|
930
|
-
}
|
|
931
|
-
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;
|
|
932
|
-
function workflowRefs(text) {
|
|
933
|
-
let data;
|
|
934
|
-
try {
|
|
935
|
-
data = Bun.YAML.parse(text);
|
|
936
|
-
} catch {
|
|
937
|
-
return null;
|
|
938
|
-
}
|
|
939
|
-
const refs = {
|
|
940
|
-
secrets: new Set,
|
|
941
|
-
vars: new Set,
|
|
942
|
-
environments: new Set,
|
|
943
|
-
hidesUses: false
|
|
944
|
-
};
|
|
945
|
-
const scan = (expression) => {
|
|
946
|
-
if (/toJSON\(\s*secrets\s*\)/.test(expression))
|
|
947
|
-
refs.hidesUses = true;
|
|
948
|
-
for (const match of expression.matchAll(CONTEXT_REF)) {
|
|
949
|
-
const name = (match[2] ?? match[3])?.toUpperCase();
|
|
950
|
-
if (!name)
|
|
951
|
-
continue;
|
|
952
|
-
(match[1] === "secrets" ? refs.secrets : refs.vars).add(name);
|
|
953
|
-
}
|
|
954
|
-
};
|
|
955
|
-
const visit = (value, key) => {
|
|
956
|
-
if (typeof value === "string") {
|
|
957
|
-
if (key === "if" && !value.includes("${{"))
|
|
958
|
-
scan(withoutStrings(value));
|
|
959
|
-
for (const expression of expressions(value))
|
|
960
|
-
scan(expression);
|
|
961
|
-
if (key === "secrets" && value.trim() === "inherit")
|
|
962
|
-
refs.hidesUses = true;
|
|
963
|
-
} else if (Array.isArray(value)) {
|
|
964
|
-
for (const item of value)
|
|
965
|
-
visit(item, null);
|
|
966
|
-
} else if (isRecord(value)) {
|
|
967
|
-
for (const [k, v] of Object.entries(value))
|
|
968
|
-
visit(v, k);
|
|
969
|
-
}
|
|
970
|
-
};
|
|
971
|
-
visit(data, null);
|
|
972
|
-
const jobs = isRecord(data) && isRecord(data.jobs) ? Object.values(data.jobs) : [];
|
|
973
|
-
for (const job of jobs) {
|
|
974
|
-
const environment = isRecord(job) ? job.environment : undefined;
|
|
975
|
-
const name = isRecord(environment) ? environment.name : environment;
|
|
976
|
-
if (typeof name === "string" && name.trim())
|
|
977
|
-
refs.environments.add(name);
|
|
978
|
-
}
|
|
979
|
-
return {
|
|
980
|
-
secrets: [...refs.secrets],
|
|
981
|
-
vars: [...refs.vars],
|
|
982
|
-
environments: [...refs.environments],
|
|
983
|
-
hidesUses: refs.hidesUses
|
|
984
|
-
};
|
|
985
|
-
}
|
|
986
|
-
function expressions(text) {
|
|
987
|
-
const found = [];
|
|
988
|
-
for (let start = text.indexOf("${{");start !== -1; start = text.indexOf("${{", start)) {
|
|
989
|
-
let i = start + 3;
|
|
990
|
-
while (i < text.length && !text.startsWith("}}", i))
|
|
991
|
-
i = text[i] === "'" ? endOfString(text, i) : i + 1;
|
|
992
|
-
found.push(withoutStrings(text.slice(start + 3, i)));
|
|
993
|
-
start = i + 2;
|
|
994
|
-
}
|
|
995
|
-
return found;
|
|
996
|
-
}
|
|
997
|
-
function withoutStrings(expression) {
|
|
998
|
-
let code = "";
|
|
999
|
-
for (let i = 0;i < expression.length; ) {
|
|
1000
|
-
if (expression[i] !== "'") {
|
|
1001
|
-
code += expression[i];
|
|
1002
|
-
i++;
|
|
1003
|
-
continue;
|
|
1004
|
-
}
|
|
1005
|
-
const end = endOfString(expression, i);
|
|
1006
|
-
const literal = expression.slice(i, end);
|
|
1007
|
-
code += /(?:secrets|vars)\s*\[\s*$/.test(code) ? literal : "''";
|
|
1008
|
-
i = end;
|
|
1009
|
-
}
|
|
1010
|
-
return code;
|
|
1011
|
-
}
|
|
1012
|
-
function endOfString(text, open) {
|
|
1013
|
-
let i = open + 1;
|
|
1014
|
-
while (i < text.length) {
|
|
1015
|
-
if (text[i] !== "'")
|
|
1016
|
-
i++;
|
|
1017
|
-
else if (text[i + 1] === "'")
|
|
1018
|
-
i += 2;
|
|
1019
|
-
else
|
|
1020
|
-
return i + 1;
|
|
1021
|
-
}
|
|
1022
|
-
return i;
|
|
1023
|
-
}
|
|
1024
|
-
var ACCOUNT_ID2 = /^[0-9a-f]{32}$/;
|
|
1025
|
-
function wranglerWorkers(text, config) {
|
|
1026
|
-
let data;
|
|
1027
|
-
try {
|
|
1028
|
-
data = config.endsWith(".toml") ? TOML2.parse(text) : Bun.JSONC.parse(text);
|
|
1029
|
-
} catch {
|
|
1030
|
-
return { ok: false };
|
|
1031
|
-
}
|
|
1032
|
-
if (!isRecord(data))
|
|
1033
|
-
return { ok: false };
|
|
1034
|
-
const topName = stringOf(data.name);
|
|
1035
|
-
const topAccount = stringOf(data.account_id);
|
|
1036
|
-
const workers = [declaration(config, null, data, topName, topAccount)];
|
|
1037
|
-
const envs = isRecord(data.env) ? data.env : {};
|
|
1038
|
-
for (const [env, raw] of Object.entries(envs)) {
|
|
1039
|
-
if (!isRecord(raw))
|
|
1040
|
-
continue;
|
|
1041
|
-
const name = stringOf(raw.name) ?? (topName ? `${topName}-${env}` : null);
|
|
1042
|
-
workers.push(declaration(config, env, raw, name, stringOf(raw.account_id) ?? topAccount));
|
|
1043
|
-
}
|
|
1044
|
-
return { ok: true, workers };
|
|
1045
|
-
}
|
|
1046
|
-
function declaration(config, env, table, worker, account) {
|
|
1047
|
-
const secrets = isRecord(table.secrets) ? table.secrets : null;
|
|
1048
|
-
const required = Array.isArray(secrets?.required) ? secrets.required.filter((n) => typeof n === "string") : null;
|
|
1049
|
-
return {
|
|
1050
|
-
config,
|
|
1051
|
-
env,
|
|
1052
|
-
worker,
|
|
1053
|
-
account: account && ACCOUNT_ID2.test(account) ? account : null,
|
|
1054
|
-
required,
|
|
1055
|
-
vars: isRecord(table.vars) ? Object.keys(table.vars) : []
|
|
1056
|
-
};
|
|
1057
|
-
}
|
|
1058
|
-
function stringOf(value) {
|
|
1059
|
-
return typeof value === "string" && value.trim() ? value : null;
|
|
1060
|
-
}
|
|
1061
|
-
var GITHUB_PROVIDED = "GITHUB_TOKEN";
|
|
1062
|
-
var LOCAL_KINDS = ["env-file"];
|
|
1063
|
-
var CLOUD_KINDS = ["github-secret", "worker-secret"];
|
|
1064
|
-
var VARIABLE_KINDS = ["worker-var", "workflow-var"];
|
|
1065
|
-
function buildDiscovery(input) {
|
|
1066
|
-
const sources = new Map;
|
|
1067
|
-
const add = (name, source) => {
|
|
1068
|
-
const list = sources.get(name) ?? [];
|
|
1069
|
-
list.push(source);
|
|
1070
|
-
sources.set(name, list);
|
|
1071
|
-
};
|
|
1072
|
-
const problems = [];
|
|
1073
|
-
const unknowns = [...input.unknowns];
|
|
1074
|
-
for (const file of input.envFiles) {
|
|
1075
|
-
for (const name of file.names) {
|
|
1076
|
-
add(name, file.kind === "set" ? { kind: "env-file", path: file.path, tracked: file.tracked } : { kind: "example-file", path: file.path });
|
|
1077
|
-
}
|
|
1078
|
-
if (file.kind === "set" && file.tracked === true) {
|
|
1079
|
-
problems.push({
|
|
1080
|
-
kind: "tracked-env-file",
|
|
1081
|
-
path: file.path,
|
|
1082
|
-
message: `${file.path} is tracked by git, so its values may be committed`
|
|
1083
|
-
});
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
const referenced = new Map;
|
|
1087
|
-
let hidesUses = false;
|
|
1088
|
-
for (const workflow of input.workflows) {
|
|
1089
|
-
hidesUses ||= workflow.refs.hidesUses;
|
|
1090
|
-
for (const name of workflow.refs.secrets) {
|
|
1091
|
-
if (name === GITHUB_PROVIDED)
|
|
1092
|
-
continue;
|
|
1093
|
-
const environments = referenced.get(name) ?? new Set;
|
|
1094
|
-
for (const environment of workflow.refs.environments)
|
|
1095
|
-
environments.add(environment);
|
|
1096
|
-
referenced.set(name, environments);
|
|
1097
|
-
add(name, { kind: "workflow-secret", path: workflow.path });
|
|
1098
|
-
}
|
|
1099
|
-
for (const name of workflow.refs.vars)
|
|
1100
|
-
add(name, { kind: "workflow-var", path: workflow.path });
|
|
1101
|
-
}
|
|
1102
|
-
const environments = new Set(input.workflows.flatMap((w) => w.refs.environments));
|
|
1103
|
-
if (input.github && environments.size) {
|
|
1104
|
-
unknowns.push({
|
|
1105
|
-
what: `GitHub environment secrets (${[...environments].join(", ")})`,
|
|
1106
|
-
reason: "discover reads repo secrets only",
|
|
1107
|
-
cloud: true
|
|
1108
|
-
});
|
|
1109
|
-
}
|
|
1110
|
-
if (input.github) {
|
|
1111
|
-
const { repo, read } = input.github;
|
|
1112
|
-
if (read.ok) {
|
|
1113
|
-
const present = new Set(read.secrets.map((s) => s.name.toUpperCase()));
|
|
1114
|
-
for (const secret of read.secrets) {
|
|
1115
|
-
add(secret.name, { kind: "github-secret", repo, updatedAt: secret.updatedAt });
|
|
1116
|
-
if (!referenced.has(secret.name.toUpperCase())) {
|
|
1117
|
-
problems.push({
|
|
1118
|
-
kind: "unreferenced-github-secret",
|
|
1119
|
-
name: secret.name,
|
|
1120
|
-
message: `no workflow here references this ${repo} secret${hidesUses ? " (a workflow passes secrets on, which can hide a use)" : ""}`
|
|
1121
|
-
});
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
for (const [name, environments] of referenced) {
|
|
1125
|
-
if (present.has(name))
|
|
1126
|
-
continue;
|
|
1127
|
-
const maybe = environments.size ? `; it may be a secret of the environment ${[...environments].join(" or ")}, which discover doesn't read` : "";
|
|
1128
|
-
problems.push({
|
|
1129
|
-
kind: "missing-github-secret",
|
|
1130
|
-
name,
|
|
1131
|
-
message: `a workflow references it, and ${repo} has no repo secret with this name${maybe}`
|
|
1132
|
-
});
|
|
1133
|
-
}
|
|
1134
|
-
} else {
|
|
1135
|
-
unknowns.push({
|
|
1136
|
-
what: `GitHub Actions secrets of ${repo}`,
|
|
1137
|
-
reason: read.reason,
|
|
1138
|
-
cloud: true
|
|
1139
|
-
});
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
for (const worker of input.workers) {
|
|
1143
|
-
const label = workerLabel(worker);
|
|
1144
|
-
for (const name of worker.required ?? []) {
|
|
1145
|
-
add(name, { kind: "worker-required", path: worker.config, worker: worker.worker });
|
|
1146
|
-
}
|
|
1147
|
-
for (const name of worker.vars) {
|
|
1148
|
-
add(name, { kind: "worker-var", path: worker.config, worker: worker.worker });
|
|
1149
|
-
}
|
|
1150
|
-
if (!worker.worker || !worker.account) {
|
|
1151
|
-
unknowns.push({
|
|
1152
|
-
what: `Worker secrets of ${label}`,
|
|
1153
|
-
cloud: true,
|
|
1154
|
-
reason: worker.worker ? `${worker.config} has no account_id, and discover doesn't guess an account` : `${worker.config} names no Worker`
|
|
1155
|
-
});
|
|
1156
|
-
continue;
|
|
1157
|
-
}
|
|
1158
|
-
const read = worker.read;
|
|
1159
|
-
if (!read)
|
|
1160
|
-
continue;
|
|
1161
|
-
if (!read.ok) {
|
|
1162
|
-
unknowns.push({ what: `Worker secrets of ${label}`, reason: read.reason, cloud: true });
|
|
1163
|
-
continue;
|
|
1164
|
-
}
|
|
1165
|
-
const present = new Set(read.secrets.map((s) => s.name));
|
|
1166
|
-
for (const secret of read.secrets) {
|
|
1167
|
-
add(secret.name, { kind: "worker-secret", worker: worker.worker, account: worker.account });
|
|
1168
|
-
}
|
|
1169
|
-
for (const name of worker.required ?? []) {
|
|
1170
|
-
if (present.has(name))
|
|
1171
|
-
continue;
|
|
1172
|
-
problems.push({
|
|
1173
|
-
kind: "missing-worker-secret",
|
|
1174
|
-
name,
|
|
1175
|
-
message: `${worker.config} requires ${name}, and the Worker ${worker.worker} doesn't have it`
|
|
1176
|
-
});
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
for (const key of input.map?.keys ?? []) {
|
|
1180
|
-
add(key.name, { kind: "map", path: input.map?.file ?? "keypin.toml", keyId: key.name });
|
|
1181
|
-
}
|
|
1182
|
-
const cloudUnknown = unknowns.some((u) => u.cloud);
|
|
1183
|
-
const names = [...sources.entries()].map(([name, list]) => {
|
|
1184
|
-
const local = list.some((s) => LOCAL_KINDS.includes(s.kind));
|
|
1185
|
-
const cloud = list.some((s) => CLOUD_KINDS.includes(s.kind));
|
|
1186
|
-
const configured = list.filter((s) => s.kind !== "map");
|
|
1187
|
-
const variable = configured.length > 0 && configured.every((s) => VARIABLE_KINDS.includes(s.kind));
|
|
1188
|
-
return {
|
|
1189
|
-
name,
|
|
1190
|
-
where: local && cloud ? "both" : local ? "local" : cloud ? "cloud" : variable ? "variable" : "declared",
|
|
1191
|
-
cloudUnknown: !cloud && cloudUnknown,
|
|
1192
|
-
mapped: list.flatMap((s) => s.kind === "map" ? [s.keyId] : []),
|
|
1193
|
-
sources: list,
|
|
1194
|
-
problems: problems.filter((p) => p.name?.toUpperCase() === name.toUpperCase()).map((p) => p.message)
|
|
1195
|
-
};
|
|
1196
|
-
}).sort((a, b) => a.name.localeCompare(b.name));
|
|
1197
|
-
return { names, problems, unknowns };
|
|
1198
|
-
}
|
|
1199
|
-
function workerLabel(worker) {
|
|
1200
|
-
const name = worker.worker ?? "(unnamed)";
|
|
1201
|
-
return worker.env ? `${name} (${worker.config}, env ${worker.env})` : `${name} (${worker.config})`;
|
|
1202
|
-
}
|
|
1203
|
-
function draftMap(names, options) {
|
|
1204
|
-
const lines = [];
|
|
1205
|
-
const runName = runEnvironment(options);
|
|
1206
|
-
const publishName = publishEnvironment(options);
|
|
1207
|
-
const vault = options.map?.vault ?? "<your vault>";
|
|
1208
|
-
const from = (environment, name) => str(formatReference({
|
|
1209
|
-
vault,
|
|
1210
|
-
item: draftItemName(options.project, environment, name),
|
|
1211
|
-
section: null,
|
|
1212
|
-
field: "password"
|
|
1213
|
-
}));
|
|
1214
|
-
for (const row of names) {
|
|
1215
|
-
if (row.mapped.length)
|
|
1216
|
-
continue;
|
|
1217
|
-
const local = row.sources.some((s) => s.kind === "env-file");
|
|
1218
|
-
const seen = new Set;
|
|
1219
|
-
const publish = row.sources.flatMap((s) => {
|
|
1220
|
-
const place = s.kind === "worker-secret" ? `${s.account}/${s.worker}` : s.kind === "github-secret" ? s.repo.toLowerCase() : "";
|
|
1221
|
-
if (!place || seen.has(place))
|
|
1222
|
-
return [];
|
|
1223
|
-
seen.add(place);
|
|
1224
|
-
if (s.kind === "worker-secret")
|
|
1225
|
-
return [
|
|
1226
|
-
['to = "cloudflare-worker"', `account = ${str(s.account)}`, `worker = ${str(s.worker)}`]
|
|
1227
|
-
];
|
|
1228
|
-
if (s.kind === "github-secret") {
|
|
1229
|
-
const account = options.githubAccount;
|
|
1230
|
-
const owner = s.repo.split("/")[0]?.toLowerCase();
|
|
1231
|
-
return [
|
|
1232
|
-
[
|
|
1233
|
-
'to = "github-actions"',
|
|
1234
|
-
`repo = ${str(s.repo)}`,
|
|
1235
|
-
...account && account.toLowerCase() !== owner ? [`account = ${str(account)}`] : []
|
|
1236
|
-
]
|
|
1237
|
-
];
|
|
1238
|
-
}
|
|
1239
|
-
return [];
|
|
1240
|
-
});
|
|
1241
|
-
if (!local && !publish.length)
|
|
1242
|
-
continue;
|
|
1243
|
-
if (!isVariableName(row.name))
|
|
1244
|
-
continue;
|
|
1245
|
-
const name = row.name;
|
|
1246
|
-
lines.push("", `[keys.${name}]`, `rotate_every = "90d"`);
|
|
1247
|
-
if (local && !(publish.length && runName === publishName)) {
|
|
1248
|
-
lines.push(`${runName} = ${from(runName, name)}`);
|
|
1249
|
-
}
|
|
1250
|
-
if (publish.length) {
|
|
1251
|
-
lines.push("", `[keys.${name}.${publishName}]`, `from = ${from(publishName, name)}`);
|
|
1252
|
-
for (const target of publish) {
|
|
1253
|
-
lines.push("", `[[keys.${name}.${publishName}.publish]]`, ...target);
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
}
|
|
1257
|
-
if (!lines.length)
|
|
1258
|
-
return null;
|
|
1259
|
-
const account = options.map?.account ?? "<your 1Password account>";
|
|
1260
|
-
const header = [
|
|
1261
|
-
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.",
|
|
1262
|
-
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.",
|
|
1263
|
-
...options.environments.join() === DEFAULT_ENVIRONMENTS.join() ? [] : ["", `environments = [${options.environments.map(str).join(", ")}]`],
|
|
1264
|
-
"",
|
|
1265
|
-
"[1password]",
|
|
1266
|
-
`account = ${str(account)}`
|
|
1267
|
-
];
|
|
1268
|
-
return `${[...header, ...lines].join(`
|
|
1269
|
-
`)}
|
|
1270
|
-
`;
|
|
1271
|
-
}
|
|
1272
|
-
function str(value) {
|
|
1273
|
-
return JSON.stringify(value);
|
|
1274
|
-
}
|
|
1275
|
-
// ../../packages/destination-cloudflare/src/token.ts
|
|
1276
|
-
import { execFile } from "child_process";
|
|
1277
|
-
import { readFile } from "fs/promises";
|
|
1278
|
-
import { homedir } from "os";
|
|
1279
|
-
import { join } from "path";
|
|
1280
|
-
var WRANGLER_CONFIG = join(homedir(), "Library/Preferences/.wrangler/config/default.toml");
|
|
1281
|
-
async function wranglerToken(path = WRANGLER_CONFIG) {
|
|
1282
|
-
let login = await readLogin(path);
|
|
1283
|
-
if (login.expired) {
|
|
1284
|
-
await refresh();
|
|
1285
|
-
login = await readLogin(path);
|
|
1286
|
-
if (login.expired)
|
|
1287
|
-
throw new Error("the wrangler login is still expired after `wrangler whoami`; run `wrangler login`");
|
|
1288
|
-
}
|
|
1289
|
-
return login.token;
|
|
1290
|
-
}
|
|
1291
|
-
async function currentWranglerToken(path = WRANGLER_CONFIG) {
|
|
1292
|
-
const login = await readLogin(path);
|
|
1293
|
-
if (login.expired)
|
|
1294
|
-
throw new Error("the wrangler login has expired; run `wrangler whoami`");
|
|
1295
|
-
return login.token;
|
|
1296
|
-
}
|
|
1297
|
-
async function readLogin(path) {
|
|
1298
|
-
let text;
|
|
1299
|
-
try {
|
|
1300
|
-
text = await readFile(path, "utf8");
|
|
1301
|
-
} catch {
|
|
1302
|
-
throw new Error(`no wrangler login at ${path}; run \`wrangler login\``);
|
|
1303
|
-
}
|
|
1304
|
-
const token = tomlString(text, "oauth_token");
|
|
1305
|
-
if (!token)
|
|
1306
|
-
throw new Error(`${path} has no oauth_token; run \`wrangler login\``);
|
|
1307
|
-
const expires = Date.parse(tomlString(text, "expiration_time") ?? "");
|
|
1308
|
-
return { token, expired: Number.isNaN(expires) || expires <= Date.now() + 60000 };
|
|
1309
|
-
}
|
|
1310
|
-
function tomlString(text, key) {
|
|
1311
|
-
for (const line of text.split(`
|
|
1312
|
-
`)) {
|
|
1313
|
-
const match = /^\s*([A-Za-z_]+)\s*=\s*"([^"]*)"\s*$/.exec(line);
|
|
1314
|
-
if (match?.[1] === key)
|
|
1315
|
-
return match[2] ?? null;
|
|
1316
|
-
}
|
|
1317
|
-
return null;
|
|
1318
|
-
}
|
|
1319
|
-
function refresh() {
|
|
1320
|
-
return new Promise((resolve, reject) => {
|
|
1321
|
-
execFile("wrangler", ["whoami"], (error) => {
|
|
1322
|
-
if (error)
|
|
1323
|
-
reject(new Error("the wrangler login has expired, and `wrangler whoami` couldn't refresh it"));
|
|
1324
|
-
else
|
|
1325
|
-
resolve();
|
|
1326
|
-
});
|
|
1327
|
-
});
|
|
1328
|
-
}
|
|
1329
|
-
|
|
1330
|
-
// ../../packages/destination-cloudflare/src/cloudflare.ts
|
|
1331
|
-
var API = "https://api.cloudflare.com/client/v4";
|
|
1332
|
-
var ACCOUNT_ID3 = /^[0-9a-f]{32}$/;
|
|
1333
|
-
var WORKER = /^[A-Za-z0-9_-]+$/;
|
|
1334
|
-
|
|
1335
|
-
class WorkerSecretDestination {
|
|
1336
|
-
capabilities = { write: true, accountCheck: true, evidence: true };
|
|
1337
|
-
#account;
|
|
1338
|
-
#worker;
|
|
1339
|
-
#tokenSource;
|
|
1340
|
-
#fetch;
|
|
1341
|
-
#token;
|
|
1342
|
-
#passed = false;
|
|
1343
|
-
constructor(options) {
|
|
1344
|
-
if (!ACCOUNT_ID3.test(options.account))
|
|
1345
|
-
throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
|
|
1346
|
-
if (!WORKER.test(options.worker))
|
|
1347
|
-
throw new Error(`"${options.worker}" isn't a Worker name`);
|
|
1348
|
-
this.#account = options.account;
|
|
1349
|
-
this.#worker = options.worker;
|
|
1350
|
-
this.#tokenSource = options.token ?? (() => wranglerToken());
|
|
1351
|
-
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
1352
|
-
}
|
|
1353
|
-
describe() {
|
|
1354
|
-
return `cloudflare worker ${this.#worker} in account ${this.#account} (worker secret)`;
|
|
1355
|
-
}
|
|
1356
|
-
async checkAccount() {
|
|
1357
|
-
this.#passed = false;
|
|
1358
|
-
const facts = { publisher: await this.#publisher(), expected: this.#account };
|
|
1359
|
-
const accounts = await this.#accountIds();
|
|
1360
|
-
if (!accounts.includes(this.#account)) {
|
|
1361
|
-
const reason = `the login can reach ${accounts.join(", ") || "no account"}, not ${this.#account}`;
|
|
1362
|
-
return { ...facts, destinationAccount: null, ok: false, reason };
|
|
1363
|
-
}
|
|
1364
|
-
const settings = await this.#request("GET", `${this.#base()}/settings`);
|
|
1365
|
-
if (settings.status === 404) {
|
|
1366
|
-
const reason = `account ${this.#account} has no Worker ${this.#worker}`;
|
|
1367
|
-
return { ...facts, destinationAccount: null, ok: false, reason };
|
|
1368
|
-
}
|
|
1369
|
-
if (settings.status !== 200)
|
|
1370
|
-
throw failure("GET", `${this.#base()}/settings`, settings);
|
|
1371
|
-
this.#passed = true;
|
|
1372
|
-
return { ...facts, destinationAccount: this.#account, ok: true };
|
|
1373
|
-
}
|
|
1374
|
-
async write(name, secret) {
|
|
1375
|
-
if (!this.#passed)
|
|
1376
|
-
throw new Error(`refusing to write to ${this.describe()}: checkAccount hasn't passed`);
|
|
1377
|
-
if (!name)
|
|
1378
|
-
throw new Error("a Worker secret needs a name");
|
|
1379
|
-
const path = `${this.#base()}/secrets`;
|
|
1380
|
-
const put = await this.#request("PUT", path, {
|
|
1381
|
-
name,
|
|
1382
|
-
text: secret.reveal(),
|
|
1383
|
-
type: "secret_text"
|
|
1384
|
-
});
|
|
1385
|
-
if (put.status !== 200)
|
|
1386
|
-
throw failure("PUT", path, put);
|
|
1387
|
-
const versions = await this.#request("GET", `${this.#base()}/versions?per_page=10`);
|
|
1388
|
-
if (versions.status !== 200)
|
|
1389
|
-
throw failure("GET", `${this.#base()}/versions`, versions);
|
|
1390
|
-
const newest = newestVersion(versions.body);
|
|
1391
|
-
return {
|
|
1392
|
-
destination: this.describe(),
|
|
1393
|
-
secret: name,
|
|
1394
|
-
versionId: newest.id,
|
|
1395
|
-
createdOn: newest.createdOn,
|
|
1396
|
-
triggeredBySecret: newest.triggeredBy === "secret",
|
|
1397
|
-
note: "a Worker's secret-change version covers all of its secrets, not only this one"
|
|
1398
|
-
};
|
|
1399
|
-
}
|
|
1400
|
-
#base() {
|
|
1401
|
-
return `/accounts/${this.#account}/workers/scripts/${this.#worker}`;
|
|
1402
|
-
}
|
|
1403
|
-
async#publisher() {
|
|
1404
|
-
const user = await this.#request("GET", "/user");
|
|
1405
|
-
const email = user.status === 200 ? objectField(user.body, "result").email : undefined;
|
|
1406
|
-
return typeof email === "string" ? email : "unknown (the token can't read /user)";
|
|
1407
|
-
}
|
|
1408
|
-
async#accountIds() {
|
|
1409
|
-
const ids = [];
|
|
1410
|
-
for (let page = 1;; page++) {
|
|
1411
|
-
const response = await this.#request("GET", `/accounts?per_page=50&page=${page}`);
|
|
1412
|
-
if (response.status !== 200)
|
|
1413
|
-
throw failure("GET", "/accounts", response);
|
|
1414
|
-
const result = response.body.result;
|
|
1415
|
-
if (!Array.isArray(result))
|
|
1416
|
-
throw new Error("Cloudflare's /accounts response has no result list");
|
|
1417
|
-
for (const account of result) {
|
|
1418
|
-
if (isRecord(account) && typeof account.id === "string")
|
|
1419
|
-
ids.push(account.id);
|
|
1420
|
-
}
|
|
1421
|
-
const pages = objectField(response.body, "result_info").total_pages;
|
|
1422
|
-
if (typeof pages !== "number" || page >= pages)
|
|
1423
|
-
return ids;
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
async#request(method, path, body) {
|
|
1427
|
-
this.#token ??= this.#tokenSource();
|
|
1428
|
-
const response = await this.#fetch(`${API}${path}`, {
|
|
1429
|
-
method,
|
|
1430
|
-
headers: {
|
|
1431
|
-
Authorization: `Bearer ${await this.#token}`,
|
|
1432
|
-
...body === undefined ? {} : { "Content-Type": "application/json" }
|
|
1433
|
-
},
|
|
1434
|
-
body: body === undefined ? undefined : JSON.stringify(body)
|
|
1435
|
-
});
|
|
1436
|
-
return { status: response.status, body: parseObject(await response.text()) };
|
|
1437
|
-
}
|
|
1438
|
-
}
|
|
1439
|
-
function failure(method, path, response) {
|
|
1440
|
-
const errors = response.body.errors;
|
|
1441
|
-
const codes = Array.isArray(errors) ? errors.map((e) => isRecord(e) ? e.code : undefined).filter((c) => typeof c === "string" || typeof c === "number") : [];
|
|
1442
|
-
const detail = codes.length ? `, codes ${codes.join(", ")}` : "";
|
|
1443
|
-
return new Error(`Cloudflare ${method} ${path.split("?")[0]} returned HTTP ${response.status}${detail}`);
|
|
1444
|
-
}
|
|
1445
|
-
function newestVersion(body) {
|
|
1446
|
-
const items = objectField(body, "result").items;
|
|
1447
|
-
if (!Array.isArray(items))
|
|
1448
|
-
throw new Error("Cloudflare's versions response has no items");
|
|
1449
|
-
const versions = items.map((item) => {
|
|
1450
|
-
const v = isRecord(item) ? item : {};
|
|
1451
|
-
const createdOn = objectField(v, "metadata").created_on;
|
|
1452
|
-
return {
|
|
1453
|
-
id: typeof v.id === "string" ? v.id : null,
|
|
1454
|
-
createdOn: typeof createdOn === "string" ? createdOn : null,
|
|
1455
|
-
triggeredBy: objectField(v, "annotations")["workers/triggered_by"]
|
|
1456
|
-
};
|
|
1457
|
-
});
|
|
1458
|
-
versions.sort((a, b) => Date.parse(b.createdOn ?? "") - Date.parse(a.createdOn ?? ""));
|
|
1459
|
-
const newest = versions[0];
|
|
1460
|
-
if (!newest?.id || !newest.createdOn)
|
|
1461
|
-
throw new Error("Cloudflare listed no version for the Worker after the write");
|
|
1462
|
-
return newest;
|
|
1463
|
-
}
|
|
1464
|
-
function parseObject(text) {
|
|
1465
|
-
try {
|
|
1466
|
-
const data = JSON.parse(text);
|
|
1467
|
-
return isRecord(data) ? data : {};
|
|
1468
|
-
} catch {
|
|
1469
|
-
return {};
|
|
1470
|
-
}
|
|
1471
|
-
}
|
|
1472
|
-
function objectField(data, field) {
|
|
1473
|
-
const value = data[field];
|
|
1474
|
-
return isRecord(value) ? value : {};
|
|
1475
|
-
}
|
|
1476
|
-
// ../../packages/destination-cloudflare/src/list.ts
|
|
1477
|
-
var API2 = "https://api.cloudflare.com/client/v4";
|
|
1478
|
-
var ACCOUNT_ID4 = /^[0-9a-f]{32}$/;
|
|
1479
|
-
var WORKER2 = /^[A-Za-z0-9_-]+$/;
|
|
1480
|
-
|
|
1481
|
-
class CloudflareReader {
|
|
1482
|
-
#tokenSource;
|
|
1483
|
-
#fetch;
|
|
1484
|
-
#token;
|
|
1485
|
-
#accounts;
|
|
1486
|
-
constructor(options) {
|
|
1487
|
-
this.#tokenSource = options.token;
|
|
1488
|
-
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
1489
|
-
}
|
|
1490
|
-
async listWorkerSecrets(account, worker) {
|
|
1491
|
-
if (!ACCOUNT_ID4.test(account))
|
|
1492
|
-
return { ok: false, reason: `"${account}" isn't a Cloudflare account ID` };
|
|
1493
|
-
if (!WORKER2.test(worker))
|
|
1494
|
-
return { ok: false, reason: `"${worker}" isn't a Worker name` };
|
|
1495
|
-
const accounts = await (this.#accounts ??= this.#accountIds());
|
|
1496
|
-
if (!Array.isArray(accounts))
|
|
1497
|
-
return { ok: false, reason: accounts.reason };
|
|
1498
|
-
if (!accounts.includes(account)) {
|
|
1499
|
-
return {
|
|
1500
|
-
ok: false,
|
|
1501
|
-
reason: `the wrangler login reaches ${accounts.join(", ") || "no account"}, not ${account}`
|
|
1502
|
-
};
|
|
1503
|
-
}
|
|
1504
|
-
const response = await this.#get(`/accounts/${account}/workers/scripts/${worker}/secrets`);
|
|
1505
|
-
if ("reason" in response)
|
|
1506
|
-
return { ok: false, reason: response.reason };
|
|
1507
|
-
if (response.status === 404)
|
|
1508
|
-
return { ok: false, reason: `account ${account} has no Worker named ${worker}` };
|
|
1509
|
-
if (response.status !== 200)
|
|
1510
|
-
return { ok: false, reason: `Cloudflare returned HTTP ${response.status}` };
|
|
1511
|
-
const result = response.body.result;
|
|
1512
|
-
if (!Array.isArray(result))
|
|
1513
|
-
return { ok: false, reason: "Cloudflare's secrets response has no result list" };
|
|
1514
|
-
return {
|
|
1515
|
-
ok: true,
|
|
1516
|
-
secrets: result.flatMap((s) => isRecord(s) && typeof s.name === "string" ? [{ name: s.name, updatedAt: null }] : [])
|
|
1517
|
-
};
|
|
1518
|
-
}
|
|
1519
|
-
async#accountIds() {
|
|
1520
|
-
const ids = [];
|
|
1521
|
-
for (let page = 1;; page++) {
|
|
1522
|
-
const response = await this.#get(`/accounts?per_page=50&page=${page}`);
|
|
1523
|
-
if ("reason" in response)
|
|
1524
|
-
return response;
|
|
1525
|
-
if (response.status !== 200)
|
|
1526
|
-
return { reason: `Cloudflare GET /accounts returned HTTP ${response.status}` };
|
|
1527
|
-
const result = response.body.result;
|
|
1528
|
-
if (!Array.isArray(result))
|
|
1529
|
-
return { reason: "Cloudflare's /accounts response has no list" };
|
|
1530
|
-
for (const account of result) {
|
|
1531
|
-
if (isRecord(account) && typeof account.id === "string")
|
|
1532
|
-
ids.push(account.id);
|
|
1533
|
-
}
|
|
1534
|
-
const info = response.body.result_info;
|
|
1535
|
-
const pages = isRecord(info) ? info.total_pages : undefined;
|
|
1536
|
-
if (typeof pages !== "number" || page >= pages)
|
|
1537
|
-
return ids;
|
|
1538
|
-
}
|
|
1539
|
-
}
|
|
1540
|
-
async#get(path) {
|
|
1541
|
-
let token;
|
|
1542
|
-
try {
|
|
1543
|
-
token = await (this.#token ??= this.#tokenSource());
|
|
1544
|
-
} catch (error) {
|
|
1545
|
-
return { reason: error instanceof Error ? error.message : "no Cloudflare token" };
|
|
1546
|
-
}
|
|
1547
|
-
const response = await this.#fetch(`${API2}${path}`, {
|
|
1548
|
-
method: "GET",
|
|
1549
|
-
headers: { Authorization: `Bearer ${token}` }
|
|
1550
|
-
});
|
|
1551
|
-
const body = await response.json().catch(() => null);
|
|
1552
|
-
return { status: response.status, body: isRecord(body) ? body : {} };
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
// ../../packages/destination-github/src/github.ts
|
|
1556
|
-
import sodium from "libsodium-wrappers";
|
|
1557
|
-
|
|
1558
|
-
// ../../packages/destination-github/src/token.ts
|
|
1559
|
-
import { execFile as execFile2 } from "child_process";
|
|
1560
|
-
function ghToken(login) {
|
|
1561
|
-
const env = { ...process.env };
|
|
1562
|
-
delete env.GH_TOKEN;
|
|
1563
|
-
delete env.GITHUB_TOKEN;
|
|
1564
|
-
const args = ["auth", "token", "--hostname", "github.com", "--user", login];
|
|
1565
|
-
return new Promise((resolve, reject) => {
|
|
1566
|
-
execFile2("gh", args, { env }, (error, stdout) => {
|
|
1567
|
-
const token = String(stdout).trim();
|
|
1568
|
-
if (error || !token)
|
|
1569
|
-
reject(new Error(`gh has no token for ${login}; run: gh auth login --hostname github.com`));
|
|
1570
|
-
else
|
|
1571
|
-
resolve(token);
|
|
1572
|
-
});
|
|
1573
|
-
});
|
|
1574
|
-
}
|
|
1575
|
-
|
|
1576
|
-
// ../../packages/destination-github/src/github.ts
|
|
1577
|
-
var API3 = "https://api.github.com";
|
|
1578
|
-
var REPO2 = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
|
|
1579
|
-
var SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1580
|
-
|
|
1581
|
-
class GitHubSecretDestination {
|
|
1582
|
-
capabilities = { write: true, accountCheck: true, evidence: true };
|
|
1583
|
-
#repo;
|
|
1584
|
-
#owner;
|
|
1585
|
-
#expected;
|
|
1586
|
-
#tokenSource;
|
|
1587
|
-
#fetch;
|
|
1588
|
-
#token;
|
|
1589
|
-
#passed = false;
|
|
1590
|
-
constructor(options) {
|
|
1591
|
-
if (!REPO2.test(options.repo))
|
|
1592
|
-
throw new Error(`"${options.repo}" isn't a GitHub repository in the form owner/name`);
|
|
1593
|
-
this.#repo = options.repo;
|
|
1594
|
-
this.#owner = options.repo.split("/")[0];
|
|
1595
|
-
this.#expected = options.account ?? this.#owner;
|
|
1596
|
-
this.#tokenSource = options.token ?? (() => ghToken(this.#expected));
|
|
1597
|
-
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
1598
|
-
}
|
|
1599
|
-
describe() {
|
|
1600
|
-
return `github ${this.#repo} (repo secret)`;
|
|
1601
|
-
}
|
|
1602
|
-
async checkAccount() {
|
|
1603
|
-
this.#passed = false;
|
|
1604
|
-
const user = await this.#get("/user");
|
|
1605
|
-
if (user.status !== 200)
|
|
1606
|
-
throw new Error(`GitHub GET /user returned HTTP ${user.status}`);
|
|
1607
|
-
const publisher = stringField(user.body, "login");
|
|
1608
|
-
const scopes = user.headers.get("x-oauth-scopes");
|
|
1609
|
-
const repo = await this.#get(`/repos/${this.#repo}`);
|
|
1610
|
-
const facts = { publisher, expected: this.#expected };
|
|
1611
|
-
if (repo.status === 404) {
|
|
1612
|
-
return {
|
|
1613
|
-
...facts,
|
|
1614
|
-
destinationAccount: null,
|
|
1615
|
-
ok: false,
|
|
1616
|
-
reason: `${publisher} can't see ${this.#repo}`
|
|
1617
|
-
};
|
|
1618
|
-
}
|
|
1619
|
-
if (repo.status !== 200)
|
|
1620
|
-
throw new Error(`GitHub GET /repos/${this.#repo} returned HTTP ${repo.status}`);
|
|
1621
|
-
const owner = stringField(objectField2(repo.body, "owner"), "login");
|
|
1622
|
-
const admin = objectField2(repo.body, "permissions").admin === true;
|
|
1623
|
-
const check = { ...facts, destinationAccount: owner, ok: false };
|
|
1624
|
-
if (!sameLogin(owner, this.#owner)) {
|
|
1625
|
-
check.reason = `${this.#repo} is owned by ${owner}, not ${this.#owner} (moved or renamed?)`;
|
|
1626
|
-
} else if (!sameLogin(publisher, this.#expected)) {
|
|
1627
|
-
check.reason = `the token acts as ${publisher}, not ${this.#expected}`;
|
|
1628
|
-
} else if (!admin) {
|
|
1629
|
-
check.reason = `${publisher} isn't an admin of ${this.#repo}, so it can't write secrets`;
|
|
1630
|
-
} else if (scopes !== null && !scopes.split(",").some((s) => s.trim() === "repo")) {
|
|
1631
|
-
check.reason = `the token lacks the repo scope (it has: ${scopes || "none"})`;
|
|
1632
|
-
} else {
|
|
1633
|
-
check.ok = true;
|
|
1634
|
-
this.#passed = true;
|
|
1635
|
-
}
|
|
1636
|
-
return check;
|
|
1637
|
-
}
|
|
1638
|
-
async write(name, secret) {
|
|
1639
|
-
if (!this.#passed)
|
|
1640
|
-
throw new Error(`refusing to write to ${this.describe()}: checkAccount hasn't passed`);
|
|
1641
|
-
if (!SECRET_NAME.test(name) || /^GITHUB_/i.test(name))
|
|
1642
|
-
throw new Error(`"${name}" isn't a valid GitHub secret name`);
|
|
1643
|
-
const key = await this.#get(`/repos/${this.#repo}/actions/secrets/public-key`);
|
|
1644
|
-
if (key.status !== 200)
|
|
1645
|
-
throw new Error(`GitHub public key for ${this.#repo}: HTTP ${key.status}`);
|
|
1646
|
-
const encrypted = await sealedBox(secret.reveal(), stringField(key.body, "key"));
|
|
1647
|
-
const path = `/repos/${this.#repo}/actions/secrets/${name}`;
|
|
1648
|
-
const put = await this.#request("PUT", path, {
|
|
1649
|
-
encrypted_value: encrypted,
|
|
1650
|
-
key_id: stringField(key.body, "key_id")
|
|
1651
|
-
});
|
|
1652
|
-
if (put.status !== 201 && put.status !== 204)
|
|
1653
|
-
throw new Error(`GitHub PUT ${path} returned HTTP ${put.status}`);
|
|
1654
|
-
const after = await this.#get(path);
|
|
1655
|
-
if (after.status !== 200)
|
|
1656
|
-
throw new Error(`GitHub GET ${path} after the write returned HTTP ${after.status}`);
|
|
1657
|
-
return {
|
|
1658
|
-
destination: this.describe(),
|
|
1659
|
-
secret: name,
|
|
1660
|
-
created: put.status === 201,
|
|
1661
|
-
updatedAt: stringField(after.body, "updated_at")
|
|
1662
|
-
};
|
|
1663
|
-
}
|
|
1664
|
-
#get(path) {
|
|
1665
|
-
return this.#request("GET", path);
|
|
1666
|
-
}
|
|
1667
|
-
async#request(method, path, body) {
|
|
1668
|
-
this.#token ??= this.#tokenSource();
|
|
1669
|
-
const response = await this.#fetch(`${API3}${path}`, {
|
|
1670
|
-
method,
|
|
1671
|
-
headers: {
|
|
1672
|
-
Authorization: `Bearer ${await this.#token}`,
|
|
1673
|
-
Accept: "application/vnd.github+json",
|
|
1674
|
-
"X-GitHub-Api-Version": "2022-11-28",
|
|
1675
|
-
...body === undefined ? {} : { "Content-Type": "application/json" }
|
|
1676
|
-
},
|
|
1677
|
-
body: body === undefined ? undefined : JSON.stringify(body)
|
|
1678
|
-
});
|
|
1679
|
-
const text = await response.text();
|
|
1680
|
-
return { status: response.status, headers: response.headers, body: parseObject2(text) };
|
|
1681
|
-
}
|
|
1682
|
-
}
|
|
1683
|
-
async function sealedBox(value, publicKey) {
|
|
1684
|
-
await sodium.ready;
|
|
1685
|
-
const key = sodium.from_base64(publicKey, sodium.base64_variants.ORIGINAL);
|
|
1686
|
-
return sodium.to_base64(sodium.crypto_box_seal(value, key), sodium.base64_variants.ORIGINAL);
|
|
1687
|
-
}
|
|
1688
|
-
function sameLogin(a, b) {
|
|
1689
|
-
return a.toLowerCase() === b.toLowerCase();
|
|
1690
|
-
}
|
|
1691
|
-
function parseObject2(text) {
|
|
1692
|
-
try {
|
|
1693
|
-
const data = JSON.parse(text);
|
|
1694
|
-
return isRecord(data) ? data : {};
|
|
1695
|
-
} catch {
|
|
1696
|
-
return {};
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
function objectField2(data, field) {
|
|
1700
|
-
const value = data[field];
|
|
1701
|
-
return isRecord(value) ? value : {};
|
|
1702
|
-
}
|
|
1703
|
-
function stringField(data, field) {
|
|
1704
|
-
const value = data[field];
|
|
1705
|
-
if (typeof value !== "string")
|
|
1706
|
-
throw new Error(`GitHub's response has no "${field}"`);
|
|
1707
|
-
return value;
|
|
1708
|
-
}
|
|
1709
|
-
// ../../packages/destination-github/src/list.ts
|
|
1710
|
-
var API4 = "https://api.github.com";
|
|
1711
|
-
var REPO3 = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
|
|
1712
|
-
async function listRepoSecrets(options) {
|
|
1713
|
-
if (!REPO3.test(options.repo))
|
|
1714
|
-
return {
|
|
1715
|
-
ok: false,
|
|
1716
|
-
reason: `"${options.repo}" isn't a GitHub repository in the form owner/name`
|
|
1717
|
-
};
|
|
1718
|
-
const fetch = options.fetch ?? globalThis.fetch;
|
|
1719
|
-
let token;
|
|
1720
|
-
try {
|
|
1721
|
-
token = await options.token();
|
|
1722
|
-
} catch (error) {
|
|
1723
|
-
return { ok: false, reason: error instanceof Error ? error.message : "no GitHub token" };
|
|
1724
|
-
}
|
|
1725
|
-
const secrets = [];
|
|
1726
|
-
for (let page = 1;; page++) {
|
|
1727
|
-
const path = `/repos/${options.repo}/actions/secrets?per_page=100&page=${page}`;
|
|
1728
|
-
const response = await fetch(`${API4}${path}`, {
|
|
1729
|
-
method: "GET",
|
|
1730
|
-
headers: {
|
|
1731
|
-
Authorization: `Bearer ${token}`,
|
|
1732
|
-
Accept: "application/vnd.github+json",
|
|
1733
|
-
"X-GitHub-Api-Version": "2022-11-28"
|
|
1734
|
-
}
|
|
1735
|
-
});
|
|
1736
|
-
if (response.status !== 200) {
|
|
1737
|
-
await response.body?.cancel();
|
|
1738
|
-
return { ok: false, reason: refusal(response.status, options.repo) };
|
|
1739
|
-
}
|
|
1740
|
-
const body = await response.json().catch(() => null);
|
|
1741
|
-
const list = isRecord(body) && Array.isArray(body.secrets) ? body.secrets : null;
|
|
1742
|
-
if (!list)
|
|
1743
|
-
return { ok: false, reason: "GitHub's secrets response has no secrets list" };
|
|
1744
|
-
for (const secret of list) {
|
|
1745
|
-
if (!isRecord(secret) || typeof secret.name !== "string")
|
|
1746
|
-
continue;
|
|
1747
|
-
secrets.push({
|
|
1748
|
-
name: secret.name,
|
|
1749
|
-
updatedAt: typeof secret.updated_at === "string" ? secret.updated_at : null
|
|
1750
|
-
});
|
|
1751
|
-
}
|
|
1752
|
-
const total = isRecord(body) && typeof body.total_count === "number" ? body.total_count : 0;
|
|
1753
|
-
if (list.length < 100 || secrets.length >= total)
|
|
1754
|
-
return { ok: true, secrets };
|
|
1755
|
-
}
|
|
1756
|
-
}
|
|
1757
|
-
function refusal(status, repo) {
|
|
1758
|
-
if (status === 404)
|
|
1759
|
-
return `HTTP 404: the login can't see ${repo}, or it isn't an admin of it`;
|
|
1760
|
-
if (status === 403)
|
|
1761
|
-
return `HTTP 403: the login isn't allowed to list ${repo}'s secrets`;
|
|
1762
|
-
if (status === 401)
|
|
1763
|
-
return "HTTP 401: the gh login's token was refused";
|
|
1764
|
-
return `GitHub returned HTTP ${status}`;
|
|
1765
|
-
}
|
|
1766
|
-
// ../../packages/provider-cloudflare/src/tokens.ts
|
|
1767
|
-
var API5 = "https://api.cloudflare.com/client/v4";
|
|
1768
|
-
var ACCOUNT_ID5 = /^[0-9a-f]{32}$/;
|
|
1769
|
-
var TOKEN_ID = /^[0-9a-f]{32}$/;
|
|
1770
|
-
|
|
1771
|
-
class CloudflareAccountTokens {
|
|
1772
|
-
#account;
|
|
1773
|
-
#admin;
|
|
1774
|
-
#fetch;
|
|
1775
|
-
constructor(options) {
|
|
1776
|
-
if (!ACCOUNT_ID5.test(options.account))
|
|
1777
|
-
throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
|
|
1778
|
-
this.#account = options.account;
|
|
1779
|
-
this.#admin = options.admin;
|
|
1780
|
-
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
1781
|
-
}
|
|
1782
|
-
describe() {
|
|
1783
|
-
return `Cloudflare account API tokens in account ${this.#account}`;
|
|
1784
|
-
}
|
|
1785
|
-
async verify(secret) {
|
|
1786
|
-
const path = `${this.#base()}/verify`;
|
|
1787
|
-
const reply = await this.#request("GET", path, secret);
|
|
1788
|
-
if (reply.status !== 200)
|
|
1789
|
-
throw failure2("GET", path, reply);
|
|
1790
|
-
const result = objectField3(reply.body, "result");
|
|
1791
|
-
return {
|
|
1792
|
-
id: tokenId(result.id, "verify"),
|
|
1793
|
-
status: text(result.status, "status"),
|
|
1794
|
-
expiresOn: optionalText(result.expires_on)
|
|
1795
|
-
};
|
|
1796
|
-
}
|
|
1797
|
-
async details(id) {
|
|
1798
|
-
const path = `${this.#base()}/${tokenId(id, "details")}`;
|
|
1799
|
-
const reply = await this.#request("GET", path, this.#admin);
|
|
1800
|
-
if (reply.status === 404)
|
|
1801
|
-
return null;
|
|
1802
|
-
if (reply.status !== 200)
|
|
1803
|
-
throw failure2("GET", path, reply);
|
|
1804
|
-
return token(objectField3(reply.body, "result"));
|
|
1805
|
-
}
|
|
1806
|
-
async issue(request) {
|
|
1807
|
-
const path = this.#base();
|
|
1808
|
-
const body = {
|
|
1809
|
-
name: request.name,
|
|
1810
|
-
policies: request.like.policies.map((policy) => ({
|
|
1811
|
-
effect: policy.effect,
|
|
1812
|
-
resources: policy.resources,
|
|
1813
|
-
permission_groups: policy.permissionGroups.map((group) => ({ id: group.id }))
|
|
1814
|
-
})),
|
|
1815
|
-
expires_on: request.expiresOn
|
|
1816
|
-
};
|
|
1817
|
-
if (request.like.condition)
|
|
1818
|
-
body.condition = request.like.condition;
|
|
1819
|
-
const reply = await this.#request("POST", path, this.#admin, body);
|
|
1820
|
-
if (reply.status >= 400 && reply.status < 500)
|
|
1821
|
-
return { refused: failure2("POST", path, reply).message };
|
|
1822
|
-
if (reply.status !== 200)
|
|
1823
|
-
throw failure2("POST", path, reply);
|
|
1824
|
-
const result = objectField3(reply.body, "result");
|
|
1825
|
-
const value = result.value;
|
|
1826
|
-
if (typeof value !== "string" || !value)
|
|
1827
|
-
throw new Error("Cloudflare's create response has no token value");
|
|
1828
|
-
return { token: token(result), value: new Secret(value) };
|
|
1829
|
-
}
|
|
1830
|
-
async revoke(id) {
|
|
1831
|
-
const path = `${this.#base()}/${tokenId(id, "revoke")}`;
|
|
1832
|
-
const reply = await this.#request("DELETE", path, this.#admin);
|
|
1833
|
-
if (reply.status === 404)
|
|
1834
|
-
return "already gone";
|
|
1835
|
-
if (reply.status !== 200)
|
|
1836
|
-
throw failure2("DELETE", path, reply);
|
|
1837
|
-
return "revoked";
|
|
1838
|
-
}
|
|
1839
|
-
#base() {
|
|
1840
|
-
return `/accounts/${this.#account}/tokens`;
|
|
1841
|
-
}
|
|
1842
|
-
async#request(method, path, auth, body) {
|
|
1843
|
-
const response = await this.#fetch(`${API5}${path}`, {
|
|
1844
|
-
method,
|
|
1845
|
-
headers: {
|
|
1846
|
-
Authorization: `Bearer ${auth.reveal()}`,
|
|
1847
|
-
...body === undefined ? {} : { "Content-Type": "application/json" }
|
|
1848
|
-
},
|
|
1849
|
-
body: body === undefined ? undefined : JSON.stringify(body)
|
|
1850
|
-
});
|
|
1851
|
-
return { status: response.status, body: parseObject3(await response.text()) };
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
function token(result) {
|
|
1855
|
-
const policies = result.policies;
|
|
1856
|
-
if (!Array.isArray(policies))
|
|
1857
|
-
throw new Error("Cloudflare's token has no policies list");
|
|
1858
|
-
const condition = result.condition;
|
|
1859
|
-
return {
|
|
1860
|
-
id: tokenId(result.id, "token"),
|
|
1861
|
-
name: text(result.name, "name"),
|
|
1862
|
-
status: text(result.status, "status"),
|
|
1863
|
-
expiresOn: optionalText(result.expires_on),
|
|
1864
|
-
lastUsedOn: optionalText(result.last_used_on),
|
|
1865
|
-
policies: policies.map(policy),
|
|
1866
|
-
condition: isJsonObject(condition) && Object.keys(condition).length ? condition : null
|
|
1867
|
-
};
|
|
1868
|
-
}
|
|
1869
|
-
function policy(raw) {
|
|
1870
|
-
if (!isRecord(raw))
|
|
1871
|
-
throw new Error("a Cloudflare token policy isn't an object");
|
|
1872
|
-
const resources = raw.resources;
|
|
1873
|
-
const groups = raw.permission_groups;
|
|
1874
|
-
if (!isJsonObject(resources))
|
|
1875
|
-
throw new Error("a Cloudflare token policy has no resources");
|
|
1876
|
-
if (!Array.isArray(groups))
|
|
1877
|
-
throw new Error("a Cloudflare token policy has no permission groups");
|
|
1878
|
-
return {
|
|
1879
|
-
effect: text(raw.effect, "effect"),
|
|
1880
|
-
resources,
|
|
1881
|
-
permissionGroups: groups.map((group) => {
|
|
1882
|
-
if (!isRecord(group))
|
|
1883
|
-
throw new Error("a Cloudflare permission group isn't an object");
|
|
1884
|
-
return {
|
|
1885
|
-
id: text(group.id, "permission group id"),
|
|
1886
|
-
name: typeof group.name === "string" ? group.name : "(unnamed)"
|
|
1887
|
-
};
|
|
1888
|
-
})
|
|
1889
|
-
};
|
|
1890
|
-
}
|
|
1891
|
-
function isJson(value) {
|
|
1892
|
-
if (value === null || ["string", "number", "boolean"].includes(typeof value))
|
|
1893
|
-
return true;
|
|
1894
|
-
if (Array.isArray(value))
|
|
1895
|
-
return value.every(isJson);
|
|
1896
|
-
return isJsonObject(value);
|
|
1897
|
-
}
|
|
1898
|
-
function isJsonObject(value) {
|
|
1899
|
-
return isRecord(value) && Object.values(value).every(isJson);
|
|
1900
|
-
}
|
|
1901
|
-
function tokenId(value, where) {
|
|
1902
|
-
if (typeof value !== "string" || !TOKEN_ID.test(value))
|
|
1903
|
-
throw new Error(`Cloudflare's ${where} response has no valid token ID`);
|
|
1904
|
-
return value;
|
|
1905
|
-
}
|
|
1906
|
-
function text(value, field) {
|
|
1907
|
-
if (typeof value !== "string")
|
|
1908
|
-
throw new Error(`Cloudflare's token has no "${field}"`);
|
|
1909
|
-
return value;
|
|
1910
|
-
}
|
|
1911
|
-
function optionalText(value) {
|
|
1912
|
-
return typeof value === "string" && value ? value : null;
|
|
1913
|
-
}
|
|
1914
|
-
function failure2(method, path, reply) {
|
|
1915
|
-
const errors = reply.body.errors;
|
|
1916
|
-
const codes = Array.isArray(errors) ? errors.map((e) => isRecord(e) ? e.code : undefined).filter((c) => typeof c === "string" || typeof c === "number") : [];
|
|
1917
|
-
const detail = codes.length ? `, codes ${codes.join(", ")}` : "";
|
|
1918
|
-
return new Error(`Cloudflare ${method} ${path.split("?")[0]} returned HTTP ${reply.status}${detail}`);
|
|
1919
|
-
}
|
|
1920
|
-
function parseObject3(body) {
|
|
1921
|
-
try {
|
|
1922
|
-
const data = JSON.parse(body);
|
|
1923
|
-
return isRecord(data) ? data : {};
|
|
1924
|
-
} catch {
|
|
1925
|
-
return {};
|
|
1926
|
-
}
|
|
1927
|
-
}
|
|
1928
|
-
function objectField3(data, field) {
|
|
1929
|
-
const value = data[field];
|
|
1930
|
-
return isRecord(value) ? value : {};
|
|
1931
|
-
}
|
|
1932
|
-
// ../../packages/vault-1password/src/sdk.ts
|
|
1933
|
-
var desktopConnect = async (account) => {
|
|
1934
|
-
const sdk = await import("@1password/sdk");
|
|
1935
|
-
const client = await sdk.createClient({
|
|
1936
|
-
auth: new sdk.DesktopAuth(account),
|
|
1937
|
-
integrationName: "keypin",
|
|
1938
|
-
integrationVersion: "0.0.0"
|
|
1939
|
-
});
|
|
1940
|
-
const field = (f) => ({ ...f, fieldType: sdk.ItemFieldType[f.fieldType] });
|
|
1941
|
-
return {
|
|
1942
|
-
vaults: { list: () => client.vaults.list() },
|
|
1943
|
-
items: {
|
|
1944
|
-
list: (vaultId) => client.items.list(vaultId),
|
|
1945
|
-
get: (vaultId, itemId) => client.items.get(vaultId, itemId),
|
|
1946
|
-
create: (params) => client.items.create({
|
|
1947
|
-
...params,
|
|
1948
|
-
category: sdk.ItemCategory[params.category],
|
|
1949
|
-
fields: params.fields?.map(field)
|
|
1950
|
-
}),
|
|
1951
|
-
put: (item) => client.items.put({
|
|
1952
|
-
...item,
|
|
1953
|
-
category: sdk.ItemCategory[item.category],
|
|
1954
|
-
fields: item.fields.map(field)
|
|
1955
|
-
})
|
|
1956
|
-
}
|
|
1957
|
-
};
|
|
1958
|
-
};
|
|
1959
|
-
|
|
1960
|
-
// ../../packages/vault-1password/src/backend.ts
|
|
1961
|
-
var VALUE_FIELD = "password";
|
|
1962
|
-
var ROTATED = "rotated";
|
|
1963
|
-
var DAY2 = /^\d{4}-\d{2}-\d{2}$/;
|
|
1964
|
-
var UNIX_SECONDS = /^\d+$/;
|
|
1965
|
-
function onePasswordBackend(connect = desktopConnect) {
|
|
1966
|
-
const clients = new Map;
|
|
1967
|
-
function client(account) {
|
|
1968
|
-
let pending = clients.get(account);
|
|
1969
|
-
if (!pending) {
|
|
1970
|
-
pending = connect(account).catch((error) => {
|
|
1971
|
-
clients.delete(account);
|
|
1972
|
-
throw new Error(`1Password account "${account}": sign-in failed: ${messageOf2(error)}`);
|
|
1973
|
-
});
|
|
1974
|
-
clients.set(account, pending);
|
|
1975
|
-
}
|
|
1976
|
-
return pending;
|
|
1977
|
-
}
|
|
1978
|
-
async function vaultId(sdk, scope) {
|
|
1979
|
-
const matches = named(await sdk.vaults.list(), scope.vault);
|
|
1980
|
-
const [match] = matches;
|
|
1981
|
-
if (!match) {
|
|
1982
|
-
throw new Error(`1Password account "${scope.account}" has no vault "${scope.vault}"`);
|
|
1983
|
-
}
|
|
1984
|
-
if (matches.length > 1) {
|
|
1985
|
-
throw new Error(`1Password account "${scope.account}" has ${matches.length} vaults named "${scope.vault}"`);
|
|
1986
|
-
}
|
|
1987
|
-
return match.id;
|
|
1988
|
-
}
|
|
1989
|
-
async function find(sdk, id, ref) {
|
|
1990
|
-
const matches = named(await sdk.items.list(id), ref.item);
|
|
1991
|
-
if (matches.length > 1)
|
|
1992
|
-
throw new Error(`${where(ref)}: ${matches.length} items have this name`);
|
|
1993
|
-
return matches[0] ?? null;
|
|
1994
|
-
}
|
|
1995
|
-
async function get(ref) {
|
|
1996
|
-
const sdk = await client(ref.account);
|
|
1997
|
-
const id = await vaultId(sdk, ref);
|
|
1998
|
-
const found = await find(sdk, id, ref);
|
|
1999
|
-
if (!found)
|
|
2000
|
-
throw new Error(`${where(ref)}: no such item`);
|
|
2001
|
-
return sdk.items.get(id, found.id);
|
|
2002
|
-
}
|
|
2003
|
-
return {
|
|
2004
|
-
capabilities: { read: true, write: true, list: true, metadata: true },
|
|
2005
|
-
async read(ref) {
|
|
2006
|
-
const item = await get(ref);
|
|
2007
|
-
return new Secret(valueField(item, ref).value);
|
|
2008
|
-
},
|
|
2009
|
-
async write(ref, secret, options = {}) {
|
|
2010
|
-
const rotated = options.rotated;
|
|
2011
|
-
if (rotated !== undefined && !isDay(rotated)) {
|
|
2012
|
-
throw new Error(`${where(ref)}: rotated must be a real day as YYYY-MM-DD, got "${rotated}"`);
|
|
2013
|
-
}
|
|
2014
|
-
const sdk = await client(ref.account);
|
|
2015
|
-
const id = await vaultId(sdk, ref);
|
|
2016
|
-
const found = await find(sdk, id, ref);
|
|
2017
|
-
if (found && options.newItem) {
|
|
2018
|
-
throw new Error(`${where(ref)}: the item already exists; keypin doesn't overwrite it`);
|
|
2019
|
-
}
|
|
2020
|
-
if (!found) {
|
|
2021
|
-
if (ref.field !== VALUE_FIELD || ref.section !== null) {
|
|
2022
|
-
throw new Error(`${where(ref)}: no such item; create it in 1Password first`);
|
|
2023
|
-
}
|
|
2024
|
-
const fields = [passwordField(secret)];
|
|
2025
|
-
if (rotated)
|
|
2026
|
-
fields.push(rotatedField(rotated));
|
|
2027
|
-
await sdk.items.create({
|
|
2028
|
-
category: "Password",
|
|
2029
|
-
vaultId: id,
|
|
2030
|
-
title: ref.item,
|
|
2031
|
-
fields
|
|
2032
|
-
});
|
|
2033
|
-
return;
|
|
2034
|
-
}
|
|
2035
|
-
const item = await sdk.items.get(id, found.id);
|
|
2036
|
-
const fields = [...item.fields];
|
|
2037
|
-
const value = valueField(item, ref);
|
|
2038
|
-
fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
|
|
2039
|
-
if (rotated) {
|
|
2040
|
-
const existing = fields.find((field) => field.title === ROTATED);
|
|
2041
|
-
if (existing)
|
|
2042
|
-
fields[fields.indexOf(existing)] = {
|
|
2043
|
-
...existing,
|
|
2044
|
-
...rotatedField(rotated),
|
|
2045
|
-
id: existing.id
|
|
2046
|
-
};
|
|
2047
|
-
else
|
|
2048
|
-
fields.push(rotatedField(rotated));
|
|
2049
|
-
}
|
|
2050
|
-
await sdk.items.put({ ...item, fields });
|
|
2051
|
-
},
|
|
2052
|
-
async list(scope) {
|
|
2053
|
-
const sdk = await client(scope.account);
|
|
2054
|
-
const items = await sdk.items.list(await vaultId(sdk, scope));
|
|
2055
|
-
return items.map((item) => ({
|
|
2056
|
-
id: item.id,
|
|
2057
|
-
title: item.title,
|
|
2058
|
-
tags: [...item.tags],
|
|
2059
|
-
updatedAt: new Date(item.updatedAt).toISOString()
|
|
2060
|
-
}));
|
|
2061
|
-
},
|
|
2062
|
-
async metadata(ref) {
|
|
2063
|
-
const item = await get(ref);
|
|
2064
|
-
const rotated = plainField(item.fields, ROTATED, ref);
|
|
2065
|
-
return { rotated: rotated === null ? null : toDay(rotated, ref) };
|
|
2066
|
-
}
|
|
2067
|
-
};
|
|
2068
|
-
}
|
|
2069
|
-
function where(ref) {
|
|
2070
|
-
return `${formatReference(ref)} (1Password account ${ref.account})`;
|
|
2071
|
-
}
|
|
2072
|
-
function named(candidates, name) {
|
|
2073
|
-
const wanted = name.toLowerCase();
|
|
2074
|
-
return candidates.filter((candidate) => candidate.id.toLowerCase() === wanted || candidate.title.toLowerCase() === wanted);
|
|
2075
|
-
}
|
|
2076
|
-
function valueField(item, ref) {
|
|
2077
|
-
const sections = ref.section === null ? [] : named(item.sections, ref.section);
|
|
2078
|
-
if (ref.section !== null && !sections.length) {
|
|
2079
|
-
throw new Error(`${where(ref)}: the item has no section "${ref.section}"`);
|
|
2080
|
-
}
|
|
2081
|
-
const [field, ...more] = named(item.fields.filter((field) => ref.section === null || sections.some((section) => section.id === field.sectionId)), ref.field);
|
|
2082
|
-
if (!field)
|
|
2083
|
-
throw new Error(`${where(ref)}: the item has no field "${ref.field}"`);
|
|
2084
|
-
if (more.length) {
|
|
2085
|
-
throw new Error(`${where(ref)}: ${more.length + 1} fields are named "${ref.field}"; name a section`);
|
|
2086
|
-
}
|
|
2087
|
-
if (field.title === ROTATED) {
|
|
2088
|
-
throw new Error(`${where(ref)}: "${ROTATED}" holds the day the value last changed; put the value in another field`);
|
|
2089
|
-
}
|
|
2090
|
-
return field;
|
|
2091
|
-
}
|
|
2092
|
-
function passwordField(secret) {
|
|
2093
|
-
return {
|
|
2094
|
-
id: VALUE_FIELD,
|
|
2095
|
-
title: VALUE_FIELD,
|
|
2096
|
-
fieldType: "Concealed",
|
|
2097
|
-
value: secret.reveal()
|
|
2098
|
-
};
|
|
2099
|
-
}
|
|
2100
|
-
function rotatedField(day) {
|
|
2101
|
-
return { id: ROTATED, title: ROTATED, fieldType: "Date", value: day };
|
|
2102
|
-
}
|
|
2103
|
-
function plainField(fields, title, ref) {
|
|
2104
|
-
const field = fields.find((candidate) => candidate.title === title);
|
|
2105
|
-
if (!field)
|
|
2106
|
-
return null;
|
|
2107
|
-
if (field.fieldType !== "Text" && field.fieldType !== "Date") {
|
|
2108
|
-
throw new Error(`${where(ref)}: field "${title}" is ${field.fieldType}, expected Text or Date`);
|
|
2109
|
-
}
|
|
2110
|
-
return field.value === "" ? null : field.value;
|
|
2111
|
-
}
|
|
2112
|
-
function toDay(value, ref) {
|
|
2113
|
-
if (DAY2.test(value))
|
|
2114
|
-
return value;
|
|
2115
|
-
if (UNIX_SECONDS.test(value)) {
|
|
2116
|
-
const date = new Date(Number(value) * 1000);
|
|
2117
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
2118
|
-
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
2119
|
-
}
|
|
2120
|
-
throw new Error(`${where(ref)}: "${ROTATED}" isn't a date: "${value}"`);
|
|
2121
|
-
}
|
|
2122
|
-
function messageOf2(error) {
|
|
2123
|
-
return error instanceof Error ? error.message : String(error);
|
|
2124
|
-
}
|
|
2125
|
-
// src/commands/discover.ts
|
|
2126
|
-
import { basename, join as join5, relative, resolve as resolve2 } from "path";
|
|
2127
|
-
import { parseArgs as parseArgs2 } from "util";
|
|
2128
|
-
|
|
2129
|
-
// src/deps.ts
|
|
2130
|
-
class UsageError extends Error {
|
|
2131
|
-
}
|
|
2132
|
-
function localDay(date) {
|
|
2133
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
2134
|
-
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
2135
|
-
}
|
|
2136
|
-
|
|
2137
|
-
// src/project.ts
|
|
2138
|
-
import { dirname, join as join2 } from "path";
|
|
2139
|
-
var MAP_FILE = "keypin.toml";
|
|
2140
|
-
async function findMap(files, cwd) {
|
|
2141
|
-
for (let folder = cwd;; folder = dirname(folder)) {
|
|
2142
|
-
const file = join2(folder, MAP_FILE);
|
|
2143
|
-
const text = await files.read(file);
|
|
2144
|
-
if (text !== null) {
|
|
2145
|
-
const result = parseMap(text, file);
|
|
2146
|
-
if (!result.ok)
|
|
2147
|
-
throw new Error(result.errors.join(`
|
|
2148
|
-
`));
|
|
2149
|
-
return result.map;
|
|
2150
|
-
}
|
|
2151
|
-
if (dirname(folder) === folder) {
|
|
2152
|
-
throw new Error(`no ${MAP_FILE} in ${cwd} or any folder above it; run "keypin init" first`);
|
|
2153
|
-
}
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
function pickEnvironment(map, requested, fallback) {
|
|
2157
|
-
if (requested === undefined || map.environments.includes(requested))
|
|
2158
|
-
return requested ?? fallback;
|
|
2159
|
-
const names = map.environments.map((name) => `"${name}"`).join(", ");
|
|
2160
|
-
throw new UsageError(`--env is one of ${names} in ${map.file}, got "${requested}"`);
|
|
2161
|
-
}
|
|
2162
|
-
|
|
2163
|
-
// src/commands/init.ts
|
|
2164
|
-
import { join as join4, resolve } from "path";
|
|
2165
|
-
import { parseArgs } from "util";
|
|
2166
|
-
|
|
2167
|
-
// src/paths.ts
|
|
2168
|
-
import { dirname as dirname2, join as join3 } from "path";
|
|
2169
|
-
function registryPath(deps) {
|
|
2170
|
-
return join3(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
|
|
2171
|
-
}
|
|
2172
|
-
function statePath(deps) {
|
|
2173
|
-
return join3(base(deps.env.XDG_STATE_HOME, deps.home, ".local/state"), "keypin", "state.json");
|
|
2174
|
-
}
|
|
2175
|
-
function base(xdg, home, fallback) {
|
|
2176
|
-
return xdg?.startsWith("/") ? xdg : join3(home, fallback);
|
|
2177
|
-
}
|
|
2178
|
-
function projectCount(registry, path) {
|
|
2179
|
-
const count = registry.projects.length;
|
|
2180
|
-
return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
|
|
2181
|
-
}
|
|
2182
|
-
function rotationsPath(deps) {
|
|
2183
|
-
return join3(dirname2(statePath(deps)), "rotations.json");
|
|
2184
|
-
}
|
|
2185
|
-
|
|
2186
|
-
// src/commands/init.ts
|
|
2187
|
-
var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
|
|
2188
|
-
# Uncomment and edit. Every field is checked; an unknown one is an error.
|
|
2189
|
-
#
|
|
2190
|
-
# The 1Password account the keys below read from: its sign-in address or account ID.
|
|
2191
|
-
# [1password]
|
|
2192
|
-
# account = "my.1password.com"
|
|
2193
|
-
#
|
|
2194
|
-
# A key, named after the variable your program reads.
|
|
2195
|
-
# [keys.EXAMPLE_API_KEY]
|
|
2196
|
-
# rotate_every = "180d" # <n>d, <n>w, <n>m or never
|
|
2197
|
-
# dev = "op://Private/my-project dev example api key/password" # what keypin run reads
|
|
2198
|
-
#
|
|
2199
|
-
# What keypin publish reads, and every place it writes it.
|
|
2200
|
-
# [keys.EXAMPLE_API_KEY.prod]
|
|
2201
|
-
# from = "op://Private/my-project prod example api key/password"
|
|
2202
|
-
#
|
|
2203
|
-
# [[keys.EXAMPLE_API_KEY.prod.publish]]
|
|
2204
|
-
# to = "cloudflare-worker"
|
|
2205
|
-
# account = "<cloudflare account ID>"
|
|
2206
|
-
# worker = "my-worker"
|
|
2207
|
-
#
|
|
2208
|
-
# [[keys.EXAMPLE_API_KEY.prod.publish]]
|
|
2209
|
-
# to = "github-actions"
|
|
2210
|
-
# repo = "owner/repo"
|
|
2211
|
-
`;
|
|
2212
|
-
async function init(args, deps) {
|
|
2213
|
-
const { positionals } = parseArgs({ args, options: {}, allowPositionals: true });
|
|
2214
|
-
if (positionals.length > 1)
|
|
2215
|
-
throw new UsageError("keypin init takes at most one folder");
|
|
2216
|
-
const folder = resolve(deps.cwd, positionals[0] ?? ".");
|
|
2217
|
-
if (!await deps.isFolder(folder))
|
|
2218
|
-
throw new Error(`${folder} isn't a folder`);
|
|
2219
|
-
const file = join4(folder, MAP_FILE);
|
|
2220
|
-
const created = await deps.createFile(file, TEMPLATE);
|
|
2221
|
-
if (created === "link")
|
|
2222
|
-
throw new Error(`${file} is a symbolic link; keypin init doesn't follow one`);
|
|
2223
|
-
deps.stderr.write(created === "created" ? `keypin: wrote ${file}
|
|
2224
|
-
` : `keypin: ${file} exists; left it as it is
|
|
2225
|
-
`);
|
|
2226
|
-
await registerProject(deps, folder);
|
|
2227
|
-
return 0;
|
|
2228
|
-
}
|
|
2229
|
-
async function registerProject(deps, folder) {
|
|
2230
|
-
const path = registryPath(deps);
|
|
2231
|
-
const registry = await register(deps.files, path, folder);
|
|
2232
|
-
deps.stderr.write(`keypin: ${folder} is registered (${projectCount(registry, path)})
|
|
2233
|
-
`);
|
|
2234
|
-
}
|
|
2235
|
-
|
|
2236
|
-
// src/commands/discover.ts
|
|
2237
|
-
async function discover(args, deps) {
|
|
2238
|
-
const { values, positionals } = parseArgs2({
|
|
2239
|
-
args,
|
|
2240
|
-
options: {
|
|
2241
|
-
json: { type: "boolean", default: false },
|
|
2242
|
-
write: { type: "boolean", default: false }
|
|
2243
|
-
},
|
|
2244
|
-
allowPositionals: true
|
|
2245
|
-
});
|
|
2246
|
-
if (positionals.length > 1)
|
|
2247
|
-
throw new UsageError("keypin discover takes at most one folder");
|
|
2248
|
-
const folder = resolve2(deps.cwd, positionals[0] ?? ".");
|
|
2249
|
-
if (!await deps.isFolder(folder))
|
|
2250
|
-
throw new Error(`${folder} isn't a folder`);
|
|
2251
|
-
const mapFile = join5(folder, MAP_FILE);
|
|
2252
|
-
const mapText = await deps.files.read(mapFile);
|
|
2253
|
-
if (values.write && mapText !== null && mapText !== TEMPLATE) {
|
|
2254
|
-
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.
|
|
2255
|
-
`);
|
|
2256
|
-
return 1;
|
|
2257
|
-
}
|
|
2258
|
-
const unknowns = [];
|
|
2259
|
-
const scan = await walk(deps, folder);
|
|
2260
|
-
const tracked = await trackedFiles(deps, folder, scan.envFiles);
|
|
2261
|
-
const envFiles = [];
|
|
2262
|
-
for (const path of scan.envFiles) {
|
|
2263
|
-
const kind = envFileKind(basename(path));
|
|
2264
|
-
if (!kind)
|
|
2265
|
-
continue;
|
|
2266
|
-
const text = await deps.files.read(join5(folder, path));
|
|
2267
|
-
if (text === null)
|
|
2268
|
-
continue;
|
|
2269
|
-
envFiles.push({ path, kind, names: envNames(text), tracked: tracked?.has(path) ?? null });
|
|
2270
|
-
}
|
|
2271
|
-
if (tracked === null && envFiles.some((f) => f.kind === "set")) {
|
|
2272
|
-
unknowns.push({
|
|
2273
|
-
what: "whether env files are tracked by git",
|
|
2274
|
-
reason: "the folder isn't in a git repository",
|
|
2275
|
-
cloud: false
|
|
2276
|
-
});
|
|
2277
|
-
}
|
|
2278
|
-
const top = (await deps.git(folder, ["rev-parse", "--show-toplevel"]))?.trim() || null;
|
|
2279
|
-
const workflows = await readWorkflows(deps, folder, top, unknowns);
|
|
2280
|
-
const workers = [];
|
|
2281
|
-
for (const config of scan.wrangler) {
|
|
2282
|
-
const text = await deps.files.read(join5(folder, config));
|
|
2283
|
-
if (text === null)
|
|
2284
|
-
continue;
|
|
2285
|
-
const parsed = wranglerWorkers(text, config);
|
|
2286
|
-
if (!parsed.ok) {
|
|
2287
|
-
unknowns.push({
|
|
2288
|
-
what: `the Workers in ${config}`,
|
|
2289
|
-
reason: "it couldn't be parsed",
|
|
2290
|
-
cloud: true
|
|
2291
|
-
});
|
|
2292
|
-
continue;
|
|
2293
|
-
}
|
|
2294
|
-
for (const worker of parsed.workers) {
|
|
2295
|
-
const read = worker.worker && worker.account ? await deps.workerSecrets(worker.account, worker.worker).catch((error) => ({
|
|
2296
|
-
ok: false,
|
|
2297
|
-
reason: messageOf(error)
|
|
2298
|
-
})) : null;
|
|
2299
|
-
workers.push({ ...worker, read });
|
|
2300
|
-
}
|
|
2301
|
-
}
|
|
2302
|
-
const origin = top ? await githubOrigin(deps, folder) : null;
|
|
2303
|
-
let github = null;
|
|
2304
|
-
let login = null;
|
|
2305
|
-
if (!top) {
|
|
2306
|
-
unknowns.push({
|
|
2307
|
-
what: "GitHub Actions secrets",
|
|
2308
|
-
reason: "the folder isn't in a git repository",
|
|
2309
|
-
cloud: true
|
|
2310
|
-
});
|
|
2311
|
-
} else if (!origin || "reason" in origin) {
|
|
2312
|
-
unknowns.push({
|
|
2313
|
-
what: "GitHub Actions secrets",
|
|
2314
|
-
reason: origin?.reason ?? "the repository has no origin remote",
|
|
2315
|
-
cloud: true
|
|
2316
|
-
});
|
|
2317
|
-
} else {
|
|
2318
|
-
login = (await deps.git(folder, ["config", "--get", "github.account"]))?.trim() || origin.owner;
|
|
2319
|
-
const read = await deps.githubSecrets(origin.repo, login).catch((error) => ({ ok: false, reason: messageOf(error) }));
|
|
2320
|
-
github = {
|
|
2321
|
-
repo: origin.repo,
|
|
2322
|
-
read: read.ok ? read : { ok: false, reason: `as ${login}: ${read.reason}` }
|
|
2323
|
-
};
|
|
2324
|
-
}
|
|
2325
|
-
let map = null;
|
|
2326
|
-
if (mapText !== null) {
|
|
2327
|
-
const parsed = parseMap(mapText, MAP_FILE);
|
|
2328
|
-
if (parsed.ok)
|
|
2329
|
-
map = parsed.map;
|
|
2330
|
-
else
|
|
2331
|
-
unknowns.push({
|
|
2332
|
-
what: `which names ${MAP_FILE} maps`,
|
|
2333
|
-
reason: parsed.errors.join("; "),
|
|
2334
|
-
cloud: false
|
|
2335
|
-
});
|
|
2336
|
-
}
|
|
2337
|
-
const discovery = buildDiscovery({ envFiles, workflows, workers, github, map, unknowns });
|
|
2338
|
-
const draft = draftMap(discovery.names, {
|
|
2339
|
-
project: basename(folder),
|
|
2340
|
-
githubAccount: login,
|
|
2341
|
-
map: map ? { account: map.account, vault: firstVault(map) } : null,
|
|
2342
|
-
environments: map?.environments ?? DEFAULT_ENVIRONMENTS,
|
|
2343
|
-
written: values.write
|
|
2344
|
-
});
|
|
2345
|
-
if (draft !== null) {
|
|
2346
|
-
const check = parseMap(draft, "draft");
|
|
2347
|
-
if (!check.ok)
|
|
2348
|
-
throw new Error(`the draft doesn't parse: ${check.errors.join("; ")}`);
|
|
2349
|
-
}
|
|
2350
|
-
if (values.write && draft === null) {
|
|
2351
|
-
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.
|
|
2352
|
-
`);
|
|
2353
|
-
return 1;
|
|
2354
|
-
}
|
|
2355
|
-
const written = values.write && draft !== null ? await writeDraft(deps, mapFile, mapText, draft) : null;
|
|
2356
|
-
const report = {
|
|
2357
|
-
folder,
|
|
2358
|
-
repository: github?.repo ?? null,
|
|
2359
|
-
login,
|
|
2360
|
-
files: {
|
|
2361
|
-
env: envFiles.map(({ path, kind, tracked: t }) => ({ path, kind, tracked: t })),
|
|
2362
|
-
wrangler: scan.wrangler,
|
|
2363
|
-
workflows: workflows.map((w) => w.path)
|
|
2364
|
-
},
|
|
2365
|
-
nestedRepositories: scan.nested,
|
|
2366
|
-
...discovery,
|
|
2367
|
-
draft,
|
|
2368
|
-
written
|
|
2369
|
-
};
|
|
2370
|
-
deps.stdout.write(values.json ? `${JSON.stringify(report, null, 2)}
|
|
2371
|
-
` : render(report, discovery));
|
|
2372
|
-
if (written !== null) {
|
|
2373
|
-
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.
|
|
2374
|
-
`);
|
|
2375
|
-
await registerProject(deps, folder);
|
|
2376
|
-
}
|
|
2377
|
-
return 0;
|
|
2378
|
-
}
|
|
2379
|
-
async function writeDraft(deps, file, found, draft) {
|
|
2380
|
-
const result = found === null ? await deps.createFile(file, draft) : await deps.replaceFile(file, TEMPLATE, draft);
|
|
2381
|
-
if (result === "link")
|
|
2382
|
-
throw new Error(`${file} is a symbolic link; keypin discover doesn't follow one`);
|
|
2383
|
-
if (result === "exists" || result === "changed")
|
|
2384
|
-
throw new Error(`${file} changed while discover ran; nothing was written. Run it again.`);
|
|
2385
|
-
return file;
|
|
2386
|
-
}
|
|
2387
|
-
async function walk(deps, root) {
|
|
2388
|
-
const scan = { envFiles: [], wrangler: [], nested: [] };
|
|
2389
|
-
const visit = async (folder) => {
|
|
2390
|
-
const entries = (await deps.listFolder(folder)).toSorted((a, b) => a.name.localeCompare(b.name));
|
|
2391
|
-
if (folder !== root && entries.some((e) => e.name === ".git")) {
|
|
2392
|
-
scan.nested.push(relative(root, folder));
|
|
2393
|
-
return;
|
|
2394
|
-
}
|
|
2395
|
-
for (const entry of entries) {
|
|
2396
|
-
const path = join5(folder, entry.name);
|
|
2397
|
-
if (entry.kind === "folder") {
|
|
2398
|
-
if (!SKIPPED_FOLDERS.has(entry.name))
|
|
2399
|
-
await visit(path);
|
|
2400
|
-
} else if (entry.kind === "file") {
|
|
2401
|
-
if (envFileKind(entry.name))
|
|
2402
|
-
scan.envFiles.push(relative(root, path));
|
|
2403
|
-
else if (WRANGLER_FILES.includes(entry.name))
|
|
2404
|
-
scan.wrangler.push(relative(root, path));
|
|
2405
|
-
}
|
|
2406
|
-
}
|
|
2407
|
-
};
|
|
2408
|
-
await visit(root);
|
|
2409
|
-
return scan;
|
|
2410
|
-
}
|
|
2411
|
-
async function trackedFiles(deps, folder, paths) {
|
|
2412
|
-
if (!paths.length)
|
|
2413
|
-
return new Set;
|
|
2414
|
-
const out = await deps.git(folder, ["ls-files", "-z", "--", ...paths]);
|
|
2415
|
-
if (out === null)
|
|
2416
|
-
return null;
|
|
2417
|
-
return new Set(out.split("\x00").filter(Boolean));
|
|
2418
|
-
}
|
|
2419
|
-
async function readWorkflows(deps, folder, top, unknowns) {
|
|
2420
|
-
const dir = join5(top ?? folder, ".github", "workflows");
|
|
2421
|
-
let entries;
|
|
2422
|
-
try {
|
|
2423
|
-
entries = await deps.listFolder(dir);
|
|
2424
|
-
} catch (error) {
|
|
2425
|
-
if (errorCode(error) !== "ENOENT") {
|
|
2426
|
-
unknowns.push({
|
|
2427
|
-
what: "the secrets the workflows use",
|
|
2428
|
-
reason: `${relative(folder, dir)} couldn't be read: ${messageOf(error)}`,
|
|
2429
|
-
cloud: false
|
|
2430
|
-
});
|
|
2431
|
-
}
|
|
2432
|
-
return [];
|
|
2433
|
-
}
|
|
2434
|
-
const workflows = [];
|
|
2435
|
-
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
2436
|
-
if (entry.kind !== "file" || !/\.ya?ml$/.test(entry.name))
|
|
2437
|
-
continue;
|
|
2438
|
-
const text = await deps.files.read(join5(dir, entry.name));
|
|
2439
|
-
if (text === null)
|
|
2440
|
-
continue;
|
|
2441
|
-
const path = relative(folder, join5(dir, entry.name));
|
|
2442
|
-
const refs = workflowRefs(text);
|
|
2443
|
-
if (refs)
|
|
2444
|
-
workflows.push({ path, refs });
|
|
2445
|
-
else
|
|
2446
|
-
unknowns.push({
|
|
2447
|
-
what: `the secrets ${path} uses`,
|
|
2448
|
-
reason: "it isn't valid YAML",
|
|
2449
|
-
cloud: false
|
|
2450
|
-
});
|
|
2451
|
-
}
|
|
2452
|
-
return workflows;
|
|
2453
|
-
}
|
|
2454
|
-
var GITHUB_REMOTE = /^(?:https:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/;
|
|
2455
|
-
async function githubOrigin(deps, folder) {
|
|
2456
|
-
const url = (await deps.git(folder, ["remote", "get-url", "origin"]))?.trim();
|
|
2457
|
-
if (!url)
|
|
2458
|
-
return null;
|
|
2459
|
-
const match = GITHUB_REMOTE.exec(url);
|
|
2460
|
-
if (!match?.[1] || !match[2])
|
|
2461
|
-
return { reason: "the origin remote isn't on github.com" };
|
|
2462
|
-
return { repo: `${match[1]}/${match[2]}`, owner: match[1] };
|
|
2463
|
-
}
|
|
2464
|
-
function firstVault(map) {
|
|
2465
|
-
const [entry] = map.keys.flatMap((key) => Object.values(key.environments).filter((e) => e));
|
|
2466
|
-
return entry?.ref.vault ?? null;
|
|
2467
|
-
}
|
|
2468
|
-
var WHERE = {
|
|
2469
|
-
both: "local and cloud",
|
|
2470
|
-
local: "local",
|
|
2471
|
-
cloud: "cloud",
|
|
2472
|
-
declared: "declared, not set",
|
|
2473
|
-
variable: "plain variable"
|
|
2474
|
-
};
|
|
2475
|
-
var LABELS = {
|
|
2476
|
-
"env-file": "local",
|
|
2477
|
-
"example-file": "expected",
|
|
2478
|
-
"github-secret": "cloud",
|
|
2479
|
-
"worker-secret": "cloud",
|
|
2480
|
-
"workflow-secret": "workflow",
|
|
2481
|
-
"workflow-var": "workflow var",
|
|
2482
|
-
"worker-required": "required by",
|
|
2483
|
-
"worker-var": "var in",
|
|
2484
|
-
map: "mapped"
|
|
2485
|
-
};
|
|
2486
|
-
function describe(source) {
|
|
2487
|
-
switch (source.kind) {
|
|
2488
|
-
case "env-file":
|
|
2489
|
-
return source.tracked ? `${source.path} (tracked by git)` : source.path;
|
|
2490
|
-
case "example-file":
|
|
2491
|
-
case "workflow-secret":
|
|
2492
|
-
case "workflow-var":
|
|
2493
|
-
return source.path;
|
|
2494
|
-
case "worker-required":
|
|
2495
|
-
case "worker-var":
|
|
2496
|
-
return source.worker ? `${source.path} (${source.worker})` : source.path;
|
|
2497
|
-
case "github-secret":
|
|
2498
|
-
return `GitHub ${source.repo}${source.updatedAt ? `, updated ${source.updatedAt.slice(0, 10)}` : ""}`;
|
|
2499
|
-
case "worker-secret":
|
|
2500
|
-
return `Worker ${source.worker} (account ${source.account.slice(0, 8)}\u2026)`;
|
|
2501
|
-
case "map":
|
|
2502
|
-
return `${source.path} key ${source.keyId}`;
|
|
2503
|
-
default: {
|
|
2504
|
-
const unknown = source;
|
|
2505
|
-
return JSON.stringify(unknown);
|
|
2506
|
-
}
|
|
2507
|
-
}
|
|
2508
|
-
}
|
|
2509
|
-
function render(report, discovery) {
|
|
2510
|
-
const lines = [`keypin discover ${report.folder}`];
|
|
2511
|
-
lines.push(` GitHub: ${report.repository ? `${report.repository} as ${report.login}` : "no GitHub origin"}`);
|
|
2512
|
-
lines.push(` read: ${count(report.files.env.length, "env file")}, ${count(report.files.wrangler.length, "wrangler config")}, ${count(report.files.workflows.length, "workflow")}`);
|
|
2513
|
-
if (report.nestedRepositories.length)
|
|
2514
|
-
lines.push(` not scanned (own git repository): ${report.nestedRepositories.join(", ")}`);
|
|
2515
|
-
const onlyMissing = (row) => row.sources.every((s) => s.kind === "workflow-secret") && discovery.problems.some((p) => p.kind === "missing-github-secret" && p.name === row.name);
|
|
2516
|
-
const missing = discovery.names.filter(onlyMissing);
|
|
2517
|
-
const shown = discovery.names.filter((row) => !onlyMissing(row));
|
|
2518
|
-
lines.push("", `Names (${discovery.names.length}):`);
|
|
2519
|
-
for (const row of shown) {
|
|
2520
|
-
const where = WHERE[row.where] + (row.cloudUnknown ? ", cloud unknown" : "");
|
|
2521
|
-
const mapped = row.mapped.length ? ", mapped" : "";
|
|
2522
|
-
lines.push(` ${row.name} [${where}${mapped}]`);
|
|
2523
|
-
const groups = new Map;
|
|
2524
|
-
for (const source of row.sources) {
|
|
2525
|
-
const label = LABELS[source.kind];
|
|
2526
|
-
groups.set(label, [...groups.get(label) ?? [], describe(source)]);
|
|
2527
|
-
}
|
|
2528
|
-
for (const [label, items] of groups)
|
|
2529
|
-
lines.push(` ${label}: ${[...new Set(items)].join(", ")}`);
|
|
2530
|
-
for (const problem of row.problems)
|
|
2531
|
-
lines.push(` ! ${problem}`);
|
|
2532
|
-
}
|
|
2533
|
-
if (missing.length) {
|
|
2534
|
-
const byWorkflow = new Map;
|
|
2535
|
-
for (const row of missing) {
|
|
2536
|
-
const files = row.sources.map(describe).join(", ");
|
|
2537
|
-
byWorkflow.set(files, [...byWorkflow.get(files) ?? [], row.name]);
|
|
2538
|
-
}
|
|
2539
|
-
const repo = report.repository ?? "the repository";
|
|
2540
|
-
lines.push("", `Referenced by a workflow, and not a repo secret of ${repo} (${missing.length}):`);
|
|
2541
|
-
for (const [files, names] of byWorkflow)
|
|
2542
|
-
lines.push(` ${files}: ${names.join(", ")}`);
|
|
2543
|
-
}
|
|
2544
|
-
if (!discovery.names.length)
|
|
2545
|
-
lines.push(" (none found)");
|
|
2546
|
-
const loose = discovery.problems.filter((p) => p.name === undefined);
|
|
2547
|
-
if (loose.length) {
|
|
2548
|
-
lines.push("", `Problems (${loose.length}):`);
|
|
2549
|
-
for (const p of loose)
|
|
2550
|
-
lines.push(` ${p.kind}: ${p.message}`);
|
|
2551
|
-
}
|
|
2552
|
-
if (discovery.unknowns.length) {
|
|
2553
|
-
lines.push("", `Unknown (${discovery.unknowns.length}):`);
|
|
2554
|
-
for (const u of discovery.unknowns)
|
|
2555
|
-
lines.push(` ${u.what}: ${u.reason}`);
|
|
2556
|
-
}
|
|
2557
|
-
lines.push("");
|
|
2558
|
-
if (report.draft === null)
|
|
2559
|
-
lines.push("No draft: every name set locally or in the cloud is already mapped.");
|
|
2560
|
-
else if (report.written !== null)
|
|
2561
|
-
lines.push(`Draft keypin.toml for the unmapped names, written to ${report.written}:`, "", report.draft);
|
|
2562
|
-
else
|
|
2563
|
-
lines.push("Draft keypin.toml for the unmapped names (not written):", "", report.draft);
|
|
2564
|
-
return `${lines.join(`
|
|
2565
|
-
`).trimEnd()}
|
|
2566
|
-
`;
|
|
2567
|
-
}
|
|
2568
|
-
function count(n, noun) {
|
|
2569
|
-
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
2570
|
-
}
|
|
2571
|
-
|
|
2572
|
-
// src/commands/import.ts
|
|
2573
|
-
import { basename as basename2, join as join6, resolve as resolve3 } from "path";
|
|
2574
|
-
import { parseArgs as parseArgs3 } from "util";
|
|
2575
|
-
|
|
2576
|
-
// src/publishing.ts
|
|
2577
|
-
var NEEDS_APPROVAL = 3;
|
|
2578
|
-
async function locked(deps, body) {
|
|
2579
|
-
const path = statePath(deps);
|
|
2580
|
-
const lockFile = `${path}.lock`;
|
|
2581
|
-
const taken = await deps.lock(lockFile);
|
|
2582
|
-
if (!taken.held) {
|
|
2583
|
-
deps.stderr.write(`${lockedMessage(lockFile, taken.holder)}
|
|
2584
|
-
`);
|
|
2585
|
-
return 1;
|
|
2586
|
-
}
|
|
2587
|
-
try {
|
|
2588
|
-
return await body(path);
|
|
2589
|
-
} finally {
|
|
2590
|
-
await taken.lock.release();
|
|
2591
|
-
}
|
|
2592
|
-
}
|
|
2593
|
-
function lockedMessage(file, holder) {
|
|
2594
|
-
if (holder.pid === null) {
|
|
2595
|
-
return `keypin: ${file} exists but names no process. If no publish or rotate is running, delete that file and try again.`;
|
|
2596
|
-
}
|
|
2597
|
-
if (holder.running === false) {
|
|
2598
|
-
return `keypin: ${file} was left by process ${holder.pid}, which isn't running any more. Delete that file and try again.`;
|
|
2599
|
-
}
|
|
2600
|
-
return `keypin: another publish or rotate (process ${holder.pid}) holds ${file} and is still running. Wait for it to finish.`;
|
|
2601
|
-
}
|
|
2602
|
-
async function checkAccounts(key, entry, deps, say, heading = "Account checks") {
|
|
2603
|
-
say(`
|
|
2604
|
-
${heading}:`);
|
|
2605
|
-
const checked = new Map;
|
|
2606
|
-
let failed = false;
|
|
2607
|
-
for (const target of entry.publish) {
|
|
2608
|
-
const label = describeTarget(target, key.name);
|
|
2609
|
-
try {
|
|
2610
|
-
const destination = deps.destination(target);
|
|
2611
|
-
const check = await destination.checkAccount();
|
|
2612
|
-
checked.set(destinationId(target, key.name), { target, destination, check });
|
|
2613
|
-
say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
|
|
2614
|
-
if (!check.ok)
|
|
2615
|
-
failed = true;
|
|
2616
|
-
} catch (error) {
|
|
2617
|
-
say(` FAILED ${label}: ${messageOf(error)}`);
|
|
2618
|
-
failed = true;
|
|
2619
|
-
}
|
|
2620
|
-
}
|
|
2621
|
-
return failed ? null : checked;
|
|
2622
|
-
}
|
|
2623
|
-
function writesFor(steps, checked) {
|
|
2624
|
-
return steps.flatMap((step) => {
|
|
2625
|
-
if (step.action !== "write")
|
|
2626
|
-
return [];
|
|
2627
|
-
const found = checked.get(step.destinationId);
|
|
2628
|
-
if (!found)
|
|
2629
|
-
throw new Error(`no account check for ${step.destinationId}`);
|
|
2630
|
-
return [{ destinationId: step.destinationId, found }];
|
|
2631
|
-
});
|
|
2632
|
-
}
|
|
2633
|
-
async function writeAll(input) {
|
|
2634
|
-
const { key, environment, mapFile, entry, secret, generation, writes, path, deps, say } = input;
|
|
2635
|
-
const id = crypto.randomUUID();
|
|
2636
|
-
let state = startOperation(input.state, {
|
|
2637
|
-
id,
|
|
2638
|
-
keyId: key.name,
|
|
2639
|
-
environment,
|
|
2640
|
-
mapFile,
|
|
2641
|
-
generation,
|
|
2642
|
-
startedAt: deps.now().toISOString(),
|
|
2643
|
-
planned: writes.map((w) => w.destinationId)
|
|
2644
|
-
});
|
|
2645
|
-
await saveState(deps.files, path, state);
|
|
2646
|
-
for (const { destinationId: written, found } of writes) {
|
|
2647
|
-
const label = describeTarget(found.target, key.name);
|
|
2648
|
-
try {
|
|
2649
|
-
const evidence = await found.destination.write(key.name, secret);
|
|
2650
|
-
state = recordReceipt(state, {
|
|
2651
|
-
keyId: key.name,
|
|
2652
|
-
environment,
|
|
2653
|
-
mapFile,
|
|
2654
|
-
source: entry.ref,
|
|
2655
|
-
destinationId: written,
|
|
2656
|
-
generation,
|
|
2657
|
-
account: {
|
|
2658
|
-
pinned: found.target.account,
|
|
2659
|
-
publisher: found.check.publisher,
|
|
2660
|
-
destinationAccount: found.check.destinationAccount ?? found.target.account
|
|
2661
|
-
},
|
|
2662
|
-
at: deps.now().toISOString(),
|
|
2663
|
-
evidence
|
|
2664
|
-
}, id);
|
|
2665
|
-
await saveState(deps.files, path, state);
|
|
2666
|
-
say(` wrote ${label}`);
|
|
2667
|
-
} catch (error) {
|
|
2668
|
-
say(` FAILED ${label}: ${messageOf(error)}`);
|
|
2669
|
-
return { ok: false, state };
|
|
2670
|
-
}
|
|
2671
|
-
}
|
|
2672
|
-
state = finishAll(state, { keyId: key.name, environment, mapFile });
|
|
2673
|
-
await saveState(deps.files, path, state);
|
|
2674
|
-
return { ok: true, state };
|
|
2675
|
-
}
|
|
2676
|
-
function finishAll(state, owner) {
|
|
2677
|
-
return unfinishedOperations(state, owner).reduce((s, op) => finishOperation(s, op.id), state);
|
|
2678
|
-
}
|
|
2679
|
-
function rerun(deps, command, args) {
|
|
2680
|
-
const end = args.includes("--") ? args.indexOf("--") : args.length;
|
|
2681
|
-
const approve = [...args.slice(0, end).filter((arg) => arg !== "--plan"), ...args.slice(end)];
|
|
2682
|
-
const words = [...deps.self, command, ...approve].map(shellWord).join(" ");
|
|
2683
|
-
return `To approve, run this in a terminal:
|
|
2684
|
-
cd ${shellWord(deps.cwd)} && ${words}`;
|
|
2685
|
-
}
|
|
2686
|
-
function planOnly(deps, command, args, needsApproval) {
|
|
2687
|
-
const say = (text) => deps.stderr.write(`${text}
|
|
2688
|
-
`);
|
|
2689
|
-
say(needsApproval ? `
|
|
2690
|
-
This plan needs yes typed in a terminal; --yes can't approve it.` : `
|
|
2691
|
-
This plan is routine: --yes can approve it.`);
|
|
2692
|
-
say("Nothing was written: --plan only shows the plan.");
|
|
2693
|
-
say(rerun(deps, command, args));
|
|
2694
|
-
return NEEDS_APPROVAL;
|
|
2695
|
-
}
|
|
2696
|
-
function shellWord(word) {
|
|
2697
|
-
return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
|
|
2698
|
-
}
|
|
2699
|
-
function accountFacts(check) {
|
|
2700
|
-
return `publisher ${check.publisher}, destination account ${check.destinationAccount ?? "unknown"}`;
|
|
2701
|
-
}
|
|
2702
|
-
function describeTarget(target, secretName) {
|
|
2703
|
-
return `${destinationId(target, secretName)} (account ${target.account})`;
|
|
2704
|
-
}
|
|
2705
|
-
|
|
2706
|
-
// src/commands/import.ts
|
|
2707
|
-
var ROTATE_EVERY = "90d";
|
|
2708
|
-
async function importEnv(args, deps) {
|
|
2709
|
-
const request = parseRequest(args);
|
|
2710
|
-
const say = (text) => deps.stderr.write(`${text}
|
|
2711
|
-
`);
|
|
2712
|
-
const envPath = resolve3(deps.cwd, request.envFile);
|
|
2713
|
-
if (envFileKind(basename2(envPath)) === "expected")
|
|
2714
|
-
throw new UsageError(`${envPath} is an example file; import the file that sets the values`);
|
|
2715
|
-
const text = await deps.files.read(envPath);
|
|
2716
|
-
if (text === null)
|
|
2717
|
-
throw new Error(`${envPath} doesn't exist`);
|
|
2718
|
-
const target = await readTarget(deps, request);
|
|
2719
|
-
const environment = runEnvironment(target.map ?? { environments: DEFAULT_ENVIRONMENTS });
|
|
2720
|
-
const project = basename2(deps.cwd);
|
|
2721
|
-
const values = envValues(text);
|
|
2722
|
-
if (!values.size)
|
|
2723
|
-
throw new Error(`${envPath} sets no variables; nothing to import`);
|
|
2724
|
-
const planned = [];
|
|
2725
|
-
const skips = [];
|
|
2726
|
-
const items = new Map;
|
|
2727
|
-
for (const [name, value] of values) {
|
|
2728
|
-
const item = draftItemName(project, environment, name);
|
|
2729
|
-
const sameItem = items.get(item.toLowerCase());
|
|
2730
|
-
const mapped = target.map?.keys.find((key) => key.name === name);
|
|
2731
|
-
if (!isVariableName(name))
|
|
2732
|
-
skips.push({
|
|
2733
|
-
name,
|
|
2734
|
-
reason: "not a variable name (letters, digits and _, not a digit first)",
|
|
2735
|
-
onlyInFile: true
|
|
2736
|
-
});
|
|
2737
|
-
else if (value.isEmpty())
|
|
2738
|
-
skips.push({ name, reason: "the value is empty", onlyInFile: false });
|
|
2739
|
-
else if (mapped?.environments[environment])
|
|
2740
|
-
skips.push({
|
|
2741
|
-
name,
|
|
2742
|
-
reason: `already mapped in ${target.file}; left as it is`,
|
|
2743
|
-
onlyInFile: false
|
|
2744
|
-
});
|
|
2745
|
-
else if (mapped)
|
|
2746
|
-
skips.push({
|
|
2747
|
-
name,
|
|
2748
|
-
reason: `mapped in ${target.file} without ${environment}; left as it is, so add its ${environment} reference by hand`,
|
|
2749
|
-
onlyInFile: true
|
|
2750
|
-
});
|
|
2751
|
-
else if (value.includes("$"))
|
|
2752
|
-
skips.push({
|
|
2753
|
-
name,
|
|
2754
|
-
reason: "the value has a $, which some loaders expand to another variable's value",
|
|
2755
|
-
onlyInFile: true
|
|
2756
|
-
});
|
|
2757
|
-
else if (sameItem !== undefined)
|
|
2758
|
-
skips.push({
|
|
2759
|
-
name,
|
|
2760
|
-
reason: `its item would be "${item}", the same as ${sameItem}'s`,
|
|
2761
|
-
onlyInFile: true
|
|
2762
|
-
});
|
|
2763
|
-
else {
|
|
2764
|
-
items.set(item.toLowerCase(), name);
|
|
2765
|
-
planned.push({ name, value, ref: refFor(target.account, request.vault, item) });
|
|
2766
|
-
}
|
|
2767
|
-
}
|
|
2768
|
-
let imports = planned;
|
|
2769
|
-
const stored = [];
|
|
2770
|
-
if (planned.length) {
|
|
2771
|
-
if (await deps.isLink(target.file))
|
|
2772
|
-
throw new Error(`${target.file} is a symbolic link; keypin import doesn't follow one`);
|
|
2773
|
-
const check = parseMap(mapText(target, planned, environment), target.file);
|
|
2774
|
-
if (!check.ok)
|
|
2775
|
-
throw new Error(`adding the keys to ${target.file} wouldn't parse, so nothing was created: ${check.errors.join("; ")}`);
|
|
2776
|
-
const scope = { kind: "1password", account: target.account, vault: request.vault };
|
|
2777
|
-
say(`keypin: listing the items in vault ${request.vault} of 1Password account ${target.account}`);
|
|
2778
|
-
const titles = new Set((await deps.vault().list(scope)).map((i) => i.title.toLowerCase()));
|
|
2779
|
-
imports = [];
|
|
2780
|
-
for (const entry of planned) {
|
|
2781
|
-
if (!titles.has(entry.ref.item.toLowerCase())) {
|
|
2782
|
-
imports.push(entry);
|
|
2783
|
-
continue;
|
|
2784
|
-
}
|
|
2785
|
-
const problem = await existingProblem(deps, entry);
|
|
2786
|
-
if (problem === null)
|
|
2787
|
-
stored.push(entry);
|
|
2788
|
-
else
|
|
2789
|
-
skips.push({
|
|
2790
|
-
name: entry.name,
|
|
2791
|
-
reason: `"${entry.ref.item}" already exists in vault ${request.vault} ${problem}; keypin doesn't overwrite it`,
|
|
2792
|
-
onlyInFile: true,
|
|
2793
|
-
exists: true
|
|
2794
|
-
});
|
|
2795
|
-
}
|
|
2796
|
-
}
|
|
2797
|
-
const today = localDay(deps.now());
|
|
2798
|
-
say(`Import ${envPath} into 1Password account ${target.account}, vault ${request.vault}:`);
|
|
2799
|
-
for (const { name, ref } of imports)
|
|
2800
|
-
say(` create "${ref.item}" (password, rotated ${today}), and map ${name} to ${formatReference(ref)}`);
|
|
2801
|
-
if (!imports.length)
|
|
2802
|
-
say(" nothing to create");
|
|
2803
|
-
for (const { name, ref } of stored)
|
|
2804
|
-
say(` map ${name} to ${formatReference(ref)}, an item that exists with the same value`);
|
|
2805
|
-
if (skips.length) {
|
|
2806
|
-
say("Skipped:");
|
|
2807
|
-
for (const skip of skips)
|
|
2808
|
-
say(` ${skip.name}: ${skip.reason}`);
|
|
2809
|
-
}
|
|
2810
|
-
const existed = skips.some((skip) => skip.exists);
|
|
2811
|
-
if (!imports.length && !stored.length)
|
|
2812
|
-
return existed ? 1 : 0;
|
|
2813
|
-
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}`);
|
|
2814
|
-
if (imports.length && !await confirmed(deps, request, imports.length))
|
|
2815
|
-
return NEEDS_APPROVAL;
|
|
2816
|
-
const created = [];
|
|
2817
|
-
for (const entry of imports) {
|
|
2818
|
-
try {
|
|
2819
|
-
await deps.vault().write(entry.ref, entry.value, { rotated: today, newItem: true });
|
|
2820
|
-
created.push(entry);
|
|
2821
|
-
say(` created "${entry.ref.item}"`);
|
|
2822
|
-
} catch (error) {
|
|
2823
|
-
say(` FAILED "${entry.ref.item}": ${messageOf(error)}`);
|
|
2824
|
-
break;
|
|
2825
|
-
}
|
|
2826
|
-
}
|
|
2827
|
-
const failed = imports.filter((entry) => !created.includes(entry)).map((i) => i.name);
|
|
2828
|
-
if (failed.length)
|
|
2829
|
-
say(`Stopped. Created ${names(created.map((i) => i.name))}; not created: ${names(failed)}.`);
|
|
2830
|
-
const mapped = planned.filter((entry) => stored.includes(entry) || created.includes(entry));
|
|
2831
|
-
if (!mapped.length)
|
|
2832
|
-
return 1;
|
|
2833
|
-
try {
|
|
2834
|
-
await writeMap(deps, target, mapped, environment);
|
|
2835
|
-
} catch (error) {
|
|
2836
|
-
say(`keypin: ${messageOf(error)}`);
|
|
2837
|
-
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:`);
|
|
2838
|
-
deps.stdout.write(mapAddition(target, mapped, environment));
|
|
2839
|
-
return 1;
|
|
2840
|
-
}
|
|
2841
|
-
say(`keypin: mapped ${names(mapped.map((i) => i.name))} in ${target.file}`);
|
|
2842
|
-
if (!target.map)
|
|
2843
|
-
await registerProject(deps, deps.cwd);
|
|
2844
|
-
const left = [...skips.filter((skip) => skip.onlyInFile).map((skip) => skip.name), ...failed];
|
|
2845
|
-
say(`The imported values are now in 1Password, and keypin run -- <command> provides them. keypin left ${envPath} as it is.`);
|
|
2846
|
-
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).");
|
|
2847
|
-
if (failed.length)
|
|
2848
|
-
say("Run keypin import again to create the rest. It maps an item it already stored, since that item holds the same value.");
|
|
2849
|
-
return failed.length || existed ? 1 : 0;
|
|
2850
|
-
}
|
|
2851
|
-
async function existingProblem(deps, entry) {
|
|
2852
|
-
try {
|
|
2853
|
-
const value = await deps.vault().read(entry.ref);
|
|
2854
|
-
return value.equals(entry.value) ? null : "with another value";
|
|
2855
|
-
} catch (error) {
|
|
2856
|
-
return `and couldn't be read (${messageOf(error)})`;
|
|
2857
|
-
}
|
|
2858
|
-
}
|
|
2859
|
-
function names(list) {
|
|
2860
|
-
return list.length ? list.join(", ") : "none";
|
|
2861
|
-
}
|
|
2862
|
-
function parseRequest(args) {
|
|
2863
|
-
const { values, positionals } = parseArgs3({
|
|
2864
|
-
args,
|
|
2865
|
-
options: {
|
|
2866
|
-
vault: { type: "string" },
|
|
2867
|
-
account: { type: "string" },
|
|
2868
|
-
yes: { type: "boolean", default: false }
|
|
2869
|
-
},
|
|
2870
|
-
allowPositionals: true
|
|
2871
|
-
});
|
|
2872
|
-
const [envFile, ...extra] = positionals;
|
|
2873
|
-
if (envFile === undefined || extra.length)
|
|
2874
|
-
throw new UsageError("keypin import takes one env file, such as .env or .dev.vars");
|
|
2875
|
-
const vault = values.vault?.trim();
|
|
2876
|
-
if (!vault)
|
|
2877
|
-
throw new UsageError("--vault is required: the 1Password vault to create the items in");
|
|
2878
|
-
if (vault.includes("/"))
|
|
2879
|
-
throw new UsageError("--vault is a vault name, without /");
|
|
2880
|
-
const account = values.account?.trim();
|
|
2881
|
-
if (values.account !== undefined && !account)
|
|
2882
|
-
throw new UsageError("--account is your 1Password sign-in address, such as my.1password.com");
|
|
2883
|
-
return { envFile, vault, account, yes: values.yes, args };
|
|
2884
|
-
}
|
|
2885
|
-
async function readTarget(deps, request) {
|
|
2886
|
-
const file = join6(deps.cwd, MAP_FILE);
|
|
2887
|
-
const found = await deps.files.read(file);
|
|
2888
|
-
if (found === null || found === TEMPLATE) {
|
|
2889
|
-
if (!request.account)
|
|
2890
|
-
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`);
|
|
2891
|
-
return { file, found, map: null, account: request.account };
|
|
2892
|
-
}
|
|
2893
|
-
const parsed = parseMap(found, file);
|
|
2894
|
-
if (!parsed.ok)
|
|
2895
|
-
throw new Error(`fix ${file} first: ${parsed.errors.join("; ")}`);
|
|
2896
|
-
const account = parsed.map.account ?? request.account;
|
|
2897
|
-
if (!account)
|
|
2898
|
-
throw new UsageError(`--account is required: ${file} has no [1password] account, so give its sign-in address, such as my.1password.com`);
|
|
2899
|
-
if (request.account && request.account !== account)
|
|
2900
|
-
throw new UsageError(`${file} uses 1Password account ${account}, not ${request.account}; drop --account`);
|
|
2901
|
-
return { file, found, map: parsed.map, account };
|
|
2902
|
-
}
|
|
2903
|
-
function refFor(account, vault, item) {
|
|
2904
|
-
return { kind: "1password", account, vault, item, section: null, field: "password" };
|
|
2905
|
-
}
|
|
2906
|
-
function keyTables(imports, environment) {
|
|
2907
|
-
return imports.map(({ name, ref }) => `
|
|
2908
|
-
[keys.${name}]
|
|
2909
|
-
rotate_every = ${str2(ROTATE_EVERY)}
|
|
2910
|
-
${environment} = ${str2(formatReference(ref))}
|
|
2911
|
-
`).join("");
|
|
2912
|
-
}
|
|
2913
|
-
function mapBase(target) {
|
|
2914
|
-
if (!target.map || target.found === null)
|
|
2915
|
-
return "";
|
|
2916
|
-
return target.found.endsWith(`
|
|
2917
|
-
`) || !target.found ? target.found : `${target.found}
|
|
2918
|
-
`;
|
|
2919
|
-
}
|
|
2920
|
-
function mapAddition(target, imports, environment) {
|
|
2921
|
-
const account = `[1password]
|
|
2922
|
-
account = ${str2(target.account)}
|
|
2923
|
-
`;
|
|
2924
|
-
const tables = keyTables(imports, environment);
|
|
2925
|
-
if (!target.map)
|
|
2926
|
-
return `# Written by keypin import. The values are in 1Password; this file holds only references.
|
|
2927
|
-
|
|
2928
|
-
${account}${tables}`;
|
|
2929
|
-
return `${target.map.account ? "" : `
|
|
2930
|
-
${account}`}${tables}`;
|
|
2931
|
-
}
|
|
2932
|
-
function mapText(target, imports, environment) {
|
|
2933
|
-
return `${mapBase(target)}${mapAddition(target, imports, environment)}`;
|
|
2934
|
-
}
|
|
2935
|
-
async function writeMap(deps, target, imports, environment) {
|
|
2936
|
-
const text = mapText(target, imports, environment);
|
|
2937
|
-
const check = parseMap(text, target.file);
|
|
2938
|
-
if (!check.ok)
|
|
2939
|
-
throw new Error(`the new ${target.file} doesn't parse: ${check.errors.join("; ")}`);
|
|
2940
|
-
const result = target.found === null ? await deps.createFile(target.file, text) : await deps.replaceFile(target.file, target.found, text);
|
|
2941
|
-
if (result === "link")
|
|
2942
|
-
throw new Error(`${target.file} is a symbolic link; keypin import doesn't follow one`);
|
|
2943
|
-
if (result === "exists" || result === "changed")
|
|
2944
|
-
throw new Error(`${target.file} changed while import ran, so it wasn't written`);
|
|
2945
|
-
}
|
|
2946
|
-
async function confirmed(deps, request, items) {
|
|
2947
|
-
const say = (text) => deps.stderr.write(`${text}
|
|
2948
|
-
`);
|
|
2949
|
-
if (request.yes)
|
|
2950
|
-
return true;
|
|
2951
|
-
if (deps.isTerminal) {
|
|
2952
|
-
const answer = await deps.ask(`Type yes to create ${count2(items, "item")} in 1Password: `);
|
|
2953
|
-
if (answer.trim() === "yes")
|
|
2954
|
-
return true;
|
|
2955
|
-
say("Not confirmed. Nothing was created.");
|
|
2956
|
-
return false;
|
|
2957
|
-
}
|
|
2958
|
-
say("Stopped: no terminal to confirm on. Nothing was created. Confirm in a terminal, or add --yes.");
|
|
2959
|
-
say(rerun(deps, "import", request.args));
|
|
2960
|
-
return false;
|
|
2961
|
-
}
|
|
2962
|
-
function count2(n, noun) {
|
|
2963
|
-
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
2964
|
-
}
|
|
2965
|
-
function str2(value) {
|
|
2966
|
-
return JSON.stringify(value);
|
|
2967
|
-
}
|
|
2968
|
-
|
|
2969
|
-
// src/commands/publish.ts
|
|
2970
|
-
import { parseArgs as parseArgs4 } from "util";
|
|
2971
|
-
|
|
2972
|
-
// src/vault.ts
|
|
2973
|
-
function announce(stderr, what, refs) {
|
|
2974
|
-
const groups = new Map;
|
|
2975
|
-
for (const ref of refs) {
|
|
2976
|
-
const where = `1Password account ${ref.account}`;
|
|
2977
|
-
groups.set(where, (groups.get(where) ?? new Set).add(formatReference(ref)));
|
|
2978
|
-
}
|
|
2979
|
-
for (const [where, references] of groups) {
|
|
2980
|
-
stderr.write(`keypin: reading ${what} from ${where}: ${[...references].join(", ")}
|
|
2981
|
-
`);
|
|
2982
|
-
}
|
|
2983
|
-
}
|
|
2984
|
-
function distinctRefs(refs) {
|
|
2985
|
-
const seen = new Map;
|
|
2986
|
-
for (const ref of refs)
|
|
2987
|
-
if (!seen.has(refKey(ref)))
|
|
2988
|
-
seen.set(refKey(ref), ref);
|
|
2989
|
-
return [...seen.values()];
|
|
2990
|
-
}
|
|
2991
|
-
var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item, ref.section, ref.field]);
|
|
2992
|
-
|
|
2993
|
-
// src/commands/publish.ts
|
|
2994
|
-
async function publish(args, deps) {
|
|
2995
|
-
const { keyId, env, yes, plan } = parseRequest2(args);
|
|
2996
|
-
const map = await findMap(deps.files, deps.cwd);
|
|
2997
|
-
const environment = pickEnvironment(map, env, publishEnvironment(map));
|
|
2998
|
-
const request = { keyId, environment, yes, plan, args };
|
|
2999
|
-
return locked(deps, (path) => publishLocked(request, map, path, deps));
|
|
3000
|
-
}
|
|
3001
|
-
function parseRequest2(args) {
|
|
3002
|
-
const { values, positionals } = parseArgs4({
|
|
3003
|
-
args,
|
|
3004
|
-
options: {
|
|
3005
|
-
env: { type: "string" },
|
|
3006
|
-
yes: { type: "boolean", default: false },
|
|
3007
|
-
all: { type: "boolean", default: false },
|
|
3008
|
-
plan: { type: "boolean", default: false }
|
|
3009
|
-
},
|
|
3010
|
-
allowPositionals: true
|
|
3011
|
-
});
|
|
3012
|
-
const [keyId, ...extra] = positionals;
|
|
3013
|
-
if (values.all) {
|
|
3014
|
-
if (positionals.length)
|
|
3015
|
-
throw new UsageError("keypin publish takes a variable name or --all, not both");
|
|
3016
|
-
return { keyId: null, env: values.env, yes: values.yes, plan: values.plan };
|
|
3017
|
-
}
|
|
3018
|
-
if (keyId === undefined || extra.length)
|
|
3019
|
-
throw new UsageError("keypin publish takes one key: the variable name, or --all");
|
|
3020
|
-
return { keyId, env: values.env, yes: values.yes, plan: values.plan };
|
|
3021
|
-
}
|
|
3022
|
-
function jobsFor(request, map, say) {
|
|
3023
|
-
const { keyId, environment } = request;
|
|
3024
|
-
const job = (key, entry) => ({
|
|
3025
|
-
key,
|
|
3026
|
-
entry,
|
|
3027
|
-
owner: { keyId: key.name, environment, mapFile: map.file }
|
|
3028
|
-
});
|
|
3029
|
-
if (keyId !== null) {
|
|
3030
|
-
const key = map.keys.find((k) => k.name === keyId);
|
|
3031
|
-
if (!key)
|
|
3032
|
-
throw new Error(`${map.file} has no key "${keyId}"`);
|
|
3033
|
-
const entry = key.environments[environment];
|
|
3034
|
-
if (!entry)
|
|
3035
|
-
throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
|
|
3036
|
-
return [job(key, entry)];
|
|
3037
|
-
}
|
|
3038
|
-
const jobs = map.keys.flatMap((key) => {
|
|
3039
|
-
const entry = key.environments[environment];
|
|
3040
|
-
return entry?.publish.length ? [job(key, entry)] : [];
|
|
3041
|
-
});
|
|
3042
|
-
const skipped = map.keys.filter((key) => !jobs.some((j) => j.key === key));
|
|
3043
|
-
if (skipped.length)
|
|
3044
|
-
say(`Not published, no ${environment} destinations: ${skipped.map((k) => k.name).join(", ")}`);
|
|
3045
|
-
return jobs;
|
|
3046
|
-
}
|
|
3047
|
-
async function publishLocked(request, map, path, deps) {
|
|
3048
|
-
const { environment } = request;
|
|
3049
|
-
const many = request.keyId === null;
|
|
3050
|
-
const say = (text) => deps.stderr.write(`${text}
|
|
3051
|
-
`);
|
|
3052
|
-
const jobs = jobsFor(request, map, say);
|
|
3053
|
-
if (many && !jobs.length) {
|
|
3054
|
-
say(`No key in ${map.file} has ${environment} destinations; nothing to publish.`);
|
|
3055
|
-
return 1;
|
|
3056
|
-
}
|
|
3057
|
-
for (const { key, entry } of jobs) {
|
|
3058
|
-
say(`Publishing ${key.name} (${environment}) from ${formatReference(entry.ref)}`);
|
|
3059
|
-
say(` 1Password account: ${entry.ref.account}`);
|
|
3060
|
-
for (const target of entry.publish)
|
|
3061
|
-
say(` to: ${describeTarget(target, key.name)}`);
|
|
3062
|
-
if (!entry.publish.length) {
|
|
3063
|
-
say(`The map lists no destinations for ${key.name} (${environment}); nothing to publish.`);
|
|
3064
|
-
return 1;
|
|
3065
|
-
}
|
|
3066
|
-
}
|
|
3067
|
-
let state = await loadState(deps.files, path);
|
|
3068
|
-
for (const { owner } of jobs) {
|
|
3069
|
-
for (const op of unfinishedOperations(state, owner)) {
|
|
3070
|
-
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.`);
|
|
3071
|
-
}
|
|
3072
|
-
}
|
|
3073
|
-
const checks = [];
|
|
3074
|
-
for (const job of jobs) {
|
|
3075
|
-
const heading = many ? `Account checks for ${job.key.name}` : "Account checks";
|
|
3076
|
-
const checked = await checkAccounts(job.key, job.entry, deps, say, heading);
|
|
3077
|
-
if (checked)
|
|
3078
|
-
checks.push({ ...job, checked });
|
|
3079
|
-
}
|
|
3080
|
-
if (checks.length < jobs.length) {
|
|
3081
|
-
say("Stopped: an account check failed. Nothing was read and nothing was written.");
|
|
3082
|
-
return 1;
|
|
3083
|
-
}
|
|
3084
|
-
const approvals = jobs.flatMap(({ key, owner }) => approvalsFor({ key, environment, mapFile: owner.mapFile, receipts: state.receipts }));
|
|
3085
|
-
if (approvals.length && !deps.isTerminal && !request.plan) {
|
|
3086
|
-
say(`
|
|
3087
|
-
Needs approval:`);
|
|
3088
|
-
for (const approval of approvals)
|
|
3089
|
-
say(` ${approval.approval}`);
|
|
3090
|
-
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.`);
|
|
3091
|
-
say(rerun(deps, "publish", request.args));
|
|
3092
|
-
return NEEDS_APPROVAL;
|
|
3093
|
-
}
|
|
3094
|
-
announce(deps.stderr, many ? "the values to publish" : "the value to publish", jobs.map((job) => job.entry.ref));
|
|
3095
|
-
const planned = [];
|
|
3096
|
-
let needsApproval = false;
|
|
3097
|
-
for (const job of checks) {
|
|
3098
|
-
const { key, entry, owner, checked } = job;
|
|
3099
|
-
let secret;
|
|
3100
|
-
try {
|
|
3101
|
-
secret = await deps.vault().read(entry.ref);
|
|
3102
|
-
} catch (error) {
|
|
3103
|
-
say(`Stopped: couldn't read ${key.name} (${formatReference(entry.ref)}): ${messageOf(error)}`);
|
|
3104
|
-
return 1;
|
|
3105
|
-
}
|
|
3106
|
-
const generation = await generationOf(secret);
|
|
3107
|
-
const plan = planPublish({
|
|
3108
|
-
key,
|
|
3109
|
-
environment,
|
|
3110
|
-
mapFile: owner.mapFile,
|
|
3111
|
-
receipts: state.receipts,
|
|
3112
|
-
generation
|
|
3113
|
-
});
|
|
3114
|
-
const writes = writesFor(plan.steps, checked);
|
|
3115
|
-
say(many ? `
|
|
3116
|
-
Plan for ${key.name}, generation ${generation}:` : `
|
|
3117
|
-
Plan for generation ${generation}:`);
|
|
3118
|
-
for (const step of plan.steps) {
|
|
3119
|
-
const found = checked.get(step.destinationId);
|
|
3120
|
-
say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
|
|
3121
|
-
if (found)
|
|
3122
|
-
say(` ${accountFacts(found.check)}`);
|
|
3123
|
-
if (step.approval)
|
|
3124
|
-
say(` needs approval: ${step.approval}`);
|
|
3125
|
-
}
|
|
3126
|
-
for (const removed of plan.removed) {
|
|
3127
|
-
say(` not in the map any more: ${removed.destinationId} (last got ${removed.lastReceipt.generation} at ${removed.lastReceipt.at}). keypin doesn't delete it.`);
|
|
3128
|
-
}
|
|
3129
|
-
needsApproval ||= plan.needsApproval;
|
|
3130
|
-
planned.push({ ...job, secret, generation, writes });
|
|
3131
|
-
}
|
|
3132
|
-
const finished = planned.filter((job) => !job.writes.length && unfinishedOperations(state, job.owner).length).reduce((s, job) => finishAll(s, job.owner), state);
|
|
3133
|
-
if (finished !== state && !request.plan) {
|
|
3134
|
-
state = finished;
|
|
3135
|
-
await saveState(deps.files, path, state);
|
|
3136
|
-
}
|
|
3137
|
-
const pending = planned.filter((job) => job.writes.length);
|
|
3138
|
-
if (!pending.length) {
|
|
3139
|
-
say("Nothing to write: every destination already has this generation.");
|
|
3140
|
-
return 0;
|
|
3141
|
-
}
|
|
3142
|
-
if (request.plan)
|
|
3143
|
-
return planOnly(deps, "publish", request.args, needsApproval);
|
|
3144
|
-
if (!await confirmed2(deps, needsApproval, request))
|
|
3145
|
-
return NEEDS_APPROVAL;
|
|
3146
|
-
for (const [index, job] of pending.entries()) {
|
|
3147
|
-
const written = await writeAll({
|
|
3148
|
-
key: job.key,
|
|
3149
|
-
environment,
|
|
3150
|
-
mapFile: job.owner.mapFile,
|
|
3151
|
-
entry: job.entry,
|
|
3152
|
-
secret: job.secret,
|
|
3153
|
-
generation: job.generation,
|
|
3154
|
-
writes: job.writes,
|
|
3155
|
-
state,
|
|
3156
|
-
path,
|
|
3157
|
-
deps,
|
|
3158
|
-
say
|
|
3159
|
-
});
|
|
3160
|
-
state = written.state;
|
|
3161
|
-
if (!written.ok) {
|
|
3162
|
-
if (many) {
|
|
3163
|
-
const left = pending.slice(index).map((j) => j.key.name);
|
|
3164
|
-
say(`Not finished: ${left.join(", ")}.`);
|
|
3165
|
-
}
|
|
3166
|
-
say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
|
|
3167
|
-
return 1;
|
|
3168
|
-
}
|
|
3169
|
-
say(`Published ${job.key.name} (${environment}) to ${job.writes.length} destination(s).`);
|
|
3170
|
-
}
|
|
3171
|
-
return 0;
|
|
3172
|
-
}
|
|
3173
|
-
async function confirmed2(deps, needsApproval, request) {
|
|
3174
|
-
const say = (text) => deps.stderr.write(`${text}
|
|
3175
|
-
`);
|
|
3176
|
-
if (request.yes && !needsApproval)
|
|
3177
|
-
return true;
|
|
3178
|
-
if (deps.isTerminal) {
|
|
3179
|
-
const answer = await deps.ask(`Type yes to write${needsApproval ? " (this plan needs approval)" : ""}: `);
|
|
3180
|
-
if (answer.trim() === "yes")
|
|
3181
|
-
return true;
|
|
3182
|
-
say("Not confirmed. Nothing was written.");
|
|
3183
|
-
return false;
|
|
3184
|
-
}
|
|
3185
|
-
say(needsApproval ? "Stopped: this plan needs approval, and --yes can't give it. Nothing was written." : "Stopped: no terminal to confirm on. Nothing was written. Add --yes, or confirm in a terminal.");
|
|
3186
|
-
say(rerun(deps, "publish", request.args));
|
|
3187
|
-
return false;
|
|
3188
|
-
}
|
|
3189
|
-
|
|
3190
|
-
// src/commands/rotate.ts
|
|
3191
|
-
import { join as join7 } from "path";
|
|
3192
|
-
import { parseArgs as parseArgs5 } from "util";
|
|
3193
|
-
var GRACE_DAYS = DUE_SOON_DAYS;
|
|
3194
|
-
async function rotate(args, deps) {
|
|
3195
|
-
const { values, positionals } = parseArgs5({
|
|
3196
|
-
args,
|
|
3197
|
-
options: {
|
|
3198
|
-
env: { type: "string" },
|
|
3199
|
-
yes: { type: "boolean", default: false },
|
|
3200
|
-
plan: { type: "boolean", default: false }
|
|
3201
|
-
},
|
|
3202
|
-
allowPositionals: true
|
|
3203
|
-
});
|
|
3204
|
-
const [keyId, ...extra] = positionals;
|
|
3205
|
-
if (keyId === undefined || extra.length)
|
|
3206
|
-
throw new UsageError("keypin rotate takes one key: the variable name");
|
|
3207
|
-
const map = await findMap(deps.files, deps.cwd);
|
|
3208
|
-
const environment = pickEnvironment(map, values.env, publishEnvironment(map));
|
|
3209
|
-
const key = map.keys.find((k) => k.name === keyId);
|
|
3210
|
-
if (!key)
|
|
3211
|
-
throw new Error(`${map.file} has no key "${keyId}"`);
|
|
3212
|
-
const entry = key.environments[environment];
|
|
3213
|
-
if (!entry)
|
|
3214
|
-
throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
|
|
3215
|
-
const spec = entry.rotate;
|
|
3216
|
-
if (!spec) {
|
|
3217
|
-
throw new Error(`key "${keyId}" has no [keys.${keyId}.${environment}.rotate] section in ${map.file}, so keypin can't make a new value`);
|
|
3218
|
-
}
|
|
3219
|
-
const say = (text) => deps.stderr.write(`${text}
|
|
3220
|
-
`);
|
|
3221
|
-
return locked(deps, async (statePath) => {
|
|
3222
|
-
const run = {
|
|
3223
|
-
map,
|
|
3224
|
-
key,
|
|
3225
|
-
entry,
|
|
3226
|
-
spec,
|
|
3227
|
-
environment,
|
|
3228
|
-
yes: values.yes,
|
|
3229
|
-
plan: values.plan,
|
|
3230
|
-
args,
|
|
3231
|
-
statePath,
|
|
3232
|
-
rotationsPath: rotationsPath(deps),
|
|
3233
|
-
deps,
|
|
3234
|
-
say
|
|
3235
|
-
};
|
|
3236
|
-
const data = await loadRotations(deps.files, run.rotationsPath);
|
|
3237
|
-
const open = unfinishedRotation(data, keyOwner(run), entry.ref);
|
|
3238
|
-
if (!open)
|
|
3239
|
-
return start(run, data);
|
|
3240
|
-
say(`An unfinished rotation of ${key.name} (${environment}), started ${open.startedAt}, is at stage "${open.stage}".`);
|
|
3241
|
-
if (open.provider !== spec.provider || open.account !== spec.account) {
|
|
3242
|
-
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.`);
|
|
3243
|
-
return 1;
|
|
3244
|
-
}
|
|
3245
|
-
switch (open.stage) {
|
|
3246
|
-
case "issuing":
|
|
3247
|
-
case "issued":
|
|
3248
|
-
return abandon(run, data, open);
|
|
3249
|
-
case "stored":
|
|
3250
|
-
return publishNew(run, data, open, null);
|
|
3251
|
-
case "published":
|
|
3252
|
-
return revokeOld(run, data, open);
|
|
3253
|
-
case "revoked":
|
|
3254
|
-
throw new Error(`rotation ${open.id} is finished`);
|
|
3255
|
-
}
|
|
3256
|
-
});
|
|
3257
|
-
}
|
|
3258
|
-
async function start(run, data) {
|
|
3259
|
-
const { key, entry, spec, environment, deps, say } = run;
|
|
3260
|
-
say(`Rotating ${key.name} (${environment}) from ${formatReference(entry.ref)}`);
|
|
3261
|
-
say(` 1Password account: ${entry.ref.account}`);
|
|
3262
|
-
say(` new token: ${spec.provider} in account ${spec.account}, made with the admin token in ${formatReference(spec.admin)}`);
|
|
3263
|
-
for (const target of entry.publish)
|
|
3264
|
-
say(` to: ${describeTarget(target, key.name)}`);
|
|
3265
|
-
if (!entry.publish.length) {
|
|
3266
|
-
say(`Stopped: the map lists no destinations for ${key.name} (${environment}), so nothing would get the new token. Nothing was changed.`);
|
|
3267
|
-
return 1;
|
|
3268
|
-
}
|
|
3269
|
-
const every = key.rotateEvery;
|
|
3270
|
-
const days = periodDays(every);
|
|
3271
|
-
if (!days) {
|
|
3272
|
-
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.`);
|
|
3273
|
-
return 1;
|
|
3274
|
-
}
|
|
3275
|
-
const state = await loadState(deps.files, run.statePath);
|
|
3276
|
-
const checked = await checkAccounts(key, entry, deps, say);
|
|
3277
|
-
if (!checked) {
|
|
3278
|
-
say("Stopped: an account check failed. Nothing was read and nothing was changed.");
|
|
3279
|
-
return 1;
|
|
3280
|
-
}
|
|
3281
|
-
const approvals = approvalsFor({ ...planFor(run), receipts: state.receipts });
|
|
3282
|
-
if (!deps.isTerminal && !run.plan && (approvals.length || !run.yes)) {
|
|
3283
|
-
for (const approval of approvals)
|
|
3284
|
-
say(` needs approval: ${approval.approval}`);
|
|
3285
|
-
say(approvals.length ? "Stopped before reading anything: this rotation needs approval, and --yes can't give it. Nothing was changed." : "Stopped before reading anything: no terminal to confirm on. Nothing was changed. Add --yes, or confirm in a terminal.");
|
|
3286
|
-
say(rerun(deps, "rotate", run.args));
|
|
3287
|
-
return NEEDS_APPROVAL;
|
|
3288
|
-
}
|
|
3289
|
-
announce(deps.stderr, "the current value and the admin token", [entry.ref, spec.admin]);
|
|
3290
|
-
const vault = deps.vault();
|
|
3291
|
-
let current;
|
|
3292
|
-
let admin;
|
|
3293
|
-
try {
|
|
3294
|
-
current = await vault.read(entry.ref);
|
|
3295
|
-
admin = await vault.read(spec.admin);
|
|
3296
|
-
} catch (error) {
|
|
3297
|
-
say(`Stopped: ${messageOf(error)}. Nothing was changed.`);
|
|
3298
|
-
return 1;
|
|
3299
|
-
}
|
|
3300
|
-
if (current.equals(admin)) {
|
|
3301
|
-
say(`Stopped: ${formatReference(spec.admin)} holds the same value as ${formatReference(entry.ref)}. The admin token needs its own field, or rotating would overwrite it. Nothing was changed.`);
|
|
3302
|
-
return 1;
|
|
3303
|
-
}
|
|
3304
|
-
const provider = deps.provider(spec, admin);
|
|
3305
|
-
const found = await provider.verify(current);
|
|
3306
|
-
if (found.status !== "active") {
|
|
3307
|
-
say(`Stopped: the current value is token ${found.id}, and it's ${found.status}. Nothing was changed.`);
|
|
3308
|
-
return 1;
|
|
3309
|
-
}
|
|
3310
|
-
const old = await provider.details(found.id);
|
|
3311
|
-
if (!old) {
|
|
3312
|
-
say(`Stopped: the admin token can't read token ${found.id}, the current value's token. Nothing was changed.`);
|
|
3313
|
-
return 1;
|
|
3314
|
-
}
|
|
3315
|
-
const today = localDay(deps.now());
|
|
3316
|
-
const name = nextName(old.name, today);
|
|
3317
|
-
const expiresOn = `${addDays(today, days + GRACE_DAYS)}T23:59:59Z`;
|
|
3318
|
-
say(`
|
|
3319
|
-
Plan:`);
|
|
3320
|
-
say(` current token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "never"}`);
|
|
3321
|
-
say(` new token: "${name}", expires ${expiresOn} (rotate_every ${every} plus ${GRACE_DAYS} days' grace)`);
|
|
3322
|
-
for (const line of describeAccess(old))
|
|
3323
|
-
say(` ${line}`);
|
|
3324
|
-
say(` store in: ${formatReference(entry.ref)}, with rotated ${today}`);
|
|
3325
|
-
for (const target of entry.publish) {
|
|
3326
|
-
const found = checked.get(destinationId(target, key.name));
|
|
3327
|
-
say(` publish to: ${describeTarget(target, key.name)}`);
|
|
3328
|
-
if (found)
|
|
3329
|
-
say(` ${accountFacts(found.check)}`);
|
|
3330
|
-
}
|
|
3331
|
-
for (const approval of approvals)
|
|
3332
|
-
say(` needs approval: ${approval.approval}`);
|
|
3333
|
-
say(` then stop: the old token stays active until you run ${again(run)} again.`);
|
|
3334
|
-
if (run.plan)
|
|
3335
|
-
return planOnly(deps, "rotate", run.args, approvals.length > 0);
|
|
3336
|
-
if (!await confirmed3(run, approvals.length > 0, "make the new token"))
|
|
3337
|
-
return NEEDS_APPROVAL;
|
|
3338
|
-
const now = deps.now().toISOString();
|
|
3339
|
-
let rotation = {
|
|
3340
|
-
id: crypto.randomUUID(),
|
|
3341
|
-
keyId: key.name,
|
|
3342
|
-
environment,
|
|
3343
|
-
mapFile: run.map.file,
|
|
3344
|
-
item: entry.ref,
|
|
3345
|
-
provider: spec.provider,
|
|
3346
|
-
account: spec.account,
|
|
3347
|
-
stage: "issuing",
|
|
3348
|
-
startedAt: now,
|
|
3349
|
-
updatedAt: now,
|
|
3350
|
-
old: {
|
|
3351
|
-
id: old.id,
|
|
3352
|
-
name: old.name,
|
|
3353
|
-
expiresOn: old.expiresOn,
|
|
3354
|
-
generation: await generationOf(current)
|
|
3355
|
-
},
|
|
3356
|
-
new: { id: null, name, expiresOn, generation: null }
|
|
3357
|
-
};
|
|
3358
|
-
data = putRotation(withoutFinished(data, keyOwner(run)), rotation);
|
|
3359
|
-
await saveRotations(deps.files, run.rotationsPath, data);
|
|
3360
|
-
const made = await provider.issue({ name, like: old, expiresOn });
|
|
3361
|
-
if ("refused" in made) {
|
|
3362
|
-
await saveRotations(deps.files, run.rotationsPath, dropRotation(data, rotation.id));
|
|
3363
|
-
say(`Stopped: ${made.refused}. No token was made, and nothing was changed.`);
|
|
3364
|
-
return 1;
|
|
3365
|
-
}
|
|
3366
|
-
const generation = await generationOf(made.value);
|
|
3367
|
-
rotation = {
|
|
3368
|
-
...rotation,
|
|
3369
|
-
stage: "issued",
|
|
3370
|
-
updatedAt: deps.now().toISOString(),
|
|
3371
|
-
new: { id: made.token.id, name: made.token.name, expiresOn: made.token.expiresOn, generation }
|
|
3372
|
-
};
|
|
3373
|
-
data = putRotation(data, rotation);
|
|
3374
|
-
await saveRotations(deps.files, run.rotationsPath, data);
|
|
3375
|
-
say(`
|
|
3376
|
-
issued ${made.token.id} "${made.token.name}", expires ${made.token.expiresOn ?? "never"}`);
|
|
3377
|
-
const problem = await checkNew(provider, made.token.id, made.value, old);
|
|
3378
|
-
if (problem) {
|
|
3379
|
-
say(` FAILED the new token's check: ${problem}`);
|
|
3380
|
-
return deleteUnchecked(run, data, rotation, provider);
|
|
3381
|
-
}
|
|
3382
|
-
say(` checked: ${made.token.id} is active and has the same policies as ${old.id}`);
|
|
3383
|
-
say(`keypin: writing the new value to ${formatReference(entry.ref)}, with rotated ${today}`);
|
|
3384
|
-
try {
|
|
3385
|
-
await vault.write(entry.ref, made.value, { rotated: today });
|
|
3386
|
-
const stored = await generationOf(await vault.read(entry.ref));
|
|
3387
|
-
if (stored !== generation)
|
|
3388
|
-
throw new Error(`the item reads back generation ${stored}, not ${generation}`);
|
|
3389
|
-
} catch (error) {
|
|
3390
|
-
say(`Stopped: couldn't store the new value: ${messageOf(error)}.`);
|
|
3391
|
-
say(`The new token ${made.token.id} exists, and the old token still works everywhere. Run ${again(run)} again to delete the new token and start over.`);
|
|
3392
|
-
return 1;
|
|
3393
|
-
}
|
|
3394
|
-
rotation = { ...rotation, stage: "stored", updatedAt: deps.now().toISOString() };
|
|
3395
|
-
data = putRotation(data, rotation);
|
|
3396
|
-
await saveRotations(deps.files, run.rotationsPath, data);
|
|
3397
|
-
say(` stored generation ${generation}`);
|
|
3398
|
-
return publishNew(run, data, rotation, { value: made.value, checked });
|
|
3399
|
-
}
|
|
3400
|
-
async function publishNew(run, data, rotation, fresh) {
|
|
3401
|
-
const { key, entry, environment, deps, say } = run;
|
|
3402
|
-
const state = await loadState(deps.files, run.statePath);
|
|
3403
|
-
let value;
|
|
3404
|
-
let checked;
|
|
3405
|
-
const resuming = fresh === null;
|
|
3406
|
-
if (fresh) {
|
|
3407
|
-
({ value, checked } = fresh);
|
|
3408
|
-
} else {
|
|
3409
|
-
say(`It stored the new value (generation ${rotation.new.generation}); this run publishes it.`);
|
|
3410
|
-
const found = await checkAccounts(key, entry, deps, say);
|
|
3411
|
-
if (!found) {
|
|
3412
|
-
say("Stopped: an account check failed. Nothing was read and nothing was written.");
|
|
3413
|
-
return 1;
|
|
3414
|
-
}
|
|
3415
|
-
checked = found;
|
|
3416
|
-
const approvals = approvalsFor({ ...planFor(run), receipts: state.receipts });
|
|
3417
|
-
if (!deps.isTerminal && !run.plan && approvals.length) {
|
|
3418
|
-
say("Stopped before reading the value: publishing needs approval, and --yes can't give it.");
|
|
3419
|
-
say(rerun(deps, "rotate", run.args));
|
|
3420
|
-
return NEEDS_APPROVAL;
|
|
3421
|
-
}
|
|
3422
|
-
announce(deps.stderr, "the value to publish and the admin token, to check the new token", [
|
|
3423
|
-
entry.ref,
|
|
3424
|
-
run.spec.admin
|
|
3425
|
-
]);
|
|
3426
|
-
value = await deps.vault().read(entry.ref);
|
|
3427
|
-
const generation = await generationOf(value);
|
|
3428
|
-
if (generation !== rotation.new.generation) {
|
|
3429
|
-
say(`Stopped: ${formatReference(entry.ref)} holds generation ${generation}, not the rotation's ${rotation.new.generation}. Something else changed it. Nothing was written.`);
|
|
3430
|
-
return 1;
|
|
3431
|
-
}
|
|
3432
|
-
const problem = await recheck(run, rotation, value);
|
|
3433
|
-
if (problem) {
|
|
3434
|
-
say(`Stopped: ${problem}. Nothing was written, and the rotation stays at "${rotation.stage}". The old token still works where it was published.`);
|
|
3435
|
-
return 1;
|
|
3436
|
-
}
|
|
3437
|
-
say(` checked: ${rotation.new.id} is active and has the same policies as ${rotation.old.id}`);
|
|
3438
|
-
}
|
|
3439
|
-
const generation = rotation.new.generation ?? await generationOf(value);
|
|
3440
|
-
const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
|
|
3441
|
-
say(`
|
|
3442
|
-
Publishing generation ${generation}:`);
|
|
3443
|
-
for (const step of plan.steps) {
|
|
3444
|
-
say(` ${step.action} ${describeTarget(step.target, key.name)}: ${step.reason}`);
|
|
3445
|
-
if (step.approval)
|
|
3446
|
-
say(` needs approval: ${step.approval}`);
|
|
3447
|
-
}
|
|
3448
|
-
const writes = writesFor(plan.steps, checked);
|
|
3449
|
-
if (run.plan)
|
|
3450
|
-
return planOnly(deps, "rotate", run.args, plan.needsApproval);
|
|
3451
|
-
if (resuming && writes.length && !await confirmed3(run, plan.needsApproval, "publish")) {
|
|
3452
|
-
return NEEDS_APPROVAL;
|
|
3453
|
-
}
|
|
3454
|
-
const written = await writeAll({
|
|
3455
|
-
key,
|
|
3456
|
-
environment,
|
|
3457
|
-
mapFile: run.map.file,
|
|
3458
|
-
entry,
|
|
3459
|
-
secret: value,
|
|
3460
|
-
generation,
|
|
3461
|
-
writes,
|
|
3462
|
-
state,
|
|
3463
|
-
path: run.statePath,
|
|
3464
|
-
deps,
|
|
3465
|
-
say
|
|
3466
|
-
});
|
|
3467
|
-
if (!written.ok) {
|
|
3468
|
-
say(`Stopped. The old token still works where the write failed. Run ${again(run)} again to finish publishing.`);
|
|
3469
|
-
return 1;
|
|
3470
|
-
}
|
|
3471
|
-
const published = {
|
|
3472
|
-
...rotation,
|
|
3473
|
-
stage: "published",
|
|
3474
|
-
updatedAt: deps.now().toISOString()
|
|
3475
|
-
};
|
|
3476
|
-
await saveRotations(deps.files, run.rotationsPath, putRotation(data, published));
|
|
3477
|
-
say(`
|
|
3478
|
-
Published. The old token ${rotation.old.id} "${rotation.old.name}" is still active.`);
|
|
3479
|
-
say("Next, check that every consumer works with the new value:");
|
|
3480
|
-
for (const target of entry.publish)
|
|
3481
|
-
say(` ${describeTarget(target, key.name)}`);
|
|
3482
|
-
say(`Then run ${again(run)} again to revoke the old token.`);
|
|
3483
|
-
return 0;
|
|
3484
|
-
}
|
|
3485
|
-
async function revokeOld(run, data, rotation) {
|
|
3486
|
-
const { key, spec, environment, deps, say } = run;
|
|
3487
|
-
const generation = rotation.new.generation;
|
|
3488
|
-
if (!generation || !rotation.new.id || !rotation.old.id) {
|
|
3489
|
-
throw new Error(`rotation ${rotation.id} has no new generation or token IDs`);
|
|
3490
|
-
}
|
|
3491
|
-
const state = await loadState(deps.files, run.statePath);
|
|
3492
|
-
const plan = planPublish({ ...planFor(run), receipts: state.receipts, generation });
|
|
3493
|
-
const behind = plan.steps.filter((step) => step.action === "write");
|
|
3494
|
-
for (const step of behind) {
|
|
3495
|
-
say(` ${step.destinationId} doesn't have generation ${generation}: ${step.reason}`);
|
|
3496
|
-
}
|
|
3497
|
-
const retired = plan.removed.filter((removed) => removed.lastReceipt.generation === rotation.old.generation);
|
|
3498
|
-
if (behind.length) {
|
|
3499
|
-
say(`Stopped: run keypin publish ${key.name}${envFlag(environment, publishEnvironment(run.map))} first. Nothing was revoked.`);
|
|
3500
|
-
return 1;
|
|
3501
|
-
}
|
|
3502
|
-
say(`Every destination of ${key.name} (${environment}) has generation ${generation}.`);
|
|
3503
|
-
for (const removed of retired) {
|
|
3504
|
-
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`);
|
|
3505
|
-
}
|
|
3506
|
-
const others = await otherHolders(run, state.receipts, rotation.old.generation, retired);
|
|
3507
|
-
if (others === null)
|
|
3508
|
-
return 1;
|
|
3509
|
-
if (others.length) {
|
|
3510
|
-
say(`Stopped: these destinations still have the old token. Put the new value in each one's vault item, then run its keypin publish. Nothing was revoked.`);
|
|
3511
|
-
for (const { receipt, owner } of others) {
|
|
3512
|
-
say(` ${describeHolder(receipt)}: ${publishCommand(owner)}`);
|
|
3513
|
-
}
|
|
3514
|
-
return 1;
|
|
3515
|
-
}
|
|
3516
|
-
if (!deps.isTerminal && !run.plan) {
|
|
3517
|
-
say("Stopped: revoking needs yes typed in a terminal, and --yes can't give it. Nothing was revoked.");
|
|
3518
|
-
say(rerun(deps, "rotate", run.args));
|
|
3519
|
-
return NEEDS_APPROVAL;
|
|
3520
|
-
}
|
|
3521
|
-
announce(deps.stderr, "the current value, to check it's the new token, and the admin token", [
|
|
3522
|
-
run.entry.ref,
|
|
3523
|
-
spec.admin
|
|
3524
|
-
]);
|
|
3525
|
-
const holds = await generationOf(await deps.vault().read(run.entry.ref));
|
|
3526
|
-
if (holds !== generation) {
|
|
3527
|
-
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.`);
|
|
3528
|
-
return 1;
|
|
3529
|
-
}
|
|
3530
|
-
const provider = deps.provider(spec, await deps.vault().read(spec.admin));
|
|
3531
|
-
const current = await provider.details(rotation.new.id);
|
|
3532
|
-
if (current?.status !== "active") {
|
|
3533
|
-
say(`Stopped: the new token ${rotation.new.id} is ${current ? current.status : "gone"}. Nothing was revoked.`);
|
|
3534
|
-
return 1;
|
|
3535
|
-
}
|
|
3536
|
-
const old = await provider.details(rotation.old.id);
|
|
3537
|
-
if (!old) {
|
|
3538
|
-
say(`The old token ${rotation.old.id} is already gone.`);
|
|
3539
|
-
if (!run.plan)
|
|
3540
|
-
return finish(run, data, rotation);
|
|
3541
|
-
say("The next run records this rotation as finished, and asks nothing.");
|
|
3542
|
-
return planOnly(deps, "rotate", run.args, true);
|
|
3543
|
-
}
|
|
3544
|
-
say(`
|
|
3545
|
-
Old token: ${old.id} "${old.name}", ${old.status}, expires ${old.expiresOn ?? "never"}`);
|
|
3546
|
-
say(` last used: ${old.lastUsedOn ?? "not reported"}`);
|
|
3547
|
-
say(`New token: ${current.id} "${current.name}", ${current.status}, expires ${current.expiresOn ?? "never"}`);
|
|
3548
|
-
if (run.plan)
|
|
3549
|
-
return planOnly(deps, "rotate", run.args, true);
|
|
3550
|
-
const answer = await deps.ask(`Type yes to revoke the old token ${old.id}: `);
|
|
3551
|
-
if (answer.trim() !== "yes") {
|
|
3552
|
-
say("Not confirmed. Nothing was revoked.");
|
|
3553
|
-
return NEEDS_APPROVAL;
|
|
3554
|
-
}
|
|
3555
|
-
say(` ${await provider.revoke(old.id)} ${old.id}`);
|
|
3556
|
-
return finish(run, data, rotation);
|
|
3557
|
-
}
|
|
3558
|
-
async function finish(run, data, rotation) {
|
|
3559
|
-
const done = { ...rotation, stage: "revoked", updatedAt: run.deps.now().toISOString() };
|
|
3560
|
-
await saveRotations(run.deps.files, run.rotationsPath, putRotation(data, done));
|
|
3561
|
-
run.say(`Rotated ${run.key.name} (${run.environment}): ${rotation.new.id} replaced ${rotation.old.id}.`);
|
|
3562
|
-
return 0;
|
|
3563
|
-
}
|
|
3564
|
-
async function abandon(run, data, rotation) {
|
|
3565
|
-
const { entry, spec, deps, say } = run;
|
|
3566
|
-
if (rotation.new.generation) {
|
|
3567
|
-
announce(deps.stderr, "the current value, to see which token it holds", [entry.ref]);
|
|
3568
|
-
const holds = await generationOf(await deps.vault().read(entry.ref));
|
|
3569
|
-
if (holds === rotation.new.generation) {
|
|
3570
|
-
const stored = {
|
|
3571
|
-
...rotation,
|
|
3572
|
-
stage: "stored",
|
|
3573
|
-
updatedAt: deps.now().toISOString()
|
|
3574
|
-
};
|
|
3575
|
-
const next = putRotation(data, stored);
|
|
3576
|
-
if (!run.plan)
|
|
3577
|
-
await saveRotations(deps.files, run.rotationsPath, next);
|
|
3578
|
-
say(`${formatReference(entry.ref)} already holds the new value (generation ${holds}).`);
|
|
3579
|
-
return publishNew(run, next, stored, null);
|
|
3580
|
-
}
|
|
3581
|
-
if (holds !== rotation.old.generation) {
|
|
3582
|
-
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.`);
|
|
3583
|
-
return 1;
|
|
3584
|
-
}
|
|
3585
|
-
}
|
|
3586
|
-
if (rotation.new.generation) {
|
|
3587
|
-
const state = await loadState(deps.files, run.statePath);
|
|
3588
|
-
const holders = holdersOf(state.receipts, rotation.new.generation);
|
|
3589
|
-
if (holders.length) {
|
|
3590
|
-
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:`);
|
|
3591
|
-
const owners = await listedOwners(run);
|
|
3592
|
-
if (owners === null)
|
|
3593
|
-
return 1;
|
|
3594
|
-
for (const r of holders) {
|
|
3595
|
-
const owner = ownerOf2(r, owners);
|
|
3596
|
-
say(` ${describeHolder(r)}: ${owner ? publishCommand(owner) : "no registered map lists it; set that secret to the old value by hand"}`);
|
|
3597
|
-
}
|
|
3598
|
-
return 1;
|
|
3599
|
-
}
|
|
3600
|
-
}
|
|
3601
|
-
say(`It stopped before the new value was stored, so the old token ${rotation.old.id} still works everywhere.`);
|
|
3602
|
-
if (run.plan) {
|
|
3603
|
-
say(rotation.new.id ? `The next run deletes the new token ${rotation.new.id} and forgets this rotation.` : `Cloudflare may have made a token named "${rotation.new.name}". The next run can't delete it: find it under Account API tokens and delete it, then the next run forgets this rotation.`);
|
|
3604
|
-
return planOnly(deps, "rotate", run.args, true);
|
|
3605
|
-
}
|
|
3606
|
-
if (!deps.isTerminal) {
|
|
3607
|
-
say("Stopped: cleaning it up needs yes typed in a terminal. Nothing was changed.");
|
|
3608
|
-
say(rerun(deps, "rotate", run.args));
|
|
3609
|
-
return NEEDS_APPROVAL;
|
|
3610
|
-
}
|
|
3611
|
-
const id = rotation.new.id;
|
|
3612
|
-
if (!id) {
|
|
3613
|
-
say(`Cloudflare may have made a token named "${rotation.new.name}". Look for it under Account API tokens and delete it if it's there.`);
|
|
3614
|
-
if ((await deps.ask("Type yes to forget this rotation: ")).trim() !== "yes") {
|
|
3615
|
-
say("Not confirmed. Nothing was changed.");
|
|
3616
|
-
return NEEDS_APPROVAL;
|
|
3617
|
-
}
|
|
3618
|
-
} else {
|
|
3619
|
-
announce(deps.stderr, "the admin token", [spec.admin]);
|
|
3620
|
-
const provider = deps.provider(spec, await deps.vault().read(spec.admin));
|
|
3621
|
-
const made = await provider.details(id);
|
|
3622
|
-
if (made) {
|
|
3623
|
-
say(`New token: ${made.id} "${made.name}", ${made.status}, its value was never stored`);
|
|
3624
|
-
if ((await deps.ask(`Type yes to delete the new token ${made.id}: `)).trim() !== "yes") {
|
|
3625
|
-
say("Not confirmed. Nothing was changed.");
|
|
3626
|
-
return NEEDS_APPROVAL;
|
|
3627
|
-
}
|
|
3628
|
-
say(` ${await provider.revoke(made.id)} ${made.id}`);
|
|
3629
|
-
} else {
|
|
3630
|
-
say(`The new token ${id} is already gone.`);
|
|
3631
|
-
}
|
|
3632
|
-
}
|
|
3633
|
-
await saveRotations(deps.files, run.rotationsPath, dropRotation(data, rotation.id));
|
|
3634
|
-
say(`Cleared. Run ${again(run)} again to start over.`);
|
|
3635
|
-
return 1;
|
|
3636
|
-
}
|
|
3637
|
-
async function deleteUnchecked(run, data, rotation, provider) {
|
|
3638
|
-
const id = rotation.new.id;
|
|
3639
|
-
if (!id)
|
|
3640
|
-
throw new Error(`rotation ${rotation.id} has no new token ID`);
|
|
3641
|
-
try {
|
|
3642
|
-
run.say(` ${await provider.revoke(id)} ${id}, the token this run made`);
|
|
3643
|
-
} catch (error) {
|
|
3644
|
-
run.say(`Couldn't delete the new token ${id}: ${messageOf(error)}.`);
|
|
3645
|
-
run.say(`Nothing else was changed, and the old token still works everywhere. Run ${again(run)} again to delete it.`);
|
|
3646
|
-
return 1;
|
|
3647
|
-
}
|
|
3648
|
-
await saveRotations(run.deps.files, run.rotationsPath, dropRotation(data, rotation.id));
|
|
3649
|
-
run.say("Stopped. Nothing else was changed, and the old token still works everywhere.");
|
|
3650
|
-
return 1;
|
|
3651
|
-
}
|
|
3652
|
-
async function recheck(run, rotation, value) {
|
|
3653
|
-
if (!rotation.new.id || !rotation.old.id)
|
|
3654
|
-
return "the rotation has no token IDs";
|
|
3655
|
-
const provider = run.deps.provider(run.spec, await run.deps.vault().read(run.spec.admin));
|
|
3656
|
-
const old = await provider.details(rotation.old.id);
|
|
3657
|
-
if (!old)
|
|
3658
|
-
return `the old token ${rotation.old.id} is gone, so its policies can't be compared`;
|
|
3659
|
-
return checkNew(provider, rotation.new.id, value, old);
|
|
3660
|
-
}
|
|
3661
|
-
function holdersOf(receipts, generation) {
|
|
3662
|
-
return latestPerSecret(receipts).filter((r) => r.generation === generation);
|
|
3663
|
-
}
|
|
3664
|
-
function describeHolder(receipt) {
|
|
3665
|
-
return `${receipt.destinationId} (${receipt.keyId}, ${receipt.environment})`;
|
|
3666
|
-
}
|
|
3667
|
-
function publishCommand(owner) {
|
|
3668
|
-
const env = envFlag(owner.environment, owner.publishDefault);
|
|
3669
|
-
const where = owner.project === null ? "" : `cd ${shellWord(owner.project)} && `;
|
|
3670
|
-
return `${where}keypin publish ${owner.keyId}${env}`;
|
|
3671
|
-
}
|
|
3672
|
-
async function listedOwners(run) {
|
|
3673
|
-
const { deps, say } = run;
|
|
3674
|
-
const owners = new Map;
|
|
3675
|
-
const list = (map, project) => {
|
|
3676
|
-
for (const k of map.keys) {
|
|
3677
|
-
for (const [name, entry] of Object.entries(k.environments)) {
|
|
3678
|
-
for (const target of entry?.publish ?? []) {
|
|
3679
|
-
const secret = secretKey(target, k.name);
|
|
3680
|
-
owners.set(secret, [
|
|
3681
|
-
...owners.get(secret) ?? [],
|
|
3682
|
-
{
|
|
3683
|
-
project,
|
|
3684
|
-
keyId: k.name,
|
|
3685
|
-
environment: name,
|
|
3686
|
-
mapFile: map.file,
|
|
3687
|
-
publishDefault: publishEnvironment(map)
|
|
3688
|
-
}
|
|
3689
|
-
]);
|
|
3690
|
-
}
|
|
3691
|
-
}
|
|
3692
|
-
}
|
|
3693
|
-
};
|
|
3694
|
-
list(run.map, null);
|
|
3695
|
-
const registry = await loadRegistry(deps.files, registryPath(deps));
|
|
3696
|
-
for (const project of registry.projects) {
|
|
3697
|
-
const file = join7(project, MAP_FILE);
|
|
3698
|
-
if (file === run.map.file)
|
|
3699
|
-
continue;
|
|
3700
|
-
const text = await deps.files.read(file);
|
|
3701
|
-
const result = text === null ? null : parseMap(text, file);
|
|
3702
|
-
if (!result?.ok) {
|
|
3703
|
-
say(`Stopped: ${file} ${result ? "has errors" : "is missing"}, so keypin can't tell which keys use these destinations. Fix it or run keypin unregister ${shellWord(project)}. Nothing was changed.`);
|
|
3704
|
-
return null;
|
|
3705
|
-
}
|
|
3706
|
-
list(result.map, project);
|
|
3707
|
-
}
|
|
3708
|
-
return owners;
|
|
3709
|
-
}
|
|
3710
|
-
function ownerOf2(receipt, owners) {
|
|
3711
|
-
const found = owners.get(receiptSecretKey(receipt)) ?? [];
|
|
3712
|
-
return found.find((o) => ownedBy(receipt, o)) ?? found.find((o) => o.keyId === receipt.keyId && o.environment === receipt.environment) ?? found[0];
|
|
3713
|
-
}
|
|
3714
|
-
var UNLISTED = "no registered map lists it any more; revoking breaks it unless that secret is gone";
|
|
3715
|
-
async function otherHolders(run, receipts, generation, retired) {
|
|
3716
|
-
const owners = await listedOwners(run);
|
|
3717
|
-
if (owners === null)
|
|
3718
|
-
return null;
|
|
3719
|
-
const shown = new Set(retired.map((r) => r.destinationId));
|
|
3720
|
-
return holdersOf(receipts, generation).flatMap((receipt) => {
|
|
3721
|
-
const owner = ownerOf2(receipt, owners);
|
|
3722
|
-
if (owner)
|
|
3723
|
-
return [{ receipt, owner }];
|
|
3724
|
-
if (!shown.has(receipt.destinationId)) {
|
|
3725
|
-
run.say(` ${describeHolder(receipt)} has the old token, and ${UNLISTED}`);
|
|
3726
|
-
}
|
|
3727
|
-
return [];
|
|
3728
|
-
});
|
|
3729
|
-
}
|
|
3730
|
-
function again(run) {
|
|
3731
|
-
return rotateCommand(run.key.name, run.environment, publishEnvironment(run.map));
|
|
3732
|
-
}
|
|
3733
|
-
async function checkNew(provider, id, value, old) {
|
|
3734
|
-
try {
|
|
3735
|
-
const seen = await provider.verify(value);
|
|
3736
|
-
if (seen.id !== id)
|
|
3737
|
-
return `the new value verifies as token ${seen.id}, not ${id}`;
|
|
3738
|
-
if (seen.status !== "active")
|
|
3739
|
-
return `the new token is ${seen.status}`;
|
|
3740
|
-
const made = await provider.details(id);
|
|
3741
|
-
if (!made)
|
|
3742
|
-
return "the admin token can't read the new token";
|
|
3743
|
-
if (!sameAccess(made, old))
|
|
3744
|
-
return `its policies differ from ${old.id}'s`;
|
|
3745
|
-
return null;
|
|
3746
|
-
} catch (error) {
|
|
3747
|
-
return messageOf(error);
|
|
3748
|
-
}
|
|
3749
|
-
}
|
|
3750
|
-
async function confirmed3(run, needsApproval, what) {
|
|
3751
|
-
const { deps, say } = run;
|
|
3752
|
-
if (run.yes && !needsApproval)
|
|
3753
|
-
return true;
|
|
3754
|
-
if (deps.isTerminal) {
|
|
3755
|
-
const answer = await deps.ask(`Type yes to ${what}${needsApproval ? " (this plan needs approval)" : ""}: `);
|
|
3756
|
-
if (answer.trim() === "yes")
|
|
3757
|
-
return true;
|
|
3758
|
-
say("Not confirmed. Nothing was changed.");
|
|
3759
|
-
return false;
|
|
3760
|
-
}
|
|
3761
|
-
say("Stopped: this plan needs approval, and --yes can't give it. Nothing was changed.");
|
|
3762
|
-
say(rerun(deps, "rotate", run.args));
|
|
3763
|
-
return false;
|
|
3764
|
-
}
|
|
3765
|
-
function withoutFinished(data, owner) {
|
|
3766
|
-
return {
|
|
3767
|
-
...data,
|
|
3768
|
-
rotations: data.rotations.filter((r) => !(ownedBy(r, owner) && r.stage === "revoked"))
|
|
3769
|
-
};
|
|
3770
|
-
}
|
|
3771
|
-
function keyOwner(run) {
|
|
3772
|
-
return { keyId: run.key.name, environment: run.environment, mapFile: run.map.file };
|
|
3773
|
-
}
|
|
3774
|
-
function planFor(run) {
|
|
3775
|
-
return { key: run.key, environment: run.environment, mapFile: run.map.file };
|
|
3776
|
-
}
|
|
3777
|
-
var DATED = /^(.*) (\d{4}-\d{2}-\d{2})(?: #(\d+))?$/;
|
|
3778
|
-
function nextName(old, today) {
|
|
3779
|
-
const match = DATED.exec(old);
|
|
3780
|
-
const base = match?.[1] ?? old;
|
|
3781
|
-
if (match?.[2] !== today)
|
|
3782
|
-
return `${base} ${today}`;
|
|
3783
|
-
return `${base} ${today} #${Number(match[3] ?? 1) + 1}`;
|
|
3784
|
-
}
|
|
3785
|
-
function describeAccess(token) {
|
|
3786
|
-
const lines = ["policies it copies:"];
|
|
3787
|
-
for (const policy of token.policies) {
|
|
3788
|
-
const groups = policy.permissionGroups.map((g) => g.name).join(", ");
|
|
3789
|
-
lines.push(` ${policy.effect} ${groups}`);
|
|
3790
|
-
for (const [resource, scope] of Object.entries(policy.resources)) {
|
|
3791
|
-
lines.push(` on ${resource}: ${JSON.stringify(scope)}`);
|
|
3792
|
-
}
|
|
3793
|
-
}
|
|
3794
|
-
lines.push(`condition: ${token.condition ? JSON.stringify(token.condition) : "none"}`);
|
|
3795
|
-
return lines;
|
|
3796
|
-
}
|
|
3797
|
-
|
|
3798
|
-
// src/commands/run.ts
|
|
3799
|
-
import { dirname as dirname3, join as join8, relative as relative2 } from "path";
|
|
3800
|
-
import { parseArgs as parseArgs6 } from "util";
|
|
3801
|
-
async function run(args, deps) {
|
|
3802
|
-
const { values, positionals } = parseArgs6({
|
|
3803
|
-
args,
|
|
3804
|
-
options: { env: { type: "string" } },
|
|
3805
|
-
allowPositionals: true
|
|
3806
|
-
});
|
|
3807
|
-
if (!positionals.length)
|
|
3808
|
-
throw new UsageError("keypin run needs a command after --");
|
|
3809
|
-
const map = await findMap(deps.files, deps.cwd);
|
|
3810
|
-
const environment = pickEnvironment(map, values.env, runEnvironment(map));
|
|
3811
|
-
const keys = map.keys.flatMap((key) => {
|
|
3812
|
-
const entry = key.environments[environment];
|
|
3813
|
-
return entry ? [{ key, ref: entry.ref }] : [];
|
|
3814
|
-
});
|
|
3815
|
-
const found = new Map;
|
|
3816
|
-
if (keys.length) {
|
|
3817
|
-
announce(deps.stderr, `${environment} values`, keys.map((k) => k.ref));
|
|
3818
|
-
const vault = deps.vault();
|
|
3819
|
-
const failures = [];
|
|
3820
|
-
for (const { key, ref } of keys) {
|
|
3821
|
-
try {
|
|
3822
|
-
found.set(key.name, await vault.read(ref));
|
|
3823
|
-
} catch (error) {
|
|
3824
|
-
failures.push(`${key.name} (${formatReference(ref)}): ${messageOf(error)}`);
|
|
3825
|
-
}
|
|
3826
|
-
}
|
|
3827
|
-
if (failures.length) {
|
|
3828
|
-
deps.stderr.write(`keypin: couldn't read, so the command didn't start:
|
|
3829
|
-
${failures.join(`
|
|
3830
|
-
`)}
|
|
3831
|
-
`);
|
|
3832
|
-
return 1;
|
|
3833
|
-
}
|
|
3834
|
-
}
|
|
3835
|
-
const env = {};
|
|
3836
|
-
for (const [name, value] of Object.entries(deps.env))
|
|
3837
|
-
if (value !== undefined)
|
|
3838
|
-
env[name] = value;
|
|
3839
|
-
for (const [name, secret] of found) {
|
|
3840
|
-
if (env[name] !== undefined) {
|
|
3841
|
-
deps.stderr.write(`keypin: ${name} was already set; using the vault's value
|
|
3842
|
-
`);
|
|
3843
|
-
}
|
|
3844
|
-
env[name] = secret.reveal();
|
|
3845
|
-
}
|
|
3846
|
-
const unsafe = Object.entries(env).filter(([, value]) => value.includes("\x00")).map(([name]) => name);
|
|
3847
|
-
if (unsafe.length) {
|
|
3848
|
-
deps.stderr.write(`keypin: ${unsafe.join(", ")} contains a NUL character, which an environment can't hold; the command didn't start
|
|
3849
|
-
`);
|
|
3850
|
-
return 1;
|
|
3851
|
-
}
|
|
3852
|
-
await warnAboutEnvFiles(deps, [...new Set([dirname3(map.file), deps.cwd])], keys.map((k) => k.key.name));
|
|
3853
|
-
let child;
|
|
3854
|
-
try {
|
|
3855
|
-
child = deps.launch(positionals, env);
|
|
3856
|
-
} catch (error) {
|
|
3857
|
-
deps.stderr.write(`keypin: couldn't start "${positionals[0]}": ${errorCode(error) ?? "unknown error"}
|
|
3858
|
-
`);
|
|
3859
|
-
return 1;
|
|
3860
|
-
}
|
|
3861
|
-
const stop = deps.onSignals((signal) => child.kill(signal));
|
|
3862
|
-
try {
|
|
3863
|
-
return await child.exited;
|
|
3864
|
-
} finally {
|
|
3865
|
-
stop();
|
|
3866
|
-
}
|
|
3867
|
-
}
|
|
3868
|
-
async function warnAboutEnvFiles(deps, folders, mapped) {
|
|
3869
|
-
if (!mapped.length)
|
|
3870
|
-
return;
|
|
3871
|
-
for (const folder of folders) {
|
|
3872
|
-
const entries = await deps.listFolder(folder).catch(() => []);
|
|
3873
|
-
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
3874
|
-
if (entry.kind !== "file" || envFileKind(entry.name) !== "set")
|
|
3875
|
-
continue;
|
|
3876
|
-
const path = join8(folder, entry.name);
|
|
3877
|
-
const text = await deps.files.read(path).catch(() => null);
|
|
3878
|
-
if (text === null)
|
|
3879
|
-
continue;
|
|
3880
|
-
const names = new Set(envNames(text));
|
|
3881
|
-
const held = mapped.filter((name) => names.has(name));
|
|
3882
|
-
if (held.length)
|
|
3883
|
-
deps.stderr.write(envFileWarning(entry.name, relative2(deps.cwd, path), held));
|
|
3884
|
-
}
|
|
3885
|
-
}
|
|
3886
|
-
}
|
|
3887
|
-
function envFileWarning(name, file, keys) {
|
|
3888
|
-
const list = keys.join(", ");
|
|
3889
|
-
const it = keys.length === 1 ? "it" : "them";
|
|
3890
|
-
const effect = name.startsWith(".dev.vars") ? `still sets ${list}; wrangler dev uses the file's value over keypin's` : `still holds a plaintext copy of ${list}; tools differ on which value wins`;
|
|
3891
|
-
return `keypin: ${file} ${effect}. Move ${it} out of the file.
|
|
3892
|
-
`;
|
|
3893
|
-
}
|
|
3894
|
-
|
|
3895
|
-
// src/commands/status.ts
|
|
3896
|
-
import { join as join9 } from "path";
|
|
3897
|
-
import { parseArgs as parseArgs7 } from "util";
|
|
3898
|
-
async function status(args, deps) {
|
|
3899
|
-
const { values, positionals } = parseArgs7({
|
|
3900
|
-
args,
|
|
3901
|
-
options: { json: { type: "boolean", default: false } },
|
|
3902
|
-
allowPositionals: true
|
|
3903
|
-
});
|
|
3904
|
-
if (positionals.length)
|
|
3905
|
-
throw new UsageError("keypin status takes no arguments");
|
|
3906
|
-
const registry = await loadRegistry(deps.files, registryPath(deps));
|
|
3907
|
-
const state = await loadState(deps.files, statePath(deps));
|
|
3908
|
-
const { rotations } = await loadRotations(deps.files, rotationsPath(deps));
|
|
3909
|
-
const maps = new Map;
|
|
3910
|
-
for (const project of registry.projects) {
|
|
3911
|
-
const file = join9(project, MAP_FILE);
|
|
3912
|
-
try {
|
|
3913
|
-
const text = await deps.files.read(file);
|
|
3914
|
-
if (text !== null)
|
|
3915
|
-
maps.set(project, parseMap(text, file));
|
|
3916
|
-
} catch (error) {
|
|
3917
|
-
deps.stderr.write(`keypin: couldn't read ${file}: ${messageOf(error)}
|
|
3918
|
-
`);
|
|
3919
|
-
}
|
|
3920
|
-
}
|
|
3921
|
-
const refs = distinctRefs([...maps.values()].flatMap((result) => result.ok ? result.map.keys.flatMap((key) => Object.values(key.environments).flatMap((e) => e ? [e.ref] : [])) : []));
|
|
3922
|
-
const metadata = new Map;
|
|
3923
|
-
if (refs.length) {
|
|
3924
|
-
announce(deps.stderr, "rotated dates (no values)", refs);
|
|
3925
|
-
const vault = deps.vault();
|
|
3926
|
-
for (const ref of refs) {
|
|
3927
|
-
try {
|
|
3928
|
-
metadata.set(refKey(ref), await vault.metadata(ref));
|
|
3929
|
-
} catch (error) {
|
|
3930
|
-
deps.stderr.write(`keypin: ${messageOf(error)}
|
|
3931
|
-
`);
|
|
3932
|
-
metadata.set(refKey(ref), null);
|
|
3933
|
-
}
|
|
3934
|
-
}
|
|
3935
|
-
}
|
|
3936
|
-
const result = buildStatus({
|
|
3937
|
-
registry,
|
|
3938
|
-
maps,
|
|
3939
|
-
receipts: state.receipts,
|
|
3940
|
-
rotations,
|
|
3941
|
-
metadata: (ref) => metadata.get(refKey(ref)) ?? null,
|
|
3942
|
-
today: localDay(deps.now())
|
|
3943
|
-
});
|
|
3944
|
-
if (values.json) {
|
|
3945
|
-
deps.stdout.write(`${JSON.stringify({ today: localDay(deps.now()), ...result }, null, 2)}
|
|
3946
|
-
`);
|
|
3947
|
-
} else {
|
|
3948
|
-
deps.stdout.write(render2(result, registry.projects.length));
|
|
3949
|
-
}
|
|
3950
|
-
return result.problems.some((p) => p.severity === "problem") ? 1 : 0;
|
|
3951
|
-
}
|
|
3952
|
-
function render2(result, projects) {
|
|
3953
|
-
if (!projects)
|
|
3954
|
-
return `No projects registered. Run "keypin init" in a project folder.
|
|
3955
|
-
`;
|
|
3956
|
-
const lines = [];
|
|
3957
|
-
const header = ["KEY", "ENV", "FROM", "ROTATED", "EVERY", "DUE"];
|
|
3958
|
-
const cells = (row) => [
|
|
3959
|
-
row.keyId,
|
|
3960
|
-
row.environment,
|
|
3961
|
-
formatReference(row.ref),
|
|
3962
|
-
row.rotated ?? "-",
|
|
3963
|
-
row.rotateEvery ?? "-",
|
|
3964
|
-
row.due ?? (row.rotateEvery === "never" ? "never" : "unknown")
|
|
3965
|
-
];
|
|
3966
|
-
const widths = header.map((h, i) => Math.max(h.length, ...result.rows.map((r) => (cells(r)[i] ?? "").length)));
|
|
3967
|
-
const line = (values) => values.map((v, i) => v.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
|
|
3968
|
-
lines.push(line(header));
|
|
3969
|
-
let project;
|
|
3970
|
-
for (const row of result.rows) {
|
|
3971
|
-
if (row.project !== project) {
|
|
3972
|
-
project = row.project;
|
|
3973
|
-
lines.push(`# ${project}`);
|
|
3974
|
-
}
|
|
3975
|
-
lines.push(line(cells(row)));
|
|
3976
|
-
for (const d of row.destinations) {
|
|
3977
|
-
const receipt = d.receipt ? `last published ${d.receipt.at} by ${d.receipt.publisher}, generation ${d.receipt.generation}` : "no receipt";
|
|
3978
|
-
lines.push(` -> ${d.destinationId} (account ${d.account}): ${receipt}`);
|
|
3979
|
-
}
|
|
3980
|
-
}
|
|
3981
|
-
if (!result.rows.length)
|
|
3982
|
-
lines.push("(no keys)");
|
|
3983
|
-
for (const [severity, title] of [
|
|
3984
|
-
["problem", "Problems"],
|
|
3985
|
-
["notice", "Notices"]
|
|
3986
|
-
]) {
|
|
3987
|
-
const found = result.problems.filter((p) => p.severity === severity);
|
|
3988
|
-
if (!found.length)
|
|
3989
|
-
continue;
|
|
3990
|
-
lines.push("", `${title} (${found.length}):`);
|
|
3991
|
-
for (const p of found)
|
|
3992
|
-
lines.push(` ${p.kind}: ${p.message.replaceAll(`
|
|
3993
|
-
`, `
|
|
3994
|
-
`)}`);
|
|
3995
|
-
}
|
|
3996
|
-
return `${lines.join(`
|
|
3997
|
-
`)}
|
|
3998
|
-
`;
|
|
3999
|
-
}
|
|
4000
|
-
|
|
4001
|
-
// src/commands/unregister.ts
|
|
4002
|
-
import { resolve as resolve4 } from "path";
|
|
4003
|
-
import { parseArgs as parseArgs8 } from "util";
|
|
4004
|
-
async function unregister2(args, deps) {
|
|
4005
|
-
const { positionals } = parseArgs8({ args, options: {}, allowPositionals: true });
|
|
4006
|
-
if (positionals.length > 1)
|
|
4007
|
-
throw new UsageError("keypin unregister takes at most one folder");
|
|
4008
|
-
const folder = resolve4(deps.cwd, positionals[0] ?? ".");
|
|
4009
|
-
const path = registryPath(deps);
|
|
4010
|
-
const before = await loadRegistry(deps.files, path);
|
|
4011
|
-
const registry = await unregister(deps.files, path, folder);
|
|
4012
|
-
if (before.projects.length === registry.projects.length) {
|
|
4013
|
-
const listed = registry.projects.map((project) => `
|
|
4014
|
-
${project}`).join("");
|
|
4015
|
-
deps.stderr.write(`keypin: ${folder} wasn't registered (${projectCount(registry, path)})${listed}
|
|
4016
|
-
`);
|
|
4017
|
-
return 1;
|
|
4018
|
-
}
|
|
4019
|
-
deps.stderr.write(`keypin: ${folder} is no longer registered (${projectCount(registry, path)})
|
|
4020
|
-
`);
|
|
4021
|
-
return 0;
|
|
4022
|
-
}
|
|
4023
|
-
// ../../package.json
|
|
4024
|
-
var version = "0.7.0";
|
|
4025
|
-
|
|
4026
|
-
// src/cli.ts
|
|
4027
|
-
var USAGE = `Usage:
|
|
4028
|
-
keypin init [folder] register a project and write a keypin.toml template
|
|
4029
|
-
keypin unregister [folder]
|
|
4030
|
-
stop listing a project; its keypin.toml stays
|
|
4031
|
-
keypin status [--json] every key in every registered project, with problems
|
|
4032
|
-
keypin discover [folder] [--json] [--write]
|
|
4033
|
-
every key name a project uses, local and in the cloud, and a draft map;
|
|
4034
|
-
--write saves the draft as keypin.toml (only when there's none, or the
|
|
4035
|
-
untouched init template) and registers the project
|
|
4036
|
-
keypin import <env-file> --vault <vault> [--account <sign-in address>] [--yes]
|
|
4037
|
-
move an env file's values into new 1Password items and map them; the
|
|
4038
|
-
account is the map's, or --account when there's no map yet. It never
|
|
4039
|
-
overwrites an item, so --yes is enough to approve it. The file stays.
|
|
4040
|
-
keypin run [--env <name>] -- <command>
|
|
4041
|
-
run a command with one environment's keys (default: the first, dev)
|
|
4042
|
-
keypin publish <VARIABLE> [--env <name>] [--yes | --plan]
|
|
4043
|
-
check accounts, plan, confirm, then write the key to every destination
|
|
4044
|
-
(default environment: the last, prod); --plan reads the value, prints
|
|
4045
|
-
the plan and the command to approve it, and writes nothing
|
|
4046
|
-
keypin publish --all [--env <name>] [--yes | --plan]
|
|
4047
|
-
the same for every key with destinations, with one plan and one approval
|
|
4048
|
-
keypin rotate <VARIABLE> [--env <name>] [--yes | --plan]
|
|
4049
|
-
replace a token with a new one that has the same permissions, publish it,
|
|
4050
|
-
and revoke the old one on the next run; --plan reads and checks the tokens,
|
|
4051
|
-
prints this run's plan and the command to approve it, and changes nothing
|
|
4052
|
-
keypin --version print the version
|
|
4053
|
-
|
|
4054
|
-
Exit codes:
|
|
4055
|
-
0 done
|
|
4056
|
-
1 failed, or status found a problem
|
|
4057
|
-
2 usage error
|
|
4058
|
-
3 stopped for approval: run the printed command in a terminal and type yes;
|
|
4059
|
-
--plan exits 3 whenever the plan would write (routine or not), 0 when there's nothing to write
|
|
4060
|
-
keypin run exits 1 if it can't start the command, then with the command's own code.
|
|
4061
|
-
`;
|
|
4062
|
-
var COMMANDS = new Map([
|
|
4063
|
-
["init", init],
|
|
4064
|
-
["unregister", unregister2],
|
|
4065
|
-
["status", status],
|
|
4066
|
-
["discover", discover],
|
|
4067
|
-
["import", importEnv],
|
|
4068
|
-
["run", run],
|
|
4069
|
-
["publish", publish],
|
|
4070
|
-
["rotate", rotate]
|
|
4071
|
-
]);
|
|
4072
|
-
async function cli(argv, deps) {
|
|
4073
|
-
const [name, ...args] = argv;
|
|
4074
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
4075
|
-
(name === undefined ? deps.stderr : deps.stdout).write(USAGE);
|
|
4076
|
-
return name === undefined ? 2 : 0;
|
|
4077
|
-
}
|
|
4078
|
-
if (name === "--version" || name === "-v") {
|
|
4079
|
-
deps.stdout.write(`${version}
|
|
4080
|
-
`);
|
|
4081
|
-
return 0;
|
|
4082
|
-
}
|
|
4083
|
-
const command = COMMANDS.get(name);
|
|
4084
|
-
if (!command) {
|
|
4085
|
-
deps.stderr.write(`keypin: unknown command "${name}"
|
|
4086
|
-
${USAGE}`);
|
|
4087
|
-
return 2;
|
|
4088
|
-
}
|
|
4089
|
-
const own = args.includes("--") ? args.slice(0, args.indexOf("--")) : args;
|
|
4090
|
-
if (own.includes("--help") || own.includes("-h")) {
|
|
4091
|
-
deps.stdout.write(USAGE);
|
|
4092
|
-
return 0;
|
|
4093
|
-
}
|
|
4094
|
-
try {
|
|
4095
|
-
return await command(args, deps);
|
|
4096
|
-
} catch (error) {
|
|
4097
|
-
if (error instanceof UsageError || errorCode(error)?.startsWith("ERR_PARSE_ARGS")) {
|
|
4098
|
-
deps.stderr.write(`keypin ${name}: ${messageOf(error)}
|
|
4099
|
-
${USAGE}`);
|
|
4100
|
-
return 2;
|
|
4101
|
-
}
|
|
4102
|
-
deps.stderr.write(`keypin ${name}: ${messageOf(error)}
|
|
4103
|
-
`);
|
|
4104
|
-
return 1;
|
|
4105
|
-
}
|
|
4106
|
-
}
|
|
4107
|
-
|
|
4108
|
-
// src/disk.ts
|
|
4109
|
-
import { constants, rmSync } from "fs";
|
|
4110
|
-
import { execFile as execFile3 } from "child_process";
|
|
4111
|
-
import { chmod, lstat, mkdir, open, readdir, rename, rm, stat } from "fs/promises";
|
|
4112
|
-
import { dirname as dirname4 } from "path";
|
|
4113
|
-
|
|
4114
|
-
// src/launch.ts
|
|
4115
|
-
var launch = (command, env) => {
|
|
4116
|
-
const child = Bun.spawn(command, { env, stdio: ["inherit", "inherit", "inherit"] });
|
|
4117
|
-
return { exited: child.exited, kill: (signal) => child.kill(signal) };
|
|
4118
|
-
};
|
|
4119
|
-
var onSignals = (handler) => {
|
|
4120
|
-
const signals = ["SIGINT", "SIGTERM"];
|
|
4121
|
-
for (const signal of signals)
|
|
4122
|
-
process.on(signal, handler);
|
|
4123
|
-
return () => {
|
|
4124
|
-
for (const signal of signals)
|
|
4125
|
-
process.off(signal, handler);
|
|
4126
|
-
};
|
|
4127
|
-
};
|
|
4128
|
-
|
|
4129
|
-
// src/disk.ts
|
|
4130
|
-
var diskFiles = {
|
|
4131
|
-
async read(path) {
|
|
4132
|
-
let handle;
|
|
4133
|
-
try {
|
|
4134
|
-
handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
4135
|
-
} catch (error) {
|
|
4136
|
-
if (errorCode(error) === "ENOENT")
|
|
4137
|
-
return null;
|
|
4138
|
-
throw error;
|
|
4139
|
-
}
|
|
4140
|
-
try {
|
|
4141
|
-
if (!(await handle.stat()).isFile())
|
|
4142
|
-
throw new Error(`${path} isn't a regular file`);
|
|
4143
|
-
return await handle.readFile("utf8");
|
|
4144
|
-
} finally {
|
|
4145
|
-
await handle.close();
|
|
4146
|
-
}
|
|
4147
|
-
},
|
|
4148
|
-
async write(path, text) {
|
|
4149
|
-
await privateFolder(dirname4(path));
|
|
4150
|
-
const handle = await open(path, PRIVATE_WRITE, 384);
|
|
4151
|
-
try {
|
|
4152
|
-
await handle.chmod(384);
|
|
4153
|
-
await handle.writeFile(text);
|
|
4154
|
-
} finally {
|
|
4155
|
-
await handle.close();
|
|
4156
|
-
}
|
|
4157
|
-
},
|
|
4158
|
-
async rename(from, to) {
|
|
4159
|
-
await rename(from, to);
|
|
4160
|
-
}
|
|
4161
|
-
};
|
|
4162
|
-
var PRIVATE_WRITE = constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW;
|
|
4163
|
-
async function privateFolder(folder) {
|
|
4164
|
-
await mkdir(folder, { recursive: true });
|
|
4165
|
-
await chmod(folder, 448);
|
|
4166
|
-
}
|
|
4167
|
-
var createFile = async (path, text) => {
|
|
4168
|
-
const found = await kindOf(path);
|
|
4169
|
-
if (found !== "missing")
|
|
4170
|
-
return found;
|
|
4171
|
-
try {
|
|
4172
|
-
const handle = await open(path, "wx");
|
|
4173
|
-
await handle.writeFile(text);
|
|
4174
|
-
await handle.close();
|
|
4175
|
-
return "created";
|
|
4176
|
-
} catch (error) {
|
|
4177
|
-
if (errorCode(error) !== "EEXIST")
|
|
4178
|
-
throw error;
|
|
4179
|
-
const now = await kindOf(path);
|
|
4180
|
-
return now === "missing" ? "exists" : now;
|
|
4181
|
-
}
|
|
4182
|
-
};
|
|
4183
|
-
function replaceFileWith(beforeRecheck) {
|
|
4184
|
-
return async (path, expected, text) => {
|
|
4185
|
-
const first = await readExpected(path, expected);
|
|
4186
|
-
if (typeof first === "string")
|
|
4187
|
-
return first;
|
|
4188
|
-
const temporary = `${path}.${crypto.randomUUID()}.tmp`;
|
|
4189
|
-
try {
|
|
4190
|
-
const handle = await open(temporary, "wx", 384);
|
|
4191
|
-
try {
|
|
4192
|
-
await handle.chmod(Number(first.mode) & 4095);
|
|
4193
|
-
await handle.writeFile(text);
|
|
4194
|
-
await handle.sync();
|
|
4195
|
-
} finally {
|
|
4196
|
-
await handle.close();
|
|
4197
|
-
}
|
|
4198
|
-
await beforeRecheck();
|
|
4199
|
-
const now = await readExpected(path, expected);
|
|
4200
|
-
if (typeof now === "string")
|
|
4201
|
-
return now;
|
|
4202
|
-
if (!sameFile(first, now))
|
|
4203
|
-
return "changed";
|
|
4204
|
-
await rename(temporary, path);
|
|
4205
|
-
return "replaced";
|
|
4206
|
-
} finally {
|
|
4207
|
-
await rm(temporary, { force: true });
|
|
4208
|
-
}
|
|
4209
|
-
};
|
|
4210
|
-
}
|
|
4211
|
-
var replaceFile = replaceFileWith(async () => {});
|
|
4212
|
-
function sameFile(a, b) {
|
|
4213
|
-
return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs;
|
|
4214
|
-
}
|
|
4215
|
-
async function readExpected(path, expected) {
|
|
4216
|
-
if (await kindOf(path) === "link")
|
|
4217
|
-
return "link";
|
|
4218
|
-
let handle;
|
|
4219
|
-
try {
|
|
4220
|
-
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
4221
|
-
} catch (error) {
|
|
4222
|
-
if (errorCode(error) === "ELOOP")
|
|
4223
|
-
return "link";
|
|
4224
|
-
if (errorCode(error) === "ENOENT")
|
|
4225
|
-
return "changed";
|
|
4226
|
-
throw error;
|
|
4227
|
-
}
|
|
4228
|
-
try {
|
|
4229
|
-
const opened = await handle.stat({ bigint: true });
|
|
4230
|
-
if (await handle.readFile("utf8") !== expected)
|
|
4231
|
-
return "changed";
|
|
4232
|
-
const found = await lstat(path, { bigint: true }).catch((error) => {
|
|
4233
|
-
if (errorCode(error) === "ENOENT")
|
|
4234
|
-
return null;
|
|
4235
|
-
throw error;
|
|
4236
|
-
});
|
|
4237
|
-
if (found === null)
|
|
4238
|
-
return "changed";
|
|
4239
|
-
if (found.isSymbolicLink())
|
|
4240
|
-
return "link";
|
|
4241
|
-
return sameFile(opened, found) ? opened : "changed";
|
|
4242
|
-
} finally {
|
|
4243
|
-
await handle.close();
|
|
4244
|
-
}
|
|
4245
|
-
}
|
|
4246
|
-
async function isLink(path) {
|
|
4247
|
-
try {
|
|
4248
|
-
return (await lstat(path)).isSymbolicLink();
|
|
4249
|
-
} catch (error) {
|
|
4250
|
-
if (errorCode(error) === "ENOENT")
|
|
4251
|
-
return false;
|
|
4252
|
-
throw error;
|
|
4253
|
-
}
|
|
4254
|
-
}
|
|
4255
|
-
async function kindOf(path) {
|
|
4256
|
-
try {
|
|
4257
|
-
const found = await lstat(path);
|
|
4258
|
-
if (found.isSymbolicLink())
|
|
4259
|
-
return "link";
|
|
4260
|
-
if (!found.isFile())
|
|
4261
|
-
throw new Error(`${path} isn't a file`);
|
|
4262
|
-
return "exists";
|
|
4263
|
-
} catch (error) {
|
|
4264
|
-
if (errorCode(error) === "ENOENT")
|
|
4265
|
-
return "missing";
|
|
4266
|
-
throw error;
|
|
4267
|
-
}
|
|
4268
|
-
}
|
|
4269
|
-
async function isFolder(path) {
|
|
4270
|
-
try {
|
|
4271
|
-
return (await stat(path)).isDirectory();
|
|
4272
|
-
} catch {
|
|
4273
|
-
return false;
|
|
4274
|
-
}
|
|
4275
|
-
}
|
|
4276
|
-
async function listFolder(path) {
|
|
4277
|
-
const entries = await readdir(path, { withFileTypes: true });
|
|
4278
|
-
return entries.map((entry) => ({
|
|
4279
|
-
name: entry.name,
|
|
4280
|
-
kind: entry.isFile() ? "file" : entry.isDirectory() ? "folder" : "other"
|
|
4281
|
-
}));
|
|
4282
|
-
}
|
|
4283
|
-
function git(folder, args) {
|
|
4284
|
-
return new Promise((resolve) => {
|
|
4285
|
-
execFile3("git", ["-C", folder, ...args], { maxBuffer: 64 * 1024 * 1024 }, (error, stdout) => {
|
|
4286
|
-
resolve(error ? null : String(stdout));
|
|
4287
|
-
});
|
|
4288
|
-
});
|
|
4289
|
-
}
|
|
4290
|
-
var diskLock = async (path) => {
|
|
4291
|
-
await privateFolder(dirname4(path));
|
|
4292
|
-
if (await take(path))
|
|
4293
|
-
return { held: true, lock: held(path) };
|
|
4294
|
-
const pid = await holderOf(path);
|
|
4295
|
-
return { held: false, holder: { pid, running: pid === null ? null : isRunning(pid) } };
|
|
4296
|
-
};
|
|
4297
|
-
async function take(path) {
|
|
4298
|
-
try {
|
|
4299
|
-
const handle = await open(path, "wx", 384);
|
|
4300
|
-
await handle.writeFile(`${process.pid}
|
|
4301
|
-
`);
|
|
4302
|
-
await handle.close();
|
|
4303
|
-
return true;
|
|
4304
|
-
} catch (error) {
|
|
4305
|
-
if (errorCode(error) === "EEXIST")
|
|
4306
|
-
return false;
|
|
4307
|
-
throw error;
|
|
4308
|
-
}
|
|
4309
|
-
}
|
|
4310
|
-
async function holderOf(path) {
|
|
4311
|
-
const text = await diskFiles.read(path);
|
|
4312
|
-
const pid = text?.match(/^(\d+)\n?$/)?.[1];
|
|
4313
|
-
return pid === undefined ? null : Number(pid);
|
|
4314
|
-
}
|
|
4315
|
-
function isRunning(pid) {
|
|
4316
|
-
try {
|
|
4317
|
-
process.kill(pid, 0);
|
|
4318
|
-
return true;
|
|
4319
|
-
} catch (error) {
|
|
4320
|
-
return errorCode(error) !== "ESRCH";
|
|
4321
|
-
}
|
|
4322
|
-
}
|
|
4323
|
-
function held(path) {
|
|
4324
|
-
const stop = onSignals((signal) => {
|
|
4325
|
-
stop();
|
|
4326
|
-
rmSync(path, { force: true });
|
|
4327
|
-
process.kill(process.pid, signal);
|
|
4328
|
-
});
|
|
4329
|
-
return {
|
|
4330
|
-
async release() {
|
|
4331
|
-
stop();
|
|
4332
|
-
await rm(path, { force: true });
|
|
4333
|
-
}
|
|
4334
|
-
};
|
|
4335
|
-
}
|
|
4336
|
-
|
|
4337
|
-
// src/start.ts
|
|
4338
|
-
var vault;
|
|
4339
|
-
var cloudflare;
|
|
4340
|
-
function destination(target) {
|
|
4341
|
-
switch (target.to) {
|
|
4342
|
-
case "cloudflare-worker":
|
|
4343
|
-
return new WorkerSecretDestination({ account: target.account, worker: target.worker });
|
|
4344
|
-
case "github-actions":
|
|
4345
|
-
return new GitHubSecretDestination({ repo: target.repo, account: target.account });
|
|
4346
|
-
default: {
|
|
4347
|
-
const unknown = target;
|
|
4348
|
-
throw new Error(`unknown destination ${JSON.stringify(unknown)}`);
|
|
4349
|
-
}
|
|
4350
|
-
}
|
|
4351
|
-
}
|
|
4352
|
-
function provider(spec, admin) {
|
|
4353
|
-
switch (spec.provider) {
|
|
4354
|
-
case "cloudflare-account-token":
|
|
4355
|
-
return new CloudflareAccountTokens({ account: spec.account, admin });
|
|
4356
|
-
default: {
|
|
4357
|
-
const unknown = spec.provider;
|
|
4358
|
-
throw new Error(`unknown provider ${JSON.stringify(unknown)}`);
|
|
4359
|
-
}
|
|
4360
|
-
}
|
|
4361
|
-
}
|
|
4362
|
-
var connect = (account) => desktopConnect(account).catch((error) => {
|
|
4363
|
-
const hint = installProblem(error);
|
|
4364
|
-
throw hint ? new Error(hint) : error;
|
|
4365
|
-
});
|
|
4366
|
-
async function ask(question) {
|
|
4367
|
-
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
4368
|
-
try {
|
|
4369
|
-
return await prompt.question(question);
|
|
4370
|
-
} finally {
|
|
4371
|
-
prompt.close();
|
|
4372
|
-
}
|
|
4373
|
-
}
|
|
4374
|
-
function main() {
|
|
4375
|
-
return cli(process.argv.slice(2), {
|
|
4376
|
-
cwd: process.cwd(),
|
|
4377
|
-
self: selfCommand(process.argv[0] ?? "bun", process.argv[1] ?? "keypin"),
|
|
4378
|
-
env: process.env,
|
|
4379
|
-
home: homedir2(),
|
|
4380
|
-
files: diskFiles,
|
|
4381
|
-
isFolder,
|
|
4382
|
-
listFolder,
|
|
4383
|
-
git,
|
|
4384
|
-
githubSecrets: (repo, login) => listRepoSecrets({ repo, token: () => ghToken(login) }),
|
|
4385
|
-
workerSecrets: (account, worker) => (cloudflare ??= new CloudflareReader({
|
|
4386
|
-
token: () => currentWranglerToken()
|
|
4387
|
-
})).listWorkerSecrets(account, worker),
|
|
4388
|
-
createFile,
|
|
4389
|
-
replaceFile,
|
|
4390
|
-
isLink,
|
|
4391
|
-
vault: () => vault ??= onePasswordBackend(connect),
|
|
4392
|
-
now: () => new Date,
|
|
4393
|
-
stdout: process.stdout,
|
|
4394
|
-
stderr: process.stderr,
|
|
4395
|
-
launch,
|
|
4396
|
-
onSignals,
|
|
4397
|
-
destination,
|
|
4398
|
-
provider,
|
|
4399
|
-
lock: diskLock,
|
|
4400
|
-
isTerminal: Boolean(process.stdin.isTTY),
|
|
4401
|
-
ask
|
|
4402
|
-
});
|
|
4403
|
-
}
|
|
4404
|
-
export {
|
|
4405
|
-
main
|
|
4406
|
-
};
|