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,300 @@
1
+ import { hash_of } from "./files.js";
2
+ import { z } from "zod";
3
+ import { CliError } from "../errors.js";
4
+ const note_schema = z.object({
5
+ id: z.string(),
6
+ path: z.string(),
7
+ kind: z.string(),
8
+ version: z.number().int(),
9
+ hash: z.string(),
10
+ size: z.number(),
11
+ revision: z.number(),
12
+ deleted: z.boolean(),
13
+ sealed_path: z.string().optional(),
14
+ });
15
+ const vault_schema = z.object({
16
+ id: z.string(),
17
+ name: z.string(),
18
+ mode: z.enum(["standard", "private"]).optional(),
19
+ revision: z.number(),
20
+ notes: z.number().optional(),
21
+ stored_bytes: z.number().optional(),
22
+ created_at: z.string().optional(),
23
+ updated_at: z.string().optional(),
24
+ });
25
+ const info_schema = z.object({
26
+ data: vault_schema,
27
+ workspace_id: z.string().optional(),
28
+ limits: z
29
+ .object({
30
+ max_file_bytes: z.number(),
31
+ max_storage_bytes: z.number().nullable(),
32
+ })
33
+ .optional(),
34
+ });
35
+ const version_schema = z.object({
36
+ version: z.number().int(),
37
+ path: z.string(),
38
+ sealed_path: z.string().optional(),
39
+ hash: z.string(),
40
+ size: z.number(),
41
+ deleted: z.boolean(),
42
+ origin: z.string(),
43
+ origin_id: z.string().nullable(),
44
+ client: z.string().nullable(),
45
+ created_at: z.string(),
46
+ });
47
+ const failure_schema = z.object({
48
+ error: z.string().optional(),
49
+ code: z.string().optional(),
50
+ reference: z.string().optional(),
51
+ retry_after: z.number().optional(),
52
+ current: note_schema.nullable().optional(),
53
+ });
54
+ export class RemoteError extends CliError {
55
+ current;
56
+ constructor(message, code, status, current, reference) {
57
+ super(message, code, { status, reference });
58
+ this.name = "RemoteError";
59
+ this.current = current;
60
+ }
61
+ }
62
+ const MAX_WAIT_MS = 60_000;
63
+ const ATTEMPTS = 4;
64
+ function wait(ms) {
65
+ return new Promise((resolve) => setTimeout(resolve, ms));
66
+ }
67
+ async function error_of(response) {
68
+ const parsed = failure_schema.safeParse(await response.json().catch(() => null));
69
+ const body = parsed.success ? parsed.data : {};
70
+ return new RemoteError(body.error ?? `Request failed with status ${response.status}`, body.code ?? `http_${response.status}`, response.status, body.current, body.reference ?? response.headers.get("x-nemu-reference") ?? undefined);
71
+ }
72
+ function retry_delay(response, attempt) {
73
+ const header = Number(response.headers.get("retry-after") ?? "");
74
+ const seconds = Number.isFinite(header) && header > 0 ? header : 2 ** attempt;
75
+ return Math.min(MAX_WAIT_MS, seconds * 1000);
76
+ }
77
+ function parse(schema, value) {
78
+ const parsed = schema.safeParse(value);
79
+ if (!parsed.success) {
80
+ throw new CliError("Nemu sent an answer this CLI does not understand. Update nemu-cli.", "invalid_response");
81
+ }
82
+ return parsed.data;
83
+ }
84
+ export class VaultApi {
85
+ transport;
86
+ vault_id;
87
+ client_label;
88
+ constructor(transport, vault_id, client_label) {
89
+ this.transport = transport;
90
+ this.vault_id = vault_id;
91
+ this.client_label = client_label;
92
+ }
93
+ async call(method, path, options = {}) {
94
+ for (let attempt = 1;; attempt += 1) {
95
+ const response = await this.transport(method, path, options);
96
+ if (response.status !== 429 || attempt >= ATTEMPTS) {
97
+ if (!response.ok)
98
+ throw await error_of(response);
99
+ return response;
100
+ }
101
+ await response.body?.cancel().catch(() => undefined);
102
+ await wait(retry_delay(response, attempt));
103
+ }
104
+ }
105
+ hash(content) {
106
+ return hash_of(content);
107
+ }
108
+ base() {
109
+ return `/api/v1/vaults/${encodeURIComponent(this.vault_id)}`;
110
+ }
111
+ async info() {
112
+ const response = await this.call("GET", this.base());
113
+ return parse(info_schema, await response.json());
114
+ }
115
+ async notes(trash = false) {
116
+ const response = await this.call("GET", `${this.base()}/notes`, {
117
+ query: trash ? { trash: "true" } : {},
118
+ });
119
+ const body = parse(z.object({ vault: vault_schema, data: z.array(note_schema) }), await response.json());
120
+ return { revision: body.vault.revision, notes: body.data };
121
+ }
122
+ async changes(since) {
123
+ const response = await this.call("GET", `${this.base()}/changes`, {
124
+ query: { since },
125
+ });
126
+ const body = parse(z.object({ data: z.array(note_schema), revision: z.number(), has_more: z.boolean() }), await response.json());
127
+ return { notes: body.data, revision: body.revision, has_more: body.has_more };
128
+ }
129
+ async read(path) {
130
+ const response = await this.call("GET", `${this.base()}/files`, {
131
+ query: { path },
132
+ timeout_ms: 120_000,
133
+ });
134
+ const content = Buffer.from(await response.arrayBuffer());
135
+ const id = response.headers.get("x-nemu-note-id");
136
+ const version = Number(response.headers.get("x-nemu-version"));
137
+ const hash = response.headers.get("x-nemu-hash");
138
+ if (id === null || hash === null || !Number.isInteger(version)) {
139
+ throw new CliError("Nemu sent a file without its version. Update nemu-cli.", "invalid_response");
140
+ }
141
+ return { content, id, version, hash };
142
+ }
143
+ async write(path, content, base_version, sealed) {
144
+ const response = await this.call("PUT", `${this.base()}/files`, {
145
+ query: { path },
146
+ headers: {
147
+ "content-type": "application/octet-stream",
148
+ "x-nemu-client": this.client_label,
149
+ ...(base_version === null ? { "if-none-match": "*" } : { "if-match": `"${base_version}"` }),
150
+ ...(sealed === undefined
151
+ ? {}
152
+ : { "x-nemu-sealed-path": sealed.sealed_path, "x-nemu-content-mac": sealed.content_hash }),
153
+ },
154
+ body: content,
155
+ timeout_ms: 120_000,
156
+ });
157
+ return parse(z.object({ data: note_schema }), await response.json()).data;
158
+ }
159
+ async remove(path, version) {
160
+ const response = await this.call("DELETE", `${this.base()}/files`, {
161
+ query: { path, version },
162
+ headers: { "x-nemu-client": this.client_label },
163
+ });
164
+ return parse(z.object({ data: note_schema }), await response.json()).data;
165
+ }
166
+ async move(from, to, base_version, sealed) {
167
+ const response = await this.call("POST", `${this.base()}/files/move`, {
168
+ headers: { "content-type": "application/json", "x-nemu-client": this.client_label },
169
+ body: JSON.stringify({
170
+ from,
171
+ to,
172
+ base_version,
173
+ ...(sealed === undefined
174
+ ? {}
175
+ : {
176
+ sealed_path: sealed.sealed_path,
177
+ content_hash: sealed.content_hash,
178
+ content: Buffer.from(sealed.content).toString("base64url"),
179
+ }),
180
+ }),
181
+ });
182
+ return parse(z.object({ data: note_schema }), await response.json()).data;
183
+ }
184
+ async record_merge(input) {
185
+ await this.call("POST", `${this.base()}/merges`, {
186
+ headers: { "content-type": "application/json", "x-nemu-client": this.client_label },
187
+ body: JSON.stringify({
188
+ path: input.path,
189
+ merged_version: input.merged_version,
190
+ remote_version: input.remote_version,
191
+ content: Buffer.from(input.local).toString("base64"),
192
+ client: this.client_label,
193
+ }),
194
+ timeout_ms: 120_000,
195
+ });
196
+ }
197
+ async read_version(note_id, version) {
198
+ const response = await this.call("GET", `${this.base()}/history/version`, {
199
+ query: { note_id, version },
200
+ timeout_ms: 120_000,
201
+ });
202
+ return Buffer.from(await response.arrayBuffer());
203
+ }
204
+ async history(note_id, limit = 200) {
205
+ const response = await this.call("GET", `${this.base()}/history`, {
206
+ query: { note_id, limit },
207
+ });
208
+ return parse(z.object({ data: z.array(version_schema) }), await response.json()).data;
209
+ }
210
+ }
211
+ const lock_schema = z.object({
212
+ id: z.string(),
213
+ kind: z.string(),
214
+ label: z.string(),
215
+ params: z.record(z.string(), z.union([z.string(), z.number()])),
216
+ created_at: z.string(),
217
+ last_used_at: z.string().nullable(),
218
+ });
219
+ const key_request_schema = z.object({
220
+ id: z.string(),
221
+ label: z.string(),
222
+ commitment: z.string(),
223
+ approver_key: z.string().nullable(),
224
+ public_key: z.string().nullable(),
225
+ nonce: z.string().nullable(),
226
+ created_at: z.string(),
227
+ expires_at: z.string(),
228
+ });
229
+ export class LockApi {
230
+ transport;
231
+ vault_id;
232
+ constructor(transport, vault_id) {
233
+ this.transport = transport;
234
+ this.vault_id = vault_id;
235
+ }
236
+ async call(method, path, body) {
237
+ const response = await this.transport(method, `/api/v1/vaults/${encodeURIComponent(this.vault_id)}${path}`, {
238
+ ...(body === undefined
239
+ ? {}
240
+ : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
241
+ });
242
+ if (!response.ok)
243
+ throw await error_of(response);
244
+ return response.json();
245
+ }
246
+ async locks() {
247
+ return parse(z.object({ data: z.array(lock_schema) }), await this.call("GET", "/locks")).data;
248
+ }
249
+ async wrapped(lock_id) {
250
+ return parse(z.object({ data: z.object({ wrapped: z.string() }) }), await this.call("GET", `/locks/${encodeURIComponent(lock_id)}`)).data.wrapped;
251
+ }
252
+ async add(lock) {
253
+ return parse(z.object({ data: z.object({ id: z.string() }) }), await this.call("POST", "/locks", lock)).data.id;
254
+ }
255
+ async remove(lock_id) {
256
+ await this.call("DELETE", `/locks/${encodeURIComponent(lock_id)}`);
257
+ }
258
+ async requests() {
259
+ return parse(z.object({ data: z.array(key_request_schema) }), await this.call("GET", "/requests")).data;
260
+ }
261
+ async ask(commitment, label) {
262
+ return parse(z.object({ data: z.object({ id: z.string(), expires_at: z.string() }) }), await this.call("POST", "/requests", { commitment, label })).data;
263
+ }
264
+ async answer_of(request_id) {
265
+ return parse(z.object({
266
+ data: z.object({
267
+ status: z.string(),
268
+ approver_key: z.string().optional(),
269
+ wrapped: z.string().optional(),
270
+ }),
271
+ }), await this.call("GET", `/requests/${encodeURIComponent(request_id)}`)).data;
272
+ }
273
+ async reveal(request_id, public_key, nonce) {
274
+ await this.call("POST", `/requests/${encodeURIComponent(request_id)}/reveal`, { public_key, nonce });
275
+ }
276
+ async offer(request_id, approver_key) {
277
+ await this.call("POST", `/requests/${encodeURIComponent(request_id)}/offer`, { approver_key });
278
+ }
279
+ async request(request_id) {
280
+ return (await this.requests()).find((entry) => entry.id === request_id) ?? null;
281
+ }
282
+ async answer(request_id, wrapped) {
283
+ await this.call("POST", `/requests/${encodeURIComponent(request_id)}`, { wrapped });
284
+ }
285
+ }
286
+ export async function list_vaults(transport) {
287
+ const response = await transport("GET", "/api/v1/vaults", {});
288
+ if (!response.ok)
289
+ throw await error_of(response);
290
+ return parse(z.object({ data: z.array(vault_schema) }), await response.json()).data;
291
+ }
292
+ export async function create_vault(transport, name, privacy) {
293
+ const response = await transport("POST", "/api/v1/vaults", {
294
+ headers: { "content-type": "application/json" },
295
+ body: JSON.stringify(privacy === undefined ? { name } : { name, id: privacy.id, mode: "private", locks: privacy.locks }),
296
+ });
297
+ if (!response.ok)
298
+ throw await error_of(response);
299
+ return parse(z.object({ data: vault_schema }), await response.json()).data;
300
+ }
@@ -0,0 +1,59 @@
1
+ import { read_credentials } from "../config.js";
2
+ import { device_name } from "../device.js";
3
+ import { CliError } from "../errors.js";
4
+ import { send } from "../http.js";
5
+ import { VERSION } from "../version.js";
6
+ import { VaultApi } from "./api.js";
7
+ import { vault_keys } from "./private/crypto.js";
8
+ import { PrivateVaultApi } from "./private/api.js";
9
+ import { load_vault_key } from "./private/keystore.js";
10
+ import { state_path_for } from "./state.js";
11
+ export function cli_transport(workspace) {
12
+ return async (method, path, options) => {
13
+ const { response } = await send(method, path, {
14
+ ...options,
15
+ workspace: workspace ?? undefined,
16
+ });
17
+ return response;
18
+ };
19
+ }
20
+ export function client_label() {
21
+ return `nemu-sync/${VERSION} ${device_name()}`.replace(/[^\x20-\x7e]/g, "").slice(0, 64);
22
+ }
23
+ export async function signed_in() {
24
+ const credentials = await read_credentials();
25
+ if (credentials === null)
26
+ throw new CliError("Not signed in. Run nemu login.", "not_signed_in");
27
+ return credentials;
28
+ }
29
+ export async function open_linked(marker) {
30
+ const credentials = await signed_in();
31
+ if (credentials.api_url !== marker.server) {
32
+ throw new CliError(`This folder is linked to a vault on ${marker.server}, but you are signed in to ${credentials.api_url}. Nothing was synced.`, "server_mismatch");
33
+ }
34
+ if (credentials.kind === "key" &&
35
+ credentials.workspace !== undefined &&
36
+ marker.workspace_id !== null &&
37
+ credentials.workspace.id !== marker.workspace_id) {
38
+ throw new CliError(`This folder belongs to another workspace than the API key you signed in with (${credentials.workspace.name}). Nothing was synced.`, "workspace_mismatch");
39
+ }
40
+ const api = new VaultApi(cli_transport(marker.workspace_id), marker.vault_id, client_label());
41
+ const info = await api.info();
42
+ const vault_key = await load_vault_key(marker.vault_id);
43
+ const is_pinned_private = marker.mode === "private" || vault_key !== null;
44
+ const says_private = info.data.mode === "private";
45
+ if (is_pinned_private !== says_private && (marker.mode !== undefined || vault_key !== null)) {
46
+ throw new CliError(`Nemu now reports "${marker.vault_name}" as ${says_private ? "private" : "not private"}, but it was ${is_pinned_private ? "private" : "not private"} when this folder was linked. A vault never changes this, so nothing was synced. Check the vault in the console.`, "vault_mode_changed");
47
+ }
48
+ if (!says_private) {
49
+ return { api, state_path: state_path_for(marker.vault_id), is_private: false };
50
+ }
51
+ if (vault_key === null) {
52
+ throw new CliError(`"${marker.vault_name}" is a private vault and is locked on this computer. Run nemu vault unlock first. Nothing was synced.`, "vault_locked");
53
+ }
54
+ return {
55
+ api: new PrivateVaultApi(api, vault_keys(marker.vault_id, vault_key)),
56
+ state_path: state_path_for(marker.vault_id),
57
+ is_private: true,
58
+ };
59
+ }