dsh-workbench-vault 0.0.0-stage → 0.3.7
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/LICENSE +21 -0
- package/README.md +26 -2
- package/cordis.patch.yml +6 -0
- package/lib/client.js +4806 -0
- package/lib/db/db.js +401 -0
- package/lib/domain/actions-sets.js +271 -0
- package/lib/domain/actions.js +532 -0
- package/lib/domain/groups.js +301 -0
- package/lib/domain/migrate.js +128 -0
- package/lib/domain/secret-input.js +33 -0
- package/lib/domain/sets.js +303 -0
- package/lib/domain/vault.js +589 -0
- package/lib/index.js +165 -0
- package/lib/infra/crypto.js +79 -0
- package/package.json +116 -4
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 保险箱核心:KDF 包裹 DEK、DEK 加密 secret,DEK 只在内存。
|
|
3
|
+
* 0.2.0:口令包裹存单行 vault_header(随云同步),device key 与使用记录留本机。
|
|
4
|
+
* A/B/C 三种 unlock_mode 共用同一套表;切换失败保持原模式。
|
|
5
|
+
*/
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
import {
|
|
8
|
+
KDF_DEFAULT,
|
|
9
|
+
deriveKey,
|
|
10
|
+
open,
|
|
11
|
+
readDeviceKey,
|
|
12
|
+
removeDeviceKey,
|
|
13
|
+
seal,
|
|
14
|
+
secretAad,
|
|
15
|
+
writeDeviceKey,
|
|
16
|
+
} from "../infra/crypto.js";
|
|
17
|
+
import {
|
|
18
|
+
SCHEMA_VERSION,
|
|
19
|
+
deviceGet,
|
|
20
|
+
deviceSet,
|
|
21
|
+
headerGet,
|
|
22
|
+
headerSet,
|
|
23
|
+
newId,
|
|
24
|
+
now,
|
|
25
|
+
secretRow,
|
|
26
|
+
touchUsage,
|
|
27
|
+
tx,
|
|
28
|
+
usageMap,
|
|
29
|
+
} from "../db/db.js";
|
|
30
|
+
import { createSets } from "./sets.js";
|
|
31
|
+
import { migrateToV3 } from "./migrate.js";
|
|
32
|
+
import { assertKind, assertMeta, assertSecretName } from "./secret-input.js";
|
|
33
|
+
|
|
34
|
+
const MODES = new Set(["A", "B", "C"]);
|
|
35
|
+
const SYNC_NOTE =
|
|
36
|
+
"vault_header(口令包裹)与 vault_secret/vault_group/vault_binding 的结构和密文会随云同步上传;" +
|
|
37
|
+
"device key 与 last_used_at 只留本机。";
|
|
38
|
+
|
|
39
|
+
function parseKdf(raw) {
|
|
40
|
+
try {
|
|
41
|
+
const value = JSON.parse(String(raw || "{}"));
|
|
42
|
+
return { ...KDF_DEFAULT, ...value };
|
|
43
|
+
} catch {
|
|
44
|
+
return { ...KDF_DEFAULT };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parseJson(raw, fallback) {
|
|
49
|
+
try {
|
|
50
|
+
return JSON.parse(String(raw));
|
|
51
|
+
} catch {
|
|
52
|
+
return fallback;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function validateMode(mode) {
|
|
57
|
+
const value = String(mode || "").toUpperCase();
|
|
58
|
+
if (!MODES.has(value)) throw new Error("unlockMode 必须是 A/B/C");
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function assertPassphrase(passphrase) {
|
|
63
|
+
const value = String(passphrase || "");
|
|
64
|
+
if (value.length < 12) throw new Error("口令至少 12 个字符");
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function createVault({ db, log = () => {} }) {
|
|
69
|
+
const sets = createSets({ db });
|
|
70
|
+
const state = {
|
|
71
|
+
dek: null,
|
|
72
|
+
lastActivity: 0,
|
|
73
|
+
failures: 0,
|
|
74
|
+
lockUntil: 0,
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
function initialized() {
|
|
78
|
+
return Boolean(headerGet(db));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function touch() {
|
|
82
|
+
if (!state.dek) return;
|
|
83
|
+
const device = deviceGet(db);
|
|
84
|
+
const idle = Number((device && device.idle_timeout_sec) || 900);
|
|
85
|
+
if (idle > 0 && state.lastActivity && now() - state.lastActivity > idle * 1000) {
|
|
86
|
+
lock();
|
|
87
|
+
throw new Error("保险箱已因空闲锁定");
|
|
88
|
+
}
|
|
89
|
+
state.lastActivity = now();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function lock() {
|
|
93
|
+
state.dek = null;
|
|
94
|
+
state.lastActivity = 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function requireUnlocked() {
|
|
98
|
+
touch();
|
|
99
|
+
if (!state.dek) throw new Error("保险箱已锁定,请先解锁");
|
|
100
|
+
return state.dek;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function checkPassphrase(passphrase) {
|
|
104
|
+
const head = headerGet(db);
|
|
105
|
+
if (!head) throw new Error("保险箱未初始化");
|
|
106
|
+
try {
|
|
107
|
+
const kek = deriveKey(String(passphrase || ""), head.salt, parseKdf(head.kdf));
|
|
108
|
+
open(kek, head.wrapped_dek, "vault:dek");
|
|
109
|
+
return true;
|
|
110
|
+
} catch {
|
|
111
|
+
throw new Error("口令错误");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function groupExists(groupId) {
|
|
116
|
+
if (!groupId) return true;
|
|
117
|
+
return Boolean(db.prepare("SELECT 1 FROM vault_group WHERE id = ? AND deleted_at IS NULL").get(String(groupId)));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function tryAutoUnlock() {
|
|
121
|
+
if (state.dek || !initialized()) return false;
|
|
122
|
+
const device = deviceGet(db);
|
|
123
|
+
if (!device || Number(device.auto_unlock) !== 1) return false;
|
|
124
|
+
if (device.unlock_mode !== "B" && device.unlock_mode !== "C") return false;
|
|
125
|
+
const deviceKey = readDeviceKey();
|
|
126
|
+
if (!device.wrapped_dek_device || !deviceKey) return false;
|
|
127
|
+
const head = headerGet(db);
|
|
128
|
+
try {
|
|
129
|
+
state.dek = open(deviceKey, device.wrapped_dek_device, "vault:device");
|
|
130
|
+
state.lastActivity = now();
|
|
131
|
+
deviceSet(db, { last_unlock_at: now(), passphrase_rev_seen: head.passphrase_rev });
|
|
132
|
+
return true;
|
|
133
|
+
} catch (error) {
|
|
134
|
+
log("自动解锁失败", String(error && error.message));
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 解锁后检查 schema_version:2 → 3 一次性迁移;失败回滚并保持 2。 */
|
|
140
|
+
function runMigration() {
|
|
141
|
+
const head = headerGet(db);
|
|
142
|
+
if (!head || Number(head.schema_version || 0) >= SCHEMA_VERSION) return "";
|
|
143
|
+
try {
|
|
144
|
+
const result = migrateToV3({ db, dek: state.dek, log });
|
|
145
|
+
return result.migrated ? "保险箱已升级到集合层(schema 3)。" : "";
|
|
146
|
+
} catch (error) {
|
|
147
|
+
log("保险箱迁移失败,已回滚", String(error && error.message));
|
|
148
|
+
return "保险箱升级失败,已回滚;下次解锁会重试。";
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function status() {
|
|
153
|
+
if (initialized()) {
|
|
154
|
+
tryAutoUnlock();
|
|
155
|
+
if (state.dek) {
|
|
156
|
+
try {
|
|
157
|
+
touch();
|
|
158
|
+
} catch {
|
|
159
|
+
/* 空闲锁定由 touch 处理,status 只回报 */
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const head = headerGet(db);
|
|
164
|
+
const device = deviceGet(db) || {};
|
|
165
|
+
const count = initialized()
|
|
166
|
+
? Number(db.prepare("SELECT COUNT(*) AS n FROM vault_secret WHERE deleted_at IS NULL").get()?.n || 0)
|
|
167
|
+
: 0;
|
|
168
|
+
const groupCount = initialized()
|
|
169
|
+
? Number(db.prepare("SELECT COUNT(*) AS n FROM vault_group WHERE deleted_at IS NULL").get()?.n || 0)
|
|
170
|
+
: 0;
|
|
171
|
+
return {
|
|
172
|
+
initialized: initialized(),
|
|
173
|
+
locked: !state.dek,
|
|
174
|
+
unlockMode: device.unlock_mode || "A",
|
|
175
|
+
revealPolicy: device.reveal_policy || "session",
|
|
176
|
+
autoUnlock: Number(device.auto_unlock) === 1,
|
|
177
|
+
idleTimeoutSec: Number(device.idle_timeout_sec || 900),
|
|
178
|
+
secretCount: count,
|
|
179
|
+
groupCount,
|
|
180
|
+
lastUnlockAt: Number(device.last_unlock_at || 0) || null,
|
|
181
|
+
passphraseRev: head ? Number(head.passphrase_rev || 1) : 0,
|
|
182
|
+
schemaVersion: head ? Number(head.schema_version || 2) : 0,
|
|
183
|
+
cloudSync: true,
|
|
184
|
+
syncNote: SYNC_NOTE,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function setup(args = {}) {
|
|
189
|
+
if (initialized()) throw new Error("保险箱已初始化");
|
|
190
|
+
const passphrase = assertPassphrase(args.passphrase);
|
|
191
|
+
const mode = validateMode(args.mode || "A");
|
|
192
|
+
const salt = randomBytes(16);
|
|
193
|
+
const dek = randomBytes(32);
|
|
194
|
+
const kdf = { ...KDF_DEFAULT };
|
|
195
|
+
const kek = deriveKey(passphrase, salt.toString("base64"), kdf);
|
|
196
|
+
const wrapped = seal(kek, dek, "vault:dek");
|
|
197
|
+
const ts = now();
|
|
198
|
+
const deviceKey = mode === "A" ? null : randomBytes(32);
|
|
199
|
+
const wrappedDevice = deviceKey ? seal(deviceKey, dek, "vault:device") : null;
|
|
200
|
+
|
|
201
|
+
tx(db, () => {
|
|
202
|
+
headerSet(db, {
|
|
203
|
+
schema_version: SCHEMA_VERSION,
|
|
204
|
+
salt: salt.toString("base64"),
|
|
205
|
+
kdf: JSON.stringify(kdf),
|
|
206
|
+
wrapped_dek: wrapped,
|
|
207
|
+
passphrase_rev: 1,
|
|
208
|
+
created_at: ts,
|
|
209
|
+
});
|
|
210
|
+
deviceSet(db, {
|
|
211
|
+
wrapped_dek_device: wrappedDevice,
|
|
212
|
+
unlock_mode: mode,
|
|
213
|
+
auto_unlock: mode === "A" ? 0 : 1,
|
|
214
|
+
reveal_policy: mode === "B" ? "passphrase" : "session",
|
|
215
|
+
idle_timeout_sec: 900,
|
|
216
|
+
last_unlock_at: ts,
|
|
217
|
+
passphrase_rev_seen: 1,
|
|
218
|
+
created_at: ts,
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
if (deviceKey) writeDeviceKey(deviceKey);
|
|
222
|
+
state.dek = dek;
|
|
223
|
+
state.lastActivity = ts;
|
|
224
|
+
return { ok: true, unlockMode: mode, cloudSync: true, syncNote: SYNC_NOTE };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function unlock(args = {}) {
|
|
228
|
+
if (!initialized()) throw new Error("保险箱未初始化");
|
|
229
|
+
if (state.dek) {
|
|
230
|
+
state.lastActivity = now();
|
|
231
|
+
return { ok: true };
|
|
232
|
+
}
|
|
233
|
+
if (state.lockUntil > now()) {
|
|
234
|
+
const left = Math.ceil((state.lockUntil - now()) / 1000);
|
|
235
|
+
throw new Error("口令错误次数过多,请 " + left + " 秒后重试");
|
|
236
|
+
}
|
|
237
|
+
const passphrase = String(args.passphrase || "");
|
|
238
|
+
const head = headerGet(db);
|
|
239
|
+
const device = deviceGet(db) || { passphrase_rev_seen: head.passphrase_rev };
|
|
240
|
+
try {
|
|
241
|
+
const kek = deriveKey(passphrase, head.salt, parseKdf(head.kdf));
|
|
242
|
+
state.dek = open(kek, head.wrapped_dek, "vault:dek");
|
|
243
|
+
state.failures = 0;
|
|
244
|
+
state.lastActivity = now();
|
|
245
|
+
deviceSet(db, { last_unlock_at: now(), passphrase_rev_seen: head.passphrase_rev });
|
|
246
|
+
const notice = runMigration();
|
|
247
|
+
if (Number(head.passphrase_rev) > Number(device.passphrase_rev_seen || 0)) {
|
|
248
|
+
return { ok: true, notice: "口令已在其他设备修改,本机已采用新口令。" + (notice ? " " + notice : "") };
|
|
249
|
+
}
|
|
250
|
+
return notice ? { ok: true, notice } : { ok: true };
|
|
251
|
+
} catch (error) {
|
|
252
|
+
state.failures += 1;
|
|
253
|
+
if (state.failures >= 5) {
|
|
254
|
+
state.failures = 0;
|
|
255
|
+
state.lockUntil = now() + 5 * 60 * 1000;
|
|
256
|
+
}
|
|
257
|
+
if (Number(head.passphrase_rev) > Number(device.passphrase_rev_seen || 0)) {
|
|
258
|
+
throw new Error("口令已在其他设备修改,请使用新口令");
|
|
259
|
+
}
|
|
260
|
+
throw new Error("口令错误");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function listSecrets(args = {}) {
|
|
265
|
+
const q = String(args.q || "").trim();
|
|
266
|
+
const kind = String(args.kind || "").trim();
|
|
267
|
+
const groupId = args.groupId == null ? "" : String(args.groupId);
|
|
268
|
+
// 谓词自带表别名前缀:历史实现事后给每个谓词拼 "s.",带括号的 OR 条件会被拼成
|
|
269
|
+
// "s.(name LIKE ? OR meta LIKE ?)" 而报 SQLite 语法错误(搜索框一输入就失败)。
|
|
270
|
+
const where = ["s.deleted_at IS NULL"];
|
|
271
|
+
const params = [];
|
|
272
|
+
if (q) {
|
|
273
|
+
where.push("(s.name LIKE ? OR s.meta LIKE ?)");
|
|
274
|
+
params.push("%" + q + "%", "%" + q + "%");
|
|
275
|
+
}
|
|
276
|
+
if (kind) {
|
|
277
|
+
where.push("s.kind = ?");
|
|
278
|
+
params.push(kind);
|
|
279
|
+
}
|
|
280
|
+
const setId = args.setId == null ? "" : String(args.setId);
|
|
281
|
+
let join = "";
|
|
282
|
+
if (groupId) {
|
|
283
|
+
join =
|
|
284
|
+
"JOIN vault_set_secret ss_g ON ss_g.secret_id = s.id AND ss_g.deleted_at IS NULL " +
|
|
285
|
+
"JOIN vault_group_set gs_g ON gs_g.set_id = ss_g.set_id AND gs_g.deleted_at IS NULL AND gs_g.group_id = ? ";
|
|
286
|
+
params.unshift(groupId);
|
|
287
|
+
} else if (setId) {
|
|
288
|
+
join =
|
|
289
|
+
"JOIN vault_set_secret ss_s ON ss_s.secret_id = s.id AND ss_s.deleted_at IS NULL AND ss_s.set_id = ? ";
|
|
290
|
+
params.unshift(setId);
|
|
291
|
+
}
|
|
292
|
+
const rows = db
|
|
293
|
+
.prepare(
|
|
294
|
+
"SELECT DISTINCT s.* FROM vault_secret s " + join + "WHERE " + where.join(" AND ") +
|
|
295
|
+
" ORDER BY s.updated_at DESC",
|
|
296
|
+
)
|
|
297
|
+
.all(...params);
|
|
298
|
+
const usage = usageMap(db);
|
|
299
|
+
return {
|
|
300
|
+
items: rows.map((row) => ({
|
|
301
|
+
...secretRow(row, usage),
|
|
302
|
+
meta: parseJson(row.meta, {}),
|
|
303
|
+
setIds: sets.setIdsOfSecret(row.id),
|
|
304
|
+
})),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function createSecret(args = {}) {
|
|
309
|
+
const dek = requireUnlocked();
|
|
310
|
+
const name = assertSecretName(args.name);
|
|
311
|
+
const kind = assertKind(args.kind);
|
|
312
|
+
const secret = String(args.secret ?? "");
|
|
313
|
+
if (!secret) throw new Error("secret 不能为空");
|
|
314
|
+
const meta = assertMeta(args.meta);
|
|
315
|
+
const groupId = args.groupId == null || args.groupId === "" ? null : String(args.groupId);
|
|
316
|
+
if (!groupExists(groupId)) throw new Error("分组不存在:" + groupId);
|
|
317
|
+
const id = newId("sec");
|
|
318
|
+
const ts = now();
|
|
319
|
+
const ciphertext = seal(dek, secret, secretAad(id, name, kind));
|
|
320
|
+
let setRow = null;
|
|
321
|
+
if (args.setId) {
|
|
322
|
+
const wanted = db.prepare("SELECT * FROM vault_set WHERE id = ? AND deleted_at IS NULL").get(String(args.setId));
|
|
323
|
+
if (!wanted) throw new Error("集合不存在:" + args.setId);
|
|
324
|
+
setRow = wanted;
|
|
325
|
+
} else if (groupId) {
|
|
326
|
+
setRow = sets.ensureDefaultSet(groupId);
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
db.prepare(
|
|
330
|
+
"INSERT INTO vault_secret(id, name, kind, meta, ciphertext, created_at, updated_at, rev) " +
|
|
331
|
+
"VALUES(?, ?, ?, ?, ?, ?, ?, 1)",
|
|
332
|
+
).run(id, name, kind, meta, ciphertext, ts, ts);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
const msg = String(error && error.message);
|
|
335
|
+
if (msg.includes("UNIQUE")) throw new Error("已有同名 secret:" + name);
|
|
336
|
+
throw error;
|
|
337
|
+
}
|
|
338
|
+
if (setRow) sets.linkSecret(setRow.id, id);
|
|
339
|
+
return { id, ok: true, setId: setRow ? setRow.id : null };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function updateSecret(args = {}) {
|
|
343
|
+
const dek = requireUnlocked();
|
|
344
|
+
const id = String(args.id || "");
|
|
345
|
+
const row = db.prepare("SELECT * FROM vault_secret WHERE id = ? AND deleted_at IS NULL").get(id);
|
|
346
|
+
if (!row) throw new Error("secret 不存在:" + id);
|
|
347
|
+
const name = args.name == null ? row.name : assertSecretName(args.name);
|
|
348
|
+
const kind = args.kind == null ? row.kind : assertKind(args.kind);
|
|
349
|
+
const meta = args.meta == null ? row.meta : assertMeta(args.meta);
|
|
350
|
+
let ciphertext = row.ciphertext;
|
|
351
|
+
if (args.secret != null && String(args.secret) !== "") {
|
|
352
|
+
ciphertext = seal(dek, String(args.secret), secretAad(id, name, kind));
|
|
353
|
+
} else if (name !== row.name || kind !== row.kind) {
|
|
354
|
+
const plain = open(dek, row.ciphertext, secretAad(id, row.name, row.kind));
|
|
355
|
+
ciphertext = seal(dek, plain, secretAad(id, name, kind));
|
|
356
|
+
}
|
|
357
|
+
const ts = now();
|
|
358
|
+
try {
|
|
359
|
+
db.prepare(
|
|
360
|
+
"UPDATE vault_secret SET name = ?, kind = ?, meta = ?, ciphertext = ?, updated_at = ?, rev = rev + 1 " +
|
|
361
|
+
"WHERE id = ?",
|
|
362
|
+
).run(name, kind, meta, ciphertext, ts, id);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
const msg = String(error && error.message);
|
|
365
|
+
if (msg.includes("UNIQUE")) throw new Error("已有同名 secret:" + name);
|
|
366
|
+
throw error;
|
|
367
|
+
}
|
|
368
|
+
if (args.groupId) {
|
|
369
|
+
const target = sets.ensureDefaultSet(String(args.groupId));
|
|
370
|
+
sets.linkSecret(target.id, id);
|
|
371
|
+
return { ok: true, setId: target.id };
|
|
372
|
+
}
|
|
373
|
+
return { ok: true };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function deleteSecret(args = {}) {
|
|
377
|
+
requireUnlocked();
|
|
378
|
+
const id = String(args.id || "");
|
|
379
|
+
const ts = now();
|
|
380
|
+
const info = db.prepare(
|
|
381
|
+
"UPDATE vault_secret SET deleted_at = ?, updated_at = ?, rev = rev + 1 WHERE id = ? AND deleted_at IS NULL",
|
|
382
|
+
).run(ts, ts, id);
|
|
383
|
+
if (!info.changes) throw new Error("secret 不存在:" + id);
|
|
384
|
+
sets.detachSecretEverywhere(id);
|
|
385
|
+
return { ok: true };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function reveal(args = {}) {
|
|
389
|
+
const dek = requireUnlocked();
|
|
390
|
+
const id = String(args.id || "");
|
|
391
|
+
const device = deviceGet(db) || {};
|
|
392
|
+
const mode = device.unlock_mode || "A";
|
|
393
|
+
const policy = device.reveal_policy || "session";
|
|
394
|
+
if (mode === "B" || policy === "passphrase") {
|
|
395
|
+
const passphrase = String(args.passphrase || "");
|
|
396
|
+
if (!passphrase) throw new Error("当前模式查看凭据需要口令");
|
|
397
|
+
checkPassphrase(passphrase);
|
|
398
|
+
}
|
|
399
|
+
const row = db.prepare("SELECT * FROM vault_secret WHERE id = ? AND deleted_at IS NULL").get(id);
|
|
400
|
+
if (!row) throw new Error("secret 不存在:" + id);
|
|
401
|
+
const secret = open(dek, row.ciphertext, secretAad(row.id, row.name, row.kind)).toString("utf8");
|
|
402
|
+
touchUsage(db, id);
|
|
403
|
+
return { secret, id: row.id, name: row.name, kind: row.kind };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function lease(args = {}) {
|
|
407
|
+
const dek = requireUnlocked();
|
|
408
|
+
const id = String(args.id || "");
|
|
409
|
+
const subjectType = String(args.subjectType || "");
|
|
410
|
+
const subjectId = String(args.subjectId || "");
|
|
411
|
+
if (subjectType && subjectId) {
|
|
412
|
+
const bound = db
|
|
413
|
+
.prepare("SELECT 1 FROM vault_binding WHERE subject_type = ? AND subject_id = ? AND deleted_at IS NULL LIMIT 1")
|
|
414
|
+
.get(subjectType, subjectId);
|
|
415
|
+
if (!bound) throw new Error("该对象未绑定任何凭据组,无法租用:" + subjectType + "/" + subjectId);
|
|
416
|
+
}
|
|
417
|
+
const ttl = Math.max(30, Math.min(300, Number(args.ttlSeconds) || 60));
|
|
418
|
+
const row = db.prepare("SELECT * FROM vault_secret WHERE id = ? AND deleted_at IS NULL").get(id);
|
|
419
|
+
if (!row) throw new Error("secret 不存在:" + id);
|
|
420
|
+
const secret = open(dek, row.ciphertext, secretAad(row.id, row.name, row.kind)).toString("utf8");
|
|
421
|
+
touchUsage(db, id);
|
|
422
|
+
return {
|
|
423
|
+
secret,
|
|
424
|
+
id: row.id,
|
|
425
|
+
name: row.name,
|
|
426
|
+
kind: row.kind,
|
|
427
|
+
setId: sets.setIdsOfSecret(row.id)[0] || null,
|
|
428
|
+
expiresAt: now() + ttl * 1000,
|
|
429
|
+
purpose: String(args.purpose || ""),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function changePassphrase(args = {}) {
|
|
434
|
+
requireUnlocked();
|
|
435
|
+
const oldPassphrase = String(args.oldPassphrase || "");
|
|
436
|
+
checkPassphrase(oldPassphrase);
|
|
437
|
+
const next = assertPassphrase(args.newPassphrase);
|
|
438
|
+
const head = headerGet(db);
|
|
439
|
+
const salt = randomBytes(16);
|
|
440
|
+
const kek = deriveKey(next, salt.toString("base64"), KDF_DEFAULT);
|
|
441
|
+
const wrapped = seal(kek, state.dek, "vault:dek");
|
|
442
|
+
const passphraseRev = Number(head.passphrase_rev || 1) + 1;
|
|
443
|
+
tx(db, () => {
|
|
444
|
+
headerSet(db, {
|
|
445
|
+
schema_version: SCHEMA_VERSION,
|
|
446
|
+
salt: salt.toString("base64"),
|
|
447
|
+
kdf: JSON.stringify(KDF_DEFAULT),
|
|
448
|
+
wrapped_dek: wrapped,
|
|
449
|
+
passphrase_rev: passphraseRev,
|
|
450
|
+
});
|
|
451
|
+
deviceSet(db, { passphrase_rev_seen: passphraseRev });
|
|
452
|
+
});
|
|
453
|
+
return { ok: true, passphraseRev };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function setUnlockMode(args = {}) {
|
|
457
|
+
if (!initialized()) throw new Error("保险箱未初始化");
|
|
458
|
+
const mode = validateMode(args.mode);
|
|
459
|
+
const before = deviceGet(db);
|
|
460
|
+
try {
|
|
461
|
+
if (!state.dek) {
|
|
462
|
+
if (!args.passphrase) throw new Error("保险箱已锁定,切换模式需要口令");
|
|
463
|
+
unlock({ passphrase: args.passphrase });
|
|
464
|
+
}
|
|
465
|
+
if (mode === "A") {
|
|
466
|
+
removeDeviceKey();
|
|
467
|
+
deviceSet(db, { wrapped_dek_device: null, unlock_mode: "A", auto_unlock: 0, reveal_policy: "session" });
|
|
468
|
+
} else {
|
|
469
|
+
const deviceKey = readDeviceKey() || randomBytes(32);
|
|
470
|
+
const wrapped = seal(deviceKey, state.dek, "vault:device");
|
|
471
|
+
writeDeviceKey(deviceKey);
|
|
472
|
+
deviceSet(db, {
|
|
473
|
+
wrapped_dek_device: wrapped,
|
|
474
|
+
unlock_mode: mode,
|
|
475
|
+
auto_unlock: 1,
|
|
476
|
+
reveal_policy: mode === "B" ? "passphrase" : "session",
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
return { ok: true, unlockMode: mode };
|
|
480
|
+
} catch (error) {
|
|
481
|
+
if (before) deviceSet(db, before);
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function rotateDeviceKey(args = {}) {
|
|
487
|
+
if (!initialized()) throw new Error("保险箱未初始化");
|
|
488
|
+
const device = deviceGet(db) || {};
|
|
489
|
+
if ((device.unlock_mode || "A") === "A") throw new Error("A 模式没有 device key");
|
|
490
|
+
if (!state.dek) throw new Error("保险箱已锁定");
|
|
491
|
+
checkPassphrase(String(args.passphrase || ""));
|
|
492
|
+
const deviceKey = randomBytes(32);
|
|
493
|
+
const wrapped = seal(deviceKey, state.dek, "vault:device");
|
|
494
|
+
writeDeviceKey(deviceKey);
|
|
495
|
+
deviceSet(db, { wrapped_dek_device: wrapped });
|
|
496
|
+
return { ok: true };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* 供受绑定约束的 plugin 写接口使用:按 (groupId, name) 幂等写入一条凭据。
|
|
501
|
+
* 绑定/授权校验在 action 层完成,这里只负责加密落库。
|
|
502
|
+
*/
|
|
503
|
+
/** 往指定集合幂等写一条凭据(全局按 name 去重);调用方负责先校验归属权限。 */
|
|
504
|
+
function writeSecretToSet(args = {}) {
|
|
505
|
+
const dek = requireUnlocked();
|
|
506
|
+
const name = assertSecretName(args.name);
|
|
507
|
+
const kind = assertKind(args.kind || "other");
|
|
508
|
+
const secret = String(args.secret ?? "");
|
|
509
|
+
if (!secret) throw new Error("secret 不能为空");
|
|
510
|
+
const meta = assertMeta(args.meta);
|
|
511
|
+
const setId = String(args.setId || "");
|
|
512
|
+
if (!setId) throw new Error("setId 必填");
|
|
513
|
+
|
|
514
|
+
const setRow = db.prepare("SELECT * FROM vault_set WHERE id = ? AND deleted_at IS NULL").get(setId);
|
|
515
|
+
if (!setRow) throw new Error("集合不存在:" + setId);
|
|
516
|
+
const row = db.prepare("SELECT * FROM vault_secret WHERE name = ? AND deleted_at IS NULL").get(name);
|
|
517
|
+
const ts = now();
|
|
518
|
+
if (row) {
|
|
519
|
+
const ciphertext = seal(dek, secret, secretAad(row.id, name, kind));
|
|
520
|
+
db.prepare(
|
|
521
|
+
"UPDATE vault_secret SET kind = ?, meta = ?, ciphertext = ?, updated_at = ?, rev = rev + 1 WHERE id = ?",
|
|
522
|
+
).run(kind, meta, ciphertext, ts, row.id);
|
|
523
|
+
sets.linkSecret(setId, row.id);
|
|
524
|
+
return { id: row.id, setId, created: false, updated: true };
|
|
525
|
+
}
|
|
526
|
+
const id = newId("sec");
|
|
527
|
+
const ciphertext = seal(dek, secret, secretAad(id, name, kind));
|
|
528
|
+
db.prepare(
|
|
529
|
+
"INSERT INTO vault_secret(id, name, kind, meta, ciphertext, created_at, updated_at, rev) " +
|
|
530
|
+
"VALUES(?, ?, ?, ?, ?, ?, ?, 1)",
|
|
531
|
+
).run(id, name, kind, meta, ciphertext, ts, ts);
|
|
532
|
+
sets.linkSecret(setId, id);
|
|
533
|
+
return { id, setId, created: true, updated: false };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** 把集合里的某条凭据摘出来;不再属于任何集合时才软删,避免误删别处还在用的凭据。 */
|
|
537
|
+
function detachSecretFromSet(args = {}) {
|
|
538
|
+
requireUnlocked();
|
|
539
|
+
const setId = String(args.setId || "");
|
|
540
|
+
if (!setId) throw new Error("setId 必填");
|
|
541
|
+
const name = assertSecretName(args.name);
|
|
542
|
+
const row = db.prepare("SELECT * FROM vault_secret WHERE name = ? AND deleted_at IS NULL").get(name);
|
|
543
|
+
if (!row) return { ok: true, removed: false };
|
|
544
|
+
sets.unlinkSecret(setId, row.id);
|
|
545
|
+
if (!sets.setIdsOfSecret(row.id).length) {
|
|
546
|
+
const ts = now();
|
|
547
|
+
db.prepare("UPDATE vault_secret SET deleted_at = ?, updated_at = ?, rev = rev + 1 WHERE id = ?").run(ts, ts, row.id);
|
|
548
|
+
return { ok: true, removed: true, deleted: true };
|
|
549
|
+
}
|
|
550
|
+
return { ok: true, removed: true, deleted: false };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function exportData() {
|
|
554
|
+
return {
|
|
555
|
+
formatVersion: 1,
|
|
556
|
+
exportedAt: new Date(now()).toISOString(),
|
|
557
|
+
secrets: [],
|
|
558
|
+
groups: [],
|
|
559
|
+
bindings: [],
|
|
560
|
+
note: "保险箱密文与 KDF 参数不进入备份;换机请重新录入凭据。",
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function importData() {
|
|
565
|
+
return { ok: true, imported: 0, skipped: 0, failed: 0, message: "保险箱不导入密文" };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
return {
|
|
569
|
+
status,
|
|
570
|
+
setup,
|
|
571
|
+
unlock,
|
|
572
|
+
lock,
|
|
573
|
+
listSecrets,
|
|
574
|
+
createSecret,
|
|
575
|
+
updateSecret,
|
|
576
|
+
deleteSecret,
|
|
577
|
+
writeSecretToSet,
|
|
578
|
+
detachSecretFromSet,
|
|
579
|
+
reveal,
|
|
580
|
+
lease,
|
|
581
|
+
changePassphrase,
|
|
582
|
+
setUnlockMode,
|
|
583
|
+
rotateDeviceKey,
|
|
584
|
+
exportData,
|
|
585
|
+
importData,
|
|
586
|
+
initialized,
|
|
587
|
+
mode: () => (deviceGet(db) || {}).unlock_mode || "A",
|
|
588
|
+
};
|
|
589
|
+
}
|