nemu-cli 1.6.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,7 @@ export function disk_path(root, relative) {
12
12
  function megabytes(bytes) {
13
13
  return `${(bytes / 1024 / 1024).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
14
14
  }
15
- export async function scan_folder(root, ignore, max_file_bytes, preferred = () => undefined) {
15
+ export async function scan_folder(root, ignore, max_file_bytes, preferred = () => undefined, hasher = hash_of) {
16
16
  const files = new Map();
17
17
  const skipped = [];
18
18
  const clashes = new Map();
@@ -58,7 +58,7 @@ export async function scan_folder(root, ignore, max_file_bytes, preferred = () =
58
58
  const content = await readFile(disk_path(root, disk)).catch(() => null);
59
59
  if (content === null)
60
60
  continue;
61
- const local = { path, disk, hash: hash_of(content), size: content.length };
61
+ const local = { path, disk, hash: hasher(content), size: content.length };
62
62
  const key = path_key(path);
63
63
  const group = clashes.get(key) ?? [];
64
64
  group.push(local);
@@ -85,13 +85,13 @@ export async function scan_folder(root, ignore, max_file_bytes, preferred = () =
85
85
  }
86
86
  return { files, skipped };
87
87
  }
88
- export async function read_hash(root, disk) {
88
+ export async function read_hash(root, disk, hasher = hash_of) {
89
89
  const content = await readFile(disk_path(root, disk)).catch(() => null);
90
- return content === null ? null : hash_of(content);
90
+ return content === null ? null : hasher(content);
91
91
  }
92
- export async function read_if(root, disk, expected_hash) {
92
+ export async function read_if(root, disk, expected_hash, hasher = hash_of) {
93
93
  const content = await readFile(disk_path(root, disk)).catch(() => null);
94
- if (content === null || hash_of(content) !== expected_hash)
94
+ if (content === null || hasher(content) !== expected_hash)
95
95
  return null;
96
96
  return content;
97
97
  }
@@ -113,7 +113,7 @@ export async function stays_inside(root, target) {
113
113
  return false;
114
114
  return real_folder === real_root || real_folder.startsWith(real_root.endsWith(sep) ? real_root : `${real_root}${sep}`);
115
115
  }
116
- export async function write_atomic_file(root, relative, content, expected) {
116
+ export async function write_atomic_file(root, relative, content, expected, hasher = hash_of) {
117
117
  const target = disk_path(root, relative);
118
118
  if (!(await stays_inside(root, target)))
119
119
  return false;
@@ -122,7 +122,7 @@ export async function write_atomic_file(root, relative, content, expected) {
122
122
  if (exists)
123
123
  return false;
124
124
  }
125
- else if ((await read_hash(root, expected.disk)) !== expected.hash) {
125
+ else if ((await read_hash(root, expected.disk, hasher)) !== expected.hash) {
126
126
  return false;
127
127
  }
128
128
  await mkdir(dirname(target), { recursive: true });
@@ -161,10 +161,10 @@ export async function rename_local(root, from, to) {
161
161
  await prune_folders(root, dirname(from));
162
162
  return true;
163
163
  }
164
- export async function delete_local(root, disk, expected_hash) {
164
+ export async function delete_local(root, disk, expected_hash, hasher = hash_of) {
165
165
  if (!(await stays_inside(root, disk_path(root, disk))))
166
166
  return false;
167
- if ((await read_hash(root, disk)) !== expected_hash)
167
+ if ((await read_hash(root, disk, hasher)) !== expected_hash)
168
168
  return false;
169
169
  await unlink(disk_path(root, disk));
170
170
  await prune_folders(root, dirname(disk));
@@ -73,7 +73,7 @@ function is_obsidian_noise(segments) {
73
73
  return true;
74
74
  return segments.includes("cache");
75
75
  }
76
- export function is_default_ignored(path, obsidian) {
76
+ export function is_default_ignored(path, obsidian, obsidian_plugins = false) {
77
77
  const segments = path.split("/");
78
78
  if (segments.some((segment) => IGNORED_SEGMENTS.has(segment)))
79
79
  return true;
@@ -83,10 +83,12 @@ export function is_default_ignored(path, obsidian) {
83
83
  return true;
84
84
  if (segments[0] === ".obsidian" && (!obsidian || is_obsidian_noise(segments)))
85
85
  return true;
86
+ if (segments[0] === ".obsidian" && segments[1] === "plugins" && !obsidian_plugins)
87
+ return true;
86
88
  return /\.(tmp|swp|crdownload|part)$/i.test(path) || path.endsWith("~");
87
89
  }
88
90
  export function is_ignored(path, options, is_folder = false) {
89
- if (is_default_ignored(path, options.obsidian))
91
+ if (is_default_ignored(path, options.obsidian, options.obsidian_plugins))
90
92
  return true;
91
93
  let ignored = false;
92
94
  for (const rule of options.rules) {
@@ -96,5 +98,6 @@ export function is_ignored(path, options, is_folder = false) {
96
98
  return ignored;
97
99
  }
98
100
  export function ignore_fingerprint(options, source) {
99
- return `${options.obsidian ? "obsidian" : "plain"}:${source.length}:${source}`;
101
+ const mode = options.obsidian ? (options.obsidian_plugins ? "obsidian+plugins" : "obsidian") : "plain";
102
+ return `${mode}:${source.length}:${source}`;
100
103
  }
@@ -0,0 +1,110 @@
1
+ import { CliError } from "../../errors.js";
2
+ import { RemoteError, } from "../api.js";
3
+ import { content_mac, open_content, open_path, remote_path, seal_content, seal_path, } from "./crypto.js";
4
+ function unreadable() {
5
+ return new CliError("A note in this private vault did not open with the key on this computer. Nothing was changed. Run nemu vault forget, then nemu vault unlock again.", "private_key_mismatch");
6
+ }
7
+ export class PrivateVaultApi {
8
+ inner;
9
+ keys;
10
+ vault_id;
11
+ constructor(inner, keys) {
12
+ this.inner = inner;
13
+ this.keys = keys;
14
+ this.vault_id = inner.vault_id;
15
+ }
16
+ hash(content) {
17
+ return content_mac(this.keys, content);
18
+ }
19
+ plain_path(remote, sealed) {
20
+ if (sealed === undefined)
21
+ throw unreadable();
22
+ try {
23
+ return open_path(this.keys, remote, sealed);
24
+ }
25
+ catch {
26
+ throw unreadable();
27
+ }
28
+ }
29
+ plain(note) {
30
+ const { sealed_path, ...rest } = note;
31
+ return { ...rest, path: this.plain_path(note.path, sealed_path) };
32
+ }
33
+ async guard(action) {
34
+ try {
35
+ return await action();
36
+ }
37
+ catch (error) {
38
+ if (error instanceof RemoteError && error.current !== undefined && error.current !== null) {
39
+ throw new RemoteError(error.message, error.code, error.status ?? 0, this.plain(error.current), error.reference);
40
+ }
41
+ throw error;
42
+ }
43
+ }
44
+ async info() {
45
+ return this.inner.info();
46
+ }
47
+ async notes(trash = false) {
48
+ const listed = await this.inner.notes(trash);
49
+ return { revision: listed.revision, notes: listed.notes.map((note) => this.plain(note)) };
50
+ }
51
+ async changes(since) {
52
+ const page = await this.inner.changes(since);
53
+ return { ...page, notes: page.notes.map((note) => this.plain(note)) };
54
+ }
55
+ async read(path) {
56
+ const remote = remote_path(this.keys, path);
57
+ const fetched = await this.guard(() => this.inner.read(remote));
58
+ try {
59
+ return { ...fetched, content: open_content(this.keys, remote, fetched.content) };
60
+ }
61
+ catch {
62
+ throw unreadable();
63
+ }
64
+ }
65
+ async write(path, content, base_version) {
66
+ const remote = remote_path(this.keys, path);
67
+ const written = await this.guard(() => this.inner.write(remote, seal_content(this.keys, path, content), base_version, {
68
+ sealed_path: seal_path(this.keys, path),
69
+ content_hash: content_mac(this.keys, content),
70
+ }));
71
+ return this.plain(written);
72
+ }
73
+ async remove(path, version) {
74
+ const removed = await this.guard(() => this.inner.remove(remote_path(this.keys, path), version));
75
+ return this.plain(removed);
76
+ }
77
+ async move(from, to, base_version) {
78
+ const current = await this.read(from);
79
+ const moved = await this.guard(() => this.inner.move(remote_path(this.keys, from), remote_path(this.keys, to), base_version, {
80
+ sealed_path: seal_path(this.keys, to),
81
+ content_hash: content_mac(this.keys, current.content),
82
+ content: seal_content(this.keys, to, current.content),
83
+ }));
84
+ return this.plain(moved);
85
+ }
86
+ async record_merge() {
87
+ return;
88
+ }
89
+ async read_version(note_id, version) {
90
+ const versions = await this.inner.history(note_id);
91
+ const found = versions.find((entry) => entry.version === version);
92
+ if (found === undefined) {
93
+ throw new RemoteError("That version is not in the history any more.", "version_not_found", 404, undefined, undefined);
94
+ }
95
+ const sealed = await this.inner.read_version(note_id, version);
96
+ try {
97
+ return open_content(this.keys, found.path, sealed);
98
+ }
99
+ catch {
100
+ throw unreadable();
101
+ }
102
+ }
103
+ async history(note_id, limit = 200) {
104
+ const versions = await this.inner.history(note_id, limit);
105
+ return versions.map((version) => {
106
+ const { sealed_path, ...rest } = version;
107
+ return { ...rest, path: this.plain_path(version.path, sealed_path) };
108
+ });
109
+ }
110
+ }
@@ -0,0 +1,212 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes, } from "node:crypto";
2
+ import { argon2id } from "hash-wasm";
3
+ export const PRIVATE_PREFIX = "private/";
4
+ const CONTENT_MAGIC = Buffer.from("NPV1", "ascii");
5
+ const NONCE_BYTES = 12;
6
+ const TAG_BYTES = 16;
7
+ const KEY_BYTES = 32;
8
+ const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
9
+ export const PASSWORD_PARAMS = { memory_kib: 65536, iterations: 3, parallelism: 1 };
10
+ export const PASSWORD_LIMITS = {
11
+ min_memory_kib: 65536,
12
+ max_memory_kib: 1048576,
13
+ min_iterations: 3,
14
+ max_iterations: 10,
15
+ max_parallelism: 4,
16
+ };
17
+ export class PrivateCryptoError extends Error {
18
+ code;
19
+ constructor(message, code) {
20
+ super(`${message} [${code}]`);
21
+ this.code = code;
22
+ this.name = "PrivateCryptoError";
23
+ }
24
+ }
25
+ function subkey(vault_key, name) {
26
+ return Buffer.from(hkdfSync("sha256", vault_key, Buffer.alloc(0), `nemu-private|${name}|v1`, KEY_BYTES));
27
+ }
28
+ export function new_vault_key() {
29
+ return randomBytes(KEY_BYTES);
30
+ }
31
+ export function vault_keys(vault_id, vault_key) {
32
+ if (vault_key.length !== KEY_BYTES)
33
+ throw new PrivateCryptoError("A vault key is 32 bytes", "bad_vault_key");
34
+ return {
35
+ vault_id,
36
+ content: subkey(vault_key, "content"),
37
+ path: subkey(vault_key, "path"),
38
+ mac: subkey(vault_key, "mac"),
39
+ };
40
+ }
41
+ export function base32(bytes) {
42
+ let bits = 0;
43
+ let value = 0;
44
+ let out = "";
45
+ for (const byte of bytes) {
46
+ value = (value << 8) | byte;
47
+ bits += 8;
48
+ while (bits >= 5) {
49
+ out += BASE32[(value >>> (bits - 5)) & 31];
50
+ bits -= 5;
51
+ }
52
+ }
53
+ if (bits > 0)
54
+ out += BASE32[(value << (5 - bits)) & 31];
55
+ return out;
56
+ }
57
+ export function unbase32(text) {
58
+ const clean = text.toLowerCase().replace(/[\s-]/g, "");
59
+ let bits = 0;
60
+ let value = 0;
61
+ const out = [];
62
+ for (const character of clean) {
63
+ const index = BASE32.indexOf(character);
64
+ if (index === -1)
65
+ throw new PrivateCryptoError("That is not a recovery key", "bad_recovery_key");
66
+ value = (value << 5) | index;
67
+ bits += 5;
68
+ if (bits >= 8) {
69
+ out.push((value >>> (bits - 8)) & 255);
70
+ bits -= 8;
71
+ }
72
+ }
73
+ return Buffer.from(out);
74
+ }
75
+ function seal(key, plaintext, aad) {
76
+ const nonce = randomBytes(NONCE_BYTES);
77
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
78
+ cipher.setAAD(Buffer.from(aad, "utf8"));
79
+ const body = Buffer.concat([cipher.update(plaintext), cipher.final()]);
80
+ return Buffer.concat([nonce, body, cipher.getAuthTag()]);
81
+ }
82
+ function open(key, sealed, aad, code) {
83
+ if (sealed.length < NONCE_BYTES + TAG_BYTES)
84
+ throw new PrivateCryptoError("Sealed data is too short", code);
85
+ const nonce = sealed.subarray(0, NONCE_BYTES);
86
+ const tag = sealed.subarray(sealed.length - TAG_BYTES);
87
+ const body = sealed.subarray(NONCE_BYTES, sealed.length - TAG_BYTES);
88
+ try {
89
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
90
+ decipher.setAAD(Buffer.from(aad, "utf8"));
91
+ decipher.setAuthTag(tag);
92
+ return Buffer.concat([decipher.update(body), decipher.final()]);
93
+ }
94
+ catch {
95
+ throw new PrivateCryptoError("Sealed data did not open: wrong key or changed bytes", code);
96
+ }
97
+ }
98
+ export function path_id(keys, path) {
99
+ const digest = createHmac("sha256", keys.mac).update(`path\u0000${path.normalize("NFC").toLowerCase()}`, "utf8").digest();
100
+ return base32(digest).slice(0, 52);
101
+ }
102
+ export function remote_path(keys, path) {
103
+ return `${PRIVATE_PREFIX}${path_id(keys, path)}`;
104
+ }
105
+ export function id_of_remote(remote) {
106
+ if (!remote.startsWith(PRIVATE_PREFIX))
107
+ throw new PrivateCryptoError("Not a private note path", "bad_remote_path");
108
+ return remote.slice(PRIVATE_PREFIX.length);
109
+ }
110
+ export function seal_path(keys, path) {
111
+ const normalized = path.normalize("NFC");
112
+ return seal(keys.path, Buffer.from(normalized, "utf8"), `path|${keys.vault_id}|${path_id(keys, normalized)}`).toString("base64url");
113
+ }
114
+ export function open_path(keys, remote, sealed_path) {
115
+ const id = id_of_remote(remote);
116
+ const path = open(keys.path, Buffer.from(sealed_path, "base64url"), `path|${keys.vault_id}|${id}`, "bad_sealed_path").toString("utf8");
117
+ if (path_id(keys, path) !== id)
118
+ throw new PrivateCryptoError("A sealed name does not belong to its note", "bad_sealed_path");
119
+ return path;
120
+ }
121
+ export function seal_content(keys, path, content) {
122
+ const sealed = seal(keys.content, Buffer.from(content), `content|${keys.vault_id}|${path_id(keys, path)}`);
123
+ return Buffer.concat([CONTENT_MAGIC, sealed]);
124
+ }
125
+ export function open_content(keys, remote, sealed) {
126
+ const bytes = Buffer.from(sealed);
127
+ if (!bytes.subarray(0, CONTENT_MAGIC.length).equals(CONTENT_MAGIC)) {
128
+ throw new PrivateCryptoError("This is not a private note", "bad_content");
129
+ }
130
+ return open(keys.content, bytes.subarray(CONTENT_MAGIC.length), `content|${keys.vault_id}|${id_of_remote(remote)}`, "bad_content");
131
+ }
132
+ export function content_mac(keys, content) {
133
+ return createHmac("sha256", keys.mac).update("content\u0000", "utf8").update(content).digest("hex");
134
+ }
135
+ export function lock_aad(vault_id, kind, params) {
136
+ const canonical = Object.keys(params)
137
+ .sort()
138
+ .map((key) => {
139
+ const value = String(params[key]);
140
+ return `${key.length}:${key}=${value.length}:${value}`;
141
+ })
142
+ .join("|");
143
+ return `lock|v2|${vault_id}|${kind}|${canonical}`;
144
+ }
145
+ export function wrap_key(kek, vault_id, kind, params, vault_key) {
146
+ return seal(kek, vault_key, lock_aad(vault_id, kind, params));
147
+ }
148
+ export function unwrap_key(kek, vault_id, kind, params, wrapped) {
149
+ return open(kek, wrapped, lock_aad(vault_id, kind, params), "wrong_secret");
150
+ }
151
+ export async function password_kek(password, salt, params = PASSWORD_PARAMS) {
152
+ const hash = await argon2id({
153
+ password: password.normalize("NFC"),
154
+ salt,
155
+ parallelism: params.parallelism,
156
+ iterations: params.iterations,
157
+ memorySize: params.memory_kib,
158
+ hashLength: KEY_BYTES,
159
+ outputType: "binary",
160
+ });
161
+ return Buffer.from(hash);
162
+ }
163
+ export function recovery_kek(recovery) {
164
+ return Buffer.from(hkdfSync("sha256", recovery, Buffer.alloc(0), "nemu-private|recovery|v1", KEY_BYTES));
165
+ }
166
+ export function format_recovery(recovery) {
167
+ return (base32(recovery).toUpperCase().match(/.{1,4}/g) ?? []).join("-");
168
+ }
169
+ export function new_request_keys() {
170
+ const { publicKey, privateKey } = generateKeyPairSync("x25519");
171
+ const jwk = publicKey.export({ format: "jwk" });
172
+ if (typeof jwk.x !== "string")
173
+ throw new PrivateCryptoError("Could not make a key pair", "keypair_failed");
174
+ return { public_key: jwk.x, private_key: privateKey };
175
+ }
176
+ export function commitment_of(public_key, nonce) {
177
+ return createHash("sha256")
178
+ .update("nemu-approve-commit|v1|", "utf8")
179
+ .update(Buffer.from(public_key, "base64url"))
180
+ .update(Buffer.from(nonce, "base64url"))
181
+ .digest("hex");
182
+ }
183
+ export function new_request() {
184
+ const keys = new_request_keys();
185
+ const nonce = randomBytes(16).toString("base64url");
186
+ return { keys, nonce, commitment: commitment_of(keys.public_key, nonce) };
187
+ }
188
+ export function approval_code(vault_id, request_id, requester_key, approver_key, nonce) {
189
+ const digest = createHash("sha256")
190
+ .update(`nemu-approve-code|v1|${vault_id}|${request_id}|`, "utf8")
191
+ .update(Buffer.from(requester_key, "base64url"))
192
+ .update(Buffer.from(approver_key, "base64url"))
193
+ .update(Buffer.from(nonce, "base64url"))
194
+ .digest();
195
+ return String(digest.readUInt32BE(0) % 1_000_000).padStart(6, "0");
196
+ }
197
+ function x25519_public(raw) {
198
+ return createPublicKey({ key: { kty: "OKP", crv: "X25519", x: raw }, format: "jwk" });
199
+ }
200
+ function approval_kek(own, other, requester_key, approver_key) {
201
+ const shared = diffieHellman({ privateKey: own, publicKey: x25519_public(other) });
202
+ const salt = Buffer.concat([Buffer.from(requester_key, "base64url"), Buffer.from(approver_key, "base64url")]);
203
+ return Buffer.from(hkdfSync("sha256", shared, salt, "nemu-private|approve|v2", KEY_BYTES));
204
+ }
205
+ export function wrap_for_request(vault_id, request_id, approver, requester_key, vault_key) {
206
+ const kek = approval_kek(approver.private_key, requester_key, requester_key, approver.public_key);
207
+ return seal(kek, vault_key, `approve|${vault_id}|${request_id}`);
208
+ }
209
+ export function unwrap_from_request(vault_id, request_id, requester, approver_key, wrapped) {
210
+ const kek = approval_kek(requester.private_key, approver_key, requester.public_key, approver_key);
211
+ return open(kek, wrapped, `approve|${vault_id}|${request_id}`, "bad_approval");
212
+ }
@@ -0,0 +1,104 @@
1
+ import { spawn } from "node:child_process";
2
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { config_dir } from "../../config.js";
5
+ import { CliError } from "../../errors.js";
6
+ const SERVICE = "nemu-vault";
7
+ const KEY_FILE_MODE = 0o600;
8
+ const WINDOWS_PROTECT = "Add-Type -AssemblyName System.Security; $in = [Console]::In.ReadToEnd().Trim(); $bytes = [Convert]::FromBase64String($in); $out = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser'); [Console]::Out.Write([Convert]::ToBase64String($out))";
9
+ const WINDOWS_UNPROTECT = "Add-Type -AssemblyName System.Security; $in = [Console]::In.ReadToEnd().Trim(); $bytes = [Convert]::FromBase64String($in); $out = [Security.Cryptography.ProtectedData]::Unprotect($bytes, $null, 'CurrentUser'); [Console]::Out.Write([Convert]::ToBase64String($out))";
10
+ function run(command, args, input) {
11
+ return new Promise((resolve) => {
12
+ const child = spawn(command, args, { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
13
+ const chunks = [];
14
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
15
+ child.on("error", () => resolve({ code: 127, stdout: "" }));
16
+ child.on("close", (code) => resolve({ code: code ?? 127, stdout: Buffer.concat(chunks).toString("utf8") }));
17
+ child.stdin.end(input);
18
+ });
19
+ }
20
+ function key_dir() {
21
+ return join(config_dir(), "vault-keys");
22
+ }
23
+ const VAULT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
24
+ function checked_id(vault_id) {
25
+ if (!VAULT_ID.test(vault_id))
26
+ throw new CliError("Not a vault id.", "invalid_vault_id");
27
+ return vault_id;
28
+ }
29
+ function key_file(vault_id) {
30
+ return join(key_dir(), `${checked_id(vault_id)}.key`);
31
+ }
32
+ export function keystore_kind() {
33
+ if (process.env.NEMU_VAULT_KEYSTORE === "file")
34
+ return "file";
35
+ if (process.platform === "darwin")
36
+ return "keychain";
37
+ if (process.platform === "win32")
38
+ return "dpapi";
39
+ return "file";
40
+ }
41
+ async function write_key_file(vault_id, text) {
42
+ await mkdir(key_dir(), { recursive: true, mode: 0o700 });
43
+ await writeFile(key_file(vault_id), text, { mode: KEY_FILE_MODE });
44
+ await chmod(key_file(vault_id), KEY_FILE_MODE).catch(() => undefined);
45
+ }
46
+ async function read_key_file(vault_id) {
47
+ return readFile(key_file(vault_id), "utf8")
48
+ .then((text) => text.trim())
49
+ .catch(() => null);
50
+ }
51
+ export async function save_vault_key(vault_id, vault_key) {
52
+ checked_id(vault_id);
53
+ const kind = keystore_kind();
54
+ const encoded = vault_key.toString("base64");
55
+ if (kind === "keychain") {
56
+ const added = await run("/usr/bin/security", ["-i"], `add-generic-password -U -s ${SERVICE} -a ${vault_id} -w ${encoded}\n`);
57
+ if (added.code !== 0)
58
+ throw new CliError("Could not save the vault key in the macOS Keychain.", "keystore_failed");
59
+ return kind;
60
+ }
61
+ if (kind === "dpapi") {
62
+ const sealed = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROTECT], encoded);
63
+ if (sealed.code !== 0 || sealed.stdout.length === 0) {
64
+ throw new CliError("Could not protect the vault key with Windows.", "keystore_failed");
65
+ }
66
+ await write_key_file(vault_id, `dpapi:${sealed.stdout.trim()}`);
67
+ return kind;
68
+ }
69
+ await write_key_file(vault_id, `plain:${encoded}`);
70
+ return kind;
71
+ }
72
+ export async function load_vault_key(vault_id) {
73
+ checked_id(vault_id);
74
+ const kind = keystore_kind();
75
+ if (kind === "keychain") {
76
+ const found = await run("/usr/bin/security", ["find-generic-password", "-s", SERVICE, "-a", vault_id, "-w"], "");
77
+ if (found.code !== 0)
78
+ return null;
79
+ const key = Buffer.from(found.stdout.trim(), "base64");
80
+ return key.length === 32 ? key : null;
81
+ }
82
+ const stored = await read_key_file(vault_id);
83
+ if (stored === null)
84
+ return null;
85
+ if (stored.startsWith("plain:")) {
86
+ const key = Buffer.from(stored.slice("plain:".length), "base64");
87
+ return key.length === 32 ? key : null;
88
+ }
89
+ if (stored.startsWith("dpapi:") && kind === "dpapi") {
90
+ const opened = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_UNPROTECT], stored.slice("dpapi:".length));
91
+ if (opened.code !== 0)
92
+ return null;
93
+ const key = Buffer.from(opened.stdout.trim(), "base64");
94
+ return key.length === 32 ? key : null;
95
+ }
96
+ return null;
97
+ }
98
+ export async function forget_vault_key(vault_id) {
99
+ checked_id(vault_id);
100
+ if (keystore_kind() === "keychain") {
101
+ await run("/usr/bin/security", ["delete-generic-password", "-s", SERVICE, "-a", vault_id], "");
102
+ }
103
+ await rm(key_file(vault_id), { force: true });
104
+ }
@@ -0,0 +1,59 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { PASSWORD_LIMITS, PASSWORD_PARAMS, PrivateCryptoError, password_kek, recovery_kek, unwrap_key, wrap_key, } from "./crypto.js";
3
+ export async function password_lock(vault_id, vault_key, password) {
4
+ const salt = randomBytes(16);
5
+ const kek = await password_kek(password, salt);
6
+ const params = {
7
+ alg: "argon2id",
8
+ salt: salt.toString("base64url"),
9
+ m: PASSWORD_PARAMS.memory_kib,
10
+ t: PASSWORD_PARAMS.iterations,
11
+ p: PASSWORD_PARAMS.parallelism,
12
+ };
13
+ return {
14
+ kind: "password",
15
+ label: "Vault password",
16
+ params,
17
+ wrapped: wrap_key(kek, vault_id, "password", params, vault_key).toString("base64url"),
18
+ };
19
+ }
20
+ export function recovery_lock(vault_id, vault_key, recovery) {
21
+ const params = { v: 1 };
22
+ return {
23
+ kind: "recovery",
24
+ label: "Recovery key",
25
+ params,
26
+ wrapped: wrap_key(recovery_kek(recovery), vault_id, "recovery", params, vault_key).toString("base64url"),
27
+ };
28
+ }
29
+ function within(value, min, max) {
30
+ const parsed = typeof value === "number" ? value : Number(value);
31
+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
32
+ throw new PrivateCryptoError("The password lock has settings outside the safe range", "bad_lock");
33
+ }
34
+ return parsed;
35
+ }
36
+ export function password_settings(params) {
37
+ if (params.alg !== "argon2id" || typeof params.salt !== "string") {
38
+ throw new PrivateCryptoError("The password lock is damaged", "bad_lock");
39
+ }
40
+ const salt = Buffer.from(params.salt, "base64url");
41
+ if (salt.length < 16)
42
+ throw new PrivateCryptoError("The password lock is damaged", "bad_lock");
43
+ return {
44
+ salt,
45
+ settings: {
46
+ memory_kib: within(params.m, PASSWORD_LIMITS.min_memory_kib, PASSWORD_LIMITS.max_memory_kib),
47
+ iterations: within(params.t, PASSWORD_LIMITS.min_iterations, PASSWORD_LIMITS.max_iterations),
48
+ parallelism: within(params.p, 1, PASSWORD_LIMITS.max_parallelism),
49
+ },
50
+ };
51
+ }
52
+ export async function open_password_lock(vault_id, params, wrapped, password) {
53
+ const { salt, settings } = password_settings(params);
54
+ const kek = await password_kek(password, salt, settings);
55
+ return unwrap_key(kek, vault_id, "password", params, Buffer.from(wrapped, "base64url"));
56
+ }
57
+ export function open_recovery_lock(vault_id, params, wrapped, recovery) {
58
+ return unwrap_key(recovery_kek(recovery), vault_id, "recovery", params, Buffer.from(wrapped, "base64url"));
59
+ }
@@ -0,0 +1,22 @@
1
+ import { ZxcvbnFactory } from "@zxcvbn-ts/core";
2
+ import { adjacencyGraphs, dictionary } from "@zxcvbn-ts/language-common";
3
+ export const MIN_PASSWORD_LENGTH = 12;
4
+ export const STRONG_SCORE = 4;
5
+ export const LONG_PASSWORD_LENGTH = 14;
6
+ export const LONG_PASSWORD_SCORE = 3;
7
+ let checker = null;
8
+ function factory() {
9
+ checker ??= new ZxcvbnFactory({ dictionary, graphs: adjacencyGraphs });
10
+ return checker;
11
+ }
12
+ export function password_problem(password, context = []) {
13
+ if (password.length < MIN_PASSWORD_LENGTH) {
14
+ return `Use at least ${MIN_PASSWORD_LENGTH} characters.`;
15
+ }
16
+ const { score } = factory().check(password, context);
17
+ const is_strong = score >= STRONG_SCORE || (password.length >= LONG_PASSWORD_LENGTH && score >= LONG_PASSWORD_SCORE);
18
+ if (!is_strong) {
19
+ return "That password is too easy to guess. Add words or characters that do not follow a pattern.";
20
+ }
21
+ return null;
22
+ }
@@ -11,6 +11,7 @@ const marker_schema = z.object({
11
11
  workspace_id: z.string().min(1).nullable(),
12
12
  server: z.string().url(),
13
13
  linked_at: z.string(),
14
+ mode: z.enum(["standard", "private"]).optional(),
14
15
  });
15
16
  const base_schema = z.object({
16
17
  path: z.string(),
@@ -21,6 +22,7 @@ const base_schema = z.object({
21
22
  const settings_schema = z.object({
22
23
  conflicts: z.enum(["merge", "file"]).default("merge"),
23
24
  obsidian: z.boolean().default(false),
25
+ obsidian_plugins: z.boolean().default(false),
24
26
  });
25
27
  const state_schema = z.object({
26
28
  version: z.literal(1),
@@ -29,9 +31,14 @@ const state_schema = z.object({
29
31
  cursor: z.number().int().nullable(),
30
32
  full_next: z.boolean().default(false),
31
33
  ignore_fingerprint: z.string().default(""),
32
- settings: settings_schema.default({ conflicts: "merge", obsidian: false }),
34
+ settings: settings_schema.default({ conflicts: "merge", obsidian: false, obsidian_plugins: false }),
33
35
  limits: z
34
- .object({ max_file_bytes: z.number(), max_storage_bytes: z.number().nullable() })
36
+ .object({
37
+ max_file_bytes: z.number(),
38
+ max_storage_bytes: z.number().nullable(),
39
+ max_upload_file_bytes: z.number().optional(),
40
+ part_bytes: z.number().optional(),
41
+ })
35
42
  .nullable()
36
43
  .default(null),
37
44
  files: z.record(z.string(), base_schema),
@@ -94,7 +101,11 @@ export function empty_state(vault_id, root, settings) {
94
101
  cursor: null,
95
102
  full_next: true,
96
103
  ignore_fingerprint: "",
97
- settings: { conflicts: settings?.conflicts ?? "merge", obsidian: settings?.obsidian ?? false },
104
+ settings: {
105
+ conflicts: settings?.conflicts ?? "merge",
106
+ obsidian: settings?.obsidian ?? false,
107
+ obsidian_plugins: settings?.obsidian_plugins ?? false,
108
+ },
98
109
  limits: null,
99
110
  files: {},
100
111
  synced_at: null,
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "1.6.1";
1
+ export const VERSION = "1.9.0";