nemu-cli 1.5.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
@@ -0,0 +1,118 @@
1
+ import { mkdir, readFile, rename, rm, rmdir, writeFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { z } from "zod";
4
+ import { config_dir } from "../config.js";
5
+ export const MARKER_FOLDER = ".nemu";
6
+ export const MARKER_FILE = "vault.json";
7
+ const marker_schema = z.object({
8
+ version: z.literal(1),
9
+ vault_id: z.string().min(1),
10
+ vault_name: z.string(),
11
+ workspace_id: z.string().min(1).nullable(),
12
+ server: z.string().url(),
13
+ linked_at: z.string(),
14
+ mode: z.enum(["standard", "private"]).optional(),
15
+ });
16
+ const base_schema = z.object({
17
+ path: z.string(),
18
+ note_id: z.string(),
19
+ version: z.number().int(),
20
+ hash: z.string(),
21
+ });
22
+ const settings_schema = z.object({
23
+ conflicts: z.enum(["merge", "file"]).default("merge"),
24
+ obsidian: z.boolean().default(false),
25
+ obsidian_plugins: z.boolean().default(false),
26
+ });
27
+ const state_schema = z.object({
28
+ version: z.literal(1),
29
+ vault_id: z.string(),
30
+ root: z.string(),
31
+ cursor: z.number().int().nullable(),
32
+ full_next: z.boolean().default(false),
33
+ ignore_fingerprint: z.string().default(""),
34
+ settings: settings_schema.default({ conflicts: "merge", obsidian: false, obsidian_plugins: false }),
35
+ limits: z
36
+ .object({ max_file_bytes: z.number(), max_storage_bytes: z.number().nullable() })
37
+ .nullable()
38
+ .default(null),
39
+ files: z.record(z.string(), base_schema),
40
+ synced_at: z.string().nullable().default(null),
41
+ });
42
+ export function marker_path(root) {
43
+ return join(root, MARKER_FOLDER, MARKER_FILE);
44
+ }
45
+ export function lock_path(root) {
46
+ return join(root, MARKER_FOLDER, "lock");
47
+ }
48
+ export function state_folder() {
49
+ return join(config_dir(), "vaults");
50
+ }
51
+ export function state_path_for(vault_id, folder = state_folder()) {
52
+ return join(folder, `${vault_id.replace(/[^\w-]/g, "")}.json`);
53
+ }
54
+ async function write_atomic(path, contents, mode) {
55
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
56
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
57
+ await writeFile(temporary, contents, { encoding: "utf-8", mode });
58
+ await rename(temporary, path);
59
+ }
60
+ async function read_json(path) {
61
+ try {
62
+ return JSON.parse(await readFile(path, "utf-8"));
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ export async function read_marker(root) {
69
+ const parsed = marker_schema.safeParse(await read_json(marker_path(root)));
70
+ return parsed.success ? parsed.data : null;
71
+ }
72
+ export async function write_marker(root, marker) {
73
+ await write_atomic(marker_path(root), `${JSON.stringify(marker, null, 2)}\n`, 0o644);
74
+ }
75
+ export async function remove_marker(root) {
76
+ await rm(marker_path(root), { force: true });
77
+ await rm(lock_path(root), { force: true });
78
+ await rmdir(join(root, MARKER_FOLDER)).catch(() => undefined);
79
+ }
80
+ export async function find_root(start) {
81
+ let current = resolve(start);
82
+ for (;;) {
83
+ if ((await read_marker(current)) !== null)
84
+ return current;
85
+ const parent = dirname(current);
86
+ if (parent === current)
87
+ return null;
88
+ current = parent;
89
+ }
90
+ }
91
+ export function empty_state(vault_id, root, settings) {
92
+ return {
93
+ version: 1,
94
+ vault_id,
95
+ root,
96
+ cursor: null,
97
+ full_next: true,
98
+ ignore_fingerprint: "",
99
+ settings: {
100
+ conflicts: settings?.conflicts ?? "merge",
101
+ obsidian: settings?.obsidian ?? false,
102
+ obsidian_plugins: settings?.obsidian_plugins ?? false,
103
+ },
104
+ limits: null,
105
+ files: {},
106
+ synced_at: null,
107
+ };
108
+ }
109
+ export async function read_state(path) {
110
+ const parsed = state_schema.safeParse(await read_json(path));
111
+ return parsed.success ? parsed.data : null;
112
+ }
113
+ export async function write_state(path, state) {
114
+ await write_atomic(path, JSON.stringify(state), 0o600);
115
+ }
116
+ export async function remove_state(path) {
117
+ await rm(path, { force: true });
118
+ }
@@ -0,0 +1,101 @@
1
+ import { watch } from "node:fs";
2
+ import { randomBytes } from "node:crypto";
3
+ import { acquire_lock } from "./lock.js";
4
+ function is_own_file(name) {
5
+ const normalized = name.split("\\").join("/");
6
+ return normalized === ".nemu" || normalized.startsWith(".nemu/") || normalized.endsWith(".nemu.tmp");
7
+ }
8
+ function open_watcher(root, on_change) {
9
+ try {
10
+ const watcher = watch(root, { recursive: true }, (_event, name) => on_change(name === null ? "" : String(name)));
11
+ return { watcher, recursive: true };
12
+ }
13
+ catch {
14
+ try {
15
+ const watcher = watch(root, (_event, name) => on_change(name === null ? "" : String(name)));
16
+ return { watcher, recursive: false };
17
+ }
18
+ catch {
19
+ return { watcher: null, recursive: false };
20
+ }
21
+ }
22
+ }
23
+ export async function watch_folder(options) {
24
+ const lock = await acquire_lock(options.root, randomBytes(8).toString("hex"));
25
+ const debounce_ms = options.debounce_ms ?? 2_500;
26
+ let running = false;
27
+ let again = false;
28
+ let stopped = false;
29
+ let timer = null;
30
+ let finish = () => undefined;
31
+ const done = new Promise((resolve) => {
32
+ finish = resolve;
33
+ });
34
+ const stop = () => {
35
+ if (stopped)
36
+ return;
37
+ stopped = true;
38
+ if (timer !== null)
39
+ clearTimeout(timer);
40
+ clearInterval(interval);
41
+ opened.watcher?.close();
42
+ process.off("SIGINT", stop);
43
+ process.off("SIGTERM", stop);
44
+ finish();
45
+ };
46
+ const cycle = async () => {
47
+ if (stopped)
48
+ return;
49
+ if (running) {
50
+ again = true;
51
+ return;
52
+ }
53
+ running = true;
54
+ try {
55
+ do {
56
+ again = false;
57
+ try {
58
+ await options.run();
59
+ }
60
+ catch (error) {
61
+ if (options.on_error(error) === "stop") {
62
+ stop();
63
+ return;
64
+ }
65
+ }
66
+ } while (again && !stopped);
67
+ }
68
+ finally {
69
+ running = false;
70
+ }
71
+ };
72
+ const schedule = () => {
73
+ if (stopped)
74
+ return;
75
+ if (timer !== null)
76
+ clearTimeout(timer);
77
+ timer = setTimeout(() => {
78
+ timer = null;
79
+ void cycle();
80
+ }, debounce_ms);
81
+ };
82
+ const opened = open_watcher(options.root, (name) => {
83
+ if (name.length > 0 && is_own_file(name))
84
+ return;
85
+ schedule();
86
+ });
87
+ const interval_ms = options.interval_ms ?? (opened.recursive ? 30_000 : 10_000);
88
+ const interval = setInterval(() => void cycle(), interval_ms);
89
+ process.on("SIGINT", stop);
90
+ process.on("SIGTERM", stop);
91
+ options.signal?.addEventListener("abort", stop);
92
+ try {
93
+ await cycle();
94
+ await done;
95
+ while (running)
96
+ await new Promise((resolve) => setTimeout(resolve, 50));
97
+ }
98
+ finally {
99
+ await lock.release();
100
+ }
101
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "1.5.0";
1
+ export const VERSION = "1.8.0";