@vaultkeepr/cli 0.0.0-stage → 0.2.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 +234 -2
- package/dist/_esm-2BJT4VTJ.js +3739 -0
- package/dist/agent-OVSW5GMB.js +17 -0
- package/dist/ccip-SAAG5KQW.js +14 -0
- package/dist/chunk-4VNS5WPM.js +42 -0
- package/dist/chunk-GOWAFN6V.js +2454 -0
- package/dist/chunk-I25CVPG3.js +4603 -0
- package/dist/chunk-UDT2YIGY.js +158 -0
- package/dist/chunk-UUCFTCF4.js +3358 -0
- package/dist/chunk-V4QISPBH.js +122 -0
- package/dist/chunk-XJMVKU2V.js +22430 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +21 -0
- package/dist/dist-XKDX6HOR.js +484 -0
- package/dist/index.d.ts +794 -0
- package/dist/index.js +215 -0
- package/dist/secp256k1-SITSPVYB.js +16 -0
- package/package.json +42 -4
|
@@ -0,0 +1,3358 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AGENT_MANDATE_PRESETS,
|
|
3
|
+
AGENT_MANDATE_REQUEST_DEFAULT_TTL_DAYS,
|
|
4
|
+
AGENT_MANDATE_REQUEST_MAX_TTL_DAYS,
|
|
5
|
+
AGENT_VAULT_SUMMARY_FILENAME,
|
|
6
|
+
AGENT_VAULT_SUMMARY_VERSION,
|
|
7
|
+
PAYLOAD_VERSION_CURRENT,
|
|
8
|
+
buildAgentMandateRequest,
|
|
9
|
+
buildPairUri,
|
|
10
|
+
decryptFromPair,
|
|
11
|
+
decryptVault,
|
|
12
|
+
decryptWithCandidates,
|
|
13
|
+
defaultMandateUrlPrefixes,
|
|
14
|
+
deleteVaultEntry,
|
|
15
|
+
deriveKeyFromPasswordArgon2,
|
|
16
|
+
derivePairSecret,
|
|
17
|
+
encryptVault,
|
|
18
|
+
entryUrlMatchesPrefixes,
|
|
19
|
+
entryUrlOrigin,
|
|
20
|
+
generatePairKeypair,
|
|
21
|
+
generateSaltArgon2,
|
|
22
|
+
getChecksumAddress,
|
|
23
|
+
getHiddenWalletFromPassword,
|
|
24
|
+
getHiddenWalletFromSecretKey,
|
|
25
|
+
isWrongPasswordError,
|
|
26
|
+
parsePairPayload,
|
|
27
|
+
parseVault,
|
|
28
|
+
serializeVault,
|
|
29
|
+
threeWayMerge
|
|
30
|
+
} from "./chunk-XJMVKU2V.js";
|
|
31
|
+
import {
|
|
32
|
+
agentBinaryCandidates,
|
|
33
|
+
runAgentDispatch,
|
|
34
|
+
spawnAgentBinary
|
|
35
|
+
} from "./chunk-V4QISPBH.js";
|
|
36
|
+
|
|
37
|
+
// src/config.ts
|
|
38
|
+
import { existsSync, renameSync } from "fs";
|
|
39
|
+
import { chmod, mkdir, readFile, writeFile } from "fs/promises";
|
|
40
|
+
import { dirname, join } from "path";
|
|
41
|
+
import { homedir } from "os";
|
|
42
|
+
var CONFIG_DIR_ENV = "VK_CONFIG_DIR";
|
|
43
|
+
var CONFIG_DIR_NAME = "vaultkeepr";
|
|
44
|
+
var LEGACY_CONFIG_DIR_NAME = "vaultkeeper";
|
|
45
|
+
var DIR_MODE = 448;
|
|
46
|
+
var FILE_MODE = 384;
|
|
47
|
+
function migrateLegacyConfigDir(dir, legacyDir = join(dirname(dir), LEGACY_CONFIG_DIR_NAME)) {
|
|
48
|
+
if (legacyDir === dir) return dir;
|
|
49
|
+
if (!existsSync(legacyDir) || existsSync(dir)) return dir;
|
|
50
|
+
try {
|
|
51
|
+
renameSync(legacyDir, dir);
|
|
52
|
+
process.stderr.write(
|
|
53
|
+
`vaultkeepr: configuration migrated from ${legacyDir} to ${dir}
|
|
54
|
+
`
|
|
55
|
+
);
|
|
56
|
+
return dir;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
59
|
+
process.stderr.write(
|
|
60
|
+
`vaultkeepr: migration of ${legacyDir} failed (${reason}); still using ${legacyDir}
|
|
61
|
+
`
|
|
62
|
+
);
|
|
63
|
+
return legacyDir;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function vaultkeeprConfigDir(env = process.env) {
|
|
67
|
+
const override = env[CONFIG_DIR_ENV];
|
|
68
|
+
if (typeof override === "string" && override.trim() !== "") {
|
|
69
|
+
return override;
|
|
70
|
+
}
|
|
71
|
+
return migrateLegacyConfigDir(join(homedir(), ".config", CONFIG_DIR_NAME));
|
|
72
|
+
}
|
|
73
|
+
function configPaths(dir = vaultkeeprConfigDir()) {
|
|
74
|
+
return {
|
|
75
|
+
dir,
|
|
76
|
+
identityPath: join(dir, "identity.json"),
|
|
77
|
+
vaultPath: join(dir, "vault.json"),
|
|
78
|
+
syncStatePath: join(dir, "sync-state.json")
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
async function ensurePrivateDir(dir) {
|
|
82
|
+
await mkdir(dir, { recursive: true, mode: DIR_MODE });
|
|
83
|
+
await chmod(dir, DIR_MODE);
|
|
84
|
+
}
|
|
85
|
+
async function writePrivateFile(path, content) {
|
|
86
|
+
await mkdir(dirname(path), { recursive: true, mode: DIR_MODE });
|
|
87
|
+
await writeFile(path, content, { mode: FILE_MODE, encoding: "utf8" });
|
|
88
|
+
await chmod(path, FILE_MODE);
|
|
89
|
+
}
|
|
90
|
+
async function readTextFile(path) {
|
|
91
|
+
return await readFile(path, "utf8");
|
|
92
|
+
}
|
|
93
|
+
async function readTextFileOrNull(path) {
|
|
94
|
+
try {
|
|
95
|
+
return await readTextFile(path);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
const code = error.code;
|
|
98
|
+
if (code === "ENOENT") return null;
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// src/identity.ts
|
|
104
|
+
var ADDRESS_RE = /^0x[0-9a-f]{40}$/;
|
|
105
|
+
function normalizeAddress(address) {
|
|
106
|
+
return address.trim().toLowerCase();
|
|
107
|
+
}
|
|
108
|
+
function validOptionalString(value) {
|
|
109
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
110
|
+
}
|
|
111
|
+
async function identityFromPairPayload(payload, options) {
|
|
112
|
+
if (typeof payload.masterPassword !== "string" || payload.masterPassword === "") {
|
|
113
|
+
throw new Error("pair payload without a vault master password");
|
|
114
|
+
}
|
|
115
|
+
const secretKey = validOptionalString(payload.secretKey);
|
|
116
|
+
if (!secretKey && payload.authType === "passkey") {
|
|
117
|
+
throw new Error(
|
|
118
|
+
"pair payload without a secret key: a passkey account cannot be read in a terminal"
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
const account = await accountForMaterial(payload.masterPassword, secretKey);
|
|
122
|
+
return {
|
|
123
|
+
version: 1,
|
|
124
|
+
address: normalizeAddress(account.address),
|
|
125
|
+
authType: payload.authType,
|
|
126
|
+
masterPassword: payload.masterPassword,
|
|
127
|
+
secretKey,
|
|
128
|
+
walletAddress: validOptionalString(payload.walletAddress),
|
|
129
|
+
licenseKey: validOptionalString(payload.licenseKey),
|
|
130
|
+
apiBase: options.apiBase.replace(/\/+$/, ""),
|
|
131
|
+
deviceName: options.deviceName,
|
|
132
|
+
pairedAt: options.pairedAt ?? Date.now()
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
async function accountForMaterial(masterPassword, secretKey) {
|
|
136
|
+
if (secretKey) {
|
|
137
|
+
return await getHiddenWalletFromSecretKey(secretKey);
|
|
138
|
+
}
|
|
139
|
+
return await getHiddenWalletFromPassword(masterPassword);
|
|
140
|
+
}
|
|
141
|
+
async function accountForIdentity(identity) {
|
|
142
|
+
return await accountForMaterial(identity.masterPassword, identity.secretKey);
|
|
143
|
+
}
|
|
144
|
+
function payloadKeyMaterial(identity) {
|
|
145
|
+
return identity.secretKey ?? identity.masterPassword;
|
|
146
|
+
}
|
|
147
|
+
function parseIdentity(json) {
|
|
148
|
+
const data = JSON.parse(json);
|
|
149
|
+
if (typeof data !== "object" || data === null || data.version !== 1 || typeof data.address !== "string" || !ADDRESS_RE.test(normalizeAddress(data.address)) || typeof data.masterPassword !== "string" || data.masterPassword === "" || data.authType !== "password" && data.authType !== "passkey" || typeof data.apiBase !== "string" || typeof data.pairedAt !== "number") {
|
|
150
|
+
throw new Error("invalid identity file: run `vaultkeepr pair` again");
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
version: 1,
|
|
154
|
+
address: normalizeAddress(data.address),
|
|
155
|
+
authType: data.authType,
|
|
156
|
+
masterPassword: data.masterPassword,
|
|
157
|
+
secretKey: validOptionalString(data.secretKey),
|
|
158
|
+
walletAddress: validOptionalString(data.walletAddress),
|
|
159
|
+
licenseKey: validOptionalString(data.licenseKey),
|
|
160
|
+
apiBase: data.apiBase,
|
|
161
|
+
deviceName: typeof data.deviceName === "string" ? data.deviceName : "vaultkeepr",
|
|
162
|
+
pairedAt: data.pairedAt
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
async function saveIdentity(path, identity) {
|
|
166
|
+
await writePrivateFile(path, `${JSON.stringify(identity)}
|
|
167
|
+
`);
|
|
168
|
+
}
|
|
169
|
+
async function loadIdentity(path) {
|
|
170
|
+
const raw = await readTextFileOrNull(path);
|
|
171
|
+
if (raw === null) return null;
|
|
172
|
+
return parseIdentity(raw);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ../sync/src/schema.ts
|
|
176
|
+
var AUTOMERGE_HEADER = new Uint8Array([133, 111, 74, 131]);
|
|
177
|
+
|
|
178
|
+
// ../sync/src/crdtVault.ts
|
|
179
|
+
import * as Automerge from "@automerge/automerge";
|
|
180
|
+
function importBinary(binary) {
|
|
181
|
+
let doc;
|
|
182
|
+
try {
|
|
183
|
+
doc = Automerge.load(binary);
|
|
184
|
+
} catch (e) {
|
|
185
|
+
throw new Error(`Failed to load CRDT document: ${e instanceof Error ? e.message : "unknown error"}`);
|
|
186
|
+
}
|
|
187
|
+
if (typeof doc.entries !== "object" || doc.entries === null) {
|
|
188
|
+
throw new Error("Invalid CRDT document: missing entries map");
|
|
189
|
+
}
|
|
190
|
+
return doc;
|
|
191
|
+
}
|
|
192
|
+
function isAutomergeBinary(data) {
|
|
193
|
+
if (typeof data === "string") {
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
if (data.length < AUTOMERGE_HEADER.length) return false;
|
|
197
|
+
return data.every(
|
|
198
|
+
(byte, i) => i < AUTOMERGE_HEADER.length ? byte === AUTOMERGE_HEADER[i] : true
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
function toVault(doc) {
|
|
202
|
+
const entries = [];
|
|
203
|
+
for (const entry of Object.values(doc.entries || {})) {
|
|
204
|
+
if (entry._deleted) continue;
|
|
205
|
+
entries.push(crdtToVaultEntry(entry));
|
|
206
|
+
}
|
|
207
|
+
const documents = [];
|
|
208
|
+
for (const secDoc of Object.values(doc.documents || {})) {
|
|
209
|
+
if (secDoc._deleted) continue;
|
|
210
|
+
documents.push(crdtToSecureDoc(secDoc));
|
|
211
|
+
}
|
|
212
|
+
const cloudFiles = [];
|
|
213
|
+
let cloudQuotaUsed = 0;
|
|
214
|
+
for (const cFile of Object.values(doc.cloudFiles || {})) {
|
|
215
|
+
if (cFile._deleted) continue;
|
|
216
|
+
cloudFiles.push(crdtToCloudFile(cFile));
|
|
217
|
+
cloudQuotaUsed += cFile.originalSize || 0;
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
version: doc.version || 1,
|
|
221
|
+
createdAt: doc.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
|
|
222
|
+
entries,
|
|
223
|
+
folders: [...doc.folders || []],
|
|
224
|
+
documents: documents.length > 0 ? documents : void 0,
|
|
225
|
+
cloudFiles: cloudFiles.length > 0 ? cloudFiles : void 0,
|
|
226
|
+
cloudFolders: doc.cloudFolders && doc.cloudFolders.length > 0 ? [...doc.cloudFolders] : void 0,
|
|
227
|
+
cloudQuotaUsed
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function crdtToVaultEntry(c) {
|
|
231
|
+
return {
|
|
232
|
+
id: c.id,
|
|
233
|
+
url: c.url,
|
|
234
|
+
username: c.username,
|
|
235
|
+
password: c.password,
|
|
236
|
+
notes: c.notes || void 0,
|
|
237
|
+
folder: c.folder || void 0,
|
|
238
|
+
totpSecret: c.totpSecret || void 0,
|
|
239
|
+
notesMasked: c.notesMasked || void 0,
|
|
240
|
+
tags: c.tags?.length ? c.tags : void 0,
|
|
241
|
+
favorite: c.favorite || void 0,
|
|
242
|
+
color: c.color || void 0,
|
|
243
|
+
passwordHistory: c.passwordHistory?.length ? c.passwordHistory : void 0,
|
|
244
|
+
passwordMaxAgeDays: c.passwordMaxAgeDays || void 0,
|
|
245
|
+
passwordChangedAt: c.passwordChangedAt || void 0,
|
|
246
|
+
createdAt: c.createdAt,
|
|
247
|
+
customGroup: c.customGroup || void 0,
|
|
248
|
+
useCount: c.useCount || void 0,
|
|
249
|
+
lastUsedAt: c.lastUsedAt || void 0,
|
|
250
|
+
modifiedAt: c.modifiedAt
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function crdtToSecureDoc(c) {
|
|
254
|
+
let ocr;
|
|
255
|
+
if (c.ocr) {
|
|
256
|
+
try {
|
|
257
|
+
ocr = JSON.parse(c.ocr);
|
|
258
|
+
} catch {
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
id: c.id,
|
|
263
|
+
type: c.type,
|
|
264
|
+
label: c.label,
|
|
265
|
+
fragments: [...c.fragments],
|
|
266
|
+
nonce: c.nonce,
|
|
267
|
+
nfcFaceFragments: c.nfcFaceFragments?.length ? [...c.nfcFaceFragments] : void 0,
|
|
268
|
+
nfcFaceNonce: c.nfcFaceNonce || void 0,
|
|
269
|
+
blurredThumbnail: c.blurredThumbnail,
|
|
270
|
+
ocr,
|
|
271
|
+
originalSize: c.originalSize,
|
|
272
|
+
mimeType: c.mimeType,
|
|
273
|
+
addedAt: c.addedAt,
|
|
274
|
+
modifiedAt: c.modifiedAt || void 0
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
function crdtToCloudFile(c) {
|
|
278
|
+
return {
|
|
279
|
+
id: c.id,
|
|
280
|
+
category: c.category,
|
|
281
|
+
fileName: c.fileName,
|
|
282
|
+
folder: c.folder || void 0,
|
|
283
|
+
fragments: [...c.fragments],
|
|
284
|
+
nonce: c.nonce,
|
|
285
|
+
thumbnail: c.thumbnail || void 0,
|
|
286
|
+
originalSize: c.originalSize,
|
|
287
|
+
mimeType: c.mimeType,
|
|
288
|
+
fragmentCount: c.fragmentCount,
|
|
289
|
+
contentHash: c.contentHash,
|
|
290
|
+
description: c.description || void 0,
|
|
291
|
+
tags: c.tags?.length ? [...c.tags] : void 0,
|
|
292
|
+
favorite: c.favorite || void 0,
|
|
293
|
+
addedAt: c.addedAt,
|
|
294
|
+
modifiedAt: c.modifiedAt || void 0
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// ../sync/src/tombstones.ts
|
|
299
|
+
import * as Automerge2 from "@automerge/automerge";
|
|
300
|
+
var TOMBSTONE_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
301
|
+
function purgeTombstones(doc, ttlMs = TOMBSTONE_TTL_MS) {
|
|
302
|
+
const cutoff = Date.now() - ttlMs;
|
|
303
|
+
const entryIdsToPurge = [];
|
|
304
|
+
const docIdsToPurge = [];
|
|
305
|
+
for (const [id, entry] of Object.entries(doc.entries || {})) {
|
|
306
|
+
if (entry._deleted && entry._deletedAt > 0 && entry._deletedAt < cutoff) {
|
|
307
|
+
entryIdsToPurge.push(id);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
for (const [id, secDoc] of Object.entries(doc.documents || {})) {
|
|
311
|
+
if (secDoc._deleted && secDoc._deletedAt > 0 && secDoc._deletedAt < cutoff) {
|
|
312
|
+
docIdsToPurge.push(id);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (entryIdsToPurge.length === 0 && docIdsToPurge.length === 0) {
|
|
316
|
+
return doc;
|
|
317
|
+
}
|
|
318
|
+
return Automerge2.change(doc, "purge-tombstones", (d) => {
|
|
319
|
+
for (const id of entryIdsToPurge) {
|
|
320
|
+
delete d.entries[id];
|
|
321
|
+
}
|
|
322
|
+
for (const id of docIdsToPurge) {
|
|
323
|
+
delete d.documents[id];
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ../sync/src/compat.ts
|
|
329
|
+
function detectPayloadFormat(plaintext) {
|
|
330
|
+
if (typeof plaintext === "string") {
|
|
331
|
+
if (plaintext.startsWith("{")) return "json";
|
|
332
|
+
try {
|
|
333
|
+
const bytes = base64ToUint8Array(plaintext);
|
|
334
|
+
if (isAutomergeBinary(bytes)) return "crdt";
|
|
335
|
+
} catch {
|
|
336
|
+
}
|
|
337
|
+
return "json";
|
|
338
|
+
}
|
|
339
|
+
return isAutomergeBinary(plaintext) ? "crdt" : "json";
|
|
340
|
+
}
|
|
341
|
+
function base64ToUint8Array(base64) {
|
|
342
|
+
const normalized = base64.replace(/-/g, "+").replace(/_/g, "/");
|
|
343
|
+
const binary = atob(normalized);
|
|
344
|
+
const bytes = new Uint8Array(binary.length);
|
|
345
|
+
for (let i = 0; i < binary.length; i++) {
|
|
346
|
+
bytes[i] = binary.charCodeAt(i);
|
|
347
|
+
}
|
|
348
|
+
return bytes;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// src/vault-codec.ts
|
|
352
|
+
function bufferToHex(bytes) {
|
|
353
|
+
return Buffer.from(bytes).toString("hex");
|
|
354
|
+
}
|
|
355
|
+
function hexToBuffer(hex) {
|
|
356
|
+
if (!/^[0-9a-fA-F]+$/.test(hex) || hex.length % 2 !== 0) {
|
|
357
|
+
throw new Error("hex invalide");
|
|
358
|
+
}
|
|
359
|
+
return new Uint8Array(Buffer.from(hex, "hex"));
|
|
360
|
+
}
|
|
361
|
+
async function derivePayloadKey(keyMaterial, salt) {
|
|
362
|
+
return await deriveKeyFromPasswordArgon2(keyMaterial, salt);
|
|
363
|
+
}
|
|
364
|
+
async function sealVaultPayload(vault, keyMaterial, now = Date.now()) {
|
|
365
|
+
const salt = generateSaltArgon2();
|
|
366
|
+
const key = await derivePayloadKey(keyMaterial, salt);
|
|
367
|
+
const plaintext = serializeVault(vault);
|
|
368
|
+
const encrypted = encryptVault(plaintext, key);
|
|
369
|
+
const envelope = {
|
|
370
|
+
ciphertext: encrypted.ciphertext,
|
|
371
|
+
nonce: encrypted.nonce,
|
|
372
|
+
salt: bufferToHex(salt),
|
|
373
|
+
commitment: encrypted.commitment ?? "",
|
|
374
|
+
version: PAYLOAD_VERSION_CURRENT,
|
|
375
|
+
updatedAt: now
|
|
376
|
+
};
|
|
377
|
+
return JSON.stringify(envelope);
|
|
378
|
+
}
|
|
379
|
+
function parseEnvelope(raw) {
|
|
380
|
+
const data = JSON.parse(raw);
|
|
381
|
+
if (typeof data !== "object" || data === null || typeof data.ciphertext !== "string" || typeof data.nonce !== "string" || typeof data.salt !== "string") {
|
|
382
|
+
throw new Error("invalid remote payload (incomplete envelope)");
|
|
383
|
+
}
|
|
384
|
+
return {
|
|
385
|
+
ciphertext: data.ciphertext,
|
|
386
|
+
nonce: data.nonce,
|
|
387
|
+
salt: data.salt,
|
|
388
|
+
commitment: typeof data.commitment === "string" ? data.commitment : "",
|
|
389
|
+
version: typeof data.version === "number" ? data.version : PAYLOAD_VERSION_CURRENT,
|
|
390
|
+
updatedAt: typeof data.updatedAt === "number" ? data.updatedAt : 0
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function vaultFromPlaintext(plaintext) {
|
|
394
|
+
if (typeof plaintext !== "string") {
|
|
395
|
+
const doc = purgeTombstones(importBinary(plaintext));
|
|
396
|
+
return { vault: toVault(doc), format: "crdt" };
|
|
397
|
+
}
|
|
398
|
+
const format = detectPayloadFormat(plaintext);
|
|
399
|
+
if (format === "crdt") {
|
|
400
|
+
const bytes = new Uint8Array(
|
|
401
|
+
Buffer.from(plaintext.replace(/-/g, "+").replace(/_/g, "/"), "base64")
|
|
402
|
+
);
|
|
403
|
+
const doc = purgeTombstones(importBinary(bytes));
|
|
404
|
+
return { vault: toVault(doc), format: "crdt" };
|
|
405
|
+
}
|
|
406
|
+
return { vault: parseVault(plaintext), format: "legacy" };
|
|
407
|
+
}
|
|
408
|
+
async function openVaultPayload(raw, identity, options = {}) {
|
|
409
|
+
const envelope = parseEnvelope(raw);
|
|
410
|
+
const salt = hexToBuffer(envelope.salt);
|
|
411
|
+
const encrypted = {
|
|
412
|
+
ciphertext: envelope.ciphertext,
|
|
413
|
+
nonce: envelope.nonce,
|
|
414
|
+
commitment: envelope.commitment,
|
|
415
|
+
version: envelope.commitment ? 2 : 1
|
|
416
|
+
};
|
|
417
|
+
const candidates = [
|
|
418
|
+
{
|
|
419
|
+
label: "password-only (V4)",
|
|
420
|
+
deriveKey: () => derivePayloadKey(identity.masterPassword, salt)
|
|
421
|
+
}
|
|
422
|
+
];
|
|
423
|
+
if (identity.secretKey) {
|
|
424
|
+
candidates.push({
|
|
425
|
+
label: "secret-key (V4)",
|
|
426
|
+
deriveKey: () => derivePayloadKey(identity.secretKey, salt)
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
const account = options.account ?? await accountForIdentity(identity);
|
|
430
|
+
candidates.push({
|
|
431
|
+
label: "V3 password+signature fallback",
|
|
432
|
+
deriveKey: async () => {
|
|
433
|
+
const { deriveKeyFromPasswordAndSignatureArgon2 } = await import("./dist-XKDX6HOR.js");
|
|
434
|
+
const message = `VaultKeepR:${getChecksumAddress(identity.address)}`;
|
|
435
|
+
const signature = await account.signMessage({ message });
|
|
436
|
+
return await deriveKeyFromPasswordAndSignatureArgon2(
|
|
437
|
+
identity.masterPassword,
|
|
438
|
+
signature,
|
|
439
|
+
salt
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
try {
|
|
444
|
+
const parsed = await decryptWithCandidates(encrypted, candidates, (plaintext, label) => ({
|
|
445
|
+
...vaultFromPlaintext(plaintext),
|
|
446
|
+
keyLabel: label
|
|
447
|
+
}));
|
|
448
|
+
return { ...parsed, updatedAt: envelope.updatedAt };
|
|
449
|
+
} catch (error) {
|
|
450
|
+
if (isWrongPasswordError(error)) {
|
|
451
|
+
throw new Error("remote vault decryption refused (unrecognised account key)");
|
|
452
|
+
}
|
|
453
|
+
throw new Error("remote vault decryption impossible");
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/entries.ts
|
|
458
|
+
var ENTRY_KINDS = ["api", "login", "card", "identity", "note", "seed", "passkey"];
|
|
459
|
+
function isEntryKind(value) {
|
|
460
|
+
return ENTRY_KINDS.includes(value);
|
|
461
|
+
}
|
|
462
|
+
function groupOf(entry) {
|
|
463
|
+
const typed = entry.type;
|
|
464
|
+
if (typed === "seed") return "seeds";
|
|
465
|
+
if (typed === "passkey") return "passkeys";
|
|
466
|
+
if (typed === "api") return "api";
|
|
467
|
+
return entry.customGroup ?? entry.folder ?? "identifiants";
|
|
468
|
+
}
|
|
469
|
+
var GROUP_TO_KIND = {
|
|
470
|
+
identifiants: "login",
|
|
471
|
+
cartes: "card",
|
|
472
|
+
notes: "note",
|
|
473
|
+
identites: "identity",
|
|
474
|
+
seeds: "seed",
|
|
475
|
+
passkeys: "passkey",
|
|
476
|
+
api: "api"
|
|
477
|
+
};
|
|
478
|
+
function entryKind(entry) {
|
|
479
|
+
const typed = entry.type;
|
|
480
|
+
if (typed === "api") return "api";
|
|
481
|
+
if (typed === "seed") return "seed";
|
|
482
|
+
if (typed === "passkey") return "passkey";
|
|
483
|
+
return GROUP_TO_KIND[groupOf(entry)] ?? "login";
|
|
484
|
+
}
|
|
485
|
+
var KIND_LABELS = {
|
|
486
|
+
api: "API key",
|
|
487
|
+
login: "Login",
|
|
488
|
+
card: "Card",
|
|
489
|
+
identity: "Identity",
|
|
490
|
+
note: "Note",
|
|
491
|
+
seed: "Seed",
|
|
492
|
+
passkey: "Passkey"
|
|
493
|
+
};
|
|
494
|
+
function entryLabel(entry) {
|
|
495
|
+
const titled = entry;
|
|
496
|
+
const label = titled.title?.trim() || entry.username?.trim() || entry.url?.trim() || "";
|
|
497
|
+
return label === "" ? entry.id.slice(0, 8) : label;
|
|
498
|
+
}
|
|
499
|
+
function entrySecret(entry) {
|
|
500
|
+
return typeof entry.password === "string" ? entry.password : "";
|
|
501
|
+
}
|
|
502
|
+
function filterByKind(entries, kind) {
|
|
503
|
+
if (!kind) return entries;
|
|
504
|
+
return entries.filter((entry) => entryKind(entry) === kind);
|
|
505
|
+
}
|
|
506
|
+
function sortEntries(entries) {
|
|
507
|
+
return [...entries].sort((a, b) => entryLabel(a).localeCompare(entryLabel(b), "en"));
|
|
508
|
+
}
|
|
509
|
+
function findEntry(entries, query) {
|
|
510
|
+
const needle = query.trim();
|
|
511
|
+
if (needle === "") throw new Error("empty entry name");
|
|
512
|
+
const lower = needle.toLowerCase();
|
|
513
|
+
const byId = entries.filter((entry) => entry.id === needle);
|
|
514
|
+
const byPrefix = entries.filter(
|
|
515
|
+
(entry) => entry.id !== needle && entry.id.toLowerCase().startsWith(lower)
|
|
516
|
+
);
|
|
517
|
+
const byLabel = entries.filter(
|
|
518
|
+
(entry) => entry.id !== needle && !entry.id.toLowerCase().startsWith(lower) && (entryLabel(entry).toLowerCase().includes(lower) || (entry.username ?? "").toLowerCase().includes(lower) || (entry.url ?? "").toLowerCase().includes(lower))
|
|
519
|
+
);
|
|
520
|
+
const matches = byId.length > 0 ? byId : byPrefix.length > 0 ? byPrefix : byLabel;
|
|
521
|
+
if (matches.length === 0) throw new Error(`no entry matches "${needle}"`);
|
|
522
|
+
if (matches.length > 1) {
|
|
523
|
+
const ids = matches.slice(0, 5).map((entry) => entry.id.slice(0, 8)).join(", ");
|
|
524
|
+
throw new Error(`"${needle}" matches ${matches.length} entries (${ids}): be more specific`);
|
|
525
|
+
}
|
|
526
|
+
return { entry: matches[0], kind: entryKind(matches[0]) };
|
|
527
|
+
}
|
|
528
|
+
var FORM_FIELDS = {
|
|
529
|
+
api: [
|
|
530
|
+
{ key: "title", label: "Label" },
|
|
531
|
+
{ key: "password", label: "Value", secret: true },
|
|
532
|
+
{ key: "url", label: "Service URL", optional: true },
|
|
533
|
+
{ key: "notes", label: "Note", optional: true }
|
|
534
|
+
],
|
|
535
|
+
login: [
|
|
536
|
+
{ key: "title", label: "Label" },
|
|
537
|
+
{ key: "url", label: "URL", optional: true },
|
|
538
|
+
{ key: "username", label: "Username", optional: true },
|
|
539
|
+
{ key: "password", label: "Password", secret: true }
|
|
540
|
+
],
|
|
541
|
+
card: [
|
|
542
|
+
{ key: "title", label: "Label" },
|
|
543
|
+
{ key: "username", label: "Cardholder", optional: true },
|
|
544
|
+
{ key: "password", label: "Number", secret: true },
|
|
545
|
+
{ key: "expiry", label: "Expiry (MM/YY)", optional: true },
|
|
546
|
+
{ key: "cvc", label: "CVC", secret: true, optional: true }
|
|
547
|
+
],
|
|
548
|
+
identity: [
|
|
549
|
+
{ key: "title", label: "Label" },
|
|
550
|
+
{ key: "username", label: "Full name", optional: true },
|
|
551
|
+
{ key: "url", label: "URL", optional: true },
|
|
552
|
+
{ key: "notes", label: "Note", optional: true }
|
|
553
|
+
],
|
|
554
|
+
note: [
|
|
555
|
+
{ key: "title", label: "Label" },
|
|
556
|
+
{ key: "notes", label: "Content" }
|
|
557
|
+
],
|
|
558
|
+
seed: [
|
|
559
|
+
{ key: "title", label: "Label" },
|
|
560
|
+
{ key: "password", label: "Recovery phrase (words)", secret: true },
|
|
561
|
+
{ key: "notes", label: "Note", optional: true }
|
|
562
|
+
],
|
|
563
|
+
passkey: []
|
|
564
|
+
};
|
|
565
|
+
var KIND_FOLDER = {
|
|
566
|
+
api: "identifiants",
|
|
567
|
+
login: "identifiants",
|
|
568
|
+
card: "cartes",
|
|
569
|
+
identity: "identites",
|
|
570
|
+
note: "notes",
|
|
571
|
+
seed: "seeds",
|
|
572
|
+
passkey: "passkeys"
|
|
573
|
+
};
|
|
574
|
+
function newEntryId() {
|
|
575
|
+
const bytes = new Uint8Array(16);
|
|
576
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
577
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
578
|
+
}
|
|
579
|
+
function buildEntry(kind, values, now = Date.now()) {
|
|
580
|
+
if (kind === "passkey") {
|
|
581
|
+
throw new Error("passkeys are created from the phone or the extension, not from a terminal");
|
|
582
|
+
}
|
|
583
|
+
const fields = FORM_FIELDS[kind];
|
|
584
|
+
const title = (values.title ?? "").trim();
|
|
585
|
+
if (title === "") throw new Error("title is required");
|
|
586
|
+
const secretField = fields.find((field) => field.secret);
|
|
587
|
+
if (secretField && (values[secretField.key] ?? "").trim() === "") {
|
|
588
|
+
throw new Error(`${secretField.label} is required`);
|
|
589
|
+
}
|
|
590
|
+
const base = {
|
|
591
|
+
id: newEntryId(),
|
|
592
|
+
url: (values.url ?? "").trim(),
|
|
593
|
+
username: (values.username ?? "").trim(),
|
|
594
|
+
password: kind === "note" ? "" : values.password ?? "",
|
|
595
|
+
notes: (values.notes ?? "").trim() || void 0,
|
|
596
|
+
folder: KIND_FOLDER[kind],
|
|
597
|
+
customGroup: KIND_FOLDER[kind],
|
|
598
|
+
title,
|
|
599
|
+
createdAt: new Date(now).toISOString(),
|
|
600
|
+
modifiedAt: now
|
|
601
|
+
};
|
|
602
|
+
if (kind === "card") {
|
|
603
|
+
const customFields = [];
|
|
604
|
+
if ((values.expiry ?? "").trim() !== "") {
|
|
605
|
+
customFields.push({ name: "Expiration", value: values.expiry.trim(), type: "text" });
|
|
606
|
+
}
|
|
607
|
+
if ((values.cvc ?? "").trim() !== "") {
|
|
608
|
+
customFields.push({ name: "CVC", value: values.cvc.trim(), type: "hidden" });
|
|
609
|
+
}
|
|
610
|
+
if (customFields.length > 0) base.customFields = customFields;
|
|
611
|
+
}
|
|
612
|
+
if (kind === "api") {
|
|
613
|
+
return { ...base, url: (values.url ?? "").trim(), username: "", type: "api" };
|
|
614
|
+
}
|
|
615
|
+
return base;
|
|
616
|
+
}
|
|
617
|
+
var DISPLAYABLE_HINT_KEYS = /* @__PURE__ */ new Set(["title", "url", "username"]);
|
|
618
|
+
function formValuesFromEntry(entry) {
|
|
619
|
+
const kind = entryKind(entry);
|
|
620
|
+
const values = {
|
|
621
|
+
title: entry.title ?? "",
|
|
622
|
+
url: entry.url ?? "",
|
|
623
|
+
username: entry.username ?? "",
|
|
624
|
+
password: entrySecret(entry),
|
|
625
|
+
notes: entry.notes ?? ""
|
|
626
|
+
};
|
|
627
|
+
if (kind === "card") {
|
|
628
|
+
for (const field of entry.customFields ?? []) {
|
|
629
|
+
if (field.name === "Expiration") values.expiry = String(field.value ?? "");
|
|
630
|
+
if (field.name === "CVC") values.cvc = String(field.value ?? "");
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return values;
|
|
634
|
+
}
|
|
635
|
+
function formHintForField(field, current) {
|
|
636
|
+
const value = current[field.key] ?? "";
|
|
637
|
+
if (value === "") return "";
|
|
638
|
+
if (field.secret || !DISPLAYABLE_HINT_KEYS.has(field.key)) return "conserv\xE9e";
|
|
639
|
+
const display = value.length > 48 ? `${value.slice(0, 47)}\u2026` : value;
|
|
640
|
+
return display;
|
|
641
|
+
}
|
|
642
|
+
function updateEntryFromValues(existing, values, now = Date.now()) {
|
|
643
|
+
const kind = entryKind(existing);
|
|
644
|
+
if (kind === "passkey") {
|
|
645
|
+
throw new Error("passkeys are edited from the phone, not from a terminal");
|
|
646
|
+
}
|
|
647
|
+
const fields = FORM_FIELDS[kind];
|
|
648
|
+
const title = (values.title ?? "").trim();
|
|
649
|
+
if (title === "") throw new Error("the label is required");
|
|
650
|
+
const secretField = fields.find((field) => field.secret);
|
|
651
|
+
if (secretField && (values[secretField.key] ?? "").trim() === "") {
|
|
652
|
+
throw new Error(`${secretField.label} is required`);
|
|
653
|
+
}
|
|
654
|
+
const notes = (values.notes ?? "").trim();
|
|
655
|
+
const updated = {
|
|
656
|
+
...existing,
|
|
657
|
+
title,
|
|
658
|
+
url: (values.url ?? "").trim(),
|
|
659
|
+
username: kind === "api" ? "" : (values.username ?? "").trim(),
|
|
660
|
+
password: kind === "note" ? "" : values.password ?? "",
|
|
661
|
+
modifiedAt: now,
|
|
662
|
+
...notes === "" ? { notes: void 0 } : { notes }
|
|
663
|
+
};
|
|
664
|
+
if (kind === "card") {
|
|
665
|
+
const others = (existing.customFields ?? []).filter(
|
|
666
|
+
(field) => field.name !== "Expiration" && field.name !== "CVC"
|
|
667
|
+
);
|
|
668
|
+
const customFields = [...others];
|
|
669
|
+
if ((values.expiry ?? "").trim() !== "") {
|
|
670
|
+
customFields.push({ name: "Expiration", value: values.expiry.trim(), type: "text" });
|
|
671
|
+
}
|
|
672
|
+
if ((values.cvc ?? "").trim() !== "") {
|
|
673
|
+
customFields.push({ name: "CVC", value: values.cvc.trim(), type: "hidden" });
|
|
674
|
+
}
|
|
675
|
+
if (customFields.length > 0) updated.customFields = customFields;
|
|
676
|
+
else delete updated.customFields;
|
|
677
|
+
}
|
|
678
|
+
if (kind === "api") {
|
|
679
|
+
updated.type = "api";
|
|
680
|
+
}
|
|
681
|
+
return updated;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// src/vault-summary.ts
|
|
685
|
+
import { join as join2 } from "path";
|
|
686
|
+
var VAULT_SUMMARY_FILENAME = AGENT_VAULT_SUMMARY_FILENAME;
|
|
687
|
+
function vaultSummaryPath(dir) {
|
|
688
|
+
return join2(dir, AGENT_VAULT_SUMMARY_FILENAME);
|
|
689
|
+
}
|
|
690
|
+
function summariseEntry(entry) {
|
|
691
|
+
return {
|
|
692
|
+
id: entry.id,
|
|
693
|
+
label: entryLabel(entry),
|
|
694
|
+
url: typeof entry.url === "string" && entry.url !== "" ? entry.url : null,
|
|
695
|
+
modifiedAt: typeof entry.modifiedAt === "number" ? entry.modifiedAt : null
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
function buildVaultSummary(vault, savedAt = Date.now()) {
|
|
699
|
+
return {
|
|
700
|
+
version: AGENT_VAULT_SUMMARY_VERSION,
|
|
701
|
+
savedAt,
|
|
702
|
+
entries: vault.entries.map(summariseEntry)
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
async function writeVaultSummary(dir, vault, savedAt = Date.now()) {
|
|
706
|
+
await writePrivateFile(
|
|
707
|
+
vaultSummaryPath(dir),
|
|
708
|
+
`${JSON.stringify(buildVaultSummary(vault, savedAt))}
|
|
709
|
+
`
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// src/vault-store.ts
|
|
714
|
+
import { dirname as dirname2 } from "path";
|
|
715
|
+
function emptyVault(now = Date.now()) {
|
|
716
|
+
return {
|
|
717
|
+
version: 1,
|
|
718
|
+
createdAt: new Date(now).toISOString(),
|
|
719
|
+
entries: [],
|
|
720
|
+
folders: []
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
function seal(vault, key) {
|
|
724
|
+
const encrypted = encryptVault(serializeVault(vault), new Uint8Array(key), {
|
|
725
|
+
wipeKeyAfterUse: false
|
|
726
|
+
});
|
|
727
|
+
return {
|
|
728
|
+
ciphertext: encrypted.ciphertext,
|
|
729
|
+
nonce: encrypted.nonce,
|
|
730
|
+
commitment: encrypted.commitment ?? ""
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
function open(block, key) {
|
|
734
|
+
const plaintext = decryptVault(
|
|
735
|
+
{
|
|
736
|
+
ciphertext: block.ciphertext,
|
|
737
|
+
nonce: block.nonce,
|
|
738
|
+
commitment: block.commitment,
|
|
739
|
+
version: 2
|
|
740
|
+
},
|
|
741
|
+
new Uint8Array(key)
|
|
742
|
+
);
|
|
743
|
+
if (typeof plaintext !== "string") {
|
|
744
|
+
throw new Error("local vault unreadable (unexpected binary format)");
|
|
745
|
+
}
|
|
746
|
+
return parseVault(plaintext);
|
|
747
|
+
}
|
|
748
|
+
async function saveLocalVault(path, identity, stored, now = Date.now()) {
|
|
749
|
+
const salt = new Uint8Array(16);
|
|
750
|
+
globalThis.crypto.getRandomValues(salt);
|
|
751
|
+
const key = await derivePayloadKey(payloadKeyMaterial(identity), salt);
|
|
752
|
+
try {
|
|
753
|
+
const file = {
|
|
754
|
+
version: 1,
|
|
755
|
+
salt: bufferToHex(salt),
|
|
756
|
+
vault: seal(stored.vault, key),
|
|
757
|
+
base: stored.base ? seal(stored.base, key) : null,
|
|
758
|
+
savedAt: now
|
|
759
|
+
};
|
|
760
|
+
await writePrivateFile(path, `${JSON.stringify(file)}
|
|
761
|
+
`);
|
|
762
|
+
} finally {
|
|
763
|
+
key.fill(0);
|
|
764
|
+
}
|
|
765
|
+
try {
|
|
766
|
+
await writeVaultSummary(dirname2(path), stored.vault, now);
|
|
767
|
+
} catch {
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
async function loadLocalVault(path, identity) {
|
|
771
|
+
const raw = await readTextFileOrNull(path);
|
|
772
|
+
if (raw === null) return null;
|
|
773
|
+
const data = JSON.parse(raw);
|
|
774
|
+
if (typeof data !== "object" || data === null || data.version !== 1 || typeof data.salt !== "string" || typeof data.vault !== "object" || data.vault === null) {
|
|
775
|
+
throw new Error("invalid local vault: run `vaultkeepr pair` again");
|
|
776
|
+
}
|
|
777
|
+
const key = await derivePayloadKey(payloadKeyMaterial(identity), hexToBuffer(data.salt));
|
|
778
|
+
try {
|
|
779
|
+
const vault = open(data.vault, key);
|
|
780
|
+
const base = data.base ? open(data.base, key) : null;
|
|
781
|
+
return { vault, base, savedAt: typeof data.savedAt === "number" ? data.savedAt : 0 };
|
|
782
|
+
} finally {
|
|
783
|
+
key.fill(0);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// src/sync.ts
|
|
788
|
+
function emptySyncState(address) {
|
|
789
|
+
return {
|
|
790
|
+
version: 1,
|
|
791
|
+
address,
|
|
792
|
+
vaultCid: null,
|
|
793
|
+
lastKnownUpdatedAt: 0,
|
|
794
|
+
lastPublishAt: null,
|
|
795
|
+
lastResolveAt: null,
|
|
796
|
+
lastError: null
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
async function loadSyncState(path, address) {
|
|
800
|
+
const raw = await readTextFileOrNull(path);
|
|
801
|
+
if (raw === null) return emptySyncState(address);
|
|
802
|
+
try {
|
|
803
|
+
const data = JSON.parse(raw);
|
|
804
|
+
if (typeof data !== "object" || data === null || data.version !== 1) {
|
|
805
|
+
return emptySyncState(address);
|
|
806
|
+
}
|
|
807
|
+
return {
|
|
808
|
+
version: 1,
|
|
809
|
+
address,
|
|
810
|
+
vaultCid: typeof data.vaultCid === "string" ? data.vaultCid : null,
|
|
811
|
+
lastKnownUpdatedAt: typeof data.lastKnownUpdatedAt === "number" ? data.lastKnownUpdatedAt : 0,
|
|
812
|
+
lastPublishAt: typeof data.lastPublishAt === "number" ? data.lastPublishAt : null,
|
|
813
|
+
lastResolveAt: typeof data.lastResolveAt === "number" ? data.lastResolveAt : null,
|
|
814
|
+
lastError: typeof data.lastError === "string" ? data.lastError : null
|
|
815
|
+
};
|
|
816
|
+
} catch {
|
|
817
|
+
return emptySyncState(address);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
async function saveSyncState(path, state) {
|
|
821
|
+
await writePrivateFile(path, `${JSON.stringify(state)}
|
|
822
|
+
`);
|
|
823
|
+
}
|
|
824
|
+
async function pullMerge(ctx) {
|
|
825
|
+
const now = ctx.now ?? Date.now;
|
|
826
|
+
const state = await loadSyncState(ctx.paths.syncStatePath, ctx.identity.address);
|
|
827
|
+
try {
|
|
828
|
+
const cid = await ctx.transport.readPointerCid(ctx.identity.address);
|
|
829
|
+
state.lastResolveAt = now();
|
|
830
|
+
if (!cid) {
|
|
831
|
+
await saveSyncState(ctx.paths.syncStatePath, state);
|
|
832
|
+
return { status: "no-pointer" };
|
|
833
|
+
}
|
|
834
|
+
if (state.vaultCid === cid && state.lastKnownUpdatedAt > 0) {
|
|
835
|
+
await saveSyncState(ctx.paths.syncStatePath, state);
|
|
836
|
+
return { status: "up-to-date", cid };
|
|
837
|
+
}
|
|
838
|
+
const raw = await ctx.transport.fetchPayload(cid);
|
|
839
|
+
const account = ctx.account ?? await accountForIdentity(ctx.identity);
|
|
840
|
+
const remote = await openVaultPayload(raw, ctx.identity, { account, now: now() });
|
|
841
|
+
if (state.vaultCid === cid && remote.updatedAt > 0 && remote.updatedAt <= state.lastKnownUpdatedAt) {
|
|
842
|
+
await saveSyncState(ctx.paths.syncStatePath, state);
|
|
843
|
+
return { status: "up-to-date", cid, remoteUpdatedAt: remote.updatedAt };
|
|
844
|
+
}
|
|
845
|
+
const local = await loadLocalVault(ctx.paths.vaultPath, ctx.identity);
|
|
846
|
+
const localVault = local?.vault;
|
|
847
|
+
const merged = localVault ? threeWayMerge(local?.base ?? null, localVault, remote.vault) : remote.vault;
|
|
848
|
+
await saveLocalVault(ctx.paths.vaultPath, ctx.identity, {
|
|
849
|
+
vault: merged,
|
|
850
|
+
base: merged
|
|
851
|
+
}, now());
|
|
852
|
+
state.vaultCid = cid;
|
|
853
|
+
state.lastKnownUpdatedAt = remote.updatedAt || now();
|
|
854
|
+
state.lastError = null;
|
|
855
|
+
await saveSyncState(ctx.paths.syncStatePath, state);
|
|
856
|
+
return { status: "merged", cid, remoteUpdatedAt: remote.updatedAt };
|
|
857
|
+
} catch (error) {
|
|
858
|
+
state.lastError = error instanceof Error ? error.message : String(error);
|
|
859
|
+
await saveSyncState(ctx.paths.syncStatePath, state);
|
|
860
|
+
throw error;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
async function publishVault(ctx, vault) {
|
|
864
|
+
const now = ctx.now ?? Date.now;
|
|
865
|
+
const state = await loadSyncState(ctx.paths.syncStatePath, ctx.identity.address);
|
|
866
|
+
const payloadStr = await sealVaultPayload(vault, payloadKeyMaterial(ctx.identity), now());
|
|
867
|
+
const cid = await ctx.transport.uploadPayload(payloadStr, ctx.identity.address);
|
|
868
|
+
const published = await ctx.transport.publishPointer(ctx.identity.address, cid);
|
|
869
|
+
if (!published) {
|
|
870
|
+
state.lastError = "pointer publication refused";
|
|
871
|
+
await saveSyncState(ctx.paths.syncStatePath, state);
|
|
872
|
+
throw new Error("pointer publication refused by the server");
|
|
873
|
+
}
|
|
874
|
+
state.vaultCid = cid;
|
|
875
|
+
state.lastKnownUpdatedAt = now();
|
|
876
|
+
state.lastPublishAt = now();
|
|
877
|
+
state.lastError = null;
|
|
878
|
+
await saveSyncState(ctx.paths.syncStatePath, state);
|
|
879
|
+
await saveLocalVault(ctx.paths.vaultPath, ctx.identity, { vault, base: vault }, now());
|
|
880
|
+
return { cid };
|
|
881
|
+
}
|
|
882
|
+
async function syncOnce(ctx, options = {}) {
|
|
883
|
+
const pull = await pullMerge(ctx);
|
|
884
|
+
let pushed = null;
|
|
885
|
+
if (options.publish) {
|
|
886
|
+
const local = await loadLocalVault(ctx.paths.vaultPath, ctx.identity);
|
|
887
|
+
if (!local) throw new Error("local vault missing: run `vaultkeepr pair` again");
|
|
888
|
+
pushed = await publishVault(ctx, local.vault);
|
|
889
|
+
}
|
|
890
|
+
return { pull, pushed };
|
|
891
|
+
}
|
|
892
|
+
async function runSyncLoop(ctx, options) {
|
|
893
|
+
const sleep = (ms) => new Promise((resolve) => {
|
|
894
|
+
const timer = setTimeout(resolve, ms);
|
|
895
|
+
options.signal?.addEventListener("abort", () => {
|
|
896
|
+
clearTimeout(timer);
|
|
897
|
+
resolve();
|
|
898
|
+
}, { once: true });
|
|
899
|
+
});
|
|
900
|
+
let iterations = 0;
|
|
901
|
+
const max = options.maxIterations ?? Number.POSITIVE_INFINITY;
|
|
902
|
+
while (!options.signal?.aborted && iterations < max) {
|
|
903
|
+
iterations++;
|
|
904
|
+
const startedAt = Date.now();
|
|
905
|
+
try {
|
|
906
|
+
const result = await syncOnce(ctx, { publish: true });
|
|
907
|
+
options.onEvent?.(
|
|
908
|
+
`sync: ${result.pull.status}${result.pushed ? " + published" : ""} (${Date.now() - startedAt} ms)`
|
|
909
|
+
);
|
|
910
|
+
} catch (error) {
|
|
911
|
+
options.onEvent?.(
|
|
912
|
+
`sync: error \u2014 ${error instanceof Error ? error.message : String(error)}`
|
|
913
|
+
);
|
|
914
|
+
}
|
|
915
|
+
if (iterations >= max) break;
|
|
916
|
+
await sleep(options.intervalMs);
|
|
917
|
+
}
|
|
918
|
+
return 0;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
// ../ipfs/dist/index.mjs
|
|
922
|
+
var IPFS_GATEWAYS_DEFAULT = ["https://ipfs.vaultkeepr.xyz/ipfs", "https://gateway.pinata.cloud/ipfs"];
|
|
923
|
+
var FETCH_TIMEOUT_MS = 3e4;
|
|
924
|
+
var IPFS_GATEWAY_TIMEOUT_MS = 15e3;
|
|
925
|
+
var customIpfsGateways = [];
|
|
926
|
+
function setIpfsGateways(gateways) {
|
|
927
|
+
customIpfsGateways = (gateways || []).filter(Boolean).map((g) => g.replace(/\/$/, ""));
|
|
928
|
+
}
|
|
929
|
+
function isIpfsCid(id) {
|
|
930
|
+
const s = (id || "").trim();
|
|
931
|
+
return s.startsWith("Qm") || s.startsWith("bafy") || s.startsWith("ba");
|
|
932
|
+
}
|
|
933
|
+
function isS3Cid(id) {
|
|
934
|
+
return (id || "").trim().startsWith("s3_");
|
|
935
|
+
}
|
|
936
|
+
function normalizeVaultLocation(input) {
|
|
937
|
+
const s = (input || "").trim();
|
|
938
|
+
if (!s) throw new Error("Identifiant vide.");
|
|
939
|
+
return s;
|
|
940
|
+
}
|
|
941
|
+
function fetchIpfsFromGateway(base, id) {
|
|
942
|
+
const url = `${base.replace(/\/$/, "")}/${id}`;
|
|
943
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
944
|
+
const timeoutId = controller ? setTimeout(() => controller.abort(), IPFS_GATEWAY_TIMEOUT_MS) : null;
|
|
945
|
+
return fetch(url, { signal: controller?.signal }).then((res) => {
|
|
946
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
947
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
948
|
+
return res.text();
|
|
949
|
+
}).catch((e) => {
|
|
950
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
951
|
+
throw e;
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
async function fetchFromIpfsGateways(cid) {
|
|
955
|
+
const id = normalizeVaultLocation(cid);
|
|
956
|
+
const gateways = [...customIpfsGateways, ...IPFS_GATEWAYS_DEFAULT].filter(Boolean);
|
|
957
|
+
if (gateways.length === 0) {
|
|
958
|
+
throw new Error("Impossible de r\xE9cup\xE9rer le contenu depuis IPFS.");
|
|
959
|
+
}
|
|
960
|
+
const attempts = gateways.map((base) => fetchIpfsFromGateway(base, id));
|
|
961
|
+
try {
|
|
962
|
+
return await Promise.any(attempts);
|
|
963
|
+
} catch {
|
|
964
|
+
throw new Error("Impossible de r\xE9cup\xE9rer le contenu depuis IPFS.");
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
async function fetchFromS3(contentId, walletAddress) {
|
|
968
|
+
const base = typeof process !== "undefined" && process.env?.NEXT_PUBLIC_APP_URL || typeof process !== "undefined" && process.env?.EXPO_PUBLIC_API_URL || "https://app.vaultkeepr.xyz";
|
|
969
|
+
const params = new URLSearchParams({ cid: contentId });
|
|
970
|
+
if (walletAddress) params.set("wallet", walletAddress.toLowerCase());
|
|
971
|
+
const url = `${base}/api/cloud/download?${params.toString()}`;
|
|
972
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
973
|
+
const timeoutId = controller ? setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS) : null;
|
|
974
|
+
try {
|
|
975
|
+
const res = await fetch(url, { signal: controller?.signal });
|
|
976
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
977
|
+
if (!res.ok) throw new Error(`S3 fetch: ${res.status}`);
|
|
978
|
+
return res.text();
|
|
979
|
+
} catch (e) {
|
|
980
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
981
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
982
|
+
if (msg.includes("AbortError") || msg.includes("abort")) {
|
|
983
|
+
throw new Error("Delai de connexion depasse (30 s).");
|
|
984
|
+
}
|
|
985
|
+
throw e;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
async function fetchFromStorage(txId, walletAddress) {
|
|
989
|
+
const id = normalizeVaultLocation(txId);
|
|
990
|
+
if (isS3Cid(id)) {
|
|
991
|
+
return fetchFromS3(id, walletAddress);
|
|
992
|
+
}
|
|
993
|
+
if (isIpfsCid(id)) {
|
|
994
|
+
return fetchFromIpfsGateways(id);
|
|
995
|
+
}
|
|
996
|
+
throw new Error("Identifiant de stockage non reconnu (CID IPFS attendu).");
|
|
997
|
+
}
|
|
998
|
+
async function fetchFromIpfs(txId) {
|
|
999
|
+
return fetchFromStorage(txId);
|
|
1000
|
+
}
|
|
1001
|
+
var envGateway = typeof process !== "undefined" && process.env?.EXPO_PUBLIC_IPFS_GATEWAY || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_IPFS_GATEWAY;
|
|
1002
|
+
if (envGateway) {
|
|
1003
|
+
setIpfsGateways([envGateway]);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
// src/transport.ts
|
|
1007
|
+
var configuredGateway = process.env.EXPO_PUBLIC_IPFS_GATEWAY ?? process.env.NEXT_PUBLIC_IPFS_GATEWAY;
|
|
1008
|
+
if (configuredGateway) {
|
|
1009
|
+
setIpfsGateways([configuredGateway]);
|
|
1010
|
+
} else {
|
|
1011
|
+
setIpfsGateways(["https://ipfs.vaultkeepr.xyz/ipfs"]);
|
|
1012
|
+
}
|
|
1013
|
+
var DEFAULT_API_BASE = "https://app.vaultkeepr.xyz";
|
|
1014
|
+
function trimBase(apiBase) {
|
|
1015
|
+
return apiBase.replace(/\/+$/, "");
|
|
1016
|
+
}
|
|
1017
|
+
function createPairTransport(apiBase, fetchImpl) {
|
|
1018
|
+
const base = trimBase(apiBase);
|
|
1019
|
+
return {
|
|
1020
|
+
async createSession(publicKeyHex, deviceName) {
|
|
1021
|
+
const res = await fetchImpl(`${base}/api/pair`, {
|
|
1022
|
+
method: "POST",
|
|
1023
|
+
headers: { "Content-Type": "application/json" },
|
|
1024
|
+
body: JSON.stringify({ publicKeyHex, deviceName, mode: "receive" })
|
|
1025
|
+
});
|
|
1026
|
+
if (!res.ok) {
|
|
1027
|
+
throw new Error(`pairing session creation refused (HTTP ${res.status})`);
|
|
1028
|
+
}
|
|
1029
|
+
const body = await res.json();
|
|
1030
|
+
if (typeof body.sessionId !== "string" || typeof body.expiresAt !== "number") {
|
|
1031
|
+
throw new Error("invalid pairing session response");
|
|
1032
|
+
}
|
|
1033
|
+
return { sessionId: body.sessionId, expiresAt: body.expiresAt };
|
|
1034
|
+
},
|
|
1035
|
+
async pollStatus(sessionId) {
|
|
1036
|
+
const res = await fetchImpl(
|
|
1037
|
+
`${base}/api/pair/${encodeURIComponent(sessionId)}/status`
|
|
1038
|
+
);
|
|
1039
|
+
if (res.status === 404 || res.status === 410) return null;
|
|
1040
|
+
if (!res.ok) {
|
|
1041
|
+
throw new Error(`pairing session status unreadable (HTTP ${res.status})`);
|
|
1042
|
+
}
|
|
1043
|
+
const body = await res.json();
|
|
1044
|
+
return {
|
|
1045
|
+
completed: body.completed === true,
|
|
1046
|
+
expiresAt: typeof body.expiresAt === "number" ? body.expiresAt : void 0,
|
|
1047
|
+
sourcePublicKeyHex: typeof body.sourcePublicKeyHex === "string" ? body.sourcePublicKeyHex : void 0,
|
|
1048
|
+
encryptedPayload: typeof body.encryptedPayload === "string" ? body.encryptedPayload : void 0
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
function openPairPayload(status, keypair) {
|
|
1054
|
+
if (typeof status.encryptedPayload !== "string" || status.encryptedPayload === "") {
|
|
1055
|
+
throw new Error("no vault received in the pairing session");
|
|
1056
|
+
}
|
|
1057
|
+
if (typeof status.sourcePublicKeyHex !== "string" || status.sourcePublicKeyHex === "") {
|
|
1058
|
+
throw new Error("pairing session without a source key");
|
|
1059
|
+
}
|
|
1060
|
+
const secret = derivePairSecret(keypair.privateKey, status.sourcePublicKeyHex);
|
|
1061
|
+
const json = decryptFromPair(status.encryptedPayload, secret);
|
|
1062
|
+
return parsePairPayload(json);
|
|
1063
|
+
}
|
|
1064
|
+
function newPairKeypair() {
|
|
1065
|
+
return generatePairKeypair();
|
|
1066
|
+
}
|
|
1067
|
+
function pairUri(sessionId, publicKeyHex) {
|
|
1068
|
+
return buildPairUri(sessionId, publicKeyHex);
|
|
1069
|
+
}
|
|
1070
|
+
function formatProofMessage(address, action, nowMs) {
|
|
1071
|
+
return `VaultKeepR:${address}:${action}:${nowMs}`;
|
|
1072
|
+
}
|
|
1073
|
+
var CID_UPDATE_PREFIX = "VaultKeepR CID Update:";
|
|
1074
|
+
function createHttpSyncTransport({
|
|
1075
|
+
apiBase,
|
|
1076
|
+
account,
|
|
1077
|
+
fetchImpl,
|
|
1078
|
+
now = Date.now
|
|
1079
|
+
}) {
|
|
1080
|
+
const base = trimBase(apiBase);
|
|
1081
|
+
const owner = account.address;
|
|
1082
|
+
const proof = async (action) => {
|
|
1083
|
+
const message = formatProofMessage(owner, action, now());
|
|
1084
|
+
return { message, signature: await account.signMessage({ message }) };
|
|
1085
|
+
};
|
|
1086
|
+
return {
|
|
1087
|
+
async readPointerCid(address) {
|
|
1088
|
+
const p = await proof("read");
|
|
1089
|
+
const query = new URLSearchParams({
|
|
1090
|
+
wallet: address.toLowerCase(),
|
|
1091
|
+
signature: p.signature,
|
|
1092
|
+
message: p.message
|
|
1093
|
+
});
|
|
1094
|
+
const res = await fetchImpl(`${base}/api/vault-cid?${query.toString()}`);
|
|
1095
|
+
if (res.status === 404 || res.status === 204) return null;
|
|
1096
|
+
if (!res.ok) throw new Error(`pointer read refused (HTTP ${res.status})`);
|
|
1097
|
+
const body = await res.json();
|
|
1098
|
+
return typeof body.cid === "string" && body.cid.trim() !== "" ? body.cid.trim() : null;
|
|
1099
|
+
},
|
|
1100
|
+
async fetchPayload(cid) {
|
|
1101
|
+
return await fetchFromIpfs(cid);
|
|
1102
|
+
},
|
|
1103
|
+
async uploadPayload(payloadStr, address) {
|
|
1104
|
+
const p = await proof("upload");
|
|
1105
|
+
const res = await fetchImpl(`${base}/api/ipfs/upload`, {
|
|
1106
|
+
method: "POST",
|
|
1107
|
+
headers: { "Content-Type": "application/json" },
|
|
1108
|
+
body: JSON.stringify({
|
|
1109
|
+
encryptedPayload: payloadStr,
|
|
1110
|
+
walletAddress: address.toLowerCase(),
|
|
1111
|
+
pointerWrite: false,
|
|
1112
|
+
signature: p.signature,
|
|
1113
|
+
message: p.message
|
|
1114
|
+
})
|
|
1115
|
+
});
|
|
1116
|
+
const body = await res.json().catch(() => ({}));
|
|
1117
|
+
if (!res.ok) {
|
|
1118
|
+
throw new Error(`IPFS publication refused (HTTP ${res.status})`);
|
|
1119
|
+
}
|
|
1120
|
+
if (typeof body.cid !== "string" || body.cid === "") {
|
|
1121
|
+
throw new Error("IPFS publication without a CID");
|
|
1122
|
+
}
|
|
1123
|
+
return body.cid;
|
|
1124
|
+
},
|
|
1125
|
+
async publishPointer(address, cid) {
|
|
1126
|
+
const message = `${CID_UPDATE_PREFIX}${cid}:${now()}`;
|
|
1127
|
+
const signature = await account.signMessage({ message });
|
|
1128
|
+
const res = await fetchImpl(`${base}/api/vault-cid`, {
|
|
1129
|
+
method: "POST",
|
|
1130
|
+
headers: { "Content-Type": "application/json" },
|
|
1131
|
+
body: JSON.stringify({
|
|
1132
|
+
walletAddress: address.toLowerCase(),
|
|
1133
|
+
cid,
|
|
1134
|
+
signature,
|
|
1135
|
+
message
|
|
1136
|
+
})
|
|
1137
|
+
});
|
|
1138
|
+
return res.ok;
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
// src/clipboard.ts
|
|
1144
|
+
import { spawn } from "child_process";
|
|
1145
|
+
function clipboardCandidates(env = {}) {
|
|
1146
|
+
const platform = env.platform ?? process.platform;
|
|
1147
|
+
const wayland = env.waylandDisplay ?? process.env.WAYLAND_DISPLAY;
|
|
1148
|
+
const display = env.display ?? process.env.DISPLAY;
|
|
1149
|
+
const termux = env.termux ?? process.env.TERMUX_VERSION;
|
|
1150
|
+
const candidates = [];
|
|
1151
|
+
if (wayland) candidates.push({ bin: "wl-copy", args: [] });
|
|
1152
|
+
if (display) candidates.push({ bin: "xclip", args: ["-selection", "clipboard"] });
|
|
1153
|
+
if (platform === "darwin") candidates.push({ bin: "pbcopy", args: [] });
|
|
1154
|
+
if (termux) candidates.push({ bin: "termux-clipboard-set", args: [] });
|
|
1155
|
+
candidates.push(
|
|
1156
|
+
{ bin: "wl-copy", args: [] },
|
|
1157
|
+
{ bin: "xclip", args: ["-selection", "clipboard"] },
|
|
1158
|
+
{ bin: "xsel", args: ["--clipboard", "--input"] },
|
|
1159
|
+
{ bin: "pbcopy", args: [] },
|
|
1160
|
+
{ bin: "termux-clipboard-set", args: [] }
|
|
1161
|
+
);
|
|
1162
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1163
|
+
return candidates.filter((candidate) => {
|
|
1164
|
+
const key = `${candidate.bin} ${candidate.args.join(" ")}`;
|
|
1165
|
+
if (seen.has(key)) return false;
|
|
1166
|
+
seen.add(key);
|
|
1167
|
+
return true;
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
var defaultClipboardRunner = (candidate, text) => new Promise((resolve) => {
|
|
1171
|
+
let settled = false;
|
|
1172
|
+
const done = (ok) => {
|
|
1173
|
+
if (settled) return;
|
|
1174
|
+
settled = true;
|
|
1175
|
+
resolve(ok);
|
|
1176
|
+
};
|
|
1177
|
+
try {
|
|
1178
|
+
const child = spawn(candidate.bin, candidate.args, {
|
|
1179
|
+
stdio: ["pipe", "ignore", "ignore"]
|
|
1180
|
+
});
|
|
1181
|
+
child.on("error", () => done(false));
|
|
1182
|
+
child.on("close", (code) => done(code === 0));
|
|
1183
|
+
child.stdin.on("error", () => done(false));
|
|
1184
|
+
child.stdin.end(text);
|
|
1185
|
+
} catch {
|
|
1186
|
+
done(false);
|
|
1187
|
+
}
|
|
1188
|
+
});
|
|
1189
|
+
async function copyToClipboard(text, options = {}) {
|
|
1190
|
+
const runner = options.runner ?? defaultClipboardRunner;
|
|
1191
|
+
const candidates = options.candidates ?? clipboardCandidates();
|
|
1192
|
+
for (const candidate of candidates) {
|
|
1193
|
+
if (await runner(candidate, text)) return { ok: true, bin: candidate.bin };
|
|
1194
|
+
}
|
|
1195
|
+
return { ok: false };
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// src/format.ts
|
|
1199
|
+
function redactAddress(address) {
|
|
1200
|
+
const value = address.trim();
|
|
1201
|
+
if (value.length < 12) return value;
|
|
1202
|
+
return `${value.slice(0, 6)}\u2026${value.slice(-4)}`;
|
|
1203
|
+
}
|
|
1204
|
+
function redactCid(cid) {
|
|
1205
|
+
if (!cid) return "\u2014";
|
|
1206
|
+
if (cid.length <= 14) return cid;
|
|
1207
|
+
return `${cid.slice(0, 8)}\u2026${cid.slice(-6)}`;
|
|
1208
|
+
}
|
|
1209
|
+
function formatWhen(ms, now = Date.now()) {
|
|
1210
|
+
if (!ms) return "never";
|
|
1211
|
+
const delta = now - ms;
|
|
1212
|
+
if (delta < 0) return new Date(ms).toLocaleString("en-US");
|
|
1213
|
+
const seconds = Math.round(delta / 1e3);
|
|
1214
|
+
if (seconds < 60) return `${seconds}s ago`;
|
|
1215
|
+
const minutes = Math.round(seconds / 60);
|
|
1216
|
+
if (minutes < 60) return `${minutes}m ago`;
|
|
1217
|
+
const hours = Math.round(minutes / 60);
|
|
1218
|
+
if (hours < 24) return `${hours}h ago`;
|
|
1219
|
+
return new Date(ms).toLocaleString("en-US", {
|
|
1220
|
+
day: "2-digit",
|
|
1221
|
+
month: "2-digit",
|
|
1222
|
+
year: "numeric",
|
|
1223
|
+
hour: "2-digit",
|
|
1224
|
+
minute: "2-digit"
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
function formatDate(ms) {
|
|
1228
|
+
if (!ms) return "\u2014";
|
|
1229
|
+
return new Date(ms).toLocaleString("en-US", {
|
|
1230
|
+
day: "2-digit",
|
|
1231
|
+
month: "2-digit",
|
|
1232
|
+
year: "numeric",
|
|
1233
|
+
hour: "2-digit",
|
|
1234
|
+
minute: "2-digit"
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
// src/version.ts
|
|
1239
|
+
import { createRequire } from "module";
|
|
1240
|
+
var require2 = createRequire(import.meta.url);
|
|
1241
|
+
var pkg = require2("../package.json");
|
|
1242
|
+
var VERSION = typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
1243
|
+
|
|
1244
|
+
// src/banner.ts
|
|
1245
|
+
var CRIMSON_TOP = [248, 48, 74];
|
|
1246
|
+
var CRIMSON_BOTTOM = [193, 18, 47];
|
|
1247
|
+
var ACCENT_CORAL = [229, 87, 87];
|
|
1248
|
+
var RESET = "\x1B[0m";
|
|
1249
|
+
function fg([r, g, b], text) {
|
|
1250
|
+
return `\x1B[38;2;${r};${g};${b}m${text}${RESET}`;
|
|
1251
|
+
}
|
|
1252
|
+
function bold(text) {
|
|
1253
|
+
return `\x1B[1m${text}${RESET}`;
|
|
1254
|
+
}
|
|
1255
|
+
function mix(from2, to, ratio) {
|
|
1256
|
+
const clamp = Math.min(1, Math.max(0, ratio));
|
|
1257
|
+
return [
|
|
1258
|
+
Math.round(from2[0] + (to[0] - from2[0]) * clamp),
|
|
1259
|
+
Math.round(from2[1] + (to[1] - from2[1]) * clamp),
|
|
1260
|
+
Math.round(from2[2] + (to[2] - from2[2]) * clamp)
|
|
1261
|
+
];
|
|
1262
|
+
}
|
|
1263
|
+
var WORDMARK = [
|
|
1264
|
+
" lllllll tttt kkkkkkkk",
|
|
1265
|
+
" l:::::l ttt:::t k::::::k",
|
|
1266
|
+
" l:::::l t:::::t k::::::k",
|
|
1267
|
+
" l:::::l t:::::t k::::::k",
|
|
1268
|
+
"vvvvvvv vvvvvvvaaaaaaaaaaaaa uuuuuu uuuuuu l::::lttttttt:::::ttttttt k:::::k kkkkkkk eeeeeeeeeeee eeeeeeeeeeee ppppp ppppppppp rrrrr rrrrrrrrr",
|
|
1269
|
+
" v:::::v v:::::v a::::::::::::a u::::u u::::u l::::lt:::::::::::::::::t k:::::k k:::::kee::::::::::::ee ee::::::::::::ee p::::ppp:::::::::p r::::rrr:::::::::r",
|
|
1270
|
+
" v:::::v v:::::v aaaaaaaaa:::::au::::u u::::u l::::lt:::::::::::::::::t k:::::k k:::::ke::::::eeeee:::::ee e::::::eeeee:::::eep:::::::::::::::::p r:::::::::::::::::r",
|
|
1271
|
+
" v:::::v v:::::v a::::au::::u u::::u l::::ltttttt:::::::tttttt k:::::k k:::::ke::::::e e:::::ee::::::e e:::::epp::::::ppppp::::::prr::::::rrrrr::::::r",
|
|
1272
|
+
" v:::::v v:::::v aaaaaaa:::::au::::u u::::u l::::l t:::::t k::::::k:::::k e:::::::eeeee::::::ee:::::::eeeee::::::e p:::::p p:::::p r:::::r r:::::r",
|
|
1273
|
+
" v:::::v v:::::v aa::::::::::::au::::u u::::u l::::l t:::::t k:::::::::::k e:::::::::::::::::e e:::::::::::::::::e p:::::p p:::::p r:::::r rrrrrrr",
|
|
1274
|
+
" v:::::v:::::v a::::aaaa::::::au::::u u::::u l::::l t:::::t k:::::::::::k e::::::eeeeeeeeeee e::::::eeeeeeeeeee p:::::p p:::::p r:::::r",
|
|
1275
|
+
" v:::::::::v a::::a a:::::au:::::uuuu:::::u l::::l t:::::t tttttt k::::::k:::::k e:::::::e e:::::::e p:::::p p::::::p r:::::r",
|
|
1276
|
+
" v:::::::v a::::a a:::::au:::::::::::::::uul::::::l t::::::tttt:::::tk::::::k k:::::ke::::::::e e::::::::e p:::::ppppp:::::::p r:::::r",
|
|
1277
|
+
" v:::::v a:::::aaaa::::::a u:::::::::::::::ul::::::l tt::::::::::::::tk::::::k k:::::ke::::::::eeeeeeee e::::::::eeeeeeee p::::::::::::::::p r:::::r",
|
|
1278
|
+
" v:::v a::::::::::aa:::a uu::::::::uu:::ul::::::l tt:::::::::::ttk::::::k k:::::kee:::::::::::::e ee:::::::::::::e p::::::::::::::pp r:::::r",
|
|
1279
|
+
" vvv aaaaaaaaaa aaaa uuuuuuuu uuuullllllll ttttttttttt kkkkkkkk kkkkkkk eeeeeeeeeeeeee eeeeeeeeeeeeee p::::::pppppppp rrrrrrr",
|
|
1280
|
+
" p:::::p",
|
|
1281
|
+
" p:::::p",
|
|
1282
|
+
" p:::::::p",
|
|
1283
|
+
" p:::::::p",
|
|
1284
|
+
" p:::::::p",
|
|
1285
|
+
" ppppppppp"
|
|
1286
|
+
];
|
|
1287
|
+
var WORDMARK_WIDTH = WORDMARK.reduce((max, line) => Math.max(max, line.length), 0);
|
|
1288
|
+
var WORDMARK_MID = [
|
|
1289
|
+
"\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557",
|
|
1290
|
+
"\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557",
|
|
1291
|
+
"\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D",
|
|
1292
|
+
"\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557",
|
|
1293
|
+
" \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551",
|
|
1294
|
+
" \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"
|
|
1295
|
+
];
|
|
1296
|
+
var WORDMARK_MID_WIDTH = WORDMARK_MID.reduce(
|
|
1297
|
+
(max, line) => Math.max(max, line.length),
|
|
1298
|
+
0
|
|
1299
|
+
);
|
|
1300
|
+
var WORDMARK_SMALL = [
|
|
1301
|
+
" _ _ _",
|
|
1302
|
+
"__ ____ _ _ _| | |_| |_____ ___ _ __ _ _",
|
|
1303
|
+
"\\ V / _` | || | | _| / / -_) -_) '_ \\ '_|",
|
|
1304
|
+
" \\_/\\__,_|\\_,_|_|\\__|_\\_\\___\\___| .__/_|",
|
|
1305
|
+
" |_|"
|
|
1306
|
+
];
|
|
1307
|
+
var WORDMARK_SMALL_WIDTH = WORDMARK_SMALL.reduce(
|
|
1308
|
+
(max, line) => Math.max(max, line.length),
|
|
1309
|
+
0
|
|
1310
|
+
);
|
|
1311
|
+
var BANNER_TIERS = [
|
|
1312
|
+
{ name: "full", minColumns: 190, rows: WORDMARK, width: WORDMARK_WIDTH },
|
|
1313
|
+
{ name: "mid", minColumns: 120, rows: WORDMARK_MID, width: WORDMARK_MID_WIDTH },
|
|
1314
|
+
{ name: "small", minColumns: 70, rows: WORDMARK_SMALL, width: WORDMARK_SMALL_WIDTH }
|
|
1315
|
+
];
|
|
1316
|
+
var MIN_FULL_BANNER_COLUMNS = 190;
|
|
1317
|
+
function resolveBannerColumns(columns, env = process.env) {
|
|
1318
|
+
if (columns !== void 0 && Number.isFinite(columns) && columns > 0) {
|
|
1319
|
+
return Math.floor(columns);
|
|
1320
|
+
}
|
|
1321
|
+
const raw = env.COLUMNS;
|
|
1322
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
1323
|
+
const parsed = Number.parseInt(raw, 10);
|
|
1324
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
|
|
1325
|
+
}
|
|
1326
|
+
var APP_SLOGAN = "The password manager that doesn't ask you to trust it.";
|
|
1327
|
+
var MINI_MARK = "[#]";
|
|
1328
|
+
function gradientRow(line, wordmarkWidth) {
|
|
1329
|
+
const span = Math.max(1, wordmarkWidth - 1);
|
|
1330
|
+
let out = "";
|
|
1331
|
+
let run = "";
|
|
1332
|
+
let runColor = null;
|
|
1333
|
+
const flush = () => {
|
|
1334
|
+
if (run !== "" && runColor) out += fg(runColor, run);
|
|
1335
|
+
run = "";
|
|
1336
|
+
runColor = null;
|
|
1337
|
+
};
|
|
1338
|
+
for (let i = 0; i < line.length; i++) {
|
|
1339
|
+
const char = line[i];
|
|
1340
|
+
if (char === " ") {
|
|
1341
|
+
flush();
|
|
1342
|
+
out += char;
|
|
1343
|
+
continue;
|
|
1344
|
+
}
|
|
1345
|
+
const color = mix(CRIMSON_TOP, CRIMSON_BOTTOM, i / span);
|
|
1346
|
+
if (runColor && (color[0] !== runColor[0] || color[1] !== runColor[1] || color[2] !== runColor[2])) {
|
|
1347
|
+
flush();
|
|
1348
|
+
}
|
|
1349
|
+
runColor = color;
|
|
1350
|
+
run += char;
|
|
1351
|
+
}
|
|
1352
|
+
flush();
|
|
1353
|
+
return out;
|
|
1354
|
+
}
|
|
1355
|
+
function renderCompactHeader(options) {
|
|
1356
|
+
const { version, colors } = options;
|
|
1357
|
+
const name = colors ? bold(fg(ACCENT_CORAL, "vaultkeepr")) : "vaultkeepr";
|
|
1358
|
+
const suffix = colors ? fg(ACCENT_CORAL, `v${version}`) : `v${version}`;
|
|
1359
|
+
return `${name} \xB7 ${suffix}`;
|
|
1360
|
+
}
|
|
1361
|
+
function renderBanner(options) {
|
|
1362
|
+
const { version, colors, columns } = options;
|
|
1363
|
+
const width = resolveBannerColumns(columns);
|
|
1364
|
+
const tier = width === void 0 ? BANNER_TIERS[0] : BANNER_TIERS.find((rung) => width >= rung.minColumns);
|
|
1365
|
+
if (!tier) {
|
|
1366
|
+
return `${renderCompactHeader(options)}
|
|
1367
|
+
`;
|
|
1368
|
+
}
|
|
1369
|
+
const wordmark = tier.rows.map((line) => colors ? gradientRow(line, tier.width) : line).join("\n");
|
|
1370
|
+
const footer = colors ? `${fg(CRIMSON_BOTTOM, APP_SLOGAN)} \xB7 ${fg(ACCENT_CORAL, `v${version}`)}` : `${APP_SLOGAN} \xB7 v${version}`;
|
|
1371
|
+
return `${wordmark}
|
|
1372
|
+
${footer}
|
|
1373
|
+
`;
|
|
1374
|
+
}
|
|
1375
|
+
function renderMiniHeader(options) {
|
|
1376
|
+
const { colors } = options;
|
|
1377
|
+
const mark = colors ? fg(CRIMSON_TOP, MINI_MARK) : MINI_MARK;
|
|
1378
|
+
return `${mark} ${renderCompactHeader(options)}`;
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
// src/ui.ts
|
|
1382
|
+
import { createInterface } from "readline/promises";
|
|
1383
|
+
var defaultIO = {
|
|
1384
|
+
out: (text) => {
|
|
1385
|
+
process.stdout.write(text);
|
|
1386
|
+
},
|
|
1387
|
+
err: (text) => {
|
|
1388
|
+
process.stderr.write(text);
|
|
1389
|
+
}
|
|
1390
|
+
};
|
|
1391
|
+
var RESET2 = "\x1B[0m";
|
|
1392
|
+
function wrap(enabled) {
|
|
1393
|
+
return (code) => (text) => enabled ? `\x1B[${code}m${text}${RESET2}` : text;
|
|
1394
|
+
}
|
|
1395
|
+
function palette(enabled) {
|
|
1396
|
+
return {
|
|
1397
|
+
bold: wrap(enabled)(1),
|
|
1398
|
+
dim: wrap(enabled)(2),
|
|
1399
|
+
red: wrap(enabled)(31),
|
|
1400
|
+
green: wrap(enabled)(32),
|
|
1401
|
+
yellow: wrap(enabled)(33),
|
|
1402
|
+
cyan: wrap(enabled)(36),
|
|
1403
|
+
magenta: wrap(enabled)(35)
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
function colorEnabled() {
|
|
1407
|
+
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === void 0 && process.env.TERM !== "dumb";
|
|
1408
|
+
}
|
|
1409
|
+
function visibleLength(text) {
|
|
1410
|
+
return text.replace(/\u001b\[[0-9;]*m/g, "").length;
|
|
1411
|
+
}
|
|
1412
|
+
function pad(text, width) {
|
|
1413
|
+
return text + " ".repeat(Math.max(0, width - visibleLength(text)));
|
|
1414
|
+
}
|
|
1415
|
+
function formatTable(headers, rows, style = {}) {
|
|
1416
|
+
const paletteValue = palette(Boolean(style.colors));
|
|
1417
|
+
const widths = headers.map(
|
|
1418
|
+
(header2, index) => Math.max(visibleLength(header2), ...rows.map((row) => visibleLength(row[index] ?? "")))
|
|
1419
|
+
);
|
|
1420
|
+
const line = (cells, colorize) => cells.map((value, index) => {
|
|
1421
|
+
const padded = pad(value, widths[index]);
|
|
1422
|
+
const color = colorize ? style.cellColor?.[index] : void 0;
|
|
1423
|
+
return color ? color(padded) : padded;
|
|
1424
|
+
}).join(" ").replace(/\s+$/, "");
|
|
1425
|
+
const header = line(headers.map((h) => h.toUpperCase()), false);
|
|
1426
|
+
const rule = widths.map((width) => "\u2500".repeat(width)).join(" ");
|
|
1427
|
+
const body = rows.map((row) => line(row, true));
|
|
1428
|
+
return `${paletteValue.dim(rule)}
|
|
1429
|
+
${paletteValue.bold(header)}
|
|
1430
|
+
${paletteValue.dim(rule)}
|
|
1431
|
+
${body.join("\n")}`;
|
|
1432
|
+
}
|
|
1433
|
+
var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1434
|
+
var Spinner = class {
|
|
1435
|
+
constructor(io, label) {
|
|
1436
|
+
this.io = io;
|
|
1437
|
+
this.label = label;
|
|
1438
|
+
this.interactive = Boolean(process.stderr.isTTY);
|
|
1439
|
+
}
|
|
1440
|
+
io;
|
|
1441
|
+
timer = null;
|
|
1442
|
+
frame = 0;
|
|
1443
|
+
label;
|
|
1444
|
+
interactive;
|
|
1445
|
+
start() {
|
|
1446
|
+
if (!this.interactive) return this;
|
|
1447
|
+
this.timer = setInterval(() => {
|
|
1448
|
+
this.frame = (this.frame + 1) % SPINNER_FRAMES.length;
|
|
1449
|
+
this.io.err(`\r\x1B[2K${SPINNER_FRAMES[this.frame]} ${this.label}`);
|
|
1450
|
+
}, 90);
|
|
1451
|
+
return this;
|
|
1452
|
+
}
|
|
1453
|
+
update(label) {
|
|
1454
|
+
this.label = label;
|
|
1455
|
+
}
|
|
1456
|
+
stop() {
|
|
1457
|
+
if (this.timer) {
|
|
1458
|
+
clearInterval(this.timer);
|
|
1459
|
+
this.timer = null;
|
|
1460
|
+
}
|
|
1461
|
+
if (this.interactive) this.io.err("\r\x1B[2K");
|
|
1462
|
+
}
|
|
1463
|
+
};
|
|
1464
|
+
function askPiped(question, input, output) {
|
|
1465
|
+
const rl = createInterface({ input, output, terminal: false });
|
|
1466
|
+
return rl.question(question).then((answer) => {
|
|
1467
|
+
rl.close();
|
|
1468
|
+
return answer;
|
|
1469
|
+
}).catch((error) => {
|
|
1470
|
+
rl.close();
|
|
1471
|
+
throw error;
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
async function ask(question, options = {}) {
|
|
1475
|
+
const input = options.input ?? process.stdin;
|
|
1476
|
+
const output = options.output ?? process.stdout;
|
|
1477
|
+
if (!options.secret || !input.isTTY || typeof input.setRawMode !== "function") {
|
|
1478
|
+
return (await askPiped(question, input, output)).trim();
|
|
1479
|
+
}
|
|
1480
|
+
output.write(question);
|
|
1481
|
+
input.setRawMode(true);
|
|
1482
|
+
input.resume();
|
|
1483
|
+
input.setEncoding("utf8");
|
|
1484
|
+
return await new Promise((resolve, reject) => {
|
|
1485
|
+
let value = "";
|
|
1486
|
+
const finish = (error) => {
|
|
1487
|
+
input.removeListener("data", onData);
|
|
1488
|
+
input.setRawMode(false);
|
|
1489
|
+
input.pause();
|
|
1490
|
+
output.write("\n");
|
|
1491
|
+
if (error) reject(error);
|
|
1492
|
+
else resolve(value);
|
|
1493
|
+
};
|
|
1494
|
+
const onData = (chunk) => {
|
|
1495
|
+
for (const char of chunk) {
|
|
1496
|
+
if (char === "\r" || char === "\n") {
|
|
1497
|
+
finish();
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
if (char === "") {
|
|
1501
|
+
finish(new Error("interrupted"));
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
if (char === "\x7F") {
|
|
1505
|
+
if (value.length > 0) {
|
|
1506
|
+
value = value.slice(0, -1);
|
|
1507
|
+
output.write("\b \b");
|
|
1508
|
+
}
|
|
1509
|
+
continue;
|
|
1510
|
+
}
|
|
1511
|
+
value += char;
|
|
1512
|
+
output.write("\u2022");
|
|
1513
|
+
}
|
|
1514
|
+
};
|
|
1515
|
+
input.on("data", onData);
|
|
1516
|
+
});
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// src/prompts.ts
|
|
1520
|
+
import {
|
|
1521
|
+
confirm as clackConfirm,
|
|
1522
|
+
intro as clackIntro,
|
|
1523
|
+
isCancel,
|
|
1524
|
+
log as clackLog,
|
|
1525
|
+
multiselect as clackMultiselect,
|
|
1526
|
+
outro as clackOutro,
|
|
1527
|
+
password as clackPassword,
|
|
1528
|
+
select as clackSelect,
|
|
1529
|
+
spinner as clackSpinner,
|
|
1530
|
+
text as clackText
|
|
1531
|
+
} from "@clack/prompts";
|
|
1532
|
+
var PromptCancelledError = class extends Error {
|
|
1533
|
+
constructor() {
|
|
1534
|
+
super("cancelled");
|
|
1535
|
+
this.name = "PromptCancelledError";
|
|
1536
|
+
}
|
|
1537
|
+
};
|
|
1538
|
+
function clackPrompter(overrides = {}) {
|
|
1539
|
+
const input = overrides.input ?? process.stdin;
|
|
1540
|
+
const output = overrides.output ?? process.stdout;
|
|
1541
|
+
const common = { input, output };
|
|
1542
|
+
return {
|
|
1543
|
+
interactive: true,
|
|
1544
|
+
intro: (title) => clackIntro(title, common),
|
|
1545
|
+
outro: (message) => clackOutro(message, common),
|
|
1546
|
+
async text({ message, placeholder, defaultValue }) {
|
|
1547
|
+
const value = await clackText({ message, placeholder, defaultValue, ...common });
|
|
1548
|
+
if (isCancel(value)) throw new PromptCancelledError();
|
|
1549
|
+
return String(value ?? "").trim();
|
|
1550
|
+
},
|
|
1551
|
+
async secret({ message }) {
|
|
1552
|
+
const value = await clackPassword({ message, ...common });
|
|
1553
|
+
if (isCancel(value)) throw new PromptCancelledError();
|
|
1554
|
+
return String(value ?? "").trim();
|
|
1555
|
+
},
|
|
1556
|
+
async confirm({ message, initialValue }) {
|
|
1557
|
+
const value = await clackConfirm({
|
|
1558
|
+
message,
|
|
1559
|
+
...initialValue === void 0 ? {} : { initialValue },
|
|
1560
|
+
...common
|
|
1561
|
+
});
|
|
1562
|
+
if (isCancel(value)) throw new PromptCancelledError();
|
|
1563
|
+
return value === true;
|
|
1564
|
+
},
|
|
1565
|
+
async select({
|
|
1566
|
+
message,
|
|
1567
|
+
choices,
|
|
1568
|
+
initialValue
|
|
1569
|
+
}) {
|
|
1570
|
+
const value = await clackSelect({
|
|
1571
|
+
message,
|
|
1572
|
+
options: choices.map((choice) => ({
|
|
1573
|
+
value: choice.value,
|
|
1574
|
+
label: choice.label,
|
|
1575
|
+
...choice.hint === void 0 ? {} : { hint: choice.hint }
|
|
1576
|
+
})),
|
|
1577
|
+
...initialValue === void 0 ? {} : { initialValue },
|
|
1578
|
+
...common
|
|
1579
|
+
});
|
|
1580
|
+
if (isCancel(value)) return null;
|
|
1581
|
+
return value;
|
|
1582
|
+
},
|
|
1583
|
+
async multiselect({
|
|
1584
|
+
message,
|
|
1585
|
+
choices,
|
|
1586
|
+
initialValues,
|
|
1587
|
+
required
|
|
1588
|
+
}) {
|
|
1589
|
+
const value = await clackMultiselect({
|
|
1590
|
+
message,
|
|
1591
|
+
options: choices.map((choice) => ({
|
|
1592
|
+
value: choice.value,
|
|
1593
|
+
label: choice.label,
|
|
1594
|
+
...choice.hint === void 0 ? {} : { hint: choice.hint }
|
|
1595
|
+
})),
|
|
1596
|
+
...initialValues === void 0 ? {} : { initialValues },
|
|
1597
|
+
...required === void 0 ? {} : { required },
|
|
1598
|
+
...common
|
|
1599
|
+
});
|
|
1600
|
+
if (isCancel(value)) return null;
|
|
1601
|
+
return value;
|
|
1602
|
+
},
|
|
1603
|
+
spinner() {
|
|
1604
|
+
const spin = clackSpinner({ output });
|
|
1605
|
+
return {
|
|
1606
|
+
start: (message) => spin.start(message),
|
|
1607
|
+
stop: (message) => spin.stop(message),
|
|
1608
|
+
error: (message) => spin.error(message)
|
|
1609
|
+
};
|
|
1610
|
+
},
|
|
1611
|
+
info: (message) => clackLog.info(message, common),
|
|
1612
|
+
success: (message) => clackLog.success(message, common),
|
|
1613
|
+
warn: (message) => clackLog.warn(message, common),
|
|
1614
|
+
error: (message) => clackLog.error(message, common)
|
|
1615
|
+
};
|
|
1616
|
+
}
|
|
1617
|
+
function plainPrompter(io, askFn = ask) {
|
|
1618
|
+
return {
|
|
1619
|
+
interactive: false,
|
|
1620
|
+
intro: () => {
|
|
1621
|
+
},
|
|
1622
|
+
outro: () => {
|
|
1623
|
+
},
|
|
1624
|
+
async text({ message }) {
|
|
1625
|
+
return (await askFn(`${message} : `)).trim();
|
|
1626
|
+
},
|
|
1627
|
+
async secret({ message }) {
|
|
1628
|
+
return (await askFn(`${message} : `, { secret: true })).trim();
|
|
1629
|
+
},
|
|
1630
|
+
async confirm({ message, initialValue }) {
|
|
1631
|
+
const hint = initialValue === true ? "[Y/n]" : "[y/N]";
|
|
1632
|
+
const answer = (await askFn(`${message} ${hint} : `)).trim().toLowerCase();
|
|
1633
|
+
if (answer === "") return initialValue === true;
|
|
1634
|
+
return answer === "y" || answer === "yes";
|
|
1635
|
+
},
|
|
1636
|
+
async select() {
|
|
1637
|
+
return null;
|
|
1638
|
+
},
|
|
1639
|
+
async multiselect() {
|
|
1640
|
+
return null;
|
|
1641
|
+
},
|
|
1642
|
+
spinner() {
|
|
1643
|
+
return { start: () => {
|
|
1644
|
+
}, stop: () => {
|
|
1645
|
+
}, error: () => {
|
|
1646
|
+
} };
|
|
1647
|
+
},
|
|
1648
|
+
info: (message) => io.out(`${message}
|
|
1649
|
+
`),
|
|
1650
|
+
success: (message) => io.out(`${message}
|
|
1651
|
+
`),
|
|
1652
|
+
warn: (message) => io.err(`${message}
|
|
1653
|
+
`),
|
|
1654
|
+
error: (message) => io.err(`${message}
|
|
1655
|
+
`)
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
function interactiveTTY() {
|
|
1659
|
+
return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
// src/commands.ts
|
|
1663
|
+
import { dirname as dirname3 } from "path";
|
|
1664
|
+
import { mkdtemp, rm, writeFile as writeFile2 } from "fs/promises";
|
|
1665
|
+
import { tmpdir } from "os";
|
|
1666
|
+
import { join as join3 } from "path";
|
|
1667
|
+
var NotPairedError = class extends Error {
|
|
1668
|
+
constructor() {
|
|
1669
|
+
super("terminal not paired: run `vaultkeepr pair`");
|
|
1670
|
+
this.name = "NotPairedError";
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
var KIND_COLORS = {
|
|
1674
|
+
api: (p, text) => p.magenta(text),
|
|
1675
|
+
login: (p, text) => p.cyan(text),
|
|
1676
|
+
card: (p, text) => p.yellow(text),
|
|
1677
|
+
identity: (p, text) => p.green(text),
|
|
1678
|
+
note: (p, text) => p.bold(text),
|
|
1679
|
+
seed: (p, text) => p.red(text),
|
|
1680
|
+
passkey: (p, text) => p.dim(text)
|
|
1681
|
+
};
|
|
1682
|
+
async function openSession(options) {
|
|
1683
|
+
const io = options.io ?? defaultIO;
|
|
1684
|
+
const paths = options.paths ?? configPaths(options.configDir);
|
|
1685
|
+
const identity = await loadIdentity(paths.identityPath);
|
|
1686
|
+
if (!identity) throw new NotPairedError();
|
|
1687
|
+
const now = options.now ?? Date.now;
|
|
1688
|
+
let account = options.account;
|
|
1689
|
+
let transport = options.transport;
|
|
1690
|
+
if (!transport) {
|
|
1691
|
+
account = account ?? await accountForIdentity(identity);
|
|
1692
|
+
transport = createHttpSyncTransport({
|
|
1693
|
+
apiBase: identity.apiBase,
|
|
1694
|
+
account,
|
|
1695
|
+
fetchImpl: options.fetchImpl ?? globalThis.fetch,
|
|
1696
|
+
now
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
return {
|
|
1700
|
+
identity,
|
|
1701
|
+
paths,
|
|
1702
|
+
io,
|
|
1703
|
+
now,
|
|
1704
|
+
transport,
|
|
1705
|
+
account,
|
|
1706
|
+
colors: options.colors ?? colorEnabled()
|
|
1707
|
+
};
|
|
1708
|
+
}
|
|
1709
|
+
function syncContext(session) {
|
|
1710
|
+
return {
|
|
1711
|
+
identity: session.identity,
|
|
1712
|
+
paths: session.paths,
|
|
1713
|
+
transport: session.transport,
|
|
1714
|
+
account: session.account,
|
|
1715
|
+
now: session.now
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
async function openVault(session, options) {
|
|
1719
|
+
let snapshot = await loadLocalVault(session.paths.vaultPath, session.identity) ?? {
|
|
1720
|
+
vault: emptyVault(session.now()),
|
|
1721
|
+
base: null
|
|
1722
|
+
};
|
|
1723
|
+
if (options.offline) return { snapshot, synced: false };
|
|
1724
|
+
try {
|
|
1725
|
+
await pullMerge(syncContext(session));
|
|
1726
|
+
snapshot = await loadLocalVault(session.paths.vaultPath, session.identity) ?? snapshot;
|
|
1727
|
+
return { snapshot, synced: true };
|
|
1728
|
+
} catch (error) {
|
|
1729
|
+
return {
|
|
1730
|
+
snapshot,
|
|
1731
|
+
synced: false,
|
|
1732
|
+
notice: `sync unavailable (${error instanceof Error ? error.message : String(error)})`
|
|
1733
|
+
};
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
async function publishBestEffort(session, vault) {
|
|
1737
|
+
try {
|
|
1738
|
+
const result = await publishVault(syncContext(session), vault);
|
|
1739
|
+
return { ok: true, cid: result.cid };
|
|
1740
|
+
} catch (error) {
|
|
1741
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
function printNotice(session, notice) {
|
|
1745
|
+
if (!notice) return;
|
|
1746
|
+
session.io.err(`${palette(session.colors).yellow("!")} ${notice}
|
|
1747
|
+
`);
|
|
1748
|
+
}
|
|
1749
|
+
function reportError(io, colors, error) {
|
|
1750
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1751
|
+
io.err(`${palette(colors).red("error")}: ${message}
|
|
1752
|
+
`);
|
|
1753
|
+
return 1;
|
|
1754
|
+
}
|
|
1755
|
+
async function runList(options = {}) {
|
|
1756
|
+
if (options.kind !== void 0 && !isEntryKind(options.kind)) {
|
|
1757
|
+
(options.io ?? defaultIO).err(`error: --kind expects ${ENTRY_KINDS.join("|")}
|
|
1758
|
+
`);
|
|
1759
|
+
return 2;
|
|
1760
|
+
}
|
|
1761
|
+
let session;
|
|
1762
|
+
try {
|
|
1763
|
+
session = await openSession(options);
|
|
1764
|
+
} catch (error) {
|
|
1765
|
+
return reportError(options.io ?? defaultIO, false, error);
|
|
1766
|
+
}
|
|
1767
|
+
const p = palette(session.colors);
|
|
1768
|
+
try {
|
|
1769
|
+
const { snapshot, notice } = await openVault(session, { offline: Boolean(options.offline) });
|
|
1770
|
+
printNotice(session, notice);
|
|
1771
|
+
const kind = options.kind;
|
|
1772
|
+
const entries = sortEntries(filterByKind(snapshot.vault.entries, kind));
|
|
1773
|
+
if (options.json) {
|
|
1774
|
+
session.io.out(`${JSON.stringify(entries.map(toListJson), null, 2)}
|
|
1775
|
+
`);
|
|
1776
|
+
return 0;
|
|
1777
|
+
}
|
|
1778
|
+
if (entries.length === 0) {
|
|
1779
|
+
const scope = kind ? ` of kind ${kind}` : "";
|
|
1780
|
+
session.io.out(`${p.dim(`No entries${scope}.`)}
|
|
1781
|
+
`);
|
|
1782
|
+
return 0;
|
|
1783
|
+
}
|
|
1784
|
+
const rows = entries.map((entry) => [
|
|
1785
|
+
KIND_LABELS[entryKind(entry)],
|
|
1786
|
+
entryLabel(entry),
|
|
1787
|
+
entry.username || entry.url || "\u2014",
|
|
1788
|
+
entry.id.slice(0, 8)
|
|
1789
|
+
]);
|
|
1790
|
+
const table = formatTable(["Type", "Label", "Username / URL", "ID"], rows, {
|
|
1791
|
+
colors: session.colors,
|
|
1792
|
+
cellColor: {
|
|
1793
|
+
0: (value) => {
|
|
1794
|
+
const kind2 = ENTRY_KINDS.find((candidate) => KIND_LABELS[candidate] === value);
|
|
1795
|
+
return kind2 ? KIND_COLORS[kind2](p, value) : value;
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
});
|
|
1799
|
+
session.io.out(`${table}
|
|
1800
|
+
`);
|
|
1801
|
+
const state = await loadSyncState(session.paths.syncStatePath, session.identity.address);
|
|
1802
|
+
session.io.out(
|
|
1803
|
+
`${p.dim(`${entries.length} ${entries.length === 1 ? "entry" : "entries"} \xB7 last sync ${formatWhen(state.lastResolveAt, session.now())} \xB7 published ${formatWhen(state.lastPublishAt, session.now())}`)}
|
|
1804
|
+
`
|
|
1805
|
+
);
|
|
1806
|
+
return 0;
|
|
1807
|
+
} catch (error) {
|
|
1808
|
+
return reportError(session.io, session.colors, error);
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
function toListJson(entry) {
|
|
1812
|
+
return {
|
|
1813
|
+
id: entry.id,
|
|
1814
|
+
kind: entryKind(entry),
|
|
1815
|
+
title: entryLabel(entry),
|
|
1816
|
+
username: entry.username ?? "",
|
|
1817
|
+
url: entry.url ?? ""
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
async function runGet(options) {
|
|
1821
|
+
let session;
|
|
1822
|
+
try {
|
|
1823
|
+
session = await openSession(options);
|
|
1824
|
+
} catch (error) {
|
|
1825
|
+
return reportError(options.io ?? defaultIO, false, error);
|
|
1826
|
+
}
|
|
1827
|
+
const p = palette(session.colors);
|
|
1828
|
+
if (typeof options.query !== "string" || options.query.trim() === "") {
|
|
1829
|
+
session.io.err("error: get expects the name or ID of an entry\n");
|
|
1830
|
+
return 2;
|
|
1831
|
+
}
|
|
1832
|
+
try {
|
|
1833
|
+
const { snapshot, notice } = await openVault(session, { offline: Boolean(options.offline) });
|
|
1834
|
+
printNotice(session, notice);
|
|
1835
|
+
const match = findEntry(snapshot.vault.entries, options.query);
|
|
1836
|
+
if (options.json) {
|
|
1837
|
+
session.io.out(`${JSON.stringify({ ...match.entry, kind: match.kind }, null, 2)}
|
|
1838
|
+
`);
|
|
1839
|
+
return 0;
|
|
1840
|
+
}
|
|
1841
|
+
if (options.reveal) {
|
|
1842
|
+
session.io.out(`${entrySecret(match.entry)}
|
|
1843
|
+
`);
|
|
1844
|
+
return 0;
|
|
1845
|
+
}
|
|
1846
|
+
const secret = entrySecret(match.entry);
|
|
1847
|
+
if (secret === "") {
|
|
1848
|
+
session.io.err(`${p.yellow("!")} this entry has no secret value to copy
|
|
1849
|
+
`);
|
|
1850
|
+
return 1;
|
|
1851
|
+
}
|
|
1852
|
+
const copy = options.copy ?? ((text) => copyToClipboard(text));
|
|
1853
|
+
const result = await copy(secret);
|
|
1854
|
+
if (!result.ok) {
|
|
1855
|
+
session.io.err(
|
|
1856
|
+
`${p.red("error")}: no usable clipboard (xclip, wl-copy, pbcopy). Use --reveal.
|
|
1857
|
+
`
|
|
1858
|
+
);
|
|
1859
|
+
return 1;
|
|
1860
|
+
}
|
|
1861
|
+
session.io.out(
|
|
1862
|
+
`${p.green("\u2713")} ${entryLabel(match.entry)} copied to the clipboard (${result.bin}).
|
|
1863
|
+
`
|
|
1864
|
+
);
|
|
1865
|
+
return 0;
|
|
1866
|
+
} catch (error) {
|
|
1867
|
+
return reportError(session.io, session.colors, error);
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
async function runAdd(options) {
|
|
1871
|
+
if (!isEntryKind(options.kind)) {
|
|
1872
|
+
(options.io ?? defaultIO).err(`error: --kind expects ${ENTRY_KINDS.join("|")}
|
|
1873
|
+
`);
|
|
1874
|
+
return 2;
|
|
1875
|
+
}
|
|
1876
|
+
const kind = options.kind;
|
|
1877
|
+
if (kind === "passkey") {
|
|
1878
|
+
(options.io ?? defaultIO).err(
|
|
1879
|
+
"error: passkeys are created from the phone or the extension\n"
|
|
1880
|
+
);
|
|
1881
|
+
return 2;
|
|
1882
|
+
}
|
|
1883
|
+
let session;
|
|
1884
|
+
try {
|
|
1885
|
+
session = await openSession(options);
|
|
1886
|
+
} catch (error) {
|
|
1887
|
+
return reportError(options.io ?? defaultIO, false, error);
|
|
1888
|
+
}
|
|
1889
|
+
const p = palette(session.colors);
|
|
1890
|
+
const prompter = options.prompter ?? (interactiveTTY() ? clackPrompter() : plainPrompter(session.io, options.askFn ?? ask));
|
|
1891
|
+
try {
|
|
1892
|
+
const { snapshot, notice } = await openVault(session, { offline: Boolean(options.offline) });
|
|
1893
|
+
printNotice(session, notice);
|
|
1894
|
+
const values = { ...options.fields ?? {} };
|
|
1895
|
+
const missing = FORM_FIELDS[kind].filter((field) => values[field.key] === void 0);
|
|
1896
|
+
if (prompter.interactive && missing.length > 0) {
|
|
1897
|
+
prompter.intro(`New ${KIND_LABELS[kind].toLowerCase()} entry`);
|
|
1898
|
+
}
|
|
1899
|
+
for (const field of missing) {
|
|
1900
|
+
const message = field.optional ? `${field.label} (optional)` : field.label;
|
|
1901
|
+
const answer = field.secret ? await prompter.secret({ message }) : await prompter.text({ message });
|
|
1902
|
+
if (answer !== "") values[field.key] = answer;
|
|
1903
|
+
}
|
|
1904
|
+
const entry = buildEntry(kind, values, session.now());
|
|
1905
|
+
const vault = { ...snapshot.vault, entries: [...snapshot.vault.entries, entry] };
|
|
1906
|
+
await saveLocalVault(session.paths.vaultPath, session.identity, { vault, base: snapshot.base }, session.now());
|
|
1907
|
+
const published = options.offline ? { ok: false, error: "offline mode" } : await publishBestEffort(session, vault);
|
|
1908
|
+
session.io.out(
|
|
1909
|
+
`${p.green("\u2713")} ${entryLabel(entry)} added (${KIND_LABELS[kind]}, ${entry.id.slice(0, 8)})
|
|
1910
|
+
`
|
|
1911
|
+
);
|
|
1912
|
+
if (published.ok) {
|
|
1913
|
+
session.io.out(`${p.dim(`Published to IPFS: ${redactCid(published.cid)}`)}
|
|
1914
|
+
`);
|
|
1915
|
+
} else {
|
|
1916
|
+
session.io.err(
|
|
1917
|
+
`${p.yellow("!")} saved locally, publish deferred (${published.error}).
|
|
1918
|
+
`
|
|
1919
|
+
);
|
|
1920
|
+
}
|
|
1921
|
+
if (prompter.interactive) prompter.outro("Done.");
|
|
1922
|
+
return 0;
|
|
1923
|
+
} catch (error) {
|
|
1924
|
+
if (error instanceof PromptCancelledError) {
|
|
1925
|
+
if (options.propagateCancel) throw error;
|
|
1926
|
+
session.io.err(`${p.red("error")}: cancelled
|
|
1927
|
+
`);
|
|
1928
|
+
return 1;
|
|
1929
|
+
}
|
|
1930
|
+
return reportError(session.io, session.colors, error);
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
async function runEdit(options) {
|
|
1934
|
+
if (typeof options.query !== "string" || options.query.trim() === "") {
|
|
1935
|
+
(options.io ?? defaultIO).err("error: edit expects the name or ID of an entry\n");
|
|
1936
|
+
return 2;
|
|
1937
|
+
}
|
|
1938
|
+
let session;
|
|
1939
|
+
try {
|
|
1940
|
+
session = await openSession(options);
|
|
1941
|
+
} catch (error) {
|
|
1942
|
+
return reportError(options.io ?? defaultIO, false, error);
|
|
1943
|
+
}
|
|
1944
|
+
const p = palette(session.colors);
|
|
1945
|
+
try {
|
|
1946
|
+
const { snapshot, notice } = await openVault(session, { offline: Boolean(options.offline) });
|
|
1947
|
+
printNotice(session, notice);
|
|
1948
|
+
const match = findEntry(snapshot.vault.entries, options.query);
|
|
1949
|
+
if (match.kind === "passkey") {
|
|
1950
|
+
session.io.err(
|
|
1951
|
+
"error: passkeys are edited from the phone, not from a terminal\n"
|
|
1952
|
+
);
|
|
1953
|
+
return 2;
|
|
1954
|
+
}
|
|
1955
|
+
const current = formValuesFromEntry(match.entry);
|
|
1956
|
+
const values = { ...current, ...options.fields ?? {} };
|
|
1957
|
+
const askFn = options.askFn ?? ((question, askOptions) => ask(question, askOptions));
|
|
1958
|
+
session.io.out(
|
|
1959
|
+
`${p.bold(`Edit ${KIND_LABELS[match.kind]} \xB7 ${entryLabel(match.entry)}`)} ${p.dim(
|
|
1960
|
+
`(${match.entry.id.slice(0, 8)})`
|
|
1961
|
+
)}
|
|
1962
|
+
`
|
|
1963
|
+
);
|
|
1964
|
+
for (const field of FORM_FIELDS[match.kind]) {
|
|
1965
|
+
if (options.fields !== void 0 && options.fields[field.key] !== void 0) continue;
|
|
1966
|
+
const hint = formHintForField(field, current);
|
|
1967
|
+
const clearHint = field.optional && (current[field.key] ?? "") !== "" ? p.dim(" [-] to clear") : "";
|
|
1968
|
+
const suffix = hint !== "" ? p.dim(` [${hint}]`) : field.optional ? p.dim(" (optional)") : "";
|
|
1969
|
+
const answer = await askFn(`${field.label}${suffix}${clearHint} : `, {
|
|
1970
|
+
secret: field.secret
|
|
1971
|
+
});
|
|
1972
|
+
if (answer === "-" && field.optional) {
|
|
1973
|
+
values[field.key] = "";
|
|
1974
|
+
} else if (answer !== "") {
|
|
1975
|
+
values[field.key] = answer;
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
const updated = updateEntryFromValues(match.entry, values, session.now());
|
|
1979
|
+
const vault = {
|
|
1980
|
+
...snapshot.vault,
|
|
1981
|
+
entries: snapshot.vault.entries.map(
|
|
1982
|
+
(entry) => entry.id === updated.id ? updated : entry
|
|
1983
|
+
)
|
|
1984
|
+
};
|
|
1985
|
+
await saveLocalVault(
|
|
1986
|
+
session.paths.vaultPath,
|
|
1987
|
+
session.identity,
|
|
1988
|
+
{ vault, base: snapshot.base },
|
|
1989
|
+
session.now()
|
|
1990
|
+
);
|
|
1991
|
+
const published = options.offline ? { ok: false, error: "offline mode" } : await publishBestEffort(session, vault);
|
|
1992
|
+
session.io.out(
|
|
1993
|
+
`${p.green("\u2713")} ${entryLabel(updated)} updated (${KIND_LABELS[match.kind]}, ${updated.id.slice(0, 8)})
|
|
1994
|
+
`
|
|
1995
|
+
);
|
|
1996
|
+
if (published.ok) {
|
|
1997
|
+
session.io.out(`${p.dim(`Published to IPFS: ${redactCid(published.cid)}`)}
|
|
1998
|
+
`);
|
|
1999
|
+
} else {
|
|
2000
|
+
session.io.err(
|
|
2001
|
+
`${p.yellow("!")} saved locally, publication deferred (${published.error}).
|
|
2002
|
+
`
|
|
2003
|
+
);
|
|
2004
|
+
}
|
|
2005
|
+
return 0;
|
|
2006
|
+
} catch (error) {
|
|
2007
|
+
return reportError(session.io, session.colors, error);
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
async function runDelete(options) {
|
|
2011
|
+
if (typeof options.query !== "string" || options.query.trim() === "") {
|
|
2012
|
+
(options.io ?? defaultIO).err("error: delete expects the name or ID of an entry\n");
|
|
2013
|
+
return 2;
|
|
2014
|
+
}
|
|
2015
|
+
let session;
|
|
2016
|
+
try {
|
|
2017
|
+
session = await openSession(options);
|
|
2018
|
+
} catch (error) {
|
|
2019
|
+
return reportError(options.io ?? defaultIO, false, error);
|
|
2020
|
+
}
|
|
2021
|
+
const p = palette(session.colors);
|
|
2022
|
+
try {
|
|
2023
|
+
const { snapshot, notice } = await openVault(session, { offline: Boolean(options.offline) });
|
|
2024
|
+
printNotice(session, notice);
|
|
2025
|
+
const match = findEntry(snapshot.vault.entries, options.query);
|
|
2026
|
+
session.io.out(`${p.bold("Delete this entry?")}
|
|
2027
|
+
`);
|
|
2028
|
+
session.io.out(` ${p.dim("Label")} ${entryLabel(match.entry)}
|
|
2029
|
+
`);
|
|
2030
|
+
session.io.out(` ${p.dim("Type")} ${KIND_LABELS[match.kind]}
|
|
2031
|
+
`);
|
|
2032
|
+
session.io.out(` ${p.dim("ID")} ${match.entry.id.slice(0, 8)}
|
|
2033
|
+
`);
|
|
2034
|
+
if (!options.yes) {
|
|
2035
|
+
const confirmFn = options.confirmFn ?? ((question) => ask(question));
|
|
2036
|
+
const answer = (await confirmFn("Confirm deletion? [y/N]: ")).trim().toLowerCase();
|
|
2037
|
+
if (answer !== "o" && answer !== "oui" && answer !== "y" && answer !== "yes") {
|
|
2038
|
+
session.io.out(`${p.dim("Cancelled.")}
|
|
2039
|
+
`);
|
|
2040
|
+
return 0;
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
const vault = deleteVaultEntry(snapshot.vault, match.entry.id, session.now());
|
|
2044
|
+
await saveLocalVault(
|
|
2045
|
+
session.paths.vaultPath,
|
|
2046
|
+
session.identity,
|
|
2047
|
+
{ vault, base: snapshot.base },
|
|
2048
|
+
session.now()
|
|
2049
|
+
);
|
|
2050
|
+
const published = options.offline ? { ok: false, error: "offline mode" } : await publishBestEffort(session, vault);
|
|
2051
|
+
session.io.out(
|
|
2052
|
+
`${p.green("\u2713")} ${entryLabel(match.entry)} deleted (${KIND_LABELS[match.kind]}, ${match.entry.id.slice(0, 8)})
|
|
2053
|
+
`
|
|
2054
|
+
);
|
|
2055
|
+
if (published.ok) {
|
|
2056
|
+
session.io.out(`${p.dim(`Tombstone published to IPFS: ${redactCid(published.cid)}`)}
|
|
2057
|
+
`);
|
|
2058
|
+
} else {
|
|
2059
|
+
session.io.err(
|
|
2060
|
+
`${p.yellow("!")} deletion saved locally, publication deferred (${published.error}).
|
|
2061
|
+
`
|
|
2062
|
+
);
|
|
2063
|
+
}
|
|
2064
|
+
return 0;
|
|
2065
|
+
} catch (error) {
|
|
2066
|
+
return reportError(session.io, session.colors, error);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
async function listDelegatableEntries(options = {}) {
|
|
2070
|
+
const session = await openSession(options);
|
|
2071
|
+
const { snapshot, notice } = await openVault(session, { offline: Boolean(options.offline) });
|
|
2072
|
+
if (notice) printNotice(session, notice);
|
|
2073
|
+
return sortEntries(snapshot.vault.entries).filter((entry) => entryKind(entry) !== "passkey").map((entry) => ({
|
|
2074
|
+
id: entry.id,
|
|
2075
|
+
label: entryLabel(entry),
|
|
2076
|
+
kind: entryKind(entry),
|
|
2077
|
+
...entry.url === void 0 || entry.url === "" ? {} : { url: entry.url }
|
|
2078
|
+
}));
|
|
2079
|
+
}
|
|
2080
|
+
function parsePrefixFlag(raw) {
|
|
2081
|
+
const parts = raw.split(",").map((part) => part.trim()).filter((part) => part !== "");
|
|
2082
|
+
if (parts.length === 0) throw new Error("--prefixes expects at least one URL");
|
|
2083
|
+
for (const part of parts) {
|
|
2084
|
+
let url;
|
|
2085
|
+
try {
|
|
2086
|
+
url = new URL(part);
|
|
2087
|
+
} catch {
|
|
2088
|
+
throw new Error(`--prefixes : URL invalide \xAB ${part} \xBB`);
|
|
2089
|
+
}
|
|
2090
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
2091
|
+
throw new Error(`--prefixes : seule une URL http(s) est accept\xE9e (\xAB ${part} \xBB)`);
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
return parts;
|
|
2095
|
+
}
|
|
2096
|
+
async function runAgentMandate(options) {
|
|
2097
|
+
const io = options.io ?? defaultIO;
|
|
2098
|
+
if (options.entries.length === 0) {
|
|
2099
|
+
io.err("error: mandate expects at least one --entry <id|label>\n");
|
|
2100
|
+
return 2;
|
|
2101
|
+
}
|
|
2102
|
+
if (options.bin.trim() === "") {
|
|
2103
|
+
io.err("error: mandate expects --bin <allowed binary name>\n");
|
|
2104
|
+
return 2;
|
|
2105
|
+
}
|
|
2106
|
+
if (options.ttlDays !== void 0 && (!Number.isInteger(options.ttlDays) || options.ttlDays < 1 || options.ttlDays > 365)) {
|
|
2107
|
+
io.err("error: --ttl-days expects an integer between 1 and 365\n");
|
|
2108
|
+
return 2;
|
|
2109
|
+
}
|
|
2110
|
+
let prefixes;
|
|
2111
|
+
try {
|
|
2112
|
+
prefixes = options.prefixes === void 0 ? void 0 : parsePrefixFlag(options.prefixes);
|
|
2113
|
+
} catch (error) {
|
|
2114
|
+
io.err(`error: ${error instanceof Error ? error.message : String(error)}
|
|
2115
|
+
`);
|
|
2116
|
+
return 2;
|
|
2117
|
+
}
|
|
2118
|
+
let session;
|
|
2119
|
+
try {
|
|
2120
|
+
session = await openSession(options);
|
|
2121
|
+
} catch (error) {
|
|
2122
|
+
return reportError(io, false, error);
|
|
2123
|
+
}
|
|
2124
|
+
const p = palette(session.colors);
|
|
2125
|
+
try {
|
|
2126
|
+
const { snapshot, notice } = await openVault(session, { offline: Boolean(options.offline) });
|
|
2127
|
+
printNotice(session, notice);
|
|
2128
|
+
const resolved = [];
|
|
2129
|
+
for (const query of options.entries) {
|
|
2130
|
+
const match = findEntry(snapshot.vault.entries, query);
|
|
2131
|
+
if (match.kind === "passkey") {
|
|
2132
|
+
io.err("error: a passkey cannot be delegated to an agent\n");
|
|
2133
|
+
return 2;
|
|
2134
|
+
}
|
|
2135
|
+
if (resolved.some((item) => item.entry.id === match.entry.id)) {
|
|
2136
|
+
io.err(`error: entry requested twice: ${entryLabel(match.entry)}
|
|
2137
|
+
`);
|
|
2138
|
+
return 2;
|
|
2139
|
+
}
|
|
2140
|
+
if (match.kind !== "api") {
|
|
2141
|
+
io.err(
|
|
2142
|
+
`${p.yellow("!")} ${entryLabel(match.entry)} is a ${KIND_LABELS[match.kind].toLowerCase()} \u2014 API entries are the usual delegation target
|
|
2143
|
+
`
|
|
2144
|
+
);
|
|
2145
|
+
}
|
|
2146
|
+
resolved.push(match);
|
|
2147
|
+
}
|
|
2148
|
+
const request = buildAgentMandateRequest({
|
|
2149
|
+
ttlDays: options.ttlDays,
|
|
2150
|
+
entries: resolved.map(({ entry }) => ({
|
|
2151
|
+
entryId: entry.id,
|
|
2152
|
+
bin: options.bin,
|
|
2153
|
+
...prefixes === void 0 ? { urlPrefixes: defaultMandateUrlPrefixes(entry.url) } : { urlPrefixes: prefixes }
|
|
2154
|
+
}))
|
|
2155
|
+
});
|
|
2156
|
+
if (prefixes !== void 0) {
|
|
2157
|
+
for (const { entry } of resolved) {
|
|
2158
|
+
if (!entryUrlMatchesPrefixes(entry.url, prefixes)) {
|
|
2159
|
+
io.err(
|
|
2160
|
+
`${p.yellow("!")} ${entryLabel(entry)}: its service URL is outside the requested domains, the mandate will refuse its calls
|
|
2161
|
+
`
|
|
2162
|
+
);
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
const apiBase = options.apiBase ?? session.identity.apiBase;
|
|
2167
|
+
io.out(`${p.bold("Mandate request")} \xB7 ${request.entries.length} entry(ies) \xB7 ${request.ttlDays} day(s) \xB7 ${options.bin}
|
|
2168
|
+
`);
|
|
2169
|
+
for (const { entry, kind } of resolved) {
|
|
2170
|
+
io.out(` ${KIND_LABELS[kind]} \xB7 ${entryLabel(entry)} (${entry.id.slice(0, 8)})
|
|
2171
|
+
`);
|
|
2172
|
+
}
|
|
2173
|
+
io.out(
|
|
2174
|
+
`${p.dim("The phone remains the signer: the request pre-fills the emission screen, confirm it on the phone.")}
|
|
2175
|
+
`
|
|
2176
|
+
);
|
|
2177
|
+
const tempRoot = options.tempRoot ?? tmpdir();
|
|
2178
|
+
const dir = await mkdtemp(join3(tempRoot, "vaultkeepr-mandate-"));
|
|
2179
|
+
try {
|
|
2180
|
+
const requestPath = join3(dir, "request.json");
|
|
2181
|
+
await writeFile2(requestPath, `${JSON.stringify(request)}
|
|
2182
|
+
`, { encoding: "utf8", mode: 384 });
|
|
2183
|
+
const argv = ["mandate", "--request-file", requestPath, "--api", apiBase];
|
|
2184
|
+
const spawn2 = options.spawn ?? spawnAgentBinary;
|
|
2185
|
+
const env = options.env ?? process.env;
|
|
2186
|
+
const code = await spawn2(agentBinaryCandidates(env, "agent"), argv, env);
|
|
2187
|
+
if (code === null) {
|
|
2188
|
+
io.err(
|
|
2189
|
+
"error: vaultkeepr-agent not found in the PATH (install the @vaultkeepr/agent-cli package)\n"
|
|
2190
|
+
);
|
|
2191
|
+
return 127;
|
|
2192
|
+
}
|
|
2193
|
+
return code;
|
|
2194
|
+
} finally {
|
|
2195
|
+
await rm(dir, { recursive: true, force: true });
|
|
2196
|
+
}
|
|
2197
|
+
} catch (error) {
|
|
2198
|
+
return reportError(io, session.colors, error);
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
async function runStatus(options = {}) {
|
|
2202
|
+
let session;
|
|
2203
|
+
try {
|
|
2204
|
+
session = await openSession(options);
|
|
2205
|
+
} catch (error) {
|
|
2206
|
+
return reportError(options.io ?? defaultIO, false, error);
|
|
2207
|
+
}
|
|
2208
|
+
const p = palette(session.colors);
|
|
2209
|
+
try {
|
|
2210
|
+
const stored = await loadLocalVault(session.paths.vaultPath, session.identity) ?? {
|
|
2211
|
+
vault: emptyVault(session.now()),
|
|
2212
|
+
base: null,
|
|
2213
|
+
savedAt: 0
|
|
2214
|
+
};
|
|
2215
|
+
if (stored.savedAt > 0) {
|
|
2216
|
+
try {
|
|
2217
|
+
await writeVaultSummary(dirname3(session.paths.vaultPath), stored.vault, stored.savedAt);
|
|
2218
|
+
} catch {
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
const state = await loadSyncState(session.paths.syncStatePath, session.identity.address);
|
|
2222
|
+
let remote = { cid: null };
|
|
2223
|
+
if (!options.offline) {
|
|
2224
|
+
try {
|
|
2225
|
+
remote = { cid: await session.transport.readPointerCid(session.identity.address) };
|
|
2226
|
+
} catch (error) {
|
|
2227
|
+
remote = { cid: null, error: error instanceof Error ? error.message : String(error) };
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2231
|
+
for (const entry of stored.vault.entries) {
|
|
2232
|
+
const kind = entryKind(entry);
|
|
2233
|
+
counts.set(kind, (counts.get(kind) ?? 0) + 1);
|
|
2234
|
+
}
|
|
2235
|
+
if (options.json) {
|
|
2236
|
+
const payload = {
|
|
2237
|
+
version: VERSION,
|
|
2238
|
+
address: redactAddress(session.identity.address),
|
|
2239
|
+
authType: session.identity.authType,
|
|
2240
|
+
apiBase: session.identity.apiBase,
|
|
2241
|
+
pairedAt: session.identity.pairedAt,
|
|
2242
|
+
vault: {
|
|
2243
|
+
entries: stored.vault.entries.length,
|
|
2244
|
+
byKind: Object.fromEntries(counts),
|
|
2245
|
+
savedAt: stored.savedAt
|
|
2246
|
+
},
|
|
2247
|
+
sync: {
|
|
2248
|
+
...state,
|
|
2249
|
+
address: redactAddress(state.address),
|
|
2250
|
+
vaultCid: redactCid(state.vaultCid)
|
|
2251
|
+
},
|
|
2252
|
+
remote: { cid: redactCid(remote.cid), error: remote.error ?? null }
|
|
2253
|
+
};
|
|
2254
|
+
session.io.out(`${JSON.stringify(payload, null, 2)}
|
|
2255
|
+
`);
|
|
2256
|
+
return 0;
|
|
2257
|
+
}
|
|
2258
|
+
session.io.out(`${renderMiniHeader({ version: VERSION, colors: session.colors })}
|
|
2259
|
+
`);
|
|
2260
|
+
session.io.out("\n");
|
|
2261
|
+
session.io.out(
|
|
2262
|
+
` ${p.dim("Account")} ${redactAddress(session.identity.address)} (${session.identity.authType})
|
|
2263
|
+
`
|
|
2264
|
+
);
|
|
2265
|
+
session.io.out(` ${p.dim("Paired")} ${formatDate(session.identity.pairedAt)}
|
|
2266
|
+
`);
|
|
2267
|
+
session.io.out(` ${p.dim("API")} ${session.identity.apiBase}
|
|
2268
|
+
`);
|
|
2269
|
+
session.io.out(
|
|
2270
|
+
` ${p.dim("Vault")} ${stored.vault.entries.length} ${stored.vault.entries.length === 1 ? "entry" : "entries"}
|
|
2271
|
+
`
|
|
2272
|
+
);
|
|
2273
|
+
const byKind = [...counts.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([kind, count]) => `${KIND_LABELS[kind]} ${count}`).join(" \xB7 ");
|
|
2274
|
+
if (byKind !== "") session.io.out(` ${p.dim(byKind)}
|
|
2275
|
+
`);
|
|
2276
|
+
session.io.out(` ${p.dim("Sync")} ${syncHeadline(state, session.now(), p, remote)}
|
|
2277
|
+
`);
|
|
2278
|
+
session.io.out(
|
|
2279
|
+
` ${p.dim("Last CID")} ${redactCid(state.vaultCid)} \xB7 remote ${remote.error ? p.red("unreadable") : redactCid(remote.cid)}
|
|
2280
|
+
`
|
|
2281
|
+
);
|
|
2282
|
+
if (state.lastError) session.io.out(` ${p.dim("Last error")} ${p.yellow(state.lastError)}
|
|
2283
|
+
`);
|
|
2284
|
+
return 0;
|
|
2285
|
+
} catch (error) {
|
|
2286
|
+
return reportError(session.io, session.colors, error);
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
function syncHeadline(state, now, p, remote) {
|
|
2290
|
+
if (remote.error) return p.red(`offline (${remote.error})`);
|
|
2291
|
+
if (!state.lastResolveAt) return p.yellow("never synced");
|
|
2292
|
+
const resolve = formatWhen(state.lastResolveAt, now);
|
|
2293
|
+
const publish = formatWhen(state.lastPublishAt, now);
|
|
2294
|
+
return `${p.green("up to date")} (read ${resolve}, published ${publish})`;
|
|
2295
|
+
}
|
|
2296
|
+
async function runSync(options = {}) {
|
|
2297
|
+
let session;
|
|
2298
|
+
try {
|
|
2299
|
+
session = await openSession(options);
|
|
2300
|
+
} catch (error) {
|
|
2301
|
+
return reportError(options.io ?? defaultIO, false, error);
|
|
2302
|
+
}
|
|
2303
|
+
const intervalMs = Math.max(1, options.intervalSeconds ?? 15) * 1e3;
|
|
2304
|
+
const controller = new AbortController();
|
|
2305
|
+
const onSigint = () => {
|
|
2306
|
+
session.io.err("\nstopping sync\u2026\n");
|
|
2307
|
+
controller.abort();
|
|
2308
|
+
};
|
|
2309
|
+
process.once("SIGINT", onSigint);
|
|
2310
|
+
const prompter = options.prompter ?? (interactiveTTY() ? clackPrompter() : plainPrompter(session.io, options.askFn ?? ask));
|
|
2311
|
+
if (options.once) {
|
|
2312
|
+
const spin = prompter.spinner();
|
|
2313
|
+
if (prompter.interactive) spin.start("Syncing\u2026");
|
|
2314
|
+
try {
|
|
2315
|
+
const result = await pullMerge(syncContext(session));
|
|
2316
|
+
const local = await loadLocalVault(session.paths.vaultPath, session.identity);
|
|
2317
|
+
const published = local ? await publishBestEffort(session, local.vault) : { ok: false };
|
|
2318
|
+
const line = `sync: ${result.status}${published.ok ? " + published" : ""}`;
|
|
2319
|
+
if (prompter.interactive) spin.stop(line);
|
|
2320
|
+
session.io.out(`${line}
|
|
2321
|
+
`);
|
|
2322
|
+
return 0;
|
|
2323
|
+
} catch (error) {
|
|
2324
|
+
if (prompter.interactive) {
|
|
2325
|
+
spin.error(`sync failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2326
|
+
}
|
|
2327
|
+
return reportError(session.io, session.colors, error);
|
|
2328
|
+
} finally {
|
|
2329
|
+
process.removeListener("SIGINT", onSigint);
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
try {
|
|
2333
|
+
return await runSyncLoop(syncContext(session), {
|
|
2334
|
+
intervalMs,
|
|
2335
|
+
signal: controller.signal,
|
|
2336
|
+
maxIterations: options.maxIterations,
|
|
2337
|
+
onEvent: (line) => session.io.out(`${line}
|
|
2338
|
+
`)
|
|
2339
|
+
});
|
|
2340
|
+
} catch (error) {
|
|
2341
|
+
return reportError(session.io, session.colors, error);
|
|
2342
|
+
} finally {
|
|
2343
|
+
process.removeListener("SIGINT", onSigint);
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
var COMPLETION_COMMANDS = [
|
|
2347
|
+
"pair",
|
|
2348
|
+
"list",
|
|
2349
|
+
"get",
|
|
2350
|
+
"add",
|
|
2351
|
+
"edit",
|
|
2352
|
+
"delete",
|
|
2353
|
+
"status",
|
|
2354
|
+
"sync",
|
|
2355
|
+
"agent",
|
|
2356
|
+
"completions",
|
|
2357
|
+
"help"
|
|
2358
|
+
];
|
|
2359
|
+
function completionScript(shell) {
|
|
2360
|
+
const kinds = ENTRY_KINDS.join(" ");
|
|
2361
|
+
if (shell === "zsh") {
|
|
2362
|
+
return `#compdef vaultkeepr
|
|
2363
|
+
_vaultkeepr() {
|
|
2364
|
+
local -a commands kinds agentCommands
|
|
2365
|
+
commands=(${COMPLETION_COMMANDS.map((command) => `'${command}'`).join(" ")})
|
|
2366
|
+
kinds=(${ENTRY_KINDS.map((kind) => `'${kind}'`).join(" ")})
|
|
2367
|
+
agentCommands=('init' 'list' 'run' 'http' 'mandate')
|
|
2368
|
+
_arguments -C \\
|
|
2369
|
+
'1:command:->commands' \\
|
|
2370
|
+
'*::argument:->args'
|
|
2371
|
+
case $state in
|
|
2372
|
+
commands) _describe 'command' commands ;;
|
|
2373
|
+
args)
|
|
2374
|
+
case $words[2] in
|
|
2375
|
+
add|list) _describe 'kind' kinds ;;
|
|
2376
|
+
edit|delete|get) _files -/ ;;
|
|
2377
|
+
agent) _describe 'sous-commande' agentCommands ;;
|
|
2378
|
+
esac
|
|
2379
|
+
;;
|
|
2380
|
+
esac
|
|
2381
|
+
}
|
|
2382
|
+
_vaultkeepr "$@"
|
|
2383
|
+
`;
|
|
2384
|
+
}
|
|
2385
|
+
return `# bash completion for vaultkeepr
|
|
2386
|
+
_vaultkeepr() {
|
|
2387
|
+
local cur prev
|
|
2388
|
+
cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
2389
|
+
prev="\${COMP_WORDS[COMP_CWORD-1]}"
|
|
2390
|
+
case "$prev" in
|
|
2391
|
+
vaultkeepr) COMPREPLY=( $(compgen -W "${COMPLETION_COMMANDS.join(" ")}" -- "$cur") ) ;;
|
|
2392
|
+
--kind) COMPREPLY=( $(compgen -W "${kinds}" -- "$cur") ) ;;
|
|
2393
|
+
add|list) COMPREPLY=( $(compgen -W "${kinds}" -- "$cur") ) ;;
|
|
2394
|
+
agent) COMPREPLY=( $(compgen -W "init list run http mandate" -- "$cur") ) ;;
|
|
2395
|
+
esac
|
|
2396
|
+
return 0
|
|
2397
|
+
}
|
|
2398
|
+
complete -F _vaultkeepr vaultkeepr
|
|
2399
|
+
`;
|
|
2400
|
+
}
|
|
2401
|
+
async function runCompletions(options) {
|
|
2402
|
+
const io = options.io ?? defaultIO;
|
|
2403
|
+
if (options.shell !== "bash" && options.shell !== "zsh") {
|
|
2404
|
+
io.err("error: completions expects bash or zsh\n");
|
|
2405
|
+
return 2;
|
|
2406
|
+
}
|
|
2407
|
+
io.out(completionScript(options.shell));
|
|
2408
|
+
return 0;
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
// src/qr.ts
|
|
2412
|
+
import { createRequire as createRequire2 } from "module";
|
|
2413
|
+
var require3 = createRequire2(import.meta.url);
|
|
2414
|
+
var QRCode = require3("qrcode-terminal/vendor/QRCode");
|
|
2415
|
+
var QRErrorCorrectLevel = require3("qrcode-terminal/vendor/QRCode/QRErrorCorrectLevel");
|
|
2416
|
+
var QR_QUIET_ZONE = 2;
|
|
2417
|
+
function cell(topDark, bottomDark) {
|
|
2418
|
+
if (topDark && bottomDark) return "\u2588";
|
|
2419
|
+
if (topDark) return "\u2580";
|
|
2420
|
+
if (bottomDark) return "\u2584";
|
|
2421
|
+
return " ";
|
|
2422
|
+
}
|
|
2423
|
+
function plainCell(dark) {
|
|
2424
|
+
return dark ? "\u2588\u2588" : " ";
|
|
2425
|
+
}
|
|
2426
|
+
function renderQr(text, options = {}) {
|
|
2427
|
+
const qr = new QRCode(-1, QRErrorCorrectLevel.M);
|
|
2428
|
+
qr.addData(text);
|
|
2429
|
+
qr.make();
|
|
2430
|
+
const count = qr.getModuleCount();
|
|
2431
|
+
const quiet = options.quietZone ?? QR_QUIET_ZONE;
|
|
2432
|
+
const total = count + quiet * 2;
|
|
2433
|
+
const dark = (row, col) => {
|
|
2434
|
+
const r = row - quiet;
|
|
2435
|
+
const c = col - quiet;
|
|
2436
|
+
if (r < 0 || c < 0 || r >= count || c >= count) return false;
|
|
2437
|
+
return qr.isDark(r, c);
|
|
2438
|
+
};
|
|
2439
|
+
const lines = [];
|
|
2440
|
+
for (let row = 0; row < total; row += 2) {
|
|
2441
|
+
let line = "";
|
|
2442
|
+
for (let col = 0; col < total; col++) {
|
|
2443
|
+
line += cell(dark(row, col), dark(row + 1, col));
|
|
2444
|
+
}
|
|
2445
|
+
lines.push(line);
|
|
2446
|
+
}
|
|
2447
|
+
const body = options.color ? lines.map((line) => `\x1B[30;47m${line}\x1B[0m`).join("\n") : (() => {
|
|
2448
|
+
const plain = [];
|
|
2449
|
+
for (let row = 0; row < total; row++) {
|
|
2450
|
+
let line = "";
|
|
2451
|
+
for (let col = 0; col < total; col++) {
|
|
2452
|
+
line += plainCell(dark(row, col));
|
|
2453
|
+
}
|
|
2454
|
+
plain.push(line, line);
|
|
2455
|
+
}
|
|
2456
|
+
return plain.join("\n");
|
|
2457
|
+
})();
|
|
2458
|
+
return `${body}
|
|
2459
|
+
`;
|
|
2460
|
+
}
|
|
2461
|
+
async function renderTerminalQr(text) {
|
|
2462
|
+
return renderQr(text, { color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR });
|
|
2463
|
+
}
|
|
2464
|
+
|
|
2465
|
+
// src/pairing.ts
|
|
2466
|
+
function formatClock(ms) {
|
|
2467
|
+
return new Date(ms).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });
|
|
2468
|
+
}
|
|
2469
|
+
function vaultFromPairPayload(vault) {
|
|
2470
|
+
if (typeof vault !== "object" || vault === null) {
|
|
2471
|
+
throw new Error("pair payload carries no vault");
|
|
2472
|
+
}
|
|
2473
|
+
return parseVault(JSON.stringify(vault));
|
|
2474
|
+
}
|
|
2475
|
+
async function runPair(options = {}) {
|
|
2476
|
+
const io = options.io ?? defaultIO;
|
|
2477
|
+
const now = options.now ?? Date.now;
|
|
2478
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
2479
|
+
const pollIntervalMs = options.pollIntervalMs ?? 1500;
|
|
2480
|
+
const apiBase = options.apiBase ?? DEFAULT_API_BASE;
|
|
2481
|
+
const paths = options.paths ?? configPaths(options.configDir);
|
|
2482
|
+
const renderQr2 = options.renderQr ?? renderTerminalQr;
|
|
2483
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
2484
|
+
const deviceName = options.deviceName ?? `vaultkeepr (${process.platform})`;
|
|
2485
|
+
const colors = palette(Boolean(process.stdout.isTTY) && process.env.NO_COLOR === void 0);
|
|
2486
|
+
const transport = createPairTransport(apiBase, fetchImpl);
|
|
2487
|
+
const keypair = newPairKeypair();
|
|
2488
|
+
let session;
|
|
2489
|
+
try {
|
|
2490
|
+
session = await transport.createSession(keypair.publicKeyHex, deviceName);
|
|
2491
|
+
} catch (error) {
|
|
2492
|
+
io.err(`error: ${error instanceof Error ? error.message : String(error)}
|
|
2493
|
+
`);
|
|
2494
|
+
return 1;
|
|
2495
|
+
}
|
|
2496
|
+
const uri = pairUri(session.sessionId, keypair.publicKeyHex);
|
|
2497
|
+
io.out(`${colors.bold("VaultKeepR")} \u2014 pairing this terminal
|
|
2498
|
+
|
|
2499
|
+
`);
|
|
2500
|
+
io.out(`${colors.cyan("1.")} On the phone: ${colors.bold("VaultKeepR \u2192 Settings \u2192 Pair a terminal")}
|
|
2501
|
+
`);
|
|
2502
|
+
io.out(`${colors.cyan("2.")} Scan this code, then confirm the vault transfer
|
|
2503
|
+
|
|
2504
|
+
`);
|
|
2505
|
+
const qr = await renderQr2(uri);
|
|
2506
|
+
io.out(qr);
|
|
2507
|
+
io.out(`${colors.dim("QR unreadable? Enter the URI:")} ${uri}
|
|
2508
|
+
`);
|
|
2509
|
+
io.out(`${colors.dim(`API: ${apiBase} \xB7 session valid until ${formatClock(session.expiresAt)}`)}
|
|
2510
|
+
|
|
2511
|
+
`);
|
|
2512
|
+
const spinner = interactiveTTY() ? clackPrompter().spinner() : { start: () => {
|
|
2513
|
+
}, stop: () => {
|
|
2514
|
+
}, error: () => {
|
|
2515
|
+
} };
|
|
2516
|
+
spinner.start("Waiting for the vault sent by the phone\u2026");
|
|
2517
|
+
let status;
|
|
2518
|
+
try {
|
|
2519
|
+
if (options.awaitPayload) {
|
|
2520
|
+
status = await options.awaitPayload(session.sessionId);
|
|
2521
|
+
} else {
|
|
2522
|
+
status = await pollForPayload(transport, session.sessionId, session.expiresAt, {
|
|
2523
|
+
pollIntervalMs,
|
|
2524
|
+
now,
|
|
2525
|
+
sleep
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
} catch (error) {
|
|
2529
|
+
spinner.stop();
|
|
2530
|
+
io.err(`error: ${error instanceof Error ? error.message : String(error)}
|
|
2531
|
+
`);
|
|
2532
|
+
return 1;
|
|
2533
|
+
}
|
|
2534
|
+
spinner.stop();
|
|
2535
|
+
let identity;
|
|
2536
|
+
let vault;
|
|
2537
|
+
try {
|
|
2538
|
+
const payload = openPairPayload(status, keypair);
|
|
2539
|
+
identity = await identityFromPairPayload(payload, {
|
|
2540
|
+
apiBase,
|
|
2541
|
+
deviceName,
|
|
2542
|
+
pairedAt: now()
|
|
2543
|
+
});
|
|
2544
|
+
vault = vaultFromPairPayload(payload.vault);
|
|
2545
|
+
} catch (error) {
|
|
2546
|
+
io.err(`error: ${error instanceof Error ? error.message : String(error)}
|
|
2547
|
+
`);
|
|
2548
|
+
return 1;
|
|
2549
|
+
}
|
|
2550
|
+
await ensurePrivateDir(paths.dir);
|
|
2551
|
+
await saveIdentity(paths.identityPath, identity);
|
|
2552
|
+
await saveLocalVault(paths.vaultPath, identity, { vault, base: null }, now());
|
|
2553
|
+
const short = `${identity.address.slice(0, 6)}\u2026${identity.address.slice(-4)}`;
|
|
2554
|
+
io.out(`${colors.green("\u2713")} Paired: ${colors.bold(short)} \xB7 ${vault.entries.length} ${vault.entries.length === 1 ? "entry" : "entries"}
|
|
2555
|
+
`);
|
|
2556
|
+
io.out(`${colors.dim(`Identity and vault in ${paths.dir} (700/600). Continuous sync: \`vaultkeepr sync\`.`)}
|
|
2557
|
+
`);
|
|
2558
|
+
return 0;
|
|
2559
|
+
}
|
|
2560
|
+
async function pollForPayload(transport, sessionId, expiresAt, options) {
|
|
2561
|
+
for (; ; ) {
|
|
2562
|
+
if (options.now() > expiresAt) {
|
|
2563
|
+
throw new Error("pairing session expired, no vault received");
|
|
2564
|
+
}
|
|
2565
|
+
const status = await transport.pollStatus(sessionId);
|
|
2566
|
+
if (status === null) {
|
|
2567
|
+
throw new Error("pairing session expired or already consumed");
|
|
2568
|
+
}
|
|
2569
|
+
if (status.completed) return status;
|
|
2570
|
+
await options.sleep(options.pollIntervalMs);
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
|
|
2574
|
+
// src/cli.ts
|
|
2575
|
+
var USAGE = `vaultkeepr \u2014 VaultKeepR vault client for the terminal (human)
|
|
2576
|
+
|
|
2577
|
+
Usage:
|
|
2578
|
+
vaultkeepr pair [--api <url>]
|
|
2579
|
+
Prints a pairing QR: VaultKeepR \u2192 Settings \u2192 Pair a terminal.
|
|
2580
|
+
The phone sends the vault sealed for this session; no master password is
|
|
2581
|
+
typed here. Identity and vault live in ~/.config/vaultkeepr/ (700/600).
|
|
2582
|
+
|
|
2583
|
+
vaultkeepr list [--kind <${ENTRY_KINDS.join("|")}>] [--json] [--offline]
|
|
2584
|
+
Table of entries (type, label, username/URL, ID). Never a value.
|
|
2585
|
+
|
|
2586
|
+
vaultkeepr get <entry> [--reveal] [--json] [--offline]
|
|
2587
|
+
Copies the value to the clipboard (wl-copy, xclip, xsel, pbcopy).
|
|
2588
|
+
--reveal prints it, --json prints the whole entry.
|
|
2589
|
+
<entry>: ID (even partial), label, username or URL.
|
|
2590
|
+
|
|
2591
|
+
vaultkeepr add [--kind <kind>] [--title <t>] [--url <u>] [--username <u>] [--note <n>]
|
|
2592
|
+
Interactive form for the chosen type (arrow-key prompts on a terminal,
|
|
2593
|
+
plain prompts when piped). The secret value is always typed at the
|
|
2594
|
+
prompt, never passed as an argument. Kind "api" = label, value, optional
|
|
2595
|
+
service URL, optional note \u2014 no username/password pair.
|
|
2596
|
+
|
|
2597
|
+
vaultkeepr edit <entry> [--title <t>] [--url <u>] [--username <u>] [--note <n>]
|
|
2598
|
+
Same form as add, pre-filled from the entry: Enter keeps the current
|
|
2599
|
+
value, "-" clears an optional field. No secret value is displayed
|
|
2600
|
+
(a "kept" mention is shown). Published like add.
|
|
2601
|
+
|
|
2602
|
+
vaultkeepr delete <entry> [--yes]
|
|
2603
|
+
Confirmation (label, type, ID \u2014 never the value), then deletion and
|
|
2604
|
+
published tombstone: the deletion propagates on the next merge.
|
|
2605
|
+
|
|
2606
|
+
vaultkeepr agent init|list|run|http|mandate [...]
|
|
2607
|
+
Single entry point for the agent family (delegates to vaultkeepr-agent
|
|
2608
|
+
and vaultkeepr-agent-http). See "vaultkeepr agent --help", notably
|
|
2609
|
+
"agent mandate": the mandate request carried by the QR, which the phone
|
|
2610
|
+
pre-fills and signs (the terminal never seals a mandate).
|
|
2611
|
+
|
|
2612
|
+
vaultkeepr status [--json] [--offline]
|
|
2613
|
+
Paired account, sync state (read, publish, remote pointer), vault
|
|
2614
|
+
statistics, version.
|
|
2615
|
+
|
|
2616
|
+
vaultkeepr sync [--interval <s>] [--once]
|
|
2617
|
+
Continuous sync: read the pointer, merge, publish local changes.
|
|
2618
|
+
Default interval 15 s. Ctrl-C to stop.
|
|
2619
|
+
|
|
2620
|
+
vaultkeepr completions <bash|zsh>
|
|
2621
|
+
Completion script to source.
|
|
2622
|
+
|
|
2623
|
+
Options:
|
|
2624
|
+
--api <url> API base (default: https://app.vaultkeepr.xyz).
|
|
2625
|
+
--kind <kind> ${ENTRY_KINDS.join(", ")}.
|
|
2626
|
+
--offline No network call: work on the local vault.
|
|
2627
|
+
--json JSON output (list, get, status). Never coloured, never branded.
|
|
2628
|
+
--reveal Print the value instead of copying it (get).
|
|
2629
|
+
--yes Delete without asking for confirmation (delete).
|
|
2630
|
+
--interval <s> Sync loop interval.
|
|
2631
|
+
--once A single sync pass.
|
|
2632
|
+
-h, --help This help.
|
|
2633
|
+
-v, --version Version.
|
|
2634
|
+
|
|
2635
|
+
Exit: 0 success, 1 runtime error (network, vault, clipboard), 2 usage.
|
|
2636
|
+
|
|
2637
|
+
Bare vaultkeepr on a terminal opens the interactive session: the menu
|
|
2638
|
+
returns after each action, agent mandate entries included; Quit or Ctrl-C
|
|
2639
|
+
leaves. A command given as an argument, a piped stdin or --json stays
|
|
2640
|
+
single-shot.
|
|
2641
|
+
`;
|
|
2642
|
+
var MENU_ACTIONS = [
|
|
2643
|
+
{ value: "list", label: "List entries", hint: "type, label, ID \u2014 never a value" },
|
|
2644
|
+
{ value: "get", label: "Copy a value", hint: "choose an entry, copies to the clipboard" },
|
|
2645
|
+
{ value: "add", label: "Add an entry", hint: "interactive form per type" },
|
|
2646
|
+
{ value: "status", label: "Status", hint: "account, vault, sync state" },
|
|
2647
|
+
{ value: "sync", label: "Sync once", hint: "read the pointer, merge, publish" },
|
|
2648
|
+
{ value: "pair", label: "Pair this terminal", hint: "scan a QR from the phone" },
|
|
2649
|
+
{
|
|
2650
|
+
value: "agent-mandate",
|
|
2651
|
+
label: "Mandate an agent",
|
|
2652
|
+
hint: "QR carries the request, the phone signs"
|
|
2653
|
+
},
|
|
2654
|
+
{ value: "agent-list", label: "Agent mandates", hint: "entries, commands, domains, expiry" },
|
|
2655
|
+
{ value: "quit", label: "Quit", hint: "leave without changing anything" }
|
|
2656
|
+
];
|
|
2657
|
+
var MENU_DEFAULT_MANDATE_BIN = "vaultkeepr-agent-http";
|
|
2658
|
+
function computedPrefixDefaults(entries) {
|
|
2659
|
+
const rows = [];
|
|
2660
|
+
const origins = [];
|
|
2661
|
+
for (const entry of entries) {
|
|
2662
|
+
const origin = entryUrlOrigin(entry.url);
|
|
2663
|
+
if (origin === null) continue;
|
|
2664
|
+
rows.push({ label: entry.label, origin });
|
|
2665
|
+
if (!origins.includes(origin)) origins.push(origin);
|
|
2666
|
+
}
|
|
2667
|
+
return { rows, origins, list: origins.join(",") };
|
|
2668
|
+
}
|
|
2669
|
+
var TOGGLE_ALL_ENTRIES = "__show_all_entries__";
|
|
2670
|
+
var TOGGLE_API_ENTRIES = "__show_api_entries__";
|
|
2671
|
+
var OTHER_BINARY = "__other_binary__";
|
|
2672
|
+
var CUSTOM_PREFIXES = "__custom_prefixes__";
|
|
2673
|
+
var PRESET_PREFIXES_PREFIX = "__preset_prefixes__:";
|
|
2674
|
+
var MANDATE_TTL_CHOICES = [30, 90, 365];
|
|
2675
|
+
async function readPrefixes(io, prompter, selected, presetDomains) {
|
|
2676
|
+
const defaults = computedPrefixDefaults(selected);
|
|
2677
|
+
const presetList = presetDomains.join(",");
|
|
2678
|
+
const accepted = (prefixes) => prefixes === void 0 || prefixes === "" ? {} : { prefixes };
|
|
2679
|
+
const applyTyped = async (typed2, shown, what, perEntry = false) => {
|
|
2680
|
+
const useShown = () => perEntry ? {} : accepted(shown);
|
|
2681
|
+
if (typed2 === "" || shown === "" || typed2 === shown) {
|
|
2682
|
+
return typed2 === "" || typed2 === shown ? useShown() : accepted(typed2);
|
|
2683
|
+
}
|
|
2684
|
+
const ok = await prompter.confirm({
|
|
2685
|
+
message: `Overriding ${what} (${shown}) with ${typed2} \u2014 OK?`,
|
|
2686
|
+
initialValue: false
|
|
2687
|
+
});
|
|
2688
|
+
if (ok) return { prefixes: typed2 };
|
|
2689
|
+
io.out(`Keeping ${what}: ${shown}
|
|
2690
|
+
`);
|
|
2691
|
+
return useShown();
|
|
2692
|
+
};
|
|
2693
|
+
if (defaults.origins.length === 1) {
|
|
2694
|
+
const serviceUrl = defaults.origins[0];
|
|
2695
|
+
const scope = selected.length === 1 ? "this entry's service URL" : `service URL of these ${defaults.rows.length} entries`;
|
|
2696
|
+
const pick = await prompter.select({
|
|
2697
|
+
message: "Allowed URL prefixes",
|
|
2698
|
+
choices: [
|
|
2699
|
+
{ value: serviceUrl, label: `${serviceUrl} (${scope})`, hint: "default" },
|
|
2700
|
+
...presetList === "" ? [] : [
|
|
2701
|
+
{
|
|
2702
|
+
value: `${PRESET_PREFIXES_PREFIX}${presetList}`,
|
|
2703
|
+
label: `Use the preset suggestion: ${presetList}`
|
|
2704
|
+
}
|
|
2705
|
+
],
|
|
2706
|
+
{ value: CUSTOM_PREFIXES, label: "Type custom prefixes\u2026", hint: "comma-separated URLs" }
|
|
2707
|
+
],
|
|
2708
|
+
initialValue: serviceUrl
|
|
2709
|
+
});
|
|
2710
|
+
if (pick === null) return null;
|
|
2711
|
+
if (pick === CUSTOM_PREFIXES) {
|
|
2712
|
+
const typed2 = (await prompter.text({
|
|
2713
|
+
message: `URL prefixes (comma-separated, empty = ${serviceUrl})`,
|
|
2714
|
+
placeholder: serviceUrl,
|
|
2715
|
+
defaultValue: serviceUrl
|
|
2716
|
+
})).trim();
|
|
2717
|
+
return await applyTyped(typed2, serviceUrl, scope);
|
|
2718
|
+
}
|
|
2719
|
+
if (pick.startsWith(PRESET_PREFIXES_PREFIX)) {
|
|
2720
|
+
return { prefixes: pick.slice(PRESET_PREFIXES_PREFIX.length) };
|
|
2721
|
+
}
|
|
2722
|
+
return {};
|
|
2723
|
+
}
|
|
2724
|
+
if (defaults.origins.length > 1) {
|
|
2725
|
+
io.out("URL prefixes default to each entry's service URL:\n");
|
|
2726
|
+
for (const row of defaults.rows) io.out(` ${row.label} \u2192 ${row.origin}
|
|
2727
|
+
`);
|
|
2728
|
+
io.out("\n");
|
|
2729
|
+
}
|
|
2730
|
+
const fallback = defaults.list === "" ? "each entry service URL" : defaults.list;
|
|
2731
|
+
const typed = (await prompter.text({
|
|
2732
|
+
message: `Allowed URL prefixes (comma-separated, empty = ${defaults.origins.length > 1 ? `each entry's own service URL: ${fallback}` : fallback}${presetList === "" ? "" : `; preset suggestion: ${presetList}`})`,
|
|
2733
|
+
// Placeholder only: @clack/prompts RENDERS it on a plain TTY, and an
|
|
2734
|
+
// empty Enter must leave the request prefix-free so each entry keeps its
|
|
2735
|
+
// own service URL. A defaultValue here would send the union to every
|
|
2736
|
+
// entry (see `applyTyped`).
|
|
2737
|
+
...defaults.list === "" ? {} : { placeholder: defaults.list }
|
|
2738
|
+
})).trim();
|
|
2739
|
+
return await applyTyped(
|
|
2740
|
+
typed,
|
|
2741
|
+
defaults.list,
|
|
2742
|
+
defaults.origins.length > 1 ? "the service URLs" : "the service URL",
|
|
2743
|
+
defaults.origins.length > 1
|
|
2744
|
+
);
|
|
2745
|
+
}
|
|
2746
|
+
async function readMandateForm(io, prompter, ordered) {
|
|
2747
|
+
const apiOnly = ordered.filter((entry) => entry.kind === "api");
|
|
2748
|
+
try {
|
|
2749
|
+
let showAll = apiOnly.length === 0;
|
|
2750
|
+
let picked = [];
|
|
2751
|
+
let selected = null;
|
|
2752
|
+
while (selected === null) {
|
|
2753
|
+
const pool = showAll ? ordered : apiOnly;
|
|
2754
|
+
const visible = picked.filter((id) => pool.some((entry) => entry.id === id));
|
|
2755
|
+
const result = await prompter.multiselect({
|
|
2756
|
+
message: "Entries to delegate",
|
|
2757
|
+
choices: [
|
|
2758
|
+
...pool.map((entry) => ({
|
|
2759
|
+
value: entry.id,
|
|
2760
|
+
label: `${entry.label} (${KIND_LABELS[entry.kind]})`,
|
|
2761
|
+
hint: entry.url ?? entry.id.slice(0, 8)
|
|
2762
|
+
})),
|
|
2763
|
+
showAll ? {
|
|
2764
|
+
value: TOGGLE_API_ENTRIES,
|
|
2765
|
+
label: "Show API entries only",
|
|
2766
|
+
hint: "API keys are the usual delegation target"
|
|
2767
|
+
} : {
|
|
2768
|
+
value: TOGGLE_ALL_ENTRIES,
|
|
2769
|
+
label: "Show all entry types",
|
|
2770
|
+
hint: "logins, notes, cards\u2026"
|
|
2771
|
+
}
|
|
2772
|
+
],
|
|
2773
|
+
initialValues: visible
|
|
2774
|
+
});
|
|
2775
|
+
if (result === null) return null;
|
|
2776
|
+
picked = result.filter(
|
|
2777
|
+
(value) => value !== TOGGLE_ALL_ENTRIES && value !== TOGGLE_API_ENTRIES
|
|
2778
|
+
);
|
|
2779
|
+
if (result.includes(showAll ? TOGGLE_API_ENTRIES : TOGGLE_ALL_ENTRIES)) {
|
|
2780
|
+
showAll = !showAll;
|
|
2781
|
+
continue;
|
|
2782
|
+
}
|
|
2783
|
+
if (picked.length === 0) return null;
|
|
2784
|
+
selected = ordered.filter((entry) => picked.includes(entry.id));
|
|
2785
|
+
}
|
|
2786
|
+
const presetId = await prompter.select({
|
|
2787
|
+
message: "Preset (pre-fills the binary)",
|
|
2788
|
+
choices: [
|
|
2789
|
+
...AGENT_MANDATE_PRESETS.map((preset2) => ({ value: preset2.id, label: preset2.label })),
|
|
2790
|
+
{ value: "manual", label: "Manual", hint: "type the binary and the domains" }
|
|
2791
|
+
]
|
|
2792
|
+
});
|
|
2793
|
+
if (presetId === null) return null;
|
|
2794
|
+
const preset = AGENT_MANDATE_PRESETS.find((candidate) => candidate.id === presetId);
|
|
2795
|
+
const defaultBin = preset?.commands[0]?.bin ?? MENU_DEFAULT_MANDATE_BIN;
|
|
2796
|
+
const presetBins = [...new Set((preset?.commands ?? []).map((command) => command.bin))];
|
|
2797
|
+
const binChoices = [...presetBins.length === 0 ? [defaultBin] : presetBins];
|
|
2798
|
+
const binPick = await prompter.select({
|
|
2799
|
+
message: "Allowed binary",
|
|
2800
|
+
choices: [
|
|
2801
|
+
...binChoices.map((bin2) => ({
|
|
2802
|
+
value: bin2,
|
|
2803
|
+
label: bin2,
|
|
2804
|
+
...bin2 === MENU_DEFAULT_MANDATE_BIN ? { hint: "HTTP broker" } : {}
|
|
2805
|
+
})),
|
|
2806
|
+
{ value: OTHER_BINARY, label: "Type another binary\u2026" }
|
|
2807
|
+
],
|
|
2808
|
+
initialValue: defaultBin
|
|
2809
|
+
});
|
|
2810
|
+
if (binPick === null) return null;
|
|
2811
|
+
let bin = binPick;
|
|
2812
|
+
if (binPick === OTHER_BINARY) {
|
|
2813
|
+
const answer = await prompter.text({
|
|
2814
|
+
message: `Binary name (default: ${defaultBin})`,
|
|
2815
|
+
defaultValue: defaultBin
|
|
2816
|
+
});
|
|
2817
|
+
bin = answer.trim() === "" ? defaultBin : answer.trim();
|
|
2818
|
+
}
|
|
2819
|
+
const presetDomains = [
|
|
2820
|
+
...new Set((preset?.commands ?? []).flatMap((command) => command.allowedUrlPrefixes ?? []))
|
|
2821
|
+
];
|
|
2822
|
+
const prefixAnswer = await readPrefixes(io, prompter, selected, presetDomains);
|
|
2823
|
+
if (prefixAnswer === null) return null;
|
|
2824
|
+
const prefixes = prefixAnswer.prefixes;
|
|
2825
|
+
const ttlPick = await prompter.select({
|
|
2826
|
+
message: "Lifetime in days",
|
|
2827
|
+
choices: MANDATE_TTL_CHOICES.map((days) => ({
|
|
2828
|
+
value: String(days),
|
|
2829
|
+
label: `${days} days`
|
|
2830
|
+
})),
|
|
2831
|
+
initialValue: String(AGENT_MANDATE_REQUEST_DEFAULT_TTL_DAYS)
|
|
2832
|
+
});
|
|
2833
|
+
if (ttlPick === null) return null;
|
|
2834
|
+
const ttlDays = Number.parseInt(ttlPick, 10);
|
|
2835
|
+
if (!Number.isInteger(ttlDays) || ttlDays < 1 || ttlDays > AGENT_MANDATE_REQUEST_MAX_TTL_DAYS) {
|
|
2836
|
+
throw new Error(
|
|
2837
|
+
`lifetime expects an integer between 1 and ${AGENT_MANDATE_REQUEST_MAX_TTL_DAYS} days`
|
|
2838
|
+
);
|
|
2839
|
+
}
|
|
2840
|
+
return {
|
|
2841
|
+
entries: selected.map((entry) => entry.id),
|
|
2842
|
+
bin,
|
|
2843
|
+
ttlDays,
|
|
2844
|
+
...prefixes === void 0 ? {} : { prefixes }
|
|
2845
|
+
};
|
|
2846
|
+
} catch (error) {
|
|
2847
|
+
if (error instanceof PromptCancelledError) return null;
|
|
2848
|
+
throw error;
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
async function menuMandate(env, io, prompter) {
|
|
2852
|
+
const configDir = env.VK_CONFIG_DIR?.trim() || void 0;
|
|
2853
|
+
let entries;
|
|
2854
|
+
try {
|
|
2855
|
+
entries = await listDelegatableEntries({ configDir, io });
|
|
2856
|
+
} catch (error) {
|
|
2857
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2858
|
+
io.err(`${palette(colorEnabled()).red("error")}: ${message}
|
|
2859
|
+
`);
|
|
2860
|
+
return 1;
|
|
2861
|
+
}
|
|
2862
|
+
if (entries.length === 0) {
|
|
2863
|
+
io.out("No entry can be delegated: the vault has no delegatable entry.\n");
|
|
2864
|
+
return 0;
|
|
2865
|
+
}
|
|
2866
|
+
const ordered = [...entries].sort((left, right) => {
|
|
2867
|
+
if (left.kind === right.kind) return left.label.localeCompare(right.label);
|
|
2868
|
+
return left.kind === "api" ? -1 : right.kind === "api" ? 1 : 0;
|
|
2869
|
+
});
|
|
2870
|
+
const form = await readMandateForm(io, prompter, ordered);
|
|
2871
|
+
if (form === null) {
|
|
2872
|
+
io.out("Nothing done.\n");
|
|
2873
|
+
return 0;
|
|
2874
|
+
}
|
|
2875
|
+
const code = await runAgentMandate({
|
|
2876
|
+
entries: form.entries,
|
|
2877
|
+
bin: form.bin,
|
|
2878
|
+
ttlDays: form.ttlDays,
|
|
2879
|
+
...form.prefixes === void 0 ? {} : { prefixes: form.prefixes },
|
|
2880
|
+
configDir,
|
|
2881
|
+
env,
|
|
2882
|
+
io
|
|
2883
|
+
});
|
|
2884
|
+
return reportAgentExit(io, code, "vaultkeepr-agent mandate");
|
|
2885
|
+
}
|
|
2886
|
+
function reportAgentExit(io, code, label) {
|
|
2887
|
+
if (code !== 0) {
|
|
2888
|
+
io.err(`${palette(colorEnabled()).red("error")}: ${label} exited with code ${code}
|
|
2889
|
+
`);
|
|
2890
|
+
}
|
|
2891
|
+
return code;
|
|
2892
|
+
}
|
|
2893
|
+
async function runMenuAction(action, env, io, prompter) {
|
|
2894
|
+
switch (action) {
|
|
2895
|
+
case "get": {
|
|
2896
|
+
const query = await prompter.text({ message: "Entry (ID, label, username or URL)" });
|
|
2897
|
+
if (query === "") {
|
|
2898
|
+
io.out("Nothing done.\n");
|
|
2899
|
+
return 0;
|
|
2900
|
+
}
|
|
2901
|
+
return await main(["get", query], env);
|
|
2902
|
+
}
|
|
2903
|
+
case "agent-mandate":
|
|
2904
|
+
return await menuMandate(env, io, prompter);
|
|
2905
|
+
case "agent-list":
|
|
2906
|
+
return reportAgentExit(
|
|
2907
|
+
io,
|
|
2908
|
+
await runAgentDispatch({ argv: ["list"], io, env }),
|
|
2909
|
+
"vaultkeepr-agent list"
|
|
2910
|
+
);
|
|
2911
|
+
default:
|
|
2912
|
+
return await main([action], env, { interactiveSession: true });
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
async function commandMenu(env, options = {}) {
|
|
2916
|
+
const colors = colorEnabled();
|
|
2917
|
+
const io = options.io ?? defaultIO;
|
|
2918
|
+
const prompter = options.prompter ?? clackPrompter();
|
|
2919
|
+
const runAction = options.runAction ?? ((action, active) => runMenuAction(action, env, io, active));
|
|
2920
|
+
io.out(renderBanner({ version: VERSION, colors, columns: process.stdout.columns }));
|
|
2921
|
+
io.out("\n");
|
|
2922
|
+
for (; ; ) {
|
|
2923
|
+
let action;
|
|
2924
|
+
try {
|
|
2925
|
+
action = await prompter.select({
|
|
2926
|
+
message: "What do you want to do?",
|
|
2927
|
+
choices: MENU_ACTIONS.map((entry) => ({
|
|
2928
|
+
value: entry.value,
|
|
2929
|
+
label: entry.label,
|
|
2930
|
+
hint: entry.hint
|
|
2931
|
+
}))
|
|
2932
|
+
});
|
|
2933
|
+
} catch (error) {
|
|
2934
|
+
if (error instanceof PromptCancelledError) {
|
|
2935
|
+
prompter.outro("Cancelled.");
|
|
2936
|
+
return 0;
|
|
2937
|
+
}
|
|
2938
|
+
throw error;
|
|
2939
|
+
}
|
|
2940
|
+
if (action === null || action === "quit") {
|
|
2941
|
+
prompter.outro("Nothing done.");
|
|
2942
|
+
return 0;
|
|
2943
|
+
}
|
|
2944
|
+
try {
|
|
2945
|
+
await runAction(action, prompter);
|
|
2946
|
+
} catch (error) {
|
|
2947
|
+
if (error instanceof PromptCancelledError) {
|
|
2948
|
+
prompter.outro("Cancelled.");
|
|
2949
|
+
return 0;
|
|
2950
|
+
}
|
|
2951
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2952
|
+
io.err(`${palette(colors).red("error")}: ${message}
|
|
2953
|
+
`);
|
|
2954
|
+
}
|
|
2955
|
+
io.out("\n");
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
var FLAGS = /* @__PURE__ */ new Set([
|
|
2959
|
+
"--json",
|
|
2960
|
+
"--reveal",
|
|
2961
|
+
"--offline",
|
|
2962
|
+
"--once",
|
|
2963
|
+
"--yes",
|
|
2964
|
+
"-h",
|
|
2965
|
+
"--help",
|
|
2966
|
+
"-v",
|
|
2967
|
+
"--version"
|
|
2968
|
+
]);
|
|
2969
|
+
var VALUED = /* @__PURE__ */ new Set(["--api", "--kind", "--title", "--url", "--username", "--note", "--interval"]);
|
|
2970
|
+
function parseArgs(argv) {
|
|
2971
|
+
const positional = [];
|
|
2972
|
+
const flags = /* @__PURE__ */ new Set();
|
|
2973
|
+
const values = /* @__PURE__ */ new Map();
|
|
2974
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2975
|
+
const arg = argv[i];
|
|
2976
|
+
if (FLAGS.has(arg)) {
|
|
2977
|
+
flags.add(arg);
|
|
2978
|
+
continue;
|
|
2979
|
+
}
|
|
2980
|
+
const [name, inlineValue] = arg.includes("=") ? arg.split(/=(.*)/s, 2) : [arg, void 0];
|
|
2981
|
+
if (VALUED.has(name)) {
|
|
2982
|
+
const value = inlineValue ?? argv[i + 1];
|
|
2983
|
+
if (typeof value !== "string" || value.startsWith("--")) {
|
|
2984
|
+
return { positional, flags, values, error: `${name} expects a value` };
|
|
2985
|
+
}
|
|
2986
|
+
values.set(name, value);
|
|
2987
|
+
if (inlineValue === void 0) i++;
|
|
2988
|
+
continue;
|
|
2989
|
+
}
|
|
2990
|
+
if (arg.startsWith("-")) {
|
|
2991
|
+
return { positional, flags, values, error: `unknown option: ${arg}` };
|
|
2992
|
+
}
|
|
2993
|
+
positional.push(arg);
|
|
2994
|
+
}
|
|
2995
|
+
return { positional, flags, values };
|
|
2996
|
+
}
|
|
2997
|
+
function parseIntervalSeconds(raw) {
|
|
2998
|
+
if (raw === void 0) return 15;
|
|
2999
|
+
if (!/^[0-9]+$/.test(raw)) return null;
|
|
3000
|
+
const seconds = Number.parseInt(raw, 10);
|
|
3001
|
+
return seconds > 0 ? seconds : null;
|
|
3002
|
+
}
|
|
3003
|
+
function fieldsFromFlags(values) {
|
|
3004
|
+
const fields = {};
|
|
3005
|
+
const title = values.get("--title");
|
|
3006
|
+
const url = values.get("--url");
|
|
3007
|
+
const username = values.get("--username");
|
|
3008
|
+
const note = values.get("--note");
|
|
3009
|
+
if (title !== void 0) fields.title = title;
|
|
3010
|
+
if (url !== void 0) fields.url = url;
|
|
3011
|
+
if (username !== void 0) fields.username = username;
|
|
3012
|
+
if (note !== void 0) fields.notes = note;
|
|
3013
|
+
return fields;
|
|
3014
|
+
}
|
|
3015
|
+
var MANDATE_VALUED = /* @__PURE__ */ new Set(["--bin", "--ttl-days", "--prefixes", "--api"]);
|
|
3016
|
+
var MANDATE_FLAGS = /* @__PURE__ */ new Set(["--offline"]);
|
|
3017
|
+
function parseMandateArgs(argv) {
|
|
3018
|
+
const entries = [];
|
|
3019
|
+
const values = /* @__PURE__ */ new Map();
|
|
3020
|
+
const flags = /* @__PURE__ */ new Set();
|
|
3021
|
+
for (let i = 0; i < argv.length; i++) {
|
|
3022
|
+
const arg = argv[i];
|
|
3023
|
+
if (arg === "-h" || arg === "--help") return { entries, values, flags, help: true };
|
|
3024
|
+
if (MANDATE_FLAGS.has(arg)) {
|
|
3025
|
+
flags.add(arg);
|
|
3026
|
+
continue;
|
|
3027
|
+
}
|
|
3028
|
+
const [name, inlineValue] = arg.includes("=") ? arg.split(/=(.*)/s, 2) : [arg, void 0];
|
|
3029
|
+
if (name === "--entry" || MANDATE_VALUED.has(name)) {
|
|
3030
|
+
const value = inlineValue ?? argv[i + 1];
|
|
3031
|
+
if (typeof value !== "string" || value === "" || value.startsWith("--")) {
|
|
3032
|
+
return { entries, values, flags, error: `${name} expects a value` };
|
|
3033
|
+
}
|
|
3034
|
+
if (name === "--entry") entries.push(value);
|
|
3035
|
+
else values.set(name, value);
|
|
3036
|
+
if (inlineValue === void 0) i++;
|
|
3037
|
+
continue;
|
|
3038
|
+
}
|
|
3039
|
+
return { entries, values, flags, error: `unknown option: ${arg}` };
|
|
3040
|
+
}
|
|
3041
|
+
return { entries, values, flags };
|
|
3042
|
+
}
|
|
3043
|
+
function parsePositiveInt(raw) {
|
|
3044
|
+
if (raw === void 0) return void 0;
|
|
3045
|
+
if (!/^[0-9]+$/.test(raw)) return null;
|
|
3046
|
+
const parsed = Number.parseInt(raw, 10);
|
|
3047
|
+
return parsed > 0 ? parsed : null;
|
|
3048
|
+
}
|
|
3049
|
+
async function main(argv, env = process.env, options = {}) {
|
|
3050
|
+
const command = argv[0];
|
|
3051
|
+
if (!command) {
|
|
3052
|
+
if (interactiveTTY()) return await commandMenu(env);
|
|
3053
|
+
process.stdout.write(USAGE);
|
|
3054
|
+
return 1;
|
|
3055
|
+
}
|
|
3056
|
+
if (command === "-h" || command === "--help" || command === "help") {
|
|
3057
|
+
process.stdout.write(USAGE);
|
|
3058
|
+
return 0;
|
|
3059
|
+
}
|
|
3060
|
+
if (command === "-v" || command === "--version" || command === "version") {
|
|
3061
|
+
process.stdout.write(`vaultkeepr ${VERSION}
|
|
3062
|
+
`);
|
|
3063
|
+
return 0;
|
|
3064
|
+
}
|
|
3065
|
+
const configDir = env.VK_CONFIG_DIR?.trim() || void 0;
|
|
3066
|
+
if (command === "agent") {
|
|
3067
|
+
const subcommand = argv[1];
|
|
3068
|
+
if (subcommand !== "mandate") {
|
|
3069
|
+
return await runAgentDispatch({ argv: argv.slice(1), io: defaultIO, env });
|
|
3070
|
+
}
|
|
3071
|
+
const parsedMandate = parseMandateArgs(argv.slice(2));
|
|
3072
|
+
if (parsedMandate.help) {
|
|
3073
|
+
const { agentUsage } = await import("./agent-OVSW5GMB.js");
|
|
3074
|
+
process.stdout.write(agentUsage());
|
|
3075
|
+
return 0;
|
|
3076
|
+
}
|
|
3077
|
+
if (parsedMandate.error) {
|
|
3078
|
+
process.stderr.write(`error: ${parsedMandate.error}
|
|
3079
|
+
`);
|
|
3080
|
+
return 2;
|
|
3081
|
+
}
|
|
3082
|
+
const ttlDays = parsePositiveInt(parsedMandate.values.get("--ttl-days"));
|
|
3083
|
+
if (ttlDays === null) {
|
|
3084
|
+
process.stderr.write("error: --ttl-days expects a positive number of days\n");
|
|
3085
|
+
return 2;
|
|
3086
|
+
}
|
|
3087
|
+
return await runAgentMandate({
|
|
3088
|
+
entries: parsedMandate.entries,
|
|
3089
|
+
bin: parsedMandate.values.get("--bin") ?? "",
|
|
3090
|
+
ttlDays,
|
|
3091
|
+
prefixes: parsedMandate.values.get("--prefixes"),
|
|
3092
|
+
apiBase: parsedMandate.values.get("--api"),
|
|
3093
|
+
offline: parsedMandate.flags.has("--offline"),
|
|
3094
|
+
configDir,
|
|
3095
|
+
env
|
|
3096
|
+
});
|
|
3097
|
+
}
|
|
3098
|
+
const parsed = parseArgs(argv.slice(1));
|
|
3099
|
+
if (parsed.error) {
|
|
3100
|
+
process.stderr.write(`error: ${parsed.error}
|
|
3101
|
+
|
|
3102
|
+
${USAGE}`);
|
|
3103
|
+
return 2;
|
|
3104
|
+
}
|
|
3105
|
+
if (parsed.flags.has("-h") || parsed.flags.has("--help")) {
|
|
3106
|
+
process.stdout.write(USAGE);
|
|
3107
|
+
return 0;
|
|
3108
|
+
}
|
|
3109
|
+
switch (command) {
|
|
3110
|
+
case "pair": {
|
|
3111
|
+
if (parsed.positional.length > 0) {
|
|
3112
|
+
process.stderr.write(`error: unexpected argument: ${parsed.positional[0]}
|
|
3113
|
+
`);
|
|
3114
|
+
return 2;
|
|
3115
|
+
}
|
|
3116
|
+
return await runPair({
|
|
3117
|
+
apiBase: parsed.values.get("--api"),
|
|
3118
|
+
configDir
|
|
3119
|
+
});
|
|
3120
|
+
}
|
|
3121
|
+
case "list": {
|
|
3122
|
+
if (parsed.positional.length > 0) {
|
|
3123
|
+
process.stderr.write(`error: unexpected argument: ${parsed.positional[0]}
|
|
3124
|
+
`);
|
|
3125
|
+
return 2;
|
|
3126
|
+
}
|
|
3127
|
+
return await runList({
|
|
3128
|
+
kind: parsed.values.get("--kind"),
|
|
3129
|
+
json: parsed.flags.has("--json"),
|
|
3130
|
+
offline: parsed.flags.has("--offline"),
|
|
3131
|
+
configDir
|
|
3132
|
+
});
|
|
3133
|
+
}
|
|
3134
|
+
case "get": {
|
|
3135
|
+
if (parsed.positional.length !== 1) {
|
|
3136
|
+
process.stderr.write("error: get expects an entry (name or ID)\n");
|
|
3137
|
+
return 2;
|
|
3138
|
+
}
|
|
3139
|
+
return await runGet({
|
|
3140
|
+
query: parsed.positional[0],
|
|
3141
|
+
reveal: parsed.flags.has("--reveal"),
|
|
3142
|
+
json: parsed.flags.has("--json"),
|
|
3143
|
+
offline: parsed.flags.has("--offline"),
|
|
3144
|
+
configDir
|
|
3145
|
+
});
|
|
3146
|
+
}
|
|
3147
|
+
case "add": {
|
|
3148
|
+
if (parsed.positional.length > 0) {
|
|
3149
|
+
process.stderr.write(`error: unexpected argument: ${parsed.positional[0]}
|
|
3150
|
+
`);
|
|
3151
|
+
return 2;
|
|
3152
|
+
}
|
|
3153
|
+
const kind = parsed.values.get("--kind");
|
|
3154
|
+
if (!kind) {
|
|
3155
|
+
if (!interactiveTTY()) {
|
|
3156
|
+
process.stderr.write(`error: add expects --kind <${ENTRY_KINDS.join("|")}>
|
|
3157
|
+
`);
|
|
3158
|
+
return 2;
|
|
3159
|
+
}
|
|
3160
|
+
const chosen = await clackPrompter().select({
|
|
3161
|
+
message: "Entry type",
|
|
3162
|
+
choices: ENTRY_KINDS.filter((candidate) => candidate !== "passkey").map((candidate) => ({
|
|
3163
|
+
value: candidate,
|
|
3164
|
+
label: KIND_LABELS[candidate]
|
|
3165
|
+
}))
|
|
3166
|
+
});
|
|
3167
|
+
if (chosen === null) {
|
|
3168
|
+
if (options.interactiveSession) throw new PromptCancelledError();
|
|
3169
|
+
process.stderr.write("error: cancelled\n");
|
|
3170
|
+
return 1;
|
|
3171
|
+
}
|
|
3172
|
+
if (!isEntryKind(chosen)) {
|
|
3173
|
+
process.stderr.write(`error: add expects --kind <${ENTRY_KINDS.join("|")}>
|
|
3174
|
+
`);
|
|
3175
|
+
return 2;
|
|
3176
|
+
}
|
|
3177
|
+
return await runAdd({
|
|
3178
|
+
kind: chosen,
|
|
3179
|
+
fields: fieldsFromFlags(parsed.values),
|
|
3180
|
+
offline: parsed.flags.has("--offline"),
|
|
3181
|
+
configDir,
|
|
3182
|
+
propagateCancel: options.interactiveSession === true
|
|
3183
|
+
});
|
|
3184
|
+
}
|
|
3185
|
+
return await runAdd({
|
|
3186
|
+
kind,
|
|
3187
|
+
fields: fieldsFromFlags(parsed.values),
|
|
3188
|
+
offline: parsed.flags.has("--offline"),
|
|
3189
|
+
configDir,
|
|
3190
|
+
propagateCancel: options.interactiveSession === true
|
|
3191
|
+
});
|
|
3192
|
+
}
|
|
3193
|
+
case "edit": {
|
|
3194
|
+
if (parsed.positional.length !== 1) {
|
|
3195
|
+
process.stderr.write("error: edit expects one entry (name or ID)\n");
|
|
3196
|
+
return 2;
|
|
3197
|
+
}
|
|
3198
|
+
return await runEdit({
|
|
3199
|
+
query: parsed.positional[0],
|
|
3200
|
+
fields: fieldsFromFlags(parsed.values),
|
|
3201
|
+
offline: parsed.flags.has("--offline"),
|
|
3202
|
+
configDir
|
|
3203
|
+
});
|
|
3204
|
+
}
|
|
3205
|
+
case "delete": {
|
|
3206
|
+
if (parsed.positional.length !== 1) {
|
|
3207
|
+
process.stderr.write("error: delete expects one entry (name or ID)\n");
|
|
3208
|
+
return 2;
|
|
3209
|
+
}
|
|
3210
|
+
return await runDelete({
|
|
3211
|
+
query: parsed.positional[0],
|
|
3212
|
+
yes: parsed.flags.has("--yes"),
|
|
3213
|
+
offline: parsed.flags.has("--offline"),
|
|
3214
|
+
configDir
|
|
3215
|
+
});
|
|
3216
|
+
}
|
|
3217
|
+
case "status": {
|
|
3218
|
+
if (parsed.positional.length > 0) {
|
|
3219
|
+
process.stderr.write(`error: unexpected argument: ${parsed.positional[0]}
|
|
3220
|
+
`);
|
|
3221
|
+
return 2;
|
|
3222
|
+
}
|
|
3223
|
+
return await runStatus({
|
|
3224
|
+
json: parsed.flags.has("--json"),
|
|
3225
|
+
offline: parsed.flags.has("--offline"),
|
|
3226
|
+
configDir
|
|
3227
|
+
});
|
|
3228
|
+
}
|
|
3229
|
+
case "sync": {
|
|
3230
|
+
if (parsed.positional.length > 0) {
|
|
3231
|
+
process.stderr.write(`error: unexpected argument: ${parsed.positional[0]}
|
|
3232
|
+
`);
|
|
3233
|
+
return 2;
|
|
3234
|
+
}
|
|
3235
|
+
const intervalSeconds = parseIntervalSeconds(parsed.values.get("--interval"));
|
|
3236
|
+
if (intervalSeconds === null) {
|
|
3237
|
+
process.stderr.write("error: --interval expects a positive number of seconds\n");
|
|
3238
|
+
return 2;
|
|
3239
|
+
}
|
|
3240
|
+
return await runSync({
|
|
3241
|
+
intervalSeconds,
|
|
3242
|
+
once: parsed.flags.has("--once"),
|
|
3243
|
+
configDir
|
|
3244
|
+
});
|
|
3245
|
+
}
|
|
3246
|
+
case "completions": {
|
|
3247
|
+
if (parsed.positional.length !== 1) {
|
|
3248
|
+
process.stderr.write("error: completions expects bash or zsh\n");
|
|
3249
|
+
return 2;
|
|
3250
|
+
}
|
|
3251
|
+
return await runCompletions({ shell: parsed.positional[0] });
|
|
3252
|
+
}
|
|
3253
|
+
default:
|
|
3254
|
+
process.stderr.write(`error: unknown command: ${command}
|
|
3255
|
+
|
|
3256
|
+
${USAGE}`);
|
|
3257
|
+
return 2;
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
|
|
3261
|
+
export {
|
|
3262
|
+
CONFIG_DIR_ENV,
|
|
3263
|
+
CONFIG_DIR_NAME,
|
|
3264
|
+
LEGACY_CONFIG_DIR_NAME,
|
|
3265
|
+
migrateLegacyConfigDir,
|
|
3266
|
+
vaultkeeprConfigDir,
|
|
3267
|
+
configPaths,
|
|
3268
|
+
ensurePrivateDir,
|
|
3269
|
+
identityFromPairPayload,
|
|
3270
|
+
accountForIdentity,
|
|
3271
|
+
payloadKeyMaterial,
|
|
3272
|
+
parseIdentity,
|
|
3273
|
+
saveIdentity,
|
|
3274
|
+
loadIdentity,
|
|
3275
|
+
derivePayloadKey,
|
|
3276
|
+
sealVaultPayload,
|
|
3277
|
+
openVaultPayload,
|
|
3278
|
+
ENTRY_KINDS,
|
|
3279
|
+
isEntryKind,
|
|
3280
|
+
entryKind,
|
|
3281
|
+
KIND_LABELS,
|
|
3282
|
+
entryLabel,
|
|
3283
|
+
entrySecret,
|
|
3284
|
+
filterByKind,
|
|
3285
|
+
findEntry,
|
|
3286
|
+
FORM_FIELDS,
|
|
3287
|
+
buildEntry,
|
|
3288
|
+
formValuesFromEntry,
|
|
3289
|
+
formHintForField,
|
|
3290
|
+
updateEntryFromValues,
|
|
3291
|
+
VAULT_SUMMARY_FILENAME,
|
|
3292
|
+
vaultSummaryPath,
|
|
3293
|
+
buildVaultSummary,
|
|
3294
|
+
writeVaultSummary,
|
|
3295
|
+
emptyVault,
|
|
3296
|
+
saveLocalVault,
|
|
3297
|
+
loadLocalVault,
|
|
3298
|
+
emptySyncState,
|
|
3299
|
+
loadSyncState,
|
|
3300
|
+
saveSyncState,
|
|
3301
|
+
pullMerge,
|
|
3302
|
+
publishVault,
|
|
3303
|
+
syncOnce,
|
|
3304
|
+
runSyncLoop,
|
|
3305
|
+
DEFAULT_API_BASE,
|
|
3306
|
+
createPairTransport,
|
|
3307
|
+
openPairPayload,
|
|
3308
|
+
newPairKeypair,
|
|
3309
|
+
pairUri,
|
|
3310
|
+
formatProofMessage,
|
|
3311
|
+
CID_UPDATE_PREFIX,
|
|
3312
|
+
createHttpSyncTransport,
|
|
3313
|
+
clipboardCandidates,
|
|
3314
|
+
copyToClipboard,
|
|
3315
|
+
redactAddress,
|
|
3316
|
+
redactCid,
|
|
3317
|
+
formatWhen,
|
|
3318
|
+
formatDate,
|
|
3319
|
+
VERSION,
|
|
3320
|
+
ACCENT_CORAL,
|
|
3321
|
+
WORDMARK,
|
|
3322
|
+
WORDMARK_WIDTH,
|
|
3323
|
+
MIN_FULL_BANNER_COLUMNS,
|
|
3324
|
+
APP_SLOGAN,
|
|
3325
|
+
renderCompactHeader,
|
|
3326
|
+
renderBanner,
|
|
3327
|
+
renderMiniHeader,
|
|
3328
|
+
defaultIO,
|
|
3329
|
+
palette,
|
|
3330
|
+
colorEnabled,
|
|
3331
|
+
formatTable,
|
|
3332
|
+
Spinner,
|
|
3333
|
+
ask,
|
|
3334
|
+
PromptCancelledError,
|
|
3335
|
+
clackPrompter,
|
|
3336
|
+
plainPrompter,
|
|
3337
|
+
interactiveTTY,
|
|
3338
|
+
runList,
|
|
3339
|
+
runGet,
|
|
3340
|
+
runAdd,
|
|
3341
|
+
runEdit,
|
|
3342
|
+
runDelete,
|
|
3343
|
+
listDelegatableEntries,
|
|
3344
|
+
runAgentMandate,
|
|
3345
|
+
runStatus,
|
|
3346
|
+
runSync,
|
|
3347
|
+
completionScript,
|
|
3348
|
+
runCompletions,
|
|
3349
|
+
QR_QUIET_ZONE,
|
|
3350
|
+
renderQr,
|
|
3351
|
+
renderTerminalQr,
|
|
3352
|
+
runPair,
|
|
3353
|
+
USAGE,
|
|
3354
|
+
MENU_ACTIONS,
|
|
3355
|
+
commandMenu,
|
|
3356
|
+
parseArgs,
|
|
3357
|
+
main
|
|
3358
|
+
};
|