@creator-notes/cnotes 0.133.0 → 0.133.3

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "creator-notes-cli",
3
- "version": "0.133.0",
3
+ "version": "0.133.3",
4
4
  "description": "CreatorNotes CLI: create notes, build canvases, search knowledge from the terminal",
5
5
  "author": {
6
6
  "name": "CreatorNotes",
@@ -23,11 +23,16 @@ import { isLocalDbEnabled } from "./auth-store.js";
23
23
  import { CliError, NotFoundError } from "./errors.js";
24
24
  import { lastLocalWriteAt, localDbDirectory } from "./local-write-mark.js";
25
25
  import { getMeta, readPinnedNoteIds, setMeta } from "../local-db/apply.js";
26
+ import { isBlankSql, readableSqlError, readOnlyAction, SQL_ONE_STATEMENT, SQL_READ_ONLY } from "../local-db/query.js";
26
27
  import { createLocalDbOps, openCopy } from "../local-db/ops.js";
27
28
  import { localDbFileName, workspaceFilePrefix } from "../local-db/protocol.js";
28
29
  import { SCHEMA_VERSION } from "../local-db/schema.js";
29
30
  import { IDLE_STATUS, WorkspaceSync } from "../local-db/sync.js";
30
31
  export { localDbDirectory };
32
+ /** Read-only in both bindings' spelling: node:sqlite reads `readOnly`, bun:sqlite `readonly`. */
33
+ const READ_ONLY_OPEN = { readOnly: true, readonly: true };
34
+ const SQLITE_OK = 0;
35
+ const SQLITE_DENY = 1;
31
36
  export const LOCAL_DB_OFF_MESSAGE = "A local copy of this workspace is not allowed on this machine yet.";
32
37
  export const LOCAL_DB_OFF_HINT = "cnotes query keeps the workspace's note metadata (titles, types, tags, canvases, who made each note, judged answers; never a note body) " +
33
38
  "in a SQLite file under the cnotes config directory. If the person agrees, they run `cnotes config set-local-db on`; " +
@@ -50,8 +55,19 @@ async function loadDatabase() {
50
55
  throw new CliError(NODE_SQLITE_HINT);
51
56
  }
52
57
  }
