keypin 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1959 @@
1
+ // @bun
2
+ import {
3
+ messageOf,
4
+ errorCode,
5
+ installProblem
6
+ } from "./chunk-8agfxsqt.js";
7
+
8
+ // src/start.ts
9
+ import { homedir as homedir2 } from "os";
10
+ import { createInterface } from "readline/promises";
11
+
12
+ // ../../packages/core/src/secret.ts
13
+ var HIDDEN = "[secret]";
14
+
15
+ class Secret {
16
+ #value;
17
+ constructor(value) {
18
+ this.#value = value;
19
+ }
20
+ reveal() {
21
+ return this.#value;
22
+ }
23
+ toString() {
24
+ return HIDDEN;
25
+ }
26
+ toJSON() {
27
+ return HIDDEN;
28
+ }
29
+ [Symbol.toPrimitive]() {
30
+ return HIDDEN;
31
+ }
32
+ [Symbol.for("nodejs.util.inspect.custom")]() {
33
+ return HIDDEN;
34
+ }
35
+ }
36
+ async function generationOf(secret) {
37
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret.reveal()));
38
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 16);
39
+ }
40
+ // ../../packages/core/src/contracts.ts
41
+ var ENVIRONMENTS = ["dev", "prod"];
42
+ // ../../packages/core/src/map.ts
43
+ var {TOML } = globalThis.Bun;
44
+
45
+ // ../../packages/core/src/record.ts
46
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
47
+
48
+ // ../../packages/core/src/rotation.ts
49
+ var DUE_SOON_DAYS = 14;
50
+ var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
51
+ var UNIT_DAYS = new Map([
52
+ ["d", 1],
53
+ ["w", 7],
54
+ ["m", 30]
55
+ ]);
56
+ function periodDays(period) {
57
+ if (period === "never")
58
+ return null;
59
+ const match = /^(\d+)([dwm])$/.exec(period ?? "");
60
+ const count = Number(match?.[1]);
61
+ const unit = UNIT_DAYS.get(match?.[2] ?? "");
62
+ if (!count || unit === undefined)
63
+ return;
64
+ return count * unit;
65
+ }
66
+ function isDay(value) {
67
+ const match = DAY.exec(value);
68
+ if (!match)
69
+ return false;
70
+ const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
71
+ return date.toISOString().slice(0, 10) === value;
72
+ }
73
+ function addDays(day, days) {
74
+ const date = new Date(`${day}T00:00:00Z`);
75
+ date.setUTCDate(date.getUTCDate() + days);
76
+ return date.toISOString().slice(0, 10);
77
+ }
78
+
79
+ // ../../packages/core/src/map.ts
80
+ var DESTINATION_KINDS = ["cloudflare-worker", "github-actions"];
81
+ function destinationId(target, secretName) {
82
+ return `${placeId(target)}:${secretName}`;
83
+ }
84
+ function secretKey(target, secretName) {
85
+ return target.to === "cloudflare-worker" ? `cloudflare-worker:${target.account}:${target.worker}:${secretName}` : `github-actions:${target.repo.toLowerCase()}:${secretName.toUpperCase()}`;
86
+ }
87
+ function receiptSecretKey(receipt) {
88
+ const [to, place, name, ...rest] = receipt.destinationId.split(":");
89
+ if (rest.length || place === undefined || name === undefined)
90
+ return receipt.destinationId;
91
+ if (to === "cloudflare-worker") {
92
+ return secretKey({ to, account: receipt.account.pinned, worker: place }, name);
93
+ }
94
+ if (to === "github-actions") {
95
+ return secretKey({ to, repo: place, account: receipt.account.pinned }, name);
96
+ }
97
+ return receipt.destinationId;
98
+ }
99
+ function placeId(target) {
100
+ return target.to === "cloudflare-worker" ? `cloudflare-worker:${target.worker}` : `github-actions:${target.repo}`;
101
+ }
102
+ function parseMap(text, file) {
103
+ let data;
104
+ try {
105
+ data = TOML.parse(text);
106
+ } catch (error) {
107
+ return {
108
+ ok: false,
109
+ errors: [`${file}: not valid TOML: ${tomlProblem(error)}`]
110
+ };
111
+ }
112
+ return validateMap(data, file);
113
+ }
114
+ var KEY_ID = /^[a-z0-9][a-z0-9-]*$/;
115
+ var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
116
+ var REPO = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
117
+ var VAULT_KINDS = ["1password"];
118
+ function validateMap(data, file) {
119
+ const errors = [];
120
+ const fail = (where, message) => errors.push(`${file}: ${where}${message}`);
121
+ if (!isRecord(data))
122
+ return { ok: false, errors: [`${file}: expected a table at the top level`] };
123
+ unknownFields(data, ["vaults", "keys"], (field) => fail("", `unknown top-level field "${field}"`));
124
+ const vaults = new Map;
125
+ const rawVaults = data.vaults ?? {};
126
+ if (!isRecord(rawVaults))
127
+ fail("", `"vaults" must be a table`);
128
+ else {
129
+ for (const [name, raw] of Object.entries(rawVaults)) {
130
+ const at = `vault "${name}": `;
131
+ if (!isRecord(raw)) {
132
+ fail(at, "must be a table");
133
+ continue;
134
+ }
135
+ unknownFields(raw, ["kind", "account", "vault"], (field) => fail(at, `unknown field "${field}"`));
136
+ const kind = requiredString(raw, "kind", (m) => fail(at, m));
137
+ const account = requiredString(raw, "account", (m) => fail(at, m));
138
+ const vault = requiredString(raw, "vault", (m) => fail(at, m));
139
+ if (kind !== undefined && !VAULT_KINDS.includes(kind)) {
140
+ fail(at, `field "kind" must be one of: ${VAULT_KINDS.join(", ")}`);
141
+ } else if (kind !== undefined && account !== undefined && vault !== undefined) {
142
+ vaults.set(name, { kind: "1password", account, vault });
143
+ }
144
+ }
145
+ }
146
+ const keys = [];
147
+ const rawKeys = data.keys ?? {};
148
+ if (!isRecord(rawKeys))
149
+ fail("", `"keys" must be a table`);
150
+ else {
151
+ for (const [id, raw] of Object.entries(rawKeys)) {
152
+ const entry = validateKey(id, raw, vaults, (where, message) => fail(`key "${id}"${where}: `, message));
153
+ if (entry)
154
+ keys.push(entry);
155
+ }
156
+ }
157
+ sharedDestinations(keys, (where, message) => fail(where, message));
158
+ return errors.length ? { ok: false, errors } : { ok: true, map: { file, keys } };
159
+ }
160
+ function sharedDestinations(keys, fail) {
161
+ const owners = new Map;
162
+ for (const key of keys) {
163
+ for (const environment of ENVIRONMENTS) {
164
+ key.environments[environment]?.publish.forEach((target, i) => {
165
+ const where = `key "${key.id}" ${environment} publish[${i}]`;
166
+ const secret = secretKey(target, key.env);
167
+ const owner = owners.get(secret);
168
+ if (owner === undefined)
169
+ owners.set(secret, where);
170
+ else
171
+ fail(`${where}: `, `writes the same destination secret as ${owner}`);
172
+ });
173
+ }
174
+ }
175
+ }
176
+ function validateKey(id, raw, vaults, fail) {
177
+ let failures = 0;
178
+ const err = (where, message) => {
179
+ failures++;
180
+ fail(where, message);
181
+ };
182
+ if (!KEY_ID.test(id))
183
+ err("", "a key ID uses lowercase letters, digits and dashes");
184
+ if (!isRecord(raw)) {
185
+ err("", "must be a table");
186
+ return;
187
+ }
188
+ unknownFields(raw, ["env", "owner", "rotate_every", "consumers", ...ENVIRONMENTS], (field) => err("", `unknown field "${field}"`));
189
+ const env = requiredString(raw, "env", (m) => err("", m));
190
+ if (env !== undefined && !ENV_NAME.test(env))
191
+ err("", `field "env" must be a variable name: letters, digits and _, not starting with a digit`);
192
+ const owner = requiredString(raw, "owner", (m) => err("", m));
193
+ const rotateEvery = optionalString(raw, "rotate_every", (m) => err("", m));
194
+ if (rotateEvery !== undefined && periodDays(rotateEvery) === undefined) {
195
+ err("", `field "rotate_every" must be <n>d, <n>w, <n>m or never`);
196
+ }
197
+ const environments = {};
198
+ for (const name of ENVIRONMENTS) {
199
+ if (raw[name] === undefined)
200
+ continue;
201
+ const entry = validateEnv(raw[name], vaults, (m) => err(` ${name}`, m));
202
+ if (entry)
203
+ environments[name] = entry;
204
+ }
205
+ for (const [name, entry] of Object.entries(environments)) {
206
+ const index = entry.publish.findIndex((target) => target.to === "github-actions");
207
+ if (env !== undefined && index !== -1 && /^GITHUB_/i.test(env)) {
208
+ err(` ${name}`, `publish[${index}]: github-actions can't take this key, because GitHub reserves secret names that start with GITHUB_; rename field "env"`);
209
+ }
210
+ }
211
+ if (!ENVIRONMENTS.some((name) => raw[name] !== undefined)) {
212
+ err("", `needs at least one of ${ENVIRONMENTS.map((n) => `"${n}"`).join(", ")}`);
213
+ }
214
+ const consumers = [];
215
+ if (raw.consumers !== undefined) {
216
+ if (!Array.isArray(raw.consumers))
217
+ err("", `field "consumers" must be a list`);
218
+ else {
219
+ raw.consumers.forEach((c, i) => {
220
+ const at = ` consumers[${i}]`;
221
+ if (!isRecord(c))
222
+ return err(at, "must be a table");
223
+ unknownFields(c, ["name", "kind"], (field) => err(at, `unknown field "${field}"`));
224
+ const name = requiredString(c, "name", (m) => err(at, m));
225
+ const kind = requiredString(c, "kind", (m) => err(at, m));
226
+ if (name !== undefined && kind !== undefined)
227
+ consumers.push({ name, kind });
228
+ });
229
+ }
230
+ }
231
+ if (failures || env === undefined || owner === undefined)
232
+ return;
233
+ return { id, env, owner, rotateEvery: rotateEvery ?? null, environments, consumers };
234
+ }
235
+ function validateEnv(raw, vaults, fail) {
236
+ if (!isRecord(raw)) {
237
+ fail("must be a table");
238
+ return;
239
+ }
240
+ let failed = false;
241
+ const err = (message) => {
242
+ failed = true;
243
+ fail(message);
244
+ };
245
+ unknownFields(raw, ["vault", "item", "publish"], (field) => err(`unknown field "${field}"`));
246
+ const vaultName = requiredString(raw, "vault", err);
247
+ const item = requiredString(raw, "item", err);
248
+ const vault = vaultName === undefined ? undefined : vaults.get(vaultName);
249
+ if (vaultName !== undefined && !vault)
250
+ err(`field "vault" names a vault that isn't under [vaults]`);
251
+ const publish = [];
252
+ const firstAt = new Map;
253
+ if (raw.publish !== undefined) {
254
+ if (!Array.isArray(raw.publish))
255
+ err(`field "publish" must be a list`);
256
+ else {
257
+ raw.publish.forEach((t, i) => {
258
+ const target = validateTarget(t, (m) => err(`publish[${i}]: ${m}`));
259
+ if (!target)
260
+ return;
261
+ const same = firstAt.get(placeId(target));
262
+ if (same !== undefined)
263
+ err(`publish[${i}]: the same destination as publish[${same}]`);
264
+ else {
265
+ firstAt.set(placeId(target), i);
266
+ publish.push(target);
267
+ }
268
+ });
269
+ }
270
+ }
271
+ if (failed || !vault || item === undefined)
272
+ return;
273
+ return { ref: { ...vault, item }, publish };
274
+ }
275
+ function validateTarget(raw, fail) {
276
+ if (!isRecord(raw)) {
277
+ fail("must be a table");
278
+ return;
279
+ }
280
+ const to = requiredString(raw, "to", fail);
281
+ if (to === undefined)
282
+ return;
283
+ let failed = false;
284
+ const err = (message) => {
285
+ failed = true;
286
+ fail(message);
287
+ };
288
+ if (to === "cloudflare-worker") {
289
+ unknownFields(raw, ["to", "account", "worker"], (field) => err(`unknown field "${field}" for ${to}`));
290
+ const account = requiredString(raw, "account", err);
291
+ const worker = requiredString(raw, "worker", err);
292
+ return failed || account === undefined || worker === undefined ? undefined : { to, account, worker };
293
+ }
294
+ if (to === "github-actions") {
295
+ unknownFields(raw, ["to", "repo", "account"], (field) => err(`unknown field "${field}" for ${to}`));
296
+ const repo = requiredString(raw, "repo", err);
297
+ const account = optionalString(raw, "account", err);
298
+ if (repo !== undefined && !REPO.test(repo))
299
+ err(`field "repo" must be "owner/name"`);
300
+ return failed || repo === undefined ? undefined : { to, repo, account: account ?? repo.split("/")[0] };
301
+ }
302
+ err(`field "to" must be one of: ${DESTINATION_KINDS.join(", ")}`);
303
+ return;
304
+ }
305
+ function tomlProblem(error) {
306
+ const message = error instanceof Error ? error.message : "unknown parse error";
307
+ const problem = message.replace(/^TOML Parse error: /, "").split(/["']|\(0x/)[0] ?? "";
308
+ return problem.replace(/(\s+but)?\s+found\s*$/, "").replace(/[\s:]+$/, "");
309
+ }
310
+ function unknownFields(table, known, report) {
311
+ for (const field of Object.keys(table))
312
+ if (!known.includes(field))
313
+ report(field);
314
+ }
315
+ function requiredString(table, field, fail) {
316
+ const value = table[field];
317
+ if (value === undefined)
318
+ fail(`missing field "${field}"`);
319
+ else if (typeof value !== "string" || !value.trim())
320
+ fail(`field "${field}" must be a non-empty string`);
321
+ else
322
+ return value;
323
+ return;
324
+ }
325
+ function optionalString(table, field, fail) {
326
+ return table[field] === undefined ? undefined : requiredString(table, field, fail);
327
+ }
328
+ // ../../packages/core/src/files.ts
329
+ async function writeJsonAtomic(files, path, data) {
330
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
331
+ await files.write(temporary, `${JSON.stringify(data, null, 2)}
332
+ `);
333
+ await files.rename(temporary, path);
334
+ }
335
+ async function readVersionedJson(files, path, versions, what) {
336
+ const text = await files.read(path);
337
+ if (text === null)
338
+ return null;
339
+ let data;
340
+ try {
341
+ data = JSON.parse(text);
342
+ } catch {
343
+ throw new Error(`${path}: the ${what} isn't valid JSON`);
344
+ }
345
+ if (!isRecord(data))
346
+ throw new Error(`${path}: the ${what} must be a JSON object`);
347
+ if (!versions.some((version) => version === data.version)) {
348
+ throw new Error(`${path}: the ${what} has schema version ${JSON.stringify(data.version ?? null)}, and this keypin reads version ${versions.join(" or ")}`);
349
+ }
350
+ return data;
351
+ }
352
+
353
+ // ../../packages/core/src/registry.ts
354
+ var REGISTRY_VERSION = 1;
355
+ var emptyRegistry = () => ({
356
+ version: REGISTRY_VERSION,
357
+ projects: [],
358
+ shared: []
359
+ });
360
+ async function loadRegistry(files, path) {
361
+ const data = await readVersionedJson(files, path, [REGISTRY_VERSION], "registry");
362
+ if (!data)
363
+ return emptyRegistry();
364
+ const { projects, shared } = data;
365
+ if (!Array.isArray(projects) || !projects.every((p) => typeof p === "string")) {
366
+ throw new Error(`${path}: the registry's "projects" must be a list of paths`);
367
+ }
368
+ if (!Array.isArray(shared) || !shared.every((s) => typeof s?.id === "string")) {
369
+ throw new Error(`${path}: the registry's "shared" must be a list of { id }`);
370
+ }
371
+ return { version: REGISTRY_VERSION, projects, shared };
372
+ }
373
+ async function register(files, path, project) {
374
+ const folder = projectPath(project);
375
+ const registry = await loadRegistry(files, path);
376
+ if (registry.projects.includes(folder))
377
+ return registry;
378
+ const next = { ...registry, projects: [...registry.projects, folder].sort() };
379
+ await writeJsonAtomic(files, path, next);
380
+ return next;
381
+ }
382
+ async function unregister(files, path, project) {
383
+ const folder = projectPath(project);
384
+ const registry = await loadRegistry(files, path);
385
+ if (!registry.projects.includes(folder))
386
+ return registry;
387
+ const next = { ...registry, projects: registry.projects.filter((p) => p !== folder) };
388
+ await writeJsonAtomic(files, path, next);
389
+ return next;
390
+ }
391
+ function projectPath(project) {
392
+ if (!project.startsWith("/"))
393
+ throw new Error(`a project path must be absolute, got "${project}"`);
394
+ return project.replace(/(.)\/+$/, "$1");
395
+ }
396
+ // ../../packages/core/src/state.ts
397
+ var STATE_VERSION = 2;
398
+ var emptyState = () => ({ version: STATE_VERSION, receipts: [], operations: [] });
399
+ async function loadState(files, path) {
400
+ const data = await readVersionedJson(files, path, [1, STATE_VERSION], "state file");
401
+ if (!data)
402
+ return emptyState();
403
+ const { operations } = data;
404
+ const receipts = Array.isArray(data.receipts) ? data.receipts.map((r) => data.version === 1 && isRecord(r) ? { ...r, source: null } : r) : data.receipts;
405
+ if (!Array.isArray(receipts) || !receipts.every(isReceipt)) {
406
+ throw new Error(`${path}: the state file's "receipts" must be a list of receipts`);
407
+ }
408
+ if (!Array.isArray(operations) || !operations.every(isOperation)) {
409
+ throw new Error(`${path}: the state file's "operations" must be a list of operations`);
410
+ }
411
+ return { version: STATE_VERSION, receipts, operations };
412
+ }
413
+ async function saveState(files, path, state) {
414
+ await writeJsonAtomic(files, path, state);
415
+ }
416
+ function startOperation(state, operation) {
417
+ if (state.operations.some((o) => o.id === operation.id))
418
+ throw new Error(`operation ${operation.id} already exists`);
419
+ return { ...state, operations: [...state.operations, { ...operation, done: [] }] };
420
+ }
421
+ function recordReceipt(state, receipt, operationId) {
422
+ const same = (r) => receiptSecretKey(r) === receiptSecretKey(receipt);
423
+ const operations = state.operations.map((o) => o.id === operationId && !o.done.includes(receipt.destinationId) ? { ...o, done: [...o.done, receipt.destinationId] } : o);
424
+ return { ...state, receipts: [...state.receipts.filter((r) => !same(r)), receipt], operations };
425
+ }
426
+ function finishOperation(state, operationId) {
427
+ return { ...state, operations: state.operations.filter((o) => o.id !== operationId) };
428
+ }
429
+ function unfinishedOperations(state, keyId, environment) {
430
+ return state.operations.filter((o) => o.keyId === keyId && o.environment === environment);
431
+ }
432
+ var isText = (value) => typeof value === "string";
433
+ function isReceipt(r) {
434
+ return isRecord(r) && [r.keyId, r.environment, r.destinationId, r.generation, r.at].every(isText) && isRecord(r.account) && isText(r.account.pinned) && isText(r.account.publisher) && isText(r.account.destinationAccount) && (r.source === null || isKeyRef(r.source)) && typeof r.evidence === "object" && r.evidence !== null;
435
+ }
436
+ function isKeyRef(ref) {
437
+ return isRecord(ref) && ref.kind === "1password" && [ref.account, ref.vault, ref.item].every(isText);
438
+ }
439
+ function isOperation(o) {
440
+ return isRecord(o) && [o.id, o.keyId, o.environment, o.generation, o.startedAt].every(isText) && Array.isArray(o.planned) && o.planned.every(isText) && Array.isArray(o.done) && o.done.every(isText);
441
+ }
442
+ // ../../packages/core/src/plan.ts
443
+ function approvalsFor(input) {
444
+ return judge(input).flatMap(({ id, approval }) => approval ? [{ destinationId: id, ...approval }] : []);
445
+ }
446
+ function planPublish(input) {
447
+ const { key, environment, generation } = input;
448
+ const steps = judge(input).map(({ id, target, receipt, approval }) => {
449
+ if (approval) {
450
+ return { action: "write", destinationId: id, target, ...approval };
451
+ }
452
+ if (receipt?.generation === generation) {
453
+ return {
454
+ action: "skip",
455
+ destinationId: id,
456
+ target,
457
+ reason: "receipt already has this generation",
458
+ approval: null
459
+ };
460
+ }
461
+ return {
462
+ action: "write",
463
+ destinationId: id,
464
+ target,
465
+ reason: "different generation",
466
+ approval: null
467
+ };
468
+ });
469
+ const listed = new Set(steps.flatMap((s) => [secretKey(s.target, key.env), s.destinationId]));
470
+ const removed = latestPerSecret(input.receipts).filter((r) => r.keyId === key.id && r.environment === environment).filter((r) => !listed.has(receiptSecretKey(r)) && !listed.has(r.destinationId)).map((r) => ({
471
+ destinationId: r.destinationId,
472
+ lastReceipt: {
473
+ generation: r.generation,
474
+ at: r.at,
475
+ destinationAccount: r.account.destinationAccount
476
+ }
477
+ }));
478
+ return {
479
+ keyId: key.id,
480
+ environment,
481
+ generation,
482
+ steps,
483
+ removed,
484
+ needsApproval: steps.some((s) => s.approval !== null)
485
+ };
486
+ }
487
+ function judge(input) {
488
+ const { key, environment } = input;
489
+ const entry = key.environments[environment];
490
+ if (!entry)
491
+ throw new Error(`key "${key.id}" has no ${environment} entry in the map`);
492
+ const newest = latestPerSecret(input.receipts);
493
+ const latest = new Map(newest.map((r) => [receiptSecretKey(r), r]));
494
+ const ours = newest.filter((r) => r.keyId === key.id && r.environment === environment);
495
+ const published = input.receipts.some((r) => r.keyId === key.id && r.environment === environment);
496
+ return entry.publish.map((target) => {
497
+ const id = destinationId(target, key.env);
498
+ const receipt = latest.get(secretKey(target, key.env)) ?? ours.find((r) => r.destinationId === id);
499
+ const needs = (reason, approval) => ({
500
+ id,
501
+ target,
502
+ receipt,
503
+ approval: { reason, approval }
504
+ });
505
+ if (!receipt) {
506
+ return needs(published ? "new destination" : "no receipt", `first write to ${id} (account ${target.account})`);
507
+ }
508
+ if (receipt.account.pinned !== target.account) {
509
+ return needs("account changed", `${id} account changed from ${receipt.account.pinned} to ${target.account}`);
510
+ }
511
+ if (!receipt.source || !sameRef(receipt.source, entry.ref)) {
512
+ const before = receipt.source ? describeRef(receipt.source) : "an item its receipt doesn't record";
513
+ return needs("item changed", `${id} was last published from ${before}, and now from ${describeRef(entry.ref)}`);
514
+ }
515
+ return { id, target, receipt, approval: null };
516
+ });
517
+ }
518
+ function latestPerSecret(receipts) {
519
+ const latest = new Map;
520
+ for (const receipt of receipts) {
521
+ const seen = latest.get(receiptSecretKey(receipt));
522
+ if (!seen || seen.at < receipt.at)
523
+ latest.set(receiptSecretKey(receipt), receipt);
524
+ }
525
+ return [...latest.values()];
526
+ }
527
+ function sameRef(a, b) {
528
+ return a.kind === b.kind && a.account === b.account && a.vault === b.vault && a.item === b.item;
529
+ }
530
+ function describeRef(ref) {
531
+ return `item "${ref.item}" (1Password account ${ref.account}, vault "${ref.vault}")`;
532
+ }
533
+ // ../../packages/core/src/status.ts
534
+ function buildStatus(input) {
535
+ if (!isDay(input.today))
536
+ throw new Error(`today must be YYYY-MM-DD, got "${input.today}"`);
537
+ const rows = [];
538
+ const problems = [];
539
+ for (const project of input.registry.projects) {
540
+ const result = input.maps.get(project);
541
+ if (!result) {
542
+ problems.push({
543
+ kind: "no-map",
544
+ severity: "problem",
545
+ project,
546
+ message: `${project} has no readable keypin.toml`
547
+ });
548
+ continue;
549
+ }
550
+ if (!result.ok) {
551
+ problems.push({
552
+ kind: "bad-map",
553
+ severity: "problem",
554
+ project,
555
+ message: result.errors.join(`
556
+ `)
557
+ });
558
+ continue;
559
+ }
560
+ const latest = new Map(latestPerSecret(input.receipts).map((r) => [receiptSecretKey(r), r]));
561
+ for (const key of result.map.keys) {
562
+ for (const environment of ENVIRONMENTS) {
563
+ const entry = key.environments[environment];
564
+ if (!entry)
565
+ continue;
566
+ const where = { project, keyId: key.id, environment };
567
+ const label = `${key.id} (${environment})`;
568
+ const add = (kind, message, extra = {}) => problems.push({
569
+ kind,
570
+ severity: kind === "due-soon" || kind === "authority-unknown" ? "notice" : "problem",
571
+ ...where,
572
+ ...extra,
573
+ message
574
+ });
575
+ const metadata = input.metadata(entry.ref);
576
+ const rotateEvery = key.rotateEvery ?? metadata?.rotateEvery ?? null;
577
+ const rotated = metadata?.rotated ?? null;
578
+ const due = rotationDue({ label, metadata, rotated, rotateEvery, today: input.today, add });
579
+ add("authority-unknown", `${label}: what this key grants is unknown, because keypin didn't create it`);
580
+ const current = input.generation?.(key.id, environment);
581
+ const destinations = entry.publish.map((target) => {
582
+ const id = destinationId(target, key.env);
583
+ const last = latest.get(secretKey(target, key.env));
584
+ const ours = last && (last.keyId === key.id && last.environment === environment || last.source !== null && sameRef(last.source, entry.ref));
585
+ const receipt = ours ? last : undefined;
586
+ if (!receipt) {
587
+ add("missing-receipt", `${label}: no receipt for ${id}, so what it holds is unknown`, {
588
+ destinationId: id
589
+ });
590
+ return { destinationId: id, account: target.account, receipt: null, stale: null };
591
+ }
592
+ const stale = current === undefined ? null : receipt.generation !== current;
593
+ if (stale) {
594
+ add("stale-receipt", `${label}: ${id} last got generation ${receipt.generation}, and the value is now ${current}`, {
595
+ destinationId: id
596
+ });
597
+ }
598
+ const { generation, at } = receipt;
599
+ return {
600
+ destinationId: id,
601
+ account: target.account,
602
+ receipt: { generation, at, publisher: receipt.account.publisher },
603
+ stale
604
+ };
605
+ });
606
+ rows.push({
607
+ ...where,
608
+ env: key.env,
609
+ owner: key.owner,
610
+ ref: entry.ref,
611
+ rotated,
612
+ rotateEvery,
613
+ due,
614
+ authority: "unknown",
615
+ destinations
616
+ });
617
+ }
618
+ }
619
+ }
620
+ return { rows, problems };
621
+ }
622
+ function rotationDue(input) {
623
+ const { label, metadata, rotated, rotateEvery, today, add } = input;
624
+ if (!metadata) {
625
+ add("rotation-unreadable", `${label}: the vault's rotation fields couldn't be read, so whether it's due is unknown`);
626
+ return null;
627
+ }
628
+ if (!rotated || !isDay(rotated)) {
629
+ add("no-rotation-date", `${label}: ${rotated ? `rotated "${rotated}" isn't YYYY-MM-DD` : "no rotated date"}`);
630
+ return null;
631
+ }
632
+ const days = periodDays(rotateEvery);
633
+ if (days === undefined) {
634
+ add("bad-rotation-period", `${label}: rotate_every is ${rotateEvery ? `"${rotateEvery}"` : "missing"}; use <n>d, <n>w, <n>m or never`);
635
+ return null;
636
+ }
637
+ if (days === null)
638
+ return null;
639
+ const due = addDays(rotated, days);
640
+ if (due < today)
641
+ add("overdue", `${label}: was due ${due} (rotated ${rotated}, every ${rotateEvery})`);
642
+ else if (due <= addDays(today, DUE_SOON_DAYS))
643
+ add("due-soon", `${label}: is due ${due} (rotated ${rotated}, every ${rotateEvery})`);
644
+ return due;
645
+ }
646
+ // ../../packages/destination-cloudflare/src/token.ts
647
+ import { execFile } from "child_process";
648
+ import { readFile } from "fs/promises";
649
+ import { homedir } from "os";
650
+ import { join } from "path";
651
+ var WRANGLER_CONFIG = join(homedir(), "Library/Preferences/.wrangler/config/default.toml");
652
+ async function wranglerToken(path = WRANGLER_CONFIG) {
653
+ let login = await readLogin(path);
654
+ if (login.expired) {
655
+ await refresh();
656
+ login = await readLogin(path);
657
+ if (login.expired)
658
+ throw new Error("the wrangler login is still expired after `wrangler whoami`; run `wrangler login`");
659
+ }
660
+ return login.token;
661
+ }
662
+ async function readLogin(path) {
663
+ let text;
664
+ try {
665
+ text = await readFile(path, "utf8");
666
+ } catch {
667
+ throw new Error(`no wrangler login at ${path}; run \`wrangler login\``);
668
+ }
669
+ const token = tomlString(text, "oauth_token");
670
+ if (!token)
671
+ throw new Error(`${path} has no oauth_token; run \`wrangler login\``);
672
+ const expires = Date.parse(tomlString(text, "expiration_time") ?? "");
673
+ return { token, expired: Number.isNaN(expires) || expires <= Date.now() + 60000 };
674
+ }
675
+ function tomlString(text, key) {
676
+ for (const line of text.split(`
677
+ `)) {
678
+ const match = /^\s*([A-Za-z_]+)\s*=\s*"([^"]*)"\s*$/.exec(line);
679
+ if (match?.[1] === key)
680
+ return match[2] ?? null;
681
+ }
682
+ return null;
683
+ }
684
+ function refresh() {
685
+ return new Promise((resolve, reject) => {
686
+ execFile("wrangler", ["whoami"], (error) => {
687
+ if (error)
688
+ reject(new Error("the wrangler login has expired, and `wrangler whoami` couldn't refresh it"));
689
+ else
690
+ resolve();
691
+ });
692
+ });
693
+ }
694
+
695
+ // ../../packages/destination-cloudflare/src/cloudflare.ts
696
+ var API = "https://api.cloudflare.com/client/v4";
697
+ var ACCOUNT_ID = /^[0-9a-f]{32}$/;
698
+ var WORKER = /^[A-Za-z0-9_-]+$/;
699
+
700
+ class WorkerSecretDestination {
701
+ capabilities = { write: true, accountCheck: true, evidence: true };
702
+ #account;
703
+ #worker;
704
+ #tokenSource;
705
+ #fetch;
706
+ #token;
707
+ #passed = false;
708
+ constructor(options) {
709
+ if (!ACCOUNT_ID.test(options.account))
710
+ throw new Error(`"${options.account}" isn't a Cloudflare account ID`);
711
+ if (!WORKER.test(options.worker))
712
+ throw new Error(`"${options.worker}" isn't a Worker name`);
713
+ this.#account = options.account;
714
+ this.#worker = options.worker;
715
+ this.#tokenSource = options.token ?? (() => wranglerToken());
716
+ this.#fetch = options.fetch ?? globalThis.fetch;
717
+ }
718
+ describe() {
719
+ return `cloudflare worker ${this.#worker} in account ${this.#account} (worker secret)`;
720
+ }
721
+ async checkAccount() {
722
+ this.#passed = false;
723
+ const facts = { publisher: await this.#publisher(), expected: this.#account };
724
+ const accounts = await this.#accountIds();
725
+ if (!accounts.includes(this.#account)) {
726
+ const reason = `the login can reach ${accounts.join(", ") || "no account"}, not ${this.#account}`;
727
+ return { ...facts, destinationAccount: null, ok: false, reason };
728
+ }
729
+ const settings = await this.#request("GET", `${this.#base()}/settings`);
730
+ if (settings.status === 404) {
731
+ const reason = `account ${this.#account} has no Worker ${this.#worker}`;
732
+ return { ...facts, destinationAccount: null, ok: false, reason };
733
+ }
734
+ if (settings.status !== 200)
735
+ throw failure("GET", `${this.#base()}/settings`, settings);
736
+ this.#passed = true;
737
+ return { ...facts, destinationAccount: this.#account, ok: true };
738
+ }
739
+ async write(name, secret) {
740
+ if (!this.#passed)
741
+ throw new Error(`refusing to write to ${this.describe()}: checkAccount hasn't passed`);
742
+ if (!name)
743
+ throw new Error("a Worker secret needs a name");
744
+ const path = `${this.#base()}/secrets`;
745
+ const put = await this.#request("PUT", path, {
746
+ name,
747
+ text: secret.reveal(),
748
+ type: "secret_text"
749
+ });
750
+ if (put.status !== 200)
751
+ throw failure("PUT", path, put);
752
+ const versions = await this.#request("GET", `${this.#base()}/versions?per_page=10`);
753
+ if (versions.status !== 200)
754
+ throw failure("GET", `${this.#base()}/versions`, versions);
755
+ const newest = newestVersion(versions.body);
756
+ return {
757
+ destination: this.describe(),
758
+ secret: name,
759
+ versionId: newest.id,
760
+ createdOn: newest.createdOn,
761
+ triggeredBySecret: newest.triggeredBy === "secret",
762
+ note: "a Worker's secret-change version covers all of its secrets, not only this one"
763
+ };
764
+ }
765
+ #base() {
766
+ return `/accounts/${this.#account}/workers/scripts/${this.#worker}`;
767
+ }
768
+ async#publisher() {
769
+ const user = await this.#request("GET", "/user");
770
+ const email = user.status === 200 ? objectField(user.body, "result").email : undefined;
771
+ return typeof email === "string" ? email : "unknown (the token can't read /user)";
772
+ }
773
+ async#accountIds() {
774
+ const ids = [];
775
+ for (let page = 1;; page++) {
776
+ const response = await this.#request("GET", `/accounts?per_page=50&page=${page}`);
777
+ if (response.status !== 200)
778
+ throw failure("GET", "/accounts", response);
779
+ const result = response.body.result;
780
+ if (!Array.isArray(result))
781
+ throw new Error("Cloudflare's /accounts response has no result list");
782
+ for (const account of result) {
783
+ if (isRecord(account) && typeof account.id === "string")
784
+ ids.push(account.id);
785
+ }
786
+ const pages = objectField(response.body, "result_info").total_pages;
787
+ if (typeof pages !== "number" || page >= pages)
788
+ return ids;
789
+ }
790
+ }
791
+ async#request(method, path, body) {
792
+ this.#token ??= this.#tokenSource();
793
+ const response = await this.#fetch(`${API}${path}`, {
794
+ method,
795
+ headers: {
796
+ Authorization: `Bearer ${await this.#token}`,
797
+ ...body === undefined ? {} : { "Content-Type": "application/json" }
798
+ },
799
+ body: body === undefined ? undefined : JSON.stringify(body)
800
+ });
801
+ return { status: response.status, body: parseObject(await response.text()) };
802
+ }
803
+ }
804
+ function failure(method, path, response) {
805
+ const errors = response.body.errors;
806
+ const codes = Array.isArray(errors) ? errors.map((e) => isRecord(e) ? e.code : undefined).filter((c) => typeof c === "string" || typeof c === "number") : [];
807
+ const detail = codes.length ? `, codes ${codes.join(", ")}` : "";
808
+ return new Error(`Cloudflare ${method} ${path.split("?")[0]} returned HTTP ${response.status}${detail}`);
809
+ }
810
+ function newestVersion(body) {
811
+ const items = objectField(body, "result").items;
812
+ if (!Array.isArray(items))
813
+ throw new Error("Cloudflare's versions response has no items");
814
+ const versions = items.map((item) => {
815
+ const v = isRecord(item) ? item : {};
816
+ const createdOn = objectField(v, "metadata").created_on;
817
+ return {
818
+ id: typeof v.id === "string" ? v.id : null,
819
+ createdOn: typeof createdOn === "string" ? createdOn : null,
820
+ triggeredBy: objectField(v, "annotations")["workers/triggered_by"]
821
+ };
822
+ });
823
+ versions.sort((a, b) => Date.parse(b.createdOn ?? "") - Date.parse(a.createdOn ?? ""));
824
+ const newest = versions[0];
825
+ if (!newest?.id || !newest.createdOn)
826
+ throw new Error("Cloudflare listed no version for the Worker after the write");
827
+ return newest;
828
+ }
829
+ function parseObject(text) {
830
+ try {
831
+ const data = JSON.parse(text);
832
+ return isRecord(data) ? data : {};
833
+ } catch {
834
+ return {};
835
+ }
836
+ }
837
+ function objectField(data, field) {
838
+ const value = data[field];
839
+ return isRecord(value) ? value : {};
840
+ }
841
+ // ../../packages/destination-github/src/github.ts
842
+ import sodium from "libsodium-wrappers";
843
+
844
+ // ../../packages/destination-github/src/token.ts
845
+ import { execFile as execFile2 } from "child_process";
846
+ function ghToken(login) {
847
+ const env = { ...process.env };
848
+ delete env.GH_TOKEN;
849
+ delete env.GITHUB_TOKEN;
850
+ const args = ["auth", "token", "--hostname", "github.com", "--user", login];
851
+ return new Promise((resolve, reject) => {
852
+ execFile2("gh", args, { env }, (error, stdout) => {
853
+ const token = String(stdout).trim();
854
+ if (error || !token)
855
+ reject(new Error(`gh has no token for ${login}; run: gh auth login --hostname github.com`));
856
+ else
857
+ resolve(token);
858
+ });
859
+ });
860
+ }
861
+
862
+ // ../../packages/destination-github/src/github.ts
863
+ var API2 = "https://api.github.com";
864
+ var REPO2 = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/;
865
+ var SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
866
+
867
+ class GitHubSecretDestination {
868
+ capabilities = { write: true, accountCheck: true, evidence: true };
869
+ #repo;
870
+ #owner;
871
+ #expected;
872
+ #tokenSource;
873
+ #fetch;
874
+ #token;
875
+ #passed = false;
876
+ constructor(options) {
877
+ if (!REPO2.test(options.repo))
878
+ throw new Error(`"${options.repo}" isn't a GitHub repository in the form owner/name`);
879
+ this.#repo = options.repo;
880
+ this.#owner = options.repo.split("/")[0];
881
+ this.#expected = options.account ?? this.#owner;
882
+ this.#tokenSource = options.token ?? (() => ghToken(this.#expected));
883
+ this.#fetch = options.fetch ?? globalThis.fetch;
884
+ }
885
+ describe() {
886
+ return `github ${this.#repo} (repo secret)`;
887
+ }
888
+ async checkAccount() {
889
+ this.#passed = false;
890
+ const user = await this.#get("/user");
891
+ if (user.status !== 200)
892
+ throw new Error(`GitHub GET /user returned HTTP ${user.status}`);
893
+ const publisher = stringField(user.body, "login");
894
+ const scopes = user.headers.get("x-oauth-scopes");
895
+ const repo = await this.#get(`/repos/${this.#repo}`);
896
+ const facts = { publisher, expected: this.#expected };
897
+ if (repo.status === 404) {
898
+ return {
899
+ ...facts,
900
+ destinationAccount: null,
901
+ ok: false,
902
+ reason: `${publisher} can't see ${this.#repo}`
903
+ };
904
+ }
905
+ if (repo.status !== 200)
906
+ throw new Error(`GitHub GET /repos/${this.#repo} returned HTTP ${repo.status}`);
907
+ const owner = stringField(objectField2(repo.body, "owner"), "login");
908
+ const admin = objectField2(repo.body, "permissions").admin === true;
909
+ const check = { ...facts, destinationAccount: owner, ok: false };
910
+ if (!sameLogin(owner, this.#owner)) {
911
+ check.reason = `${this.#repo} is owned by ${owner}, not ${this.#owner} (moved or renamed?)`;
912
+ } else if (!sameLogin(publisher, this.#expected)) {
913
+ check.reason = `the token acts as ${publisher}, not ${this.#expected}`;
914
+ } else if (!admin) {
915
+ check.reason = `${publisher} isn't an admin of ${this.#repo}, so it can't write secrets`;
916
+ } else if (scopes !== null && !scopes.split(",").some((s) => s.trim() === "repo")) {
917
+ check.reason = `the token lacks the repo scope (it has: ${scopes || "none"})`;
918
+ } else {
919
+ check.ok = true;
920
+ this.#passed = true;
921
+ }
922
+ return check;
923
+ }
924
+ async write(name, secret) {
925
+ if (!this.#passed)
926
+ throw new Error(`refusing to write to ${this.describe()}: checkAccount hasn't passed`);
927
+ if (!SECRET_NAME.test(name) || /^GITHUB_/i.test(name))
928
+ throw new Error(`"${name}" isn't a valid GitHub secret name`);
929
+ const key = await this.#get(`/repos/${this.#repo}/actions/secrets/public-key`);
930
+ if (key.status !== 200)
931
+ throw new Error(`GitHub public key for ${this.#repo}: HTTP ${key.status}`);
932
+ const encrypted = await sealedBox(secret.reveal(), stringField(key.body, "key"));
933
+ const path = `/repos/${this.#repo}/actions/secrets/${name}`;
934
+ const put = await this.#request("PUT", path, {
935
+ encrypted_value: encrypted,
936
+ key_id: stringField(key.body, "key_id")
937
+ });
938
+ if (put.status !== 201 && put.status !== 204)
939
+ throw new Error(`GitHub PUT ${path} returned HTTP ${put.status}`);
940
+ const after = await this.#get(path);
941
+ if (after.status !== 200)
942
+ throw new Error(`GitHub GET ${path} after the write returned HTTP ${after.status}`);
943
+ return {
944
+ destination: this.describe(),
945
+ secret: name,
946
+ created: put.status === 201,
947
+ updatedAt: stringField(after.body, "updated_at")
948
+ };
949
+ }
950
+ #get(path) {
951
+ return this.#request("GET", path);
952
+ }
953
+ async#request(method, path, body) {
954
+ this.#token ??= this.#tokenSource();
955
+ const response = await this.#fetch(`${API2}${path}`, {
956
+ method,
957
+ headers: {
958
+ Authorization: `Bearer ${await this.#token}`,
959
+ Accept: "application/vnd.github+json",
960
+ "X-GitHub-Api-Version": "2022-11-28",
961
+ ...body === undefined ? {} : { "Content-Type": "application/json" }
962
+ },
963
+ body: body === undefined ? undefined : JSON.stringify(body)
964
+ });
965
+ const text = await response.text();
966
+ return { status: response.status, headers: response.headers, body: parseObject2(text) };
967
+ }
968
+ }
969
+ async function sealedBox(value, publicKey) {
970
+ await sodium.ready;
971
+ const key = sodium.from_base64(publicKey, sodium.base64_variants.ORIGINAL);
972
+ return sodium.to_base64(sodium.crypto_box_seal(value, key), sodium.base64_variants.ORIGINAL);
973
+ }
974
+ function sameLogin(a, b) {
975
+ return a.toLowerCase() === b.toLowerCase();
976
+ }
977
+ function parseObject2(text) {
978
+ try {
979
+ const data = JSON.parse(text);
980
+ return isRecord(data) ? data : {};
981
+ } catch {
982
+ return {};
983
+ }
984
+ }
985
+ function objectField2(data, field) {
986
+ const value = data[field];
987
+ return isRecord(value) ? value : {};
988
+ }
989
+ function stringField(data, field) {
990
+ const value = data[field];
991
+ if (typeof value !== "string")
992
+ throw new Error(`GitHub's response has no "${field}"`);
993
+ return value;
994
+ }
995
+ // ../../packages/vault-1password/src/sdk.ts
996
+ var desktopConnect = async (account) => {
997
+ const sdk = await import("@1password/sdk");
998
+ const client = await sdk.createClient({
999
+ auth: new sdk.DesktopAuth(account),
1000
+ integrationName: "keypin",
1001
+ integrationVersion: "0.0.0"
1002
+ });
1003
+ const field = (f) => ({ ...f, fieldType: sdk.ItemFieldType[f.fieldType] });
1004
+ return {
1005
+ vaults: { list: () => client.vaults.list() },
1006
+ items: {
1007
+ list: (vaultId) => client.items.list(vaultId),
1008
+ get: (vaultId, itemId) => client.items.get(vaultId, itemId),
1009
+ create: (params) => client.items.create({
1010
+ ...params,
1011
+ category: sdk.ItemCategory[params.category],
1012
+ fields: params.fields?.map(field)
1013
+ }),
1014
+ put: (item) => client.items.put({
1015
+ ...item,
1016
+ category: sdk.ItemCategory[item.category],
1017
+ fields: item.fields.map(field)
1018
+ })
1019
+ }
1020
+ };
1021
+ };
1022
+
1023
+ // ../../packages/vault-1password/src/backend.ts
1024
+ var VALUE_FIELD = "password";
1025
+ var ROTATED = "rotated";
1026
+ var ROTATE_EVERY = "rotate_every";
1027
+ var DAY2 = /^\d{4}-\d{2}-\d{2}$/;
1028
+ var UNIX_SECONDS = /^\d+$/;
1029
+ function onePasswordBackend(connect = desktopConnect) {
1030
+ const clients = new Map;
1031
+ function client(account) {
1032
+ let pending = clients.get(account);
1033
+ if (!pending) {
1034
+ pending = connect(account).catch((error) => {
1035
+ clients.delete(account);
1036
+ throw new Error(`1Password account "${account}": sign-in failed: ${messageOf2(error)}`);
1037
+ });
1038
+ clients.set(account, pending);
1039
+ }
1040
+ return pending;
1041
+ }
1042
+ async function vaultId(sdk, scope) {
1043
+ const matches = (await sdk.vaults.list()).filter((vault) => vault.title === scope.vault);
1044
+ const [match] = matches;
1045
+ if (!match) {
1046
+ throw new Error(`1Password account "${scope.account}" has no vault "${scope.vault}"`);
1047
+ }
1048
+ if (matches.length > 1) {
1049
+ throw new Error(`1Password account "${scope.account}" has ${matches.length} vaults named "${scope.vault}"`);
1050
+ }
1051
+ return match.id;
1052
+ }
1053
+ async function find(sdk, id, ref) {
1054
+ const matches = (await sdk.items.list(id)).filter((item) => item.title === ref.item);
1055
+ if (matches.length > 1)
1056
+ throw new Error(`${where(ref)}: ${matches.length} items have this name`);
1057
+ return matches[0] ?? null;
1058
+ }
1059
+ async function get(ref) {
1060
+ const sdk = await client(ref.account);
1061
+ const id = await vaultId(sdk, ref);
1062
+ const found = await find(sdk, id, ref);
1063
+ if (!found)
1064
+ throw new Error(`${where(ref)}: no such item`);
1065
+ return sdk.items.get(id, found.id);
1066
+ }
1067
+ return {
1068
+ capabilities: { read: true, write: true, list: true, metadata: true },
1069
+ async read(ref) {
1070
+ const item = await get(ref);
1071
+ const field = valueField(item.fields);
1072
+ if (!field)
1073
+ throw new Error(`${where(ref)}: no "${VALUE_FIELD}" field`);
1074
+ return new Secret(field.value);
1075
+ },
1076
+ async write(ref, secret, options = {}) {
1077
+ const rotated = options.rotated;
1078
+ if (rotated !== undefined && !isDay(rotated)) {
1079
+ throw new Error(`${where(ref)}: rotated must be a real day as YYYY-MM-DD, got "${rotated}"`);
1080
+ }
1081
+ const sdk = await client(ref.account);
1082
+ const id = await vaultId(sdk, ref);
1083
+ const found = await find(sdk, id, ref);
1084
+ if (!found) {
1085
+ const fields = [passwordField(secret)];
1086
+ if (rotated)
1087
+ fields.push(rotatedField(rotated));
1088
+ await sdk.items.create({
1089
+ category: "Password",
1090
+ vaultId: id,
1091
+ title: ref.item,
1092
+ fields
1093
+ });
1094
+ return;
1095
+ }
1096
+ const item = await sdk.items.get(id, found.id);
1097
+ const fields = [...item.fields];
1098
+ const value = valueField(fields);
1099
+ if (value)
1100
+ fields[fields.indexOf(value)] = { ...value, value: secret.reveal() };
1101
+ else
1102
+ fields.push(passwordField(secret));
1103
+ if (rotated) {
1104
+ const existing = fields.find((field) => field.title === ROTATED);
1105
+ if (existing)
1106
+ fields[fields.indexOf(existing)] = {
1107
+ ...existing,
1108
+ ...rotatedField(rotated),
1109
+ id: existing.id
1110
+ };
1111
+ else
1112
+ fields.push(rotatedField(rotated));
1113
+ }
1114
+ await sdk.items.put({ ...item, fields });
1115
+ },
1116
+ async list(scope) {
1117
+ const sdk = await client(scope.account);
1118
+ const items = await sdk.items.list(await vaultId(sdk, scope));
1119
+ return items.map((item) => ({
1120
+ id: item.id,
1121
+ title: item.title,
1122
+ tags: [...item.tags],
1123
+ updatedAt: new Date(item.updatedAt).toISOString()
1124
+ }));
1125
+ },
1126
+ async metadata(ref) {
1127
+ const item = await get(ref);
1128
+ const rotated = plainField(item.fields, ROTATED, ref);
1129
+ const rotateEvery = plainField(item.fields, ROTATE_EVERY, ref);
1130
+ return { rotated: rotated === null ? null : toDay(rotated, ref), rotateEvery };
1131
+ }
1132
+ };
1133
+ }
1134
+ function where(ref) {
1135
+ return `1Password ${ref.account} / ${ref.vault} / ${ref.item}`;
1136
+ }
1137
+ function valueField(fields) {
1138
+ return fields.find((field) => field.id === VALUE_FIELD) ?? fields.find((field) => field.title === VALUE_FIELD);
1139
+ }
1140
+ function passwordField(secret) {
1141
+ return {
1142
+ id: VALUE_FIELD,
1143
+ title: VALUE_FIELD,
1144
+ fieldType: "Concealed",
1145
+ value: secret.reveal()
1146
+ };
1147
+ }
1148
+ function rotatedField(day) {
1149
+ return { id: ROTATED, title: ROTATED, fieldType: "Date", value: day };
1150
+ }
1151
+ function plainField(fields, title, ref) {
1152
+ const field = fields.find((candidate) => candidate.title === title);
1153
+ if (!field)
1154
+ return null;
1155
+ if (field.fieldType !== "Text" && field.fieldType !== "Date") {
1156
+ throw new Error(`${where(ref)}: field "${title}" is ${field.fieldType}, expected Text or Date`);
1157
+ }
1158
+ return field.value === "" ? null : field.value;
1159
+ }
1160
+ function toDay(value, ref) {
1161
+ if (DAY2.test(value))
1162
+ return value;
1163
+ if (UNIX_SECONDS.test(value)) {
1164
+ const date = new Date(Number(value) * 1000);
1165
+ const pad = (n) => String(n).padStart(2, "0");
1166
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
1167
+ }
1168
+ throw new Error(`${where(ref)}: "${ROTATED}" isn't a date: "${value}"`);
1169
+ }
1170
+ function messageOf2(error) {
1171
+ return error instanceof Error ? error.message : String(error);
1172
+ }
1173
+ // src/commands/init.ts
1174
+ import { join as join4, resolve } from "path";
1175
+ import { parseArgs } from "util";
1176
+
1177
+ // src/deps.ts
1178
+ class UsageError extends Error {
1179
+ }
1180
+ function localDay(date) {
1181
+ const pad = (n) => String(n).padStart(2, "0");
1182
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
1183
+ }
1184
+
1185
+ // src/paths.ts
1186
+ import { join as join2 } from "path";
1187
+ function registryPath(deps) {
1188
+ return join2(base(deps.env.XDG_CONFIG_HOME, deps.home, ".config"), "keypin", "registry.json");
1189
+ }
1190
+ function statePath(deps) {
1191
+ return join2(base(deps.env.XDG_STATE_HOME, deps.home, ".local/state"), "keypin", "state.json");
1192
+ }
1193
+ function base(xdg, home, fallback) {
1194
+ return xdg?.startsWith("/") ? xdg : join2(home, fallback);
1195
+ }
1196
+ function projectCount(registry, path) {
1197
+ const count = registry.projects.length;
1198
+ return `${count} ${count === 1 ? "project" : "projects"} in ${path}`;
1199
+ }
1200
+
1201
+ // src/project.ts
1202
+ import { dirname, join as join3 } from "path";
1203
+ var MAP_FILE = "keypin.toml";
1204
+ async function findMap(files, cwd) {
1205
+ for (let folder = cwd;; folder = dirname(folder)) {
1206
+ const file = join3(folder, MAP_FILE);
1207
+ const text = await files.read(file);
1208
+ if (text !== null) {
1209
+ const result = parseMap(text, file);
1210
+ if (!result.ok)
1211
+ throw new Error(result.errors.join(`
1212
+ `));
1213
+ return result.map;
1214
+ }
1215
+ if (dirname(folder) === folder) {
1216
+ throw new Error(`no ${MAP_FILE} in ${cwd} or any folder above it; run "keypin init" first`);
1217
+ }
1218
+ }
1219
+ }
1220
+
1221
+ // src/commands/init.ts
1222
+ var TEMPLATE = `# keypin.toml: this project's keys. It holds names and places, never values.
1223
+ # Uncomment and edit. Every field is checked; an unknown one is an error.
1224
+ #
1225
+ # A vault the keys below read from. The name ("personal") is yours to choose.
1226
+ # [vaults.personal]
1227
+ # kind = "1password"
1228
+ # account = "my.1password.com"
1229
+ # vault = "Private"
1230
+ #
1231
+ # A key. Its ID ("example-api-key") stays the same when vault items are renamed.
1232
+ # [keys.example-api-key]
1233
+ # env = "EXAMPLE_API_KEY" # the variable your program reads
1234
+ # owner = "my-project"
1235
+ # rotate_every = "180d" # <n>d, <n>w, <n>m or never; leave out to use the vault item's rotate_every
1236
+ #
1237
+ # Where keypin run reads the value from.
1238
+ # [keys.example-api-key.dev]
1239
+ # vault = "personal"
1240
+ # item = "my-project dev example api key"
1241
+ #
1242
+ # Where keypin publish reads it from, and every place it writes it.
1243
+ # [keys.example-api-key.prod]
1244
+ # vault = "personal"
1245
+ # item = "my-project prod example api key"
1246
+ #
1247
+ # [[keys.example-api-key.prod.publish]]
1248
+ # to = "cloudflare-worker"
1249
+ # account = "<cloudflare account ID>"
1250
+ # worker = "my-worker"
1251
+ #
1252
+ # [[keys.example-api-key.prod.publish]]
1253
+ # to = "github-actions"
1254
+ # repo = "owner/repo"
1255
+ `;
1256
+ async function init(args, deps) {
1257
+ const { positionals } = parseArgs({ args, options: {}, allowPositionals: true });
1258
+ if (positionals.length > 1)
1259
+ throw new UsageError("keypin init takes at most one folder");
1260
+ const folder = resolve(deps.cwd, positionals[0] ?? ".");
1261
+ if (!await deps.isFolder(folder))
1262
+ throw new Error(`${folder} isn't a folder`);
1263
+ const file = join4(folder, MAP_FILE);
1264
+ const created = await deps.createFile(file, TEMPLATE);
1265
+ if (created === "link")
1266
+ throw new Error(`${file} is a symbolic link; keypin init doesn't follow one`);
1267
+ deps.stderr.write(created === "created" ? `keypin: wrote ${file}
1268
+ ` : `keypin: ${file} exists; left it as it is
1269
+ `);
1270
+ const path = registryPath(deps);
1271
+ const registry = await register(deps.files, path, folder);
1272
+ deps.stderr.write(`keypin: ${folder} is registered (${projectCount(registry, path)})
1273
+ `);
1274
+ return 0;
1275
+ }
1276
+
1277
+ // src/commands/publish.ts
1278
+ import { parseArgs as parseArgs2 } from "util";
1279
+
1280
+ // src/vault.ts
1281
+ function announce(stderr, what, refs) {
1282
+ const groups = new Map;
1283
+ for (const ref of refs) {
1284
+ const where = `1Password account ${ref.account}, vault "${ref.vault}"`;
1285
+ groups.set(where, (groups.get(where) ?? new Set).add(ref.item));
1286
+ }
1287
+ for (const [where, items] of groups) {
1288
+ const names = [...items].map((item) => `"${item}"`).join(", ");
1289
+ stderr.write(`keypin: reading ${what} from ${where}: ${names}
1290
+ `);
1291
+ }
1292
+ }
1293
+ function distinctRefs(refs) {
1294
+ const seen = new Map;
1295
+ for (const ref of refs)
1296
+ if (!seen.has(refKey(ref)))
1297
+ seen.set(refKey(ref), ref);
1298
+ return [...seen.values()];
1299
+ }
1300
+ var refKey = (ref) => JSON.stringify([ref.kind, ref.account, ref.vault, ref.item]);
1301
+
1302
+ // src/commands/publish.ts
1303
+ var NEEDS_APPROVAL = 2;
1304
+ async function publish(args, deps) {
1305
+ const request = parseRequest(args);
1306
+ const map = await findMap(deps.files, deps.cwd);
1307
+ const path = statePath(deps);
1308
+ const lockFile = `${path}.lock`;
1309
+ const taken = await deps.lock(lockFile);
1310
+ if (!taken.held) {
1311
+ deps.stderr.write(`${lockedMessage(lockFile, taken.holder)}
1312
+ `);
1313
+ return 1;
1314
+ }
1315
+ try {
1316
+ return await publishLocked({ ...request, args }, map, path, deps);
1317
+ } finally {
1318
+ await taken.lock.release();
1319
+ }
1320
+ }
1321
+ function lockedMessage(file, holder) {
1322
+ if (holder.pid === null) {
1323
+ return `keypin: ${file} exists but names no process. If no publish is running, delete that file and try again.`;
1324
+ }
1325
+ if (holder.running === false) {
1326
+ return `keypin: ${file} was left by process ${holder.pid}, which isn't running any more. Delete that file and try again.`;
1327
+ }
1328
+ return `keypin: another publish (process ${holder.pid}) holds ${file} and is still running. Wait for it to finish.`;
1329
+ }
1330
+ function parseRequest(args) {
1331
+ const { values, positionals } = parseArgs2({
1332
+ args,
1333
+ options: {
1334
+ env: { type: "string", default: "prod" },
1335
+ yes: { type: "boolean", default: false }
1336
+ },
1337
+ allowPositionals: true
1338
+ });
1339
+ const [keyId, ...extra] = positionals;
1340
+ if (keyId === undefined || extra.length)
1341
+ throw new UsageError("keypin publish takes one key ID");
1342
+ const environment = ENVIRONMENTS.find((name) => name === values.env);
1343
+ if (!environment) {
1344
+ throw new UsageError(`--env is ${ENVIRONMENTS.join(" or ")}, got "${values.env}"`);
1345
+ }
1346
+ return { keyId, environment, yes: values.yes };
1347
+ }
1348
+ async function publishLocked(request, map, path, deps) {
1349
+ const { keyId, environment } = request;
1350
+ const key = map.keys.find((k) => k.id === keyId);
1351
+ if (!key)
1352
+ throw new Error(`${map.file} has no key "${keyId}"`);
1353
+ const entry = key.environments[environment];
1354
+ if (!entry)
1355
+ throw new Error(`key "${keyId}" has no ${environment} entry in ${map.file}`);
1356
+ const say = (text) => deps.stderr.write(`${text}
1357
+ `);
1358
+ say(`Publishing ${keyId} (${environment}) as ${key.env}, from item "${entry.ref.item}"`);
1359
+ say(` vault: 1Password account ${entry.ref.account}, vault "${entry.ref.vault}"`);
1360
+ for (const target of entry.publish)
1361
+ say(` to: ${describeTarget(target, key.env)}`);
1362
+ if (!entry.publish.length) {
1363
+ say(`The map lists no destinations for ${keyId} (${environment}); nothing to publish.`);
1364
+ return 1;
1365
+ }
1366
+ let state = await loadState(deps.files, path);
1367
+ for (const op of unfinishedOperations(state, keyId, environment)) {
1368
+ say(`An earlier publish (started ${op.startedAt}, generation ${op.generation}) didn't finish: wrote ${op.done.length} of ${op.planned.length} (${op.done.join(", ") || "none"}). This run plans again from the receipts.`);
1369
+ }
1370
+ say(`
1371
+ Account checks:`);
1372
+ const checked = new Map;
1373
+ let failed = false;
1374
+ for (const target of entry.publish) {
1375
+ const label = describeTarget(target, key.env);
1376
+ try {
1377
+ const destination = deps.destination(target);
1378
+ const check = await destination.checkAccount();
1379
+ checked.set(destinationId(target, key.env), { target, destination, check });
1380
+ say(` ${check.ok ? "ok" : "FAILED"} ${label}: ${accountFacts(check)}${check.ok ? "" : `: ${check.reason ?? "no reason given"}`}`);
1381
+ if (!check.ok)
1382
+ failed = true;
1383
+ } catch (error) {
1384
+ say(` FAILED ${label}: ${messageOf(error)}`);
1385
+ failed = true;
1386
+ }
1387
+ }
1388
+ if (failed) {
1389
+ say("Stopped: an account check failed. Nothing was read and nothing was written.");
1390
+ return 1;
1391
+ }
1392
+ const approvals = approvalsFor({ key, environment, receipts: state.receipts });
1393
+ if (approvals.length && !deps.isTerminal) {
1394
+ say(`
1395
+ Needs approval:`);
1396
+ for (const approval of approvals)
1397
+ say(` ${approval.approval}`);
1398
+ say(`Stopped before reading the value: this publish needs approval, and --yes can't give it. Nothing was read and nothing was written.`);
1399
+ say(rerun(deps, request.args));
1400
+ return NEEDS_APPROVAL;
1401
+ }
1402
+ announce(deps.stderr, "the value to publish", [entry.ref]);
1403
+ let secret;
1404
+ try {
1405
+ secret = await deps.vault().read(entry.ref);
1406
+ } catch (error) {
1407
+ say(`Stopped: couldn't read ${keyId} (item "${entry.ref.item}"): ${messageOf(error)}`);
1408
+ return 1;
1409
+ }
1410
+ const generation = await generationOf(secret);
1411
+ const plan = planPublish({ key, environment, receipts: state.receipts, generation });
1412
+ say(`
1413
+ Plan for generation ${generation}:`);
1414
+ const writes = [];
1415
+ for (const step of plan.steps) {
1416
+ const found = checked.get(step.destinationId);
1417
+ if (!found)
1418
+ throw new Error(`no account check for ${step.destinationId}`);
1419
+ say(` ${step.action} ${describeTarget(step.target, key.env)}: ${step.reason}`);
1420
+ say(` ${accountFacts(found.check)}`);
1421
+ if (step.approval)
1422
+ say(` needs approval: ${step.approval}`);
1423
+ if (step.action === "write")
1424
+ writes.push({ destinationId: step.destinationId, found });
1425
+ }
1426
+ for (const removed of plan.removed) {
1427
+ say(` not in the map any more: ${removed.destinationId} (last got ${removed.lastReceipt.generation} at ${removed.lastReceipt.at}). keypin doesn't delete it.`);
1428
+ }
1429
+ if (!writes.length) {
1430
+ say("Nothing to write: every destination already has this generation.");
1431
+ if (unfinishedOperations(state, keyId, environment).length) {
1432
+ await saveState(deps.files, path, finishAll(state, keyId, environment));
1433
+ }
1434
+ return 0;
1435
+ }
1436
+ if (!await confirmed(deps, plan.needsApproval, request))
1437
+ return NEEDS_APPROVAL;
1438
+ const id = crypto.randomUUID();
1439
+ state = startOperation(state, {
1440
+ id,
1441
+ keyId,
1442
+ environment,
1443
+ generation,
1444
+ startedAt: deps.now().toISOString(),
1445
+ planned: writes.map((w) => w.destinationId)
1446
+ });
1447
+ await saveState(deps.files, path, state);
1448
+ for (const { destinationId: written, found } of writes) {
1449
+ const label = describeTarget(found.target, key.env);
1450
+ try {
1451
+ const evidence = await found.destination.write(key.env, secret);
1452
+ state = recordReceipt(state, {
1453
+ keyId,
1454
+ environment,
1455
+ source: entry.ref,
1456
+ destinationId: written,
1457
+ generation,
1458
+ account: {
1459
+ pinned: found.target.account,
1460
+ publisher: found.check.publisher,
1461
+ destinationAccount: found.check.destinationAccount ?? found.target.account
1462
+ },
1463
+ at: deps.now().toISOString(),
1464
+ evidence
1465
+ }, id);
1466
+ await saveState(deps.files, path, state);
1467
+ say(` wrote ${label}`);
1468
+ } catch (error) {
1469
+ say(` FAILED ${label}: ${messageOf(error)}`);
1470
+ say("Stopped. Finished writes keep their receipts; run keypin publish again to continue.");
1471
+ return 1;
1472
+ }
1473
+ }
1474
+ state = finishAll(state, keyId, environment);
1475
+ await saveState(deps.files, path, state);
1476
+ say(`Published ${keyId} (${environment}) to ${writes.length} destination(s).`);
1477
+ return 0;
1478
+ }
1479
+ async function confirmed(deps, needsApproval, request) {
1480
+ const say = (text) => deps.stderr.write(`${text}
1481
+ `);
1482
+ if (request.yes && !needsApproval)
1483
+ return true;
1484
+ if (deps.isTerminal) {
1485
+ const answer = await deps.ask(`Type yes to write${needsApproval ? " (this plan needs approval)" : ""}: `);
1486
+ if (answer.trim() === "yes")
1487
+ return true;
1488
+ say("Not confirmed. Nothing was written.");
1489
+ return false;
1490
+ }
1491
+ say(needsApproval ? "Stopped: this plan needs approval, and --yes can't give it. Nothing was written." : "Stopped: no terminal to confirm on. Nothing was written. Add --yes, or confirm in a terminal.");
1492
+ say(rerun(deps, request.args));
1493
+ return false;
1494
+ }
1495
+ function rerun(deps, args) {
1496
+ const command = [...deps.self, "publish", ...args].map(shellWord).join(" ");
1497
+ return `To approve, run this in a terminal:
1498
+ cd ${shellWord(deps.cwd)} && ${command}`;
1499
+ }
1500
+ function shellWord(word) {
1501
+ return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
1502
+ }
1503
+ function finishAll(state, keyId, environment) {
1504
+ return unfinishedOperations(state, keyId, environment).reduce((s, op) => finishOperation(s, op.id), state);
1505
+ }
1506
+ function accountFacts(check) {
1507
+ return `publisher ${check.publisher}, destination account ${check.destinationAccount ?? "unknown"}`;
1508
+ }
1509
+ function describeTarget(target, secretName) {
1510
+ return `${destinationId(target, secretName)} (account ${target.account})`;
1511
+ }
1512
+
1513
+ // src/commands/run.ts
1514
+ import { parseArgs as parseArgs3 } from "util";
1515
+ async function run(args, deps) {
1516
+ const { positionals } = parseArgs3({ args, options: {}, allowPositionals: true });
1517
+ if (!positionals.length)
1518
+ throw new UsageError("keypin run needs a command after --");
1519
+ const map = await findMap(deps.files, deps.cwd);
1520
+ const keys = map.keys.flatMap((key) => {
1521
+ const dev = key.environments.dev;
1522
+ return dev ? [{ key, ref: dev.ref }] : [];
1523
+ });
1524
+ const skipped = map.keys.filter((key) => !key.environments.dev).map((key) => key.id);
1525
+ if (skipped.length)
1526
+ deps.stderr.write(`keypin: no dev entry, not added: ${skipped.join(", ")}
1527
+ `);
1528
+ const values = new Map;
1529
+ if (keys.length) {
1530
+ announce(deps.stderr, "dev values", keys.map((k) => k.ref));
1531
+ const vault = deps.vault();
1532
+ const failures = [];
1533
+ for (const { key, ref } of keys) {
1534
+ try {
1535
+ values.set(key.env, await vault.read(ref));
1536
+ } catch (error) {
1537
+ failures.push(`${key.id} (item "${ref.item}"): ${messageOf(error)}`);
1538
+ }
1539
+ }
1540
+ if (failures.length) {
1541
+ deps.stderr.write(`keypin: couldn't read, so the command didn't start:
1542
+ ${failures.join(`
1543
+ `)}
1544
+ `);
1545
+ return 1;
1546
+ }
1547
+ }
1548
+ const env = {};
1549
+ for (const [name, value] of Object.entries(deps.env))
1550
+ if (value !== undefined)
1551
+ env[name] = value;
1552
+ for (const [name, secret] of values) {
1553
+ if (env[name] !== undefined) {
1554
+ deps.stderr.write(`keypin: ${name} was already set; using the vault's value
1555
+ `);
1556
+ }
1557
+ env[name] = secret.reveal();
1558
+ }
1559
+ const unsafe = Object.entries(env).filter(([, value]) => value.includes("\x00")).map(([name]) => name);
1560
+ if (unsafe.length) {
1561
+ deps.stderr.write(`keypin: ${unsafe.join(", ")} contains a NUL character, which an environment can't hold; the command didn't start
1562
+ `);
1563
+ return 1;
1564
+ }
1565
+ let child;
1566
+ try {
1567
+ child = deps.launch(positionals, env);
1568
+ } catch (error) {
1569
+ deps.stderr.write(`keypin: couldn't start "${positionals[0]}": ${errorCode(error) ?? "unknown error"}
1570
+ `);
1571
+ return 1;
1572
+ }
1573
+ const stop = deps.onSignals((signal) => child.kill(signal));
1574
+ try {
1575
+ return await child.exited;
1576
+ } finally {
1577
+ stop();
1578
+ }
1579
+ }
1580
+
1581
+ // src/commands/status.ts
1582
+ import { join as join5 } from "path";
1583
+ import { parseArgs as parseArgs4 } from "util";
1584
+ async function status(args, deps) {
1585
+ const { values, positionals } = parseArgs4({
1586
+ args,
1587
+ options: { json: { type: "boolean", default: false } },
1588
+ allowPositionals: true
1589
+ });
1590
+ if (positionals.length)
1591
+ throw new UsageError("keypin status takes no arguments");
1592
+ const registry = await loadRegistry(deps.files, registryPath(deps));
1593
+ const state = await loadState(deps.files, statePath(deps));
1594
+ const maps = new Map;
1595
+ for (const project of registry.projects) {
1596
+ const file = join5(project, MAP_FILE);
1597
+ try {
1598
+ const text = await deps.files.read(file);
1599
+ if (text !== null)
1600
+ maps.set(project, parseMap(text, file));
1601
+ } catch (error) {
1602
+ deps.stderr.write(`keypin: couldn't read ${file}: ${messageOf(error)}
1603
+ `);
1604
+ }
1605
+ }
1606
+ const refs = distinctRefs([...maps.values()].flatMap((result) => result.ok ? result.map.keys.flatMap((key) => Object.values(key.environments).map((e) => e.ref)) : []));
1607
+ const metadata = new Map;
1608
+ if (refs.length) {
1609
+ announce(deps.stderr, "rotation fields (no values)", refs);
1610
+ const vault = deps.vault();
1611
+ for (const ref of refs) {
1612
+ try {
1613
+ metadata.set(refKey(ref), await vault.metadata(ref));
1614
+ } catch (error) {
1615
+ deps.stderr.write(`keypin: ${messageOf(error)}
1616
+ `);
1617
+ metadata.set(refKey(ref), null);
1618
+ }
1619
+ }
1620
+ }
1621
+ const result = buildStatus({
1622
+ registry,
1623
+ maps,
1624
+ receipts: state.receipts,
1625
+ metadata: (ref) => metadata.get(refKey(ref)) ?? null,
1626
+ today: localDay(deps.now())
1627
+ });
1628
+ if (values.json) {
1629
+ deps.stdout.write(`${JSON.stringify({ today: localDay(deps.now()), ...result }, null, 2)}
1630
+ `);
1631
+ } else {
1632
+ deps.stdout.write(render(result, registry.projects.length));
1633
+ }
1634
+ return result.problems.some((p) => p.severity === "problem") ? 1 : 0;
1635
+ }
1636
+ function render(result, projects) {
1637
+ if (!projects)
1638
+ return `No projects registered. Run "keypin init" in a project folder.
1639
+ `;
1640
+ const lines = [];
1641
+ const header = ["KEY", "ENV", "VARIABLE", "OWNER", "ITEM", "ROTATED", "EVERY", "DUE"];
1642
+ const cells = (row) => [
1643
+ row.keyId,
1644
+ row.environment,
1645
+ row.env,
1646
+ row.owner,
1647
+ row.ref.item,
1648
+ row.rotated ?? "-",
1649
+ row.rotateEvery ?? "-",
1650
+ row.due ?? (row.rotateEvery === "never" ? "never" : "unknown")
1651
+ ];
1652
+ const widths = header.map((h, i) => Math.max(h.length, ...result.rows.map((r) => (cells(r)[i] ?? "").length)));
1653
+ const line = (values) => values.map((v, i) => v.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
1654
+ lines.push(line(header));
1655
+ let project;
1656
+ for (const row of result.rows) {
1657
+ if (row.project !== project) {
1658
+ project = row.project;
1659
+ lines.push(`# ${project}`);
1660
+ }
1661
+ lines.push(line(cells(row)));
1662
+ for (const d of row.destinations) {
1663
+ const receipt = d.receipt ? `last published ${d.receipt.at} by ${d.receipt.publisher}, generation ${d.receipt.generation}` : "no receipt";
1664
+ lines.push(` -> ${d.destinationId} (account ${d.account}): ${receipt}`);
1665
+ }
1666
+ }
1667
+ if (!result.rows.length)
1668
+ lines.push("(no keys)");
1669
+ for (const [severity, title] of [
1670
+ ["problem", "Problems"],
1671
+ ["notice", "Notices"]
1672
+ ]) {
1673
+ const found = shown(result.problems.filter((p) => p.severity === severity));
1674
+ if (!found.length)
1675
+ continue;
1676
+ lines.push("", `${title} (${found.length}):`);
1677
+ for (const p of found)
1678
+ lines.push(` ${p.kind}: ${p.message.replaceAll(`
1679
+ `, `
1680
+ `)}`);
1681
+ }
1682
+ return `${lines.join(`
1683
+ `)}
1684
+ `;
1685
+ }
1686
+ function shown(problems) {
1687
+ const unknown = problems.filter((p) => p.kind === "authority-unknown");
1688
+ const rest = problems.filter((p) => p.kind !== "authority-unknown");
1689
+ if (!unknown.length)
1690
+ return rest;
1691
+ const keys = [...new Set(unknown.map((p) => p.keyId ?? p.project))];
1692
+ const subject = keys.length === 1 ? "1 key" : `${keys.length} keys`;
1693
+ return [
1694
+ ...rest,
1695
+ {
1696
+ kind: "authority-unknown",
1697
+ message: `${subject} (${keys.join(", ")}): what each grants is unknown, because keypin didn't create it`
1698
+ }
1699
+ ];
1700
+ }
1701
+
1702
+ // src/commands/unregister.ts
1703
+ import { resolve as resolve2 } from "path";
1704
+ import { parseArgs as parseArgs5 } from "util";
1705
+ async function unregister2(args, deps) {
1706
+ const { positionals } = parseArgs5({ args, options: {}, allowPositionals: true });
1707
+ if (positionals.length > 1)
1708
+ throw new UsageError("keypin unregister takes at most one folder");
1709
+ const folder = resolve2(deps.cwd, positionals[0] ?? ".");
1710
+ const path = registryPath(deps);
1711
+ const before = await loadRegistry(deps.files, path);
1712
+ const registry = await unregister(deps.files, path, folder);
1713
+ if (before.projects.length === registry.projects.length) {
1714
+ const listed = registry.projects.map((project) => `
1715
+ ${project}`).join("");
1716
+ deps.stderr.write(`keypin: ${folder} wasn't registered (${projectCount(registry, path)})${listed}
1717
+ `);
1718
+ return 1;
1719
+ }
1720
+ deps.stderr.write(`keypin: ${folder} is no longer registered (${projectCount(registry, path)})
1721
+ `);
1722
+ return 0;
1723
+ }
1724
+ // ../../package.json
1725
+ var version = "0.1.0";
1726
+
1727
+ // src/cli.ts
1728
+ var USAGE = `Usage:
1729
+ keypin init [folder] register a project and write a keypin.toml template
1730
+ keypin unregister [folder]
1731
+ stop listing a project; its keypin.toml stays
1732
+ keypin status [--json] every key in every registered project, with problems
1733
+ keypin run -- <command> run a command with this project's dev keys in its environment
1734
+ keypin publish <key-id> [--env prod|dev] [--yes]
1735
+ check accounts, plan, confirm, then write the key to every destination
1736
+ keypin --version print the version
1737
+ `;
1738
+ var COMMANDS = new Map([
1739
+ ["init", init],
1740
+ ["unregister", unregister2],
1741
+ ["status", status],
1742
+ ["run", run],
1743
+ ["publish", publish]
1744
+ ]);
1745
+ async function cli(argv, deps) {
1746
+ const [name, ...args] = argv;
1747
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1748
+ (name === undefined ? deps.stderr : deps.stdout).write(USAGE);
1749
+ return name === undefined ? 2 : 0;
1750
+ }
1751
+ if (name === "--version" || name === "-v") {
1752
+ deps.stdout.write(`${version}
1753
+ `);
1754
+ return 0;
1755
+ }
1756
+ const command = COMMANDS.get(name);
1757
+ if (!command) {
1758
+ deps.stderr.write(`keypin: unknown command "${name}"
1759
+ ${USAGE}`);
1760
+ return 2;
1761
+ }
1762
+ try {
1763
+ return await command(args, deps);
1764
+ } catch (error) {
1765
+ if (error instanceof UsageError || errorCode(error)?.startsWith("ERR_PARSE_ARGS")) {
1766
+ deps.stderr.write(`keypin ${name}: ${messageOf(error)}
1767
+ ${USAGE}`);
1768
+ return 2;
1769
+ }
1770
+ deps.stderr.write(`keypin ${name}: ${messageOf(error)}
1771
+ `);
1772
+ return 1;
1773
+ }
1774
+ }
1775
+
1776
+ // src/disk.ts
1777
+ import { constants, rmSync } from "fs";
1778
+ import { chmod, lstat, mkdir, open, readFile as readFile2, rename, rm, stat } from "fs/promises";
1779
+ import { dirname as dirname2 } from "path";
1780
+
1781
+ // src/launch.ts
1782
+ var launch = (command, env) => {
1783
+ const child = Bun.spawn(command, { env, stdio: ["inherit", "inherit", "inherit"] });
1784
+ return { exited: child.exited, kill: (signal) => child.kill(signal) };
1785
+ };
1786
+ var onSignals = (handler) => {
1787
+ const signals = ["SIGINT", "SIGTERM"];
1788
+ for (const signal of signals)
1789
+ process.on(signal, handler);
1790
+ return () => {
1791
+ for (const signal of signals)
1792
+ process.off(signal, handler);
1793
+ };
1794
+ };
1795
+
1796
+ // src/disk.ts
1797
+ var diskFiles = {
1798
+ async read(path) {
1799
+ try {
1800
+ return await readFile2(path, "utf8");
1801
+ } catch (error) {
1802
+ if (errorCode(error) === "ENOENT")
1803
+ return null;
1804
+ throw error;
1805
+ }
1806
+ },
1807
+ async write(path, text) {
1808
+ await privateFolder(dirname2(path));
1809
+ const handle = await open(path, PRIVATE_WRITE, 384);
1810
+ try {
1811
+ await handle.chmod(384);
1812
+ await handle.writeFile(text);
1813
+ } finally {
1814
+ await handle.close();
1815
+ }
1816
+ },
1817
+ async rename(from, to) {
1818
+ await rename(from, to);
1819
+ }
1820
+ };
1821
+ var PRIVATE_WRITE = constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW;
1822
+ async function privateFolder(folder) {
1823
+ await mkdir(folder, { recursive: true });
1824
+ await chmod(folder, 448);
1825
+ }
1826
+ var createFile = async (path, text) => {
1827
+ const found = await kindOf(path);
1828
+ if (found !== "missing")
1829
+ return found;
1830
+ try {
1831
+ const handle = await open(path, "wx");
1832
+ await handle.writeFile(text);
1833
+ await handle.close();
1834
+ return "created";
1835
+ } catch (error) {
1836
+ if (errorCode(error) !== "EEXIST")
1837
+ throw error;
1838
+ const now = await kindOf(path);
1839
+ return now === "missing" ? "exists" : now;
1840
+ }
1841
+ };
1842
+ async function kindOf(path) {
1843
+ try {
1844
+ const found = await lstat(path);
1845
+ if (found.isSymbolicLink())
1846
+ return "link";
1847
+ if (!found.isFile())
1848
+ throw new Error(`${path} isn't a file`);
1849
+ return "exists";
1850
+ } catch (error) {
1851
+ if (errorCode(error) === "ENOENT")
1852
+ return "missing";
1853
+ throw error;
1854
+ }
1855
+ }
1856
+ async function isFolder(path) {
1857
+ try {
1858
+ return (await stat(path)).isDirectory();
1859
+ } catch {
1860
+ return false;
1861
+ }
1862
+ }
1863
+ var diskLock = async (path) => {
1864
+ await privateFolder(dirname2(path));
1865
+ if (await take(path))
1866
+ return { held: true, lock: held(path) };
1867
+ const pid = await holderOf(path);
1868
+ return { held: false, holder: { pid, running: pid === null ? null : isRunning(pid) } };
1869
+ };
1870
+ async function take(path) {
1871
+ try {
1872
+ const handle = await open(path, "wx", 384);
1873
+ await handle.writeFile(`${process.pid}
1874
+ `);
1875
+ await handle.close();
1876
+ return true;
1877
+ } catch (error) {
1878
+ if (errorCode(error) === "EEXIST")
1879
+ return false;
1880
+ throw error;
1881
+ }
1882
+ }
1883
+ async function holderOf(path) {
1884
+ const text = await diskFiles.read(path);
1885
+ const pid = text?.match(/^(\d+)\n?$/)?.[1];
1886
+ return pid === undefined ? null : Number(pid);
1887
+ }
1888
+ function isRunning(pid) {
1889
+ try {
1890
+ process.kill(pid, 0);
1891
+ return true;
1892
+ } catch (error) {
1893
+ return errorCode(error) !== "ESRCH";
1894
+ }
1895
+ }
1896
+ function held(path) {
1897
+ const stop = onSignals((signal) => {
1898
+ stop();
1899
+ rmSync(path, { force: true });
1900
+ process.kill(process.pid, signal);
1901
+ });
1902
+ return {
1903
+ async release() {
1904
+ stop();
1905
+ await rm(path, { force: true });
1906
+ }
1907
+ };
1908
+ }
1909
+
1910
+ // src/start.ts
1911
+ var vault;
1912
+ function destination(target) {
1913
+ switch (target.to) {
1914
+ case "cloudflare-worker":
1915
+ return new WorkerSecretDestination({ account: target.account, worker: target.worker });
1916
+ case "github-actions":
1917
+ return new GitHubSecretDestination({ repo: target.repo, account: target.account });
1918
+ default: {
1919
+ const unknown = target;
1920
+ throw new Error(`unknown destination ${JSON.stringify(unknown)}`);
1921
+ }
1922
+ }
1923
+ }
1924
+ var connect = (account) => desktopConnect(account).catch((error) => {
1925
+ const hint = installProblem(error);
1926
+ throw hint ? new Error(hint) : error;
1927
+ });
1928
+ async function ask(question) {
1929
+ const prompt = createInterface({ input: process.stdin, output: process.stderr });
1930
+ try {
1931
+ return await prompt.question(question);
1932
+ } finally {
1933
+ prompt.close();
1934
+ }
1935
+ }
1936
+ function main() {
1937
+ return cli(process.argv.slice(2), {
1938
+ cwd: process.cwd(),
1939
+ self: process.argv.slice(0, 2),
1940
+ env: process.env,
1941
+ home: homedir2(),
1942
+ files: diskFiles,
1943
+ isFolder,
1944
+ createFile,
1945
+ vault: () => vault ??= onePasswordBackend(connect),
1946
+ now: () => new Date,
1947
+ stdout: process.stdout,
1948
+ stderr: process.stderr,
1949
+ launch,
1950
+ onSignals,
1951
+ destination,
1952
+ lock: diskLock,
1953
+ isTerminal: Boolean(process.stdin.isTTY),
1954
+ ask
1955
+ });
1956
+ }
1957
+ export {
1958
+ main
1959
+ };