53
- /** The handle the shared code needs, over one open database. */
54
- function wrap(handle) {
58
+ /**
59
+ * The handle the shared code needs, over one open database.
60
+ *
61
+ * `rows` is the SQL box's guarantee, and SQLite enforces it, not a text check.
62
+ * The statement runs on a second connection to the same file opened
63
+ * read-only, so no statement it prepares can write and no PRAGMA can switch
64
+ * that off. The binding compiles exactly one statement; where it says how
65
+ * much of the text that was (node:sqlite's `sourceSQL`), anything after it
66
+ * but whitespace and comments is refused before a step runs. Where the
67
+ * binding has an authorizer (node:sqlite 24.10+), it refuses every action but
68
+ * reading while the statement is prepared, so ATTACH never opens a file.
69
+ */
70
+ function wrap(handle, openReader) {
55
71
  return {
56
72
  run: (sql, params = []) => {
57
73
  if (params.length)
@@ -73,17 +89,34 @@ function wrap(handle) {
73
89
  }
74
90
  },
75
91
  rows: (sql, params = []) => {
76
- // query_only makes SQLite itself refuse any write, whatever the text says.
77
- handle.exec("PRAGMA query_only = 1");
92
+ const reader = openReader();
78
93
  try {
79
- const stmt = handle.prepare(sql);
94
+ reader.setAuthorizer?.((code, arg1) => (readOnlyAction(code, arg1) ? SQLITE_OK : SQLITE_DENY));
95
+ let stmt;
96
+ try {
97
+ stmt = reader.prepare(sql);
98
+ }
99
+ catch (err) {
100
+ throw new Error(readableSqlError(err instanceof Error ? err.message : String(err)));
101
+ }
102
+ const compiled = stmt.sourceSQL;
103
+ if (typeof compiled === "string" && (!sql.startsWith(compiled) || !isBlankSql(sql.slice(compiled.length)))) {
104
+ throw new Error(SQL_ONE_STATEMENT);
105
+ }
80
106
  const columns = stmt.columns ? stmt.columns().map((c) => c.name) : (stmt.columnNames ?? []);
81
- const objects = stmt.all(...params);
107
+ let objects;
108
+ try {
109
+ objects = stmt.all(...params);
110
+ }
111
+ catch (err) {
112
+ const message = err instanceof Error ? err.message : String(err);
113
+ throw new Error(/readonly/i.test(message) ? SQL_READ_ONLY : readableSqlError(message));
114
+ }
82
115
  const names = columns.length ? columns : Object.keys(objects[0] ?? {});
83
116
  return { columns: names, rows: objects.map((o) => names.map((c) => o[c] ?? null)) };
84
117
  }
85
118
  finally {
86
- handle.exec("PRAGMA query_only = 0");
119
+ reader.close();
87
120
  }
88
121
  },
89
122
  };
@@ -138,10 +171,11 @@ export class LocalCopyStore {
138
171
  const path = join(this.directory, fileName.replace(/^\//, ""));
139
172
  this.handle = new this.Database(path);
140
173
  this.openPath = path;
141
- const db = wrap(this.handle);
174
+ const db = wrap(this.handle, () => new this.Database(path, READ_ONLY_OPEN));
142
175
  this.sqlDb = db;
143
176
  this.ops = createLocalDbOps(db);
144
- const opened = openCopy(db, true);
177
+ // The CLI owns its directory outright, so a wipe-first open always wiped.
178
+ const opened = { ...openCopy(db, true), wiped: wipeFirst };
145
179
  this.fresh = opened.fresh;
146
180
  return opened;
147
181
  }
@@ -151,12 +185,12 @@ export class LocalCopyStore {
151
185
  if (this.openPath && this.openPath.includes(prefix))
152
186
  this.close();
153
187
  this.removeFiles((name) => name.startsWith(prefix));
154
- return null;
188
+ return { forgotten: true };
155
189
  }
156
190
  case "wipe":
157
191
  this.close();
158
192
  this.wipeAll();
159
- return null;
193
+ return { wiped: true };
160
194
  default: {
161
195
  const handler = this.db[op];
162
196
  return handler(args);
@@ -28,8 +28,22 @@ import { DISPLAY_ID_CORE } from "./display-id.js";
28
28
  const DISPLAY_ID_RE = new RegExp(String.raw `^${DISPLAY_ID_CORE}(@v\d+)?$`);
29
29
  /** An `@key` batch placeholder (only valid inside `notes create`). */
30
30
  const AT_KEY_RE = /^@[A-Za-z][\w-]*$/;
31
- /** Every inline relationship mention, well-formed or not. */
32
- const MENTION_RE = /\[([^\]]*)\]\(relationship:([^)]*)\)/g;
31
+ /**
32
+ * Every inline relationship mention, well-formed or not. The link text holds
33
+ * no "[": a stray bracket earlier in the prose would otherwise become the
34
+ * start of the link text and swallow the sentence up to a valid mention.
35
+ */
36
+ const MENTION_RE = /\[([^[\]]*)\]\(relationship:([^)]*)\)/g;
37
+ /**
38
+ * The markdown with code blocks and inline code blanked out. The parser
39
+ * reads a mention inside code as code, so a note that documents the syntax
40
+ * (`[Title](relationship:slug)`) holds no link to lint.
41
+ */
42
+ function withoutCode(markdown) {
43
+ return markdown
44
+ .replace(/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1[ \t]*$/gm, " ")
45
+ .replace(/(`+)[\s\S]*?\1/g, " ");
46
+ }
33
47
  /** Extract the target token from link text: the part before an optional `: Title` or `|alias`. */
34
48
  function targetOf(linkText) {
35
49
  const cut = linkText.search(/[:|]/);
@@ -51,7 +65,7 @@ function isValidTarget(target, allowAtKey) {
51
65
  */
52
66
  export function lintMentionMarkdown(markdown, allowAtKey) {
53
67
  const issues = [];
54
- for (const m of markdown.matchAll(MENTION_RE)) {
68
+ for (const m of withoutCode(markdown).matchAll(MENTION_RE)) {
55
69
  const raw = m[0];
56
70
  const linkText = m[1];
57
71
  const type = m[2].trim();
@@ -11,7 +11,7 @@
11
11
  * files stay with the storage, so they are not here.
12
12
  */
13
13
  import { applyAnswers, applyHead, applyNotes, applyPlacements, countRows, getMeta, readWorkspaceLayout, reconcileNotes, setMeta } from "./apply.js";
14
- import { buildCountQuery, buildFacetQuery, buildGroupCountsQuery, buildResultsQuery, checkReadOnlySql } from "./query.js";
14
+ import { buildCountQuery, buildFacetQuery, buildGroupCountsQuery, buildResultsQuery, checkReadOnlySql, wrapReadOnlySql } from "./query.js";
15
15
  import { ensureSchema } from "./schema.js";
16
16
  export const NEWEST_KEY = "newest_note_updated_at";
17
17
  export const RECONCILED_KEY = "last_reconciled_at";
@@ -31,20 +31,23 @@ export function openCopy(db, persistent) {
31
31
  fresh,
32
32
  newestNoteUpdatedAt: Number(getMeta(db, NEWEST_KEY) ?? 0),
33
33
  reconciledAt: Number(getMeta(db, RECONCILED_KEY) ?? 0),
34
+ wiped: false,
34
35
  };
35
36
  }
36
37
  /**
37
- * Run one SELECT (or WITH ... SELECT) and return rows as arrays. The caller
38
- * wraps it in `PRAGMA query_only` where the handle supports it; the text check
39
- * here is for a readable error, not the guarantee. `deadlineMs` goes to a
40
- * handle that can interrupt the query (the browser worker); others ignore it.
38
+ * Run one SELECT (or WITH ... SELECT) and return rows as arrays. The text
39
+ * check here is for a readable error, not the guarantee: the handle's `rows`
40
+ * prepares exactly one statement and has SQLite refuse anything but a read
41
+ * (the browser worker's in lib/local-db/wasm-handle.ts, the CLI's in
42
+ * cli/src/lib/local-db-store.ts). `deadlineMs` goes to a handle that can
43
+ * interrupt the query (the browser worker); others ignore it.
41
44
  */
42
45
  export function runReadOnlySql(db, sql, maxRows, deadlineMs) {
43
46
  const checked = checkReadOnlySql(sql);
44
47
  if (!checked.ok)
45
48
  throw new Error(checked.reason);
46
49
  const start = now();
47
- const wrapped = `SELECT * FROM (${checked.sql}) LIMIT ${maxRows + 1}`;
50
+ const wrapped = wrapReadOnlySql(checked.sql, maxRows + 1);
48
51
  let columns;
49
52
  let rows;
50
53
  if (db.rows) {
@@ -167,18 +167,124 @@ export function buildFacetQuery(filter, field, limit) {
167
167
  params: [...counts.params, limit],
168
168
  };
169
169
  }
170
+ export const SQL_EMPTY = "Type a SELECT statement.";
171
+ export const SQL_READ_ONLY = "Only SELECT statements run here.";
172
+ export const SQL_ONE_STATEMENT = "Run one statement at a time.";
173
+ export const SQL_UNCLOSED = "A quote in the statement is not closed.";
170
174
  /**
171
- * The SQL box runs one SELECT (or WITH ... SELECT) statement. The worker also
172
- * runs it with `PRAGMA query_only` on, so this check is for a readable error,
173
- * not the guarantee.
175
+ * Walk SQL the way SQLite's tokenizer splits it: quoted strings and
176
+ * identifiers ('…', "…", `…`, […]) and comments (-- to the end of the line,
177
+ * /* to *\/ or the end) are skipped as a whole, so a quote inside a comment or
178
+ * a semicolon inside a string never counts. Returns where the first statement
179
+ * starts, where the first semicolon outside them sits, and whether a quote
180
+ * runs off the end.
181
+ */
182
+ function scanSql(sql) {
183
+ let start = -1;
184
+ let i = 0;
185
+ while (i < sql.length) {
186
+ const c = sql[i];
187
+ const next = sql[i + 1];
188
+ if (c === "-" && next === "-") {
189
+ const end = sql.indexOf("\n", i + 2);
190
+ i = end === -1 ? sql.length : end + 1;
191
+ continue;
192
+ }
193
+ if (c === "/" && next === "*") {
194
+ const end = sql.indexOf("*/", i + 2);
195
+ i = end === -1 ? sql.length : end + 2;
196
+ continue;
197
+ }
198
+ if (/\s/.test(c)) {
199
+ i += 1;
200
+ continue;
201
+ }
202
+ if (c === ";")
203
+ return { start, semicolon: i, unclosed: false };
204
+ if (start === -1)
205
+ start = i;
206
+ const close = c === "'" || c === '"' || c === "`" ? c : c === "[" ? "]" : null;
207
+ if (close) {
208
+ let j = i + 1;
209
+ for (;;) {
210
+ const end = sql.indexOf(close, j);
211
+ if (end === -1)
212
+ return { start, semicolon: -1, unclosed: true };
213
+ // A doubled quote is an escaped quote inside the string ([…] has no escape).
214
+ if (close !== "]" && sql[end + 1] === close) {
215
+ j = end + 2;
216
+ continue;
217
+ }
218
+ i = end + 1;
219
+ break;
220
+ }
221
+ continue;
222
+ }
223
+ i += 1;
224
+ }
225
+ return { start, semicolon: -1, unclosed: false };
226
+ }
227
+ /** True when SQL holds nothing SQLite would run: whitespace, comments and semicolons only. */
228
+ export function isBlankSql(sql) {
229
+ let rest = sql;
230
+ for (;;) {
231
+ const scan = scanSql(rest);
232
+ if (scan.unclosed || scan.start !== -1)
233
+ return false;
234
+ if (scan.semicolon === -1)
235
+ return true;
236
+ rest = rest.slice(scan.semicolon + 1);
237
+ }
238
+ }
239
+ /**
240
+ * The SQL box runs one SELECT (or WITH ... SELECT) statement. This check is
241
+ * for a readable error, not the guarantee: the handle that runs the statement
242
+ * prepares exactly one and refuses anything that is not a read
243
+ * (`readOnlyAction` below, and each handle's `rows`).
174
244
  */
175
245
  export function checkReadOnlySql(sql) {
176
- const trimmed = sql.trim().replace(/;\s*$/, "");
177
- if (!trimmed)
178
- return { ok: false, reason: "Type a SELECT statement." };
179
- if (!/^(select|with)\b/i.test(trimmed))
180
- return { ok: false, reason: "Only SELECT statements run here." };
181
- if (/;/.test(trimmed.replace(/'(?:[^']|'')*'/g, "''")))
182
- return { ok: false, reason: "Run one statement at a time." };
183
- return { ok: true, sql: trimmed };
246
+ const scan = scanSql(sql);
247
+ if (scan.unclosed)
248
+ return { ok: false, reason: SQL_UNCLOSED };
249
+ const end = scan.semicolon === -1 ? sql.length : scan.semicolon;
250
+ const more = scan.semicolon !== -1 && !isBlankSql(sql.slice(scan.semicolon + 1));
251
+ if (scan.start === -1)
252
+ return { ok: false, reason: more ? SQL_ONE_STATEMENT : SQL_EMPTY };
253
+ if (more)
254
+ return { ok: false, reason: SQL_ONE_STATEMENT };
255
+ const statement = sql.slice(scan.start, end).trim();
256
+ if (!/^(select|with)\b/i.test(statement))
257
+ return { ok: false, reason: SQL_READ_ONLY };
258
+ return { ok: true, sql: statement };
259
+ }
260
+ /**
261
+ * A checked statement inside the row cap. The newlines keep a trailing
262
+ * `-- comment` from swallowing the closing parenthesis.
263
+ */
264
+ export function wrapReadOnlySql(sql, limit) {
265
+ return `SELECT * FROM (\n${sql}\n) LIMIT ${limit}`;
266
+ }
267
+ /** SQLite authorizer action codes (sqlite3.h) that a read needs. */
268
+ const SQLITE_PRAGMA = 19;
269
+ const SQLITE_READ = 20;
270
+ const SQLITE_SELECT = 21;
271
+ const SQLITE_FUNCTION = 31;
272
+ const SQLITE_RECURSIVE = 33;
273
+ /** Pragmas a SELECT may read as table-valued functions (`pragma_table_info('notes')`): the schema, never a setting. */
274
+ const READABLE_PRAGMAS = new Set(["table_info", "table_xinfo", "table_list", "index_list", "index_info", "index_xinfo", "foreign_key_list"]);
275
+ /**
276
+ * The authorizer for the SQL box: SQLite asks it about every action a
277
+ * statement would take while preparing it, and a refusal fails the prepare.
278
+ * Only reading tables, calling functions, recursive CTEs and reading the
279
+ * schema pass; a write, ATTACH, a PRAGMA that sets anything, a transaction or
280
+ * a schema change is refused by the engine, whatever the text says.
281
+ */
282
+ export function readOnlyAction(code, arg1) {
283
+ if (code === SQLITE_SELECT || code === SQLITE_READ || code === SQLITE_FUNCTION || code === SQLITE_RECURSIVE)
284
+ return true;
285
+ return code === SQLITE_PRAGMA && arg1 !== null && READABLE_PRAGMAS.has(arg1.toLowerCase());
286
+ }
287
+ /** SQLite's own refusal from the authorizer, said the way the box says it. */
288
+ export function readableSqlError(message) {
289
+ return /not authorized/i.test(message) ? SQL_READ_ONLY : message;
184
290
  }
@@ -139,7 +139,10 @@ export class WorkspaceSync {
139
139
  fileName: localDbFileName(head.userId, this.workspaceId),
140
140
  wipeFirst: this.options.wipePending?.() ?? false,
141
141
  });
142
- this.options.clearWipePending?.();
142
+ // Only a wipe that happened clears the flag: a tab that does not hold the
143
+ // files deletes nothing, and the copies must still go on a later open.
144
+ if (opened.wiped)
145
+ this.options.clearWipePending?.();
143
146
  this.opened = true;
144
147
  this.newest = opened.fresh ? 0 : opened.newestNoteUpdatedAt;
145
148
  const every = this.options.reconcileEvery;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@creator-notes/cnotes",
3
- "version": "0.133.0",
3
+ "version": "0.133.3",
4
4
  "description": "CLI for CreatorNotes — create notes, build canvases, search knowledge from the terminal",
5
5
  "type": "module",
6
6
  "bin": {