scorpiox-bot-plugin-notes
←plugin_notes.cc
1624 lines · 49 KBHEADBlameDownload
1/*
2 * plugin_notes - SCORPIOX BOT open-source markdown notes for your node
3 *
4 * A single clean-room C99 binary that serves THREE modes:
5 * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6 * 2. ?action=... / ?format=json / POST -> JSON node API
7 * 3. GET (default) -> two-pane markdown editor
8 *
9 * Storage: one file per note, `<id>.md`, plus `index.json` holding the
10 * metadata and the ordering. Both live inside `<plugin dir>/.notes/`
11 * (Linux/macOS) or `%LOCALAPPDATA%\scorpiox\plugins\.notes\` (Windows), and
12 * `$NOTES_DIR` overrides the location for tests and for people who want their
13 * notes somewhere else. Every write goes to `<name>.tmp` and is then renamed
14 * over the real file, so a kill -9 mid-write leaves the previous content
15 * intact rather than a truncated note.
16 *
17 * Note ids are generated by this binary (`[a-z0-9]{12}`), never taken from the
18 * client as a path, and any id that arrives in a request is validated against
19 * that shape before it can touch the filesystem. Markdown is rendered
20 * server-side with raw HTML escaped first, so a note containing `<script>` or
21 * a `javascript:` link renders as inert text.
22 *
23 * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
24 * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
25 * scorpiox-server on the node.
26 *
27 * MIT License. Copyright (c) 2026 SCORPIOX INC.
28 */
29
30/* Must come before every include on Windows: MinGW defaults to 0x502
31 * (Server 2003), which hides MoveFileExA and the wide-path helpers. */
32#if defined(_WIN32) && !defined(_WIN32_WINNT)
33# define _WIN32_WINNT 0x0601
34#endif
35
36#if !defined(_WIN32)
37# define _POSIX_C_SOURCE 200809L
38# define _DEFAULT_SOURCE 1
39# if defined(__APPLE__)
40# define _DARWIN_C_SOURCE 1
41# endif
42#endif
43
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#include <ctype.h>
48#include <errno.h>
49#include <time.h>
50
51#if defined(_WIN32)
52# define WIN32_LEAN_AND_MEAN
53# include <windows.h>
54# include <direct.h>
55# include <io.h>
56#else
57# include <unistd.h>
58# include <sys/stat.h>
59# include <sys/types.h>
60#endif
61
62#include "bot_theme_plugin.h"
63#include "ui_html.h"
64
65#define PLUGIN_SLUG "notes"
66#define PLUGIN_ID "plugin_notes"
67#define PLUGIN_VER "1.0.0"
68#define PLUGIN_NAME "notes"
69#define PLUGIN_DESC "Markdown notes"
70
71#define PATH_SZ 1024
72#define ID_LEN 12
73#define ID_BUF (ID_LEN + 1)
74#define TITLE_MAX 300
75#define MAX_NOTES 2000
76#define BODY_MAX (512 * 1024) /* hard cap on one note, spec'd */
77#define REQ_MAX (BODY_MAX + 8192) /* JSON envelope around it */
78#define TRASH_DIR ".trash"
79
80typedef struct {
81 char id[ID_BUF];
82 char title[TITLE_MAX];
83 int pinned;
84 char created[24];
85 char updated[24];
86} note_meta_t;
87
88static note_meta_t g_meta[MAX_NOTES];
89static int g_count;
90
91static char g_dir[PATH_SZ]; /* <notes dir> */
92static char g_trash[PATH_SZ]; /* <notes dir>/.trash */
93
94/* ------------------------------------------------------------------ */
95/* Growable byte buffer */
96/* ------------------------------------------------------------------ */
97
98typedef struct {
99 char *p;
100 size_t n;
101 size_t cap;
102} buf_t;
103
104static void buf_init(buf_t *b)
105{
106 b->p = NULL;
107 b->n = 0;
108 b->cap = 0;
109}
110
111static int buf_need(buf_t *b, size_t extra)
112{
113 size_t want = b->n + extra + 1;
114 char *np;
115 if (want <= b->cap) return 1;
116 if (b->cap == 0) b->cap = 1024;
117 while (b->cap < want) {
118 if (b->cap > (size_t)64 * 1024 * 1024) return 0;
119 b->cap *= 2;
120 }
121 np = (char *)realloc(b->p, b->cap);
122 if (!np) return 0;
123 b->p = np;
124 return 1;
125}
126
127static void buf_add(buf_t *b, const char *s, size_t n)
128{
129 if (!s || n == 0) return;
130 if (!buf_need(b, n)) return;
131 memcpy(b->p + b->n, s, n);
132 b->n += n;
133 b->p[b->n] = '\0';
134}
135
136static void buf_puts(buf_t *b, const char *s)
137{
138 if (s) buf_add(b, s, strlen(s));
139}
140
141static void buf_putc(buf_t *b, char c)
142{
143 buf_add(b, &c, 1);
144}
145
146static const char *buf_str(buf_t *b)
147{
148 return b->p ? b->p : "";
149}
150
151static void buf_free(buf_t *b)
152{
153 free(b->p);
154 buf_init(b);
155}
156
157/* ------------------------------------------------------------------ */
158/* Small utilities */
159/* ------------------------------------------------------------------ */
160
161static void str_copy(char *dst, size_t sz, const char *src)
162{
163 size_t n;
164 if (!dst || sz == 0) return;
165 if (!src) { dst[0] = '\0'; return; }
166 n = strlen(src);
167 if (n >= sz) n = sz - 1;
168 memcpy(dst, src, n);
169 dst[n] = '\0';
170}
171
172static void path_join(char *out, size_t sz, const char *a, const char *b)
173{
174 size_t n;
175 if (!out || sz == 0) return;
176 out[0] = '\0';
177 if (!a) a = "";
178 if (!b) b = "";
179 str_copy(out, sz, a);
180 n = strlen(out);
181 if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) {
182 out[n++] = '/';
183 out[n] = '\0';
184 }
185 if (n + strlen(b) < sz) str_copy(out + n, sz - n, b);
186}
187
188static void url_decode(char *s)
189{
190 char *o = s;
191 if (!s) return;
192 while (*s) {
193 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
194 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
195 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
196 *o++ = (char)((hi << 4) | lo);
197 s += 3;
198 } else if (*s == '+') {
199 *o++ = ' ';
200 s++;
201 } else {
202 *o++ = *s++;
203 }
204 }
205 *o = '\0';
206}
207
208static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
209{
210 size_t klen;
211 const char *p;
212
213 if (!out || outsz == 0) return 0;
214 out[0] = '\0';
215 if (!qs || !key) return 0;
216 klen = strlen(key);
217
218 for (p = qs; *p; ) {
219 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
220 const char *v = p + klen + 1;
221 size_t i = 0;
222 while (*v && *v != '&' && i + 1 < outsz)
223 out[i++] = *v++;
224 out[i] = '\0';
225 url_decode(out);
226 return 1;
227 }
228 p = strchr(p, '&');
229 if (!p) break;
230 p++;
231 }
232 return 0;
233}
234
235static void json_str(buf_t *b, const char *s)
236{
237 buf_putc(b, '"');
238 for (; s && *s; s++) {
239 unsigned char c = (unsigned char)*s;
240 switch (c) {
241 case '"': buf_puts(b, "\\\""); break;
242 case '\\': buf_puts(b, "\\\\"); break;
243 case '\n': buf_puts(b, "\\n"); break;
244 case '\r': buf_puts(b, "\\r"); break;
245 case '\t': buf_puts(b, "\\t"); break;
246 default:
247 if (c < 0x20) {
248 char tmp[8];
249 sprintf(tmp, "\\u%04x", c);
250 buf_puts(b, tmp);
251 } else {
252 buf_putc(b, (char)c);
253 }
254 }
255 }
256 buf_putc(b, '"');
257}
258
259static void iso_now(char *out, size_t sz)
260{
261 time_t t = time(NULL);
262 struct tm tmv;
263#if defined(_WIN32)
264 gmtime_s(&tmv, &t);
265#else
266 gmtime_r(&t, &tmv);
267#endif
268 strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
269}
270
271static int valid_id(const char *id)
272{
273 int i;
274 if (!id) return 0;
275 if (strlen(id) != ID_LEN) return 0;
276 for (i = 0; i < ID_LEN; i++) {
277 char c = id[i];
278 if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) return 0;
279 }
280 return 1;
281}
282
283static void gen_id(char *out)
284{
285 static const char *alpha = "abcdefghijklmnopqrstuvwxyz0123456789";
286 unsigned int seed;
287 int i;
288#if defined(_WIN32)
289 seed = (unsigned int)GetTickCount() ^ (unsigned int)time(NULL);
290#else
291 seed = (unsigned int)time(NULL) ^ ((unsigned int)getpid() << 16);
292#endif
293 seed ^= (unsigned int)(size_t)out;
294 seed = seed * 1103515245u + 12345u;
295 for (i = 0; i < ID_LEN; i++) {
296 seed = seed * 1103515245u + 12345u;
297 out[i] = alpha[(seed >> 16) % 36u];
298 }
299 out[ID_LEN] = '\0';
300}
301
302/* ------------------------------------------------------------------ */
303/* Filesystem helpers */
304/* ------------------------------------------------------------------ */
305
306static void mkdir_one(const char *p)
307{
308#if defined(_WIN32)
309 _mkdir(p);
310#else
311 mkdir(p, 0700);
312#endif
313}
314
315static int path_is_dir(const char *p)
316{
317#if defined(_WIN32)
318 DWORD a = GetFileAttributesA(p);
319 return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY);
320#else
321 struct stat st;
322 return stat(p, &st) == 0 && S_ISDIR(st.st_mode);
323#endif
324}
325
326static int file_exists(const char *p)
327{
328#if defined(_WIN32)
329 return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES;
330#else
331 return access(p, F_OK) == 0;
332#endif
333}
334
335/* Atomic replace: write to <dst>.tmp, then move it over <dst>. */
336static int atomic_write(const char *dst, const char *data, size_t len)
337{
338 char tmp[PATH_SZ + 8];
339 FILE *f;
340 size_t wrote;
341
342 if (!dst || strlen(dst) + 5 >= sizeof tmp) return 0;
343 sprintf(tmp, "%s.tmp", dst);
344
345 f = fopen(tmp, "wb");
346 if (!f) return 0;
347 wrote = fwrite(data, 1, len, f);
348 if (fflush(f) != 0) { fclose(f); remove(tmp); return 0; }
349#if !defined(_WIN32)
350 fsync(fileno(f));
351#endif
352 if (fclose(f) != 0) { remove(tmp); return 0; }
353 if (wrote != len) { remove(tmp); return 0; }
354
355#if defined(_WIN32)
356 if (!MoveFileExA(tmp, dst, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
357 remove(tmp);
358 return 0;
359 }
360#else
361 if (rename(tmp, dst) != 0) { remove(tmp); return 0; }
362#endif
363 return 1;
364}
365
366static char *read_whole_file(const char *path, size_t *out_len)
367{
368 FILE *f;
369 long sz;
370 char *p;
371 size_t got;
372
373 f = fopen(path, "rb");
374 if (!f) return NULL;
375 if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
376 sz = ftell(f);
377 if (sz < 0) { fclose(f); return NULL; }
378 if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
379 p = (char *)malloc((size_t)sz + 1);
380 if (!p) { fclose(f); return NULL; }
381 got = fread(p, 1, (size_t)sz, f);
382 fclose(f);
383 p[got] = '\0';
384 if (out_len) *out_len = got;
385 return p;
386}
387
388/* ------------------------------------------------------------------ */
389/* Tiny JSON reader (only what index.json and the save payload need) */
390/* ------------------------------------------------------------------ */
391
392/* Copy a JSON string value starting at *pp (which points at the opening
393 * quote) into out. Returns 1 on success and advances *pp past the closing
394 * quote. Handles the escapes this plugin can emit plus \uXXXX as UTF-8. */
395static int json_read_string(const char **pp, char *out, size_t outsz)
396{
397 const char *p = *pp;
398 size_t o = 0;
399
400 if (!p || *p != '"') return 0;
401 p++;
402 while (*p && *p != '"') {
403 unsigned char c = (unsigned char)*p;
404 if (c == '\\') {
405 p++;
406 switch (*p) {
407 case '"': c = '"'; break;
408 case '\\': c = '\\'; break;
409 case '/': c = '/'; break;
410 case 'b': c = '\b'; break;
411 case 'f': c = '\f'; break;
412 case 'n': c = '\n'; break;
413 case 'r': c = '\r'; break;
414 case 't': c = '\t'; break;
415 case 'u': {
416 unsigned int cp = 0;
417 int i;
418 for (i = 0; i < 4 && p[1]; i++) {
419 char h = p[1 + i];
420 cp <<= 4;
421 if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0');
422 else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10);
423 else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10);
424 }
425 p += 4;
426 /* BMP only; enough for the control characters we emit */
427 if (cp == 0) {
428 c = 0;
429 } else if (cp < 0x80) {
430 c = (unsigned char)cp;
431 } else if (cp < 0x800) {
432 if (o + 1 < outsz) out[o++] = (char)(0xC0 | (cp >> 6));
433 c = (unsigned char)(0x80 | (cp & 0x3F));
434 } else {
435 if (o + 2 < outsz) {
436 out[o++] = (char)(0xE0 | (cp >> 12));
437 out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F));
438 }
439 c = (unsigned char)(0x80 | (cp & 0x3F));
440 }
441 if (c == 0) { p++; continue; }
442 break;
443 }
444 default: c = (unsigned char)*p; break;
445 }
446 p++;
447 } else {
448 p++;
449 }
450 if (o + 1 < outsz) out[o++] = (char)c;
451 }
452 if (*p == '"') p++;
453 if (outsz) out[o < outsz ? o : outsz - 1] = '\0';
454 *pp = p;
455 return 1;
456}
457
458/* Read a JSON string into a freshly allocated buffer. Bodies can be 512 KiB,
459 * so they must never land in a fixed-size stack frame. */
460static char *json_dup_string(const char **pp)
461{
462 const char *p = *pp;
463 buf_t b;
464
465 if (!p || *p != '"') return NULL;
466 buf_init(&b);
467 if (!buf_need(&b, 0)) return NULL;
468 p++;
469
470 while (*p && *p != '"') {
471 unsigned char c = (unsigned char)*p;
472 if (c == '\\') {
473 p++;
474 switch (*p) {
475 case '"': c = '"'; break;
476 case '\\': c = '\\'; break;
477 case '/': c = '/'; break;
478 case 'b': c = '\b'; break;
479 case 'f': c = '\f'; break;
480 case 'n': c = '\n'; break;
481 case 'r': c = '\r'; break;
482 case 't': c = '\t'; break;
483 case 'u': {
484 unsigned int cp = 0;
485 int i;
486 for (i = 0; i < 4 && p[1]; i++) {
487 char h = p[1 + i];
488 cp <<= 4;
489 if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0');
490 else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10);
491 else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10);
492 }
493 p += 4;
494 if (cp < 0x80 && cp) {
495 buf_putc(&b, (char)cp);
496 } else if (cp >= 0x80 && cp < 0x800) {
497 buf_putc(&b, (char)(0xC0 | (cp >> 6)));
498 buf_putc(&b, (char)(0x80 | (cp & 0x3F)));
499 } else if (cp >= 0x800) {
500 buf_putc(&b, (char)(0xE0 | (cp >> 12)));
501 buf_putc(&b, (char)(0x80 | ((cp >> 6) & 0x3F)));
502 buf_putc(&b, (char)(0x80 | (cp & 0x3F)));
503 }
504 p++;
505 continue;
506 }
507 default: c = (unsigned char)*p; break;
508 }
509 p++;
510 } else {
511 p++;
512 }
513 buf_putc(&b, (char)c);
514 }
515 if (*p == '"') p++;
516 *pp = p;
517 if (!b.p) { char *e = (char *)malloc(1); if (e) e[0] = '\0'; return e; }
518 return b.p;
519}
520
521/* Find `"key"` in a flat object body and copy its string value. */
522static int json_find_str(const char *json, const char *key, char *out, size_t outsz)
523{
524 char pat[64];
525 const char *p;
526
527 if (!json || !key) return 0;
528 sprintf(pat, "\"%s\"", key);
529 p = json;
530 while ((p = strstr(p, pat)) != NULL) {
531 const char *q = p + strlen(pat);
532 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
533 if (*q == ':') {
534 q++;
535 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
536 if (*q == '"') return json_read_string(&q, out, outsz);
537 return 0;
538 }
539 p += strlen(pat);
540 }
541 return 0;
542}
543
544/* Same, for a small non-negative integer (accepts a quoted form too). */
545static int json_find_int(const char *json, const char *key, int *out)
546{
547 char pat[64];
548 char raw[32];
549 const char *p;
550
551 if (!json || !key) return 0;
552 sprintf(pat, "\"%s\"", key);
553 p = json;
554 while ((p = strstr(p, pat)) != NULL) {
555 const char *q = p + strlen(pat);
556 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
557 if (*q == ':') {
558 q++;
559 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
560 if (*q == '"') {
561 if (!json_read_string(&q, raw, sizeof raw)) return 0;
562 } else if (strncmp(q, "true", 4) == 0) {
563 *out = 1; /* a JSON boolean is not a string */
564 return 1;
565 } else if (strncmp(q, "false", 5) == 0) {
566 *out = 0;
567 return 1;
568 } else {
569 size_t i = 0;
570 while (q[i] && (isdigit((unsigned char)q[i]) || q[i] == '-') && i + 1 < sizeof raw) {
571 raw[i] = q[i];
572 i++;
573 }
574 raw[i] = '\0';
575 }
576 *out = atoi(raw);
577 return 1;
578 }
579 p += strlen(pat);
580 }
581 return 0;
582}
583
584/* ------------------------------------------------------------------ */
585/* Node authentication */
586/* ------------------------------------------------------------------ */
587
588static void require_node_auth(void)
589{
590 const char *np = getenv("BOT_PASSWORD");
591 const char *xp;
592 const char *auth;
593 const char *qs;
594 char qpwd[256];
595
596 if (!np || !*np) return;
597
598 xp = getenv("HTTP_X_BOT_PASSWORD");
599 if (xp && strcmp(xp, np) == 0) return;
600
601 auth = getenv("HTTP_AUTHORIZATION");
602 if (auth) {
603 while (*auth == ' ') auth++;
604 if (strncmp(auth, "Bearer ", 7) == 0) {
605 auth += 7;
606 while (*auth == ' ') auth++;
607 if (strcmp(auth, np) == 0) return;
608 }
609 }
610
611 qs = getenv("QUERY_STRING");
612 if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0)
613 return;
614
615 fputs("Status: 401 Unauthorized\r\n"
616 "Content-Type: application/json; charset=utf-8\r\n"
617 "Cache-Control: no-store\r\n"
618 "X-Content-Type-Options: nosniff\r\n\r\n"
619 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
620 exit(0);
621}
622
623/* ------------------------------------------------------------------ */
624/* Notes directory resolution */
625/* ------------------------------------------------------------------ */
626
627static int ensure_notes_dir(void)
628{
629 char base[PATH_SZ];
630 const char *env = getenv("NOTES_DIR");
631 const char *bp;
632
633 if (g_dir[0]) return 1;
634
635 if (env && *env) {
636 str_copy(base, sizeof base, env);
637 } else if ((bp = getenv("BOT_PLUGIN_DIR")) != NULL && *bp) {
638 str_copy(base, sizeof base, bp);
639 mkdir_one(base);
640 path_join(g_dir, sizeof g_dir, base, ".notes");
641 mkdir_one(g_dir);
642 path_join(g_trash, sizeof g_trash, g_dir, TRASH_DIR);
643 mkdir_one(g_trash);
644 return path_is_dir(g_dir);
645 } else {
646#if defined(_WIN32)
647 const char *la = getenv("LOCALAPPDATA");
648 char p1[PATH_SZ], p2[PATH_SZ];
649 if (la && *la) {
650 path_join(p1, sizeof p1, la, "scorpiox");
651 } else {
652 const char *up = getenv("USERPROFILE");
653 if (up && *up) path_join(p1, sizeof p1, up, ".scorpiox");
654 else str_copy(p1, sizeof p1, ".");
655 }
656 mkdir_one(p1);
657 path_join(p2, sizeof p2, p1, "plugins");
658 mkdir_one(p2);
659 path_join(base, sizeof base, p2, ".notes");
660#else
661 const char *home = getenv("HOME");
662 #if defined(__APPLE__)
663 if (access("/workspace", W_OK) == 0) {
664 char p2[PATH_SZ];
665 path_join(p2, sizeof p2, "/workspace/.scorpiox", "plugins");
666 mkdir_one(p2);
667 path_join(base, sizeof base, p2, ".notes");
668 } else
669 #endif
670 if (home && *home) {
671 char p1[PATH_SZ], p2[PATH_SZ];
672 path_join(p1, sizeof p1, home, ".scorpiox");
673 mkdir_one(p1);
674 path_join(p2, sizeof p2, p1, "plugins");
675 mkdir_one(p2);
676 path_join(base, sizeof base, p2, ".notes");
677 } else {
678 str_copy(base, sizeof base, ".notes");
679 }
680#endif
681 }
682
683 str_copy(g_dir, sizeof g_dir, base);
684 mkdir_one(g_dir);
685 path_join(g_trash, sizeof g_trash, g_dir, TRASH_DIR);
686 mkdir_one(g_trash);
687 return path_is_dir(g_dir);
688}
689
690static void note_path(char *out, size_t sz, const char *id)
691{
692 char name[32];
693 sprintf(name, "%s.md", id);
694 path_join(out, sz, g_dir, name);
695}
696
697static void index_path(char *out, size_t sz)
698{
699 path_join(out, sz, g_dir, "index.json");
700}
701
702/* Read index.json into g_meta[]. A missing index is an empty store, and a
703 * truncated one loses the metadata but never the .md bodies. */
704static void load_index(void)
705{
706 char path[PATH_SZ];
707 char *text;
708 const char *p;
709
710 g_count = 0;
711 index_path(path, sizeof path);
712 text = read_whole_file(path, NULL);
713 if (!text) return;
714
715 p = text;
716 /* Walk every object inside the top-level array. */
717 while ((p = strchr(p, '{')) != NULL) {
718 const char *end = strchr(p, '}');
719 char obj[8192];
720 size_t n;
721 note_meta_t m;
722
723 if (!end) break;
724 n = (size_t)(end - p) + 1;
725 if (n >= sizeof obj) n = sizeof obj - 1;
726 memcpy(obj, p, n);
727 obj[n] = '\0';
728 p = end + 1;
729
730 memset(&m, 0, sizeof m);
731 if (!json_find_str(obj, "id", m.id, sizeof m.id)) continue;
732 if (!valid_id(m.id)) continue;
733 if (!json_find_str(obj, "title", m.title, sizeof m.title))
734 str_copy(m.title, sizeof m.title, "");
735 json_find_int(obj, "pinned", &m.pinned);
736 if (!json_find_str(obj, "created", m.created, sizeof m.created))
737 m.created[0] = '\0';
738 if (!json_find_str(obj, "updated", m.updated, sizeof m.updated))
739 m.updated[0] = '\0';
740
741 if (g_count < MAX_NOTES) g_meta[g_count++] = m;
742 }
743 free(text);
744}
745
746static int meta_find(const char *id)
747{
748 int i;
749 for (i = 0; i < g_count; i++)
750 if (strcmp(g_meta[i].id, id) == 0) return i;
751 return -1;
752}
753
754/* Pinned first, then most recently updated. */
755static int meta_cmp(const note_meta_t *a, const note_meta_t *b)
756{
757 if (a->pinned != b->pinned) return b->pinned - a->pinned;
758 return strcmp(b->updated, a->updated);
759}
760
761static void sort_meta(void)
762{
763 int i, j;
764 for (i = 1; i < g_count; i++) {
765 note_meta_t key = g_meta[i];
766 j = i - 1;
767 while (j >= 0 && meta_cmp(&g_meta[j], &key) > 0) {
768 g_meta[j + 1] = g_meta[j];
769 j--;
770 }
771 g_meta[j + 1] = key;
772 }
773}
774
775static int save_index(void)
776{
777 buf_t b;
778 char path[PATH_SZ];
779 int i, ok;
780
781 buf_init(&b);
782 buf_puts(&b, "{\"version\":1,\"notes\":[\n");
783 for (i = 0; i < g_count; i++) {
784 buf_puts(&b, i ? ",\n" : "");
785 buf_puts(&b, " {\"id\":");
786 json_str(&b, g_meta[i].id);
787 buf_puts(&b, ",\"title\":");
788 json_str(&b, g_meta[i].title);
789 buf_puts(&b, ",\"pinned\":");
790 buf_putc(&b, g_meta[i].pinned ? '1' : '0');
791 buf_puts(&b, ",\"created\":");
792 json_str(&b, g_meta[i].created);
793 buf_puts(&b, ",\"updated\":");
794 json_str(&b, g_meta[i].updated);
795 buf_putc(&b, '}');
796 }
797 buf_puts(&b, "\n]}\n");
798
799 index_path(path, sizeof path);
800 ok = atomic_write(path, buf_str(&b), b.n);
801 buf_free(&b);
802 return ok;
803}
804
805/* ------------------------------------------------------------------ */
806/* Markdown -> HTML (server side, escaped first) */
807/* ------------------------------------------------------------------ */
808
809static void esc_html_into(buf_t *b, const char *s, size_t n)
810{
811 size_t i;
812 for (i = 0; i < n; i++) {
813 switch (s[i]) {
814 case '&': buf_puts(b, "&amp;"); break;
815 case '<': buf_puts(b, "&lt;"); break;
816 case '>': buf_puts(b, "&gt;"); break;
817 case '"': buf_puts(b, "&quot;"); break;
818 case '\'': buf_puts(b, "&#39;"); break;
819 default: buf_putc(b, s[i]);
820 }
821 }
822}
823
824static int url_is_safe(const char *u)
825{
826 size_t i;
827 if (!u || !*u) return 0;
828 if (u[0] == '/' || u[0] == '#') return 1;
829 for (i = 0; u[i]; i++) {
830 unsigned char c = (unsigned char)u[i];
831 if (c == ':' || c == '/' || c == '?' || c == '#' || c == '&' ||
832 c == '=' || c == '.' || c == '_' || c == '-' || c == '%' ||
833 c == '+' || c == '~' || c == '@' || c == ',') continue;
834 if (c <= ' ') return 0;
835 }
836 if (strncmp(u, "https://", 8) == 0 || strncmp(u, "http://", 7) == 0 ||
837 strncmp(u, "mailto:", 7) == 0)
838 return 1;
839 return 0;
840}
841
842/* Escape a run of raw note text into the output buffer. Every literal
843 * character in a note goes through here, so note content can never emit a
844 * tag, an attribute or a script. */
845static void esc_into(buf_t *b, const char *s, size_t n)
846{
847 size_t i;
848 for (i = 0; i < n; i++) {
849 switch (s[i]) {
850 case '&': buf_puts(b, "&amp;"); break;
851 case '<': buf_puts(b, "&lt;"); break;
852 case '>': buf_puts(b, "&gt;"); break;
853 case '"': buf_puts(b, "&quot;"); break;
854 case '\'': buf_puts(b, "&#39;"); break;
855 default: buf_putc(b, s[i]);
856 }
857 }
858}
859
860/* Inline pass over raw text: **bold**, *italic*, `code`, [text](url).
861 * Everything it emits is a fixed tag name and every literal byte is escaped,
862 * so the only attribute in the output is a URL that passed url_is_safe(). */
863static void inline_into(buf_t *b, const char *s)
864{
865 size_t i = 0;
866 size_t n = strlen(s);
867
868 while (i < n) {
869 char c = s[i];
870
871 /* `code` - content is escaped like any other literal text */
872 if (c == '`') {
873 const char *close = strchr(s + i + 1, '`');
874 if (close && close > s + i + 1) {
875 buf_puts(b, "<code>");
876 esc_into(b, s + i + 1, (size_t)(close - (s + i + 1)));
877 buf_puts(b, "</code>");
878 i = (size_t)(close - s) + 1;
879 continue;
880 }
881 }
882
883 /* **bold** */
884 if (c == '*' && i + 1 < n && s[i + 1] == '*') {
885 const char *close = strstr(s + i + 2, "**");
886 if (close && close > s + i + 2) {
887 buf_puts(b, "<strong>");
888 esc_into(b, s + i + 2, (size_t)(close - (s + i + 2)));
889 buf_puts(b, "</strong>");
890 i = (size_t)(close - s) + 2;
891 continue;
892 }
893 }
894
895 /* *italic* / _italic_ */
896 if (c == '*' || c == '_') {
897 const char *close = strchr(s + i + 1, c);
898 if (close && close > s + i + 1 && !isspace((unsigned char)s[i + 1])) {
899 buf_puts(b, "<em>");
900 esc_into(b, s + i + 1, (size_t)(close - (s + i + 1)));
901 buf_puts(b, "</em>");
902 i = (size_t)(close - s) + 1;
903 continue;
904 }
905 }
906
907 /* [text](url) - the href is emitted only when url_is_safe() agrees */
908 if (c == '[') {
909 const char *rb = strchr(s + i + 1, ']');
910 if (rb && rb[1] == '(') {
911 const char *rp = strchr(rb + 2, ')');
912 if (rp) {
913 char url[512];
914 size_t ul = (size_t)(rp - (rb + 2));
915 if (ul < sizeof url) {
916 memcpy(url, rb + 2, ul);
917 url[ul] = '\0';
918 if (url_is_safe(url)) {
919 buf_puts(b, "<a href=\"");
920 esc_into(b, url, ul);
921 buf_puts(b, "\" rel=\"noopener noreferrer\" target=\"_blank\">");
922 esc_into(b, s + i + 1, (size_t)(rb - (s + i + 1)));
923 buf_puts(b, "</a>");
924 i = (size_t)(rp - s) + 1;
925 continue;
926 }
927 }
928 }
929 }
930 }
931
932 esc_into(b, &c, 1);
933 i++;
934 }
935}
936
937/* Render one raw line's inline markup. */
938static void inline_line(buf_t *b, const char *line, size_t len)
939{
940 char *tmp = (char *)malloc(len + 1);
941 if (!tmp) return;
942 memcpy(tmp, line, len);
943 tmp[len] = '\0';
944 inline_into(b, tmp);
945 free(tmp);
946}
947
948static void render_markdown(buf_t *out, const char *md)
949{
950 const char *p = md ? md : "";
951 int in_code = 0;
952 int in_list = 0;
953 int in_olist = 0;
954 int para_open = 0;
955 buf_t esc;
956
957 buf_init(&esc);
958
959 while (*p) {
960 const char *eol = strchr(p, '\n');
961 size_t len = eol ? (size_t)(eol - p) : strlen(p);
962 char line[4096];
963 size_t l = len < sizeof line - 1 ? len : sizeof line - 1;
964
965 memcpy(line, p, l);
966 line[l] = '\0';
967 while (l > 0 && line[l - 1] == '\r') line[--l] = '\0';
968
969 if (in_code) {
970 if (l >= 3 && line[0] == '`' && line[1] == '`' && line[2] == '`') {
971 buf_puts(out, "</code></pre>\n");
972 in_code = 0;
973 } else {
974 esc_html_into(out, line, l);
975 buf_putc(out, '\n');
976 }
977 p = eol ? eol + 1 : p + len;
978 continue;
979 }
980
981 if (l >= 3 && line[0] == '`' && line[1] == '`' && line[2] == '`') {
982 if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; }
983 if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; }
984 if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; }
985 buf_puts(out, "<pre><code>");
986 in_code = 1;
987 p = eol ? eol + 1 : p + len;
988 continue;
989 }
990
991 if (l == 0) {
992 if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; }
993 if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; }
994 if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; }
995 p = eol ? eol + 1 : p + len;
996 continue;
997 }
998
999 /* horizontal rule */
1000 if (l >= 3 && (line[0] == '-' || line[0] == '*' || line[0] == '_')) {
1001 int all = 1, j;
1002 char ch = line[0];
1003 int cnt = 0;
1004 for (j = 0; j < (int)l; j++) {
1005 if (line[j] == ch) cnt++;
1006 else if (line[j] != ' ') { all = 0; break; }
1007 }
1008 if (all && cnt >= 3) {
1009 if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; }
1010 if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; }
1011 if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; }
1012 buf_puts(out, "<hr>\n");
1013 p = eol ? eol + 1 : p + len;
1014 continue;
1015 }
1016 }
1017
1018 /* heading */
1019 if (line[0] == '#') {
1020 int n = 0, j = 0;
1021 while (j < (int)l && line[j] == '#' && n < 6) { n++; j++; }
1022 if (n > 0 && (j >= (int)l || line[j] == ' ')) {
1023 char tag[8];
1024 if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; }
1025 if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; }
1026 if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; }
1027 while (j < (int)l && line[j] == ' ') j++;
1028 sprintf(tag, "h%d", n);
1029 buf_puts(out, "<"); buf_puts(out, tag); buf_puts(out, ">");
1030 while (l > (size_t)j && line[l - 1] == '#') l--;
1031 while (l > (size_t)j && line[l - 1] == ' ') l--;
1032 inline_line(out, line + j, l - (size_t)j);
1033 buf_puts(out, "</"); buf_puts(out, tag); buf_puts(out, ">\n");
1034 p = eol ? eol + 1 : p + len;
1035 continue;
1036 }
1037 }
1038
1039 /* blockquote */
1040 if (line[0] == '>') {
1041 size_t j = 1;
1042 if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; }
1043 if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; }
1044 if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; }
1045 while (j < l && line[j] == ' ') j++;
1046 buf_puts(out, "<blockquote>");
1047 inline_line(out, line + j, l - j);
1048 buf_puts(out, "</blockquote>\n");
1049 p = eol ? eol + 1 : p + len;
1050 continue;
1051 }
1052
1053 /* unordered list item */
1054 if ((line[0] == '-' || line[0] == '*' || line[0] == '+') && l > 1 && line[1] == ' ') {
1055 if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; }
1056 if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; }
1057 if (!in_list) { buf_puts(out, "<ul>\n"); in_list = 1; }
1058 buf_puts(out, "<li>");
1059 inline_line(out, line + 2, l - 2);
1060 buf_puts(out, "</li>\n");
1061 p = eol ? eol + 1 : p + len;
1062 continue;
1063 }
1064
1065 /* ordered list item */
1066 if (isdigit((unsigned char)line[0])) {
1067 size_t j = 0;
1068 while (j < l && isdigit((unsigned char)line[j])) j++;
1069 if (j < l && line[j] == '.' && j + 1 < l && line[j + 1] == ' ') {
1070 if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; }
1071 if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; }
1072 if (!in_olist) { buf_puts(out, "<ol>\n"); in_olist = 1; }
1073 buf_puts(out, "<li>");
1074 inline_line(out, line + j + 2, l - j - 2);
1075 buf_puts(out, "</li>\n");
1076 p = eol ? eol + 1 : p + len;
1077 continue;
1078 }
1079 }
1080
1081 /* paragraph text (consecutive lines join with a space) */
1082 if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; }
1083 if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; }
1084 if (para_open) buf_putc(out, ' ');
1085 else { buf_puts(out, "<p>"); para_open = 1; }
1086 inline_line(out, line, l);
1087 p = eol ? eol + 1 : p + len;
1088 }
1089
1090 if (in_code) buf_puts(out, "</code></pre>\n");
1091 if (in_list) buf_puts(out, "</ul>\n");
1092 if (in_olist) buf_puts(out, "</ol>\n");
1093 if (para_open) buf_puts(out, "</p>\n");
1094 buf_free(&esc);
1095}
1096
1097/* ------------------------------------------------------------------ */
1098/* Request body */
1099/* ------------------------------------------------------------------ */
1100
1101/* Read the POST body only when the frontend actually sent one (guarded on
1102 * CONTENT_LENGTH, so an inherited empty stdin never blocks the process),
1103 * and never beyond REQ_MAX. */
1104static int read_request_body(char *out, size_t sz)
1105{
1106 const char *cl = getenv("CONTENT_LENGTH");
1107 long len;
1108 size_t got;
1109
1110 if (!out || sz == 0) return 0;
1111 out[0] = '\0';
1112 if (!cl || !*cl) return 0;
1113 len = strtol(cl, NULL, 10);
1114 if (len <= 0) return 0;
1115 if ((size_t)len >= sz) return -1; /* too large -> caller answers 413 */
1116 got = fread(out, 1, (size_t)len, stdin);
1117 out[got] = '\0';
1118 return (int)got;
1119}
1120
1121static void json_header(void)
1122{
1123 fputs("Content-Type: application/json; charset=utf-8\r\n"
1124 "Cache-Control: no-store\r\n"
1125 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1126}
1127
1128static void json_err(int code, const char *status, const char *msg)
1129{
1130 if (code == 400)
1131 fputs("Status: 400 Bad Request\r\n", stdout);
1132 else if (code == 404)
1133 fputs("Status: 404 Not Found\r\n", stdout);
1134 else if (code == 413)
1135 fputs("Status: 413 Payload Too Large\r\n", stdout);
1136 else if (code == 500)
1137 fputs("Status: 500 Internal Server Error\r\n", stdout);
1138 json_header();
1139 printf("{\"ok\":false,\"error\":");
1140 {
1141 buf_t b;
1142 buf_init(&b);
1143 json_str(&b, msg ? msg : status);
1144 fputs(buf_str(&b), stdout);
1145 buf_free(&b);
1146 }
1147 fputs("}\n", stdout);
1148}
1149
1150/* ------------------------------------------------------------------ */
1151/* API actions */
1152/* ------------------------------------------------------------------ */
1153
1154/* Push the metadata rows, optionally filtered, onto the response. */
1155static void emit_list(const char *only_id, const char *needle)
1156{
1157 buf_t rows, env;
1158 int i, shown = 0;
1159 char lneedle[256];
1160
1161 buf_init(&rows);
1162 buf_init(&env);
1163
1164 if (needle) {
1165 size_t k;
1166 str_copy(lneedle, sizeof lneedle, needle);
1167 for (k = 0; lneedle[k]; k++)
1168 lneedle[k] = (char)tolower((unsigned char)lneedle[k]);
1169 } else {
1170 lneedle[0] = '\0';
1171 }
1172
1173 for (i = 0; i < g_count; i++) {
1174 char path[PATH_SZ];
1175 char *body = NULL;
1176 int match = 1;
1177
1178 if (only_id && strcmp(g_meta[i].id, only_id) != 0) continue;
1179
1180 if (lneedle[0]) {
1181 char ltitle[TITLE_MAX];
1182 size_t k, j;
1183
1184 str_copy(ltitle, sizeof ltitle, g_meta[i].title);
1185 for (k = 0; ltitle[k]; k++)
1186 ltitle[k] = (char)tolower((unsigned char)ltitle[k]);
1187 match = strstr(ltitle, lneedle) != NULL;
1188
1189 if (!match) {
1190 note_path(path, sizeof path, g_meta[i].id);
1191 body = read_whole_file(path, NULL);
1192 if (body) {
1193 size_t n = strlen(body);
1194 for (j = 0; j < n; j++)
1195 body[j] = (char)tolower((unsigned char)body[j]);
1196 match = strstr(body, lneedle) != NULL;
1197 body[j] = '\0';
1198 }
1199 free(body);
1200 }
1201 }
1202
1203 if (!match) continue;
1204
1205 buf_puts(&rows, shown ? ",\n {\"id\":" : "\n {\"id\":");
1206 json_str(&rows, g_meta[i].id);
1207 buf_puts(&rows, ",\"title\":");
1208 json_str(&rows, g_meta[i].title);
1209 buf_puts(&rows, ",\"pinned\":");
1210 buf_putc(&rows, g_meta[i].pinned ? '1' : '0');
1211 buf_puts(&rows, ",\"created\":");
1212 json_str(&rows, g_meta[i].created);
1213 buf_puts(&rows, ",\"updated\":");
1214 json_str(&rows, g_meta[i].updated);
1215 buf_putc(&rows, '}');
1216 shown++;
1217 }
1218
1219 buf_puts(&env, "{\"ok\":true,\"count\":");
1220 {
1221 char num[16];
1222 sprintf(num, "%d", shown);
1223 buf_puts(&env, num);
1224 }
1225 buf_puts(&env, ",\"notes\":[");
1226 buf_puts(&env, buf_str(&rows));
1227 buf_puts(&env, shown ? "\n]}\n" : "]}\n");
1228 fwrite(buf_str(&env), 1, env.n, stdout);
1229
1230 buf_free(&rows);
1231 buf_free(&env);
1232}
1233
1234static void do_list(void)
1235{
1236 json_header();
1237 emit_list(NULL, NULL);
1238}
1239
1240static void do_search(const char *q)
1241{
1242 json_header();
1243 emit_list(NULL, (q && *q) ? q : NULL);
1244}
1245
1246static void do_get(const char *id)
1247{
1248 int idx;
1249 char path[PATH_SZ];
1250 char *body;
1251
1252 if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; }
1253 idx = meta_find(id);
1254 if (idx < 0) { json_err(404, "Not Found", "note not found"); return; }
1255
1256 note_path(path, sizeof path, id);
1257 body = read_whole_file(path, NULL);
1258
1259 json_header();
1260 {
1261 buf_t b;
1262 buf_init(&b);
1263 buf_puts(&b, "{\"ok\":true,\"note\":{\"id\":");
1264 json_str(&b, g_meta[idx].id);
1265 buf_puts(&b, ",\"title\":");
1266 json_str(&b, g_meta[idx].title);
1267 buf_puts(&b, ",\"pinned\":");
1268 buf_putc(&b, g_meta[idx].pinned ? '1' : '0');
1269 buf_puts(&b, ",\"created\":");
1270 json_str(&b, g_meta[idx].created);
1271 buf_puts(&b, ",\"updated\":");
1272 json_str(&b, g_meta[idx].updated);
1273 buf_puts(&b, ",\"body\":");
1274 json_str(&b, body ? body : "");
1275 buf_puts(&b, "}}\n");
1276 fwrite(buf_str(&b), 1, b.n, stdout);
1277 buf_free(&b);
1278 }
1279 free(body);
1280}
1281
1282static void do_save(const char *body_json)
1283{
1284 char id[64] = "";
1285 char title[TITLE_MAX] = "";
1286 char *body = NULL;
1287 int pinned = 0;
1288 int idx;
1289 char path[PATH_SZ];
1290 char now[24];
1291 note_meta_t m;
1292
1293 if (!body_json || !*body_json) {
1294 json_err(400, "Bad Request", "empty body");
1295 return;
1296 }
1297
1298 json_find_str(body_json, "id", id, sizeof id);
1299 json_find_str(body_json, "title", title, sizeof title);
1300
1301 /* The body is the only large field: take it straight out of the JSON. */
1302 {
1303 const char *p = strstr(body_json, "\"body\"");
1304 if (p) {
1305 const char *q = p + 6;
1306 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
1307 if (*q == ':') {
1308 q++;
1309 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
1310 if (*q == '"') body = json_dup_string(&q);
1311 }
1312 }
1313 }
1314 if (!body) {
1315 json_err(400, "Bad Request", "missing body field");
1316 return;
1317 }
1318 if (strlen(body) > (size_t)BODY_MAX) {
1319 free(body);
1320 json_err(413, "Payload Too Large", "note body exceeds 512 KiB");
1321 return;
1322 }
1323
1324 if (id[0] && !valid_id(id)) {
1325 free(body);
1326 json_err(400, "Bad Request", "invalid id");
1327 return;
1328 }
1329
1330 if (!json_find_int(body_json, "pinned", &pinned)) pinned = 0;
1331 pinned = pinned ? 1 : 0;
1332
1333 iso_now(now, sizeof now);
1334
1335 idx = id[0] ? meta_find(id) : -1;
1336 memset(&m, 0, sizeof m);
1337 if (idx >= 0) {
1338 m = g_meta[idx];
1339 if (json_find_int(body_json, "pinned", &pinned)) m.pinned = pinned ? 1 : 0;
1340 } else {
1341 if (id[0]) str_copy(m.id, sizeof m.id, id);
1342 else gen_id(m.id);
1343 str_copy(m.created, sizeof m.created, now);
1344 m.pinned = pinned;
1345 }
1346 str_copy(m.title, sizeof m.title, title);
1347 str_copy(m.updated, sizeof m.updated, now);
1348
1349 /* Write the body first: a metadata row must never point at a note that
1350 * was never written. */
1351 note_path(path, sizeof path, m.id);
1352 if (!atomic_write(path, body, strlen(body))) {
1353 free(body);
1354 json_err(500, "Internal Server Error", "could not write note");
1355 return;
1356 }
1357 free(body);
1358
1359 if (idx >= 0) g_meta[idx] = m;
1360 else if (g_count < MAX_NOTES) g_meta[g_count++] = m;
1361 else { json_err(500, "Internal Server Error", "note limit reached"); return; }
1362
1363 sort_meta();
1364 if (!save_index()) {
1365 json_err(500, "Internal Server Error", "could not write index");
1366 return;
1367 }
1368
1369 json_header();
1370 {
1371 buf_t b;
1372 buf_init(&b);
1373 buf_puts(&b, "{\"ok\":true,\"note\":{\"id\":");
1374 json_str(&b, m.id);
1375 buf_puts(&b, ",\"title\":");
1376 json_str(&b, m.title);
1377 buf_puts(&b, ",\"pinned\":");
1378 buf_putc(&b, m.pinned ? '1' : '0');
1379 buf_puts(&b, ",\"created\":");
1380 json_str(&b, m.created);
1381 buf_puts(&b, ",\"updated\":");
1382 json_str(&b, m.updated);
1383 buf_puts(&b, "}}\n");
1384 fwrite(buf_str(&b), 1, b.n, stdout);
1385 buf_free(&b);
1386 }
1387}
1388
1389static void do_pin(const char *id, const char *body_json, const char *qs)
1390{
1391 int idx, pin = -1;
1392 char v[16];
1393
1394 if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; }
1395 idx = meta_find(id);
1396 if (idx < 0) { json_err(404, "Not Found", "note not found"); return; }
1397
1398 if (!json_find_int(body_json ? body_json : "", "pin", &pin)) {
1399 if (qs && get_query_val(qs, "pin", v, sizeof v)) pin = atoi(v);
1400 }
1401 if (pin < 0) pin = g_meta[idx].pinned ? 0 : 1;
1402
1403 g_meta[idx].pinned = pin ? 1 : 0;
1404 iso_now(g_meta[idx].updated, sizeof g_meta[idx].updated);
1405 sort_meta();
1406 if (!save_index()) { json_err(500, "Internal Server Error", "could not write index"); return; }
1407
1408 json_header();
1409 printf("{\"ok\":true,\"id\":\"%s\",\"pinned\":%d}\n", id, g_meta[meta_find(id)].pinned);
1410}
1411
1412static void do_delete(const char *id)
1413{
1414 int idx, i;
1415 char src[PATH_SZ], dst[PATH_SZ], name[32];
1416
1417 if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; }
1418 idx = meta_find(id);
1419 if (idx < 0) { json_err(404, "Not Found", "note not found"); return; }
1420
1421 note_path(src, sizeof src, id);
1422 sprintf(name, "%s.md", id);
1423 path_join(dst, sizeof dst, g_trash, name);
1424
1425 if (file_exists(src)) {
1426 /* Keep a copy in .trash so a wrong click is recoverable. */
1427#if defined(_WIN32)
1428 MoveFileExA(src, dst, MOVEFILE_REPLACE_EXISTING);
1429#else
1430 rename(src, dst);
1431#endif
1432 }
1433
1434 for (i = idx; i < g_count - 1; i++) g_meta[i] = g_meta[i + 1];
1435 if (g_count > 0) g_count--;
1436
1437 if (!save_index()) { json_err(500, "Internal Server Error", "could not write index"); return; }
1438
1439 json_header();
1440 printf("{\"ok\":true,\"deleted\":\"%s\",\"trash\":true}\n", id);
1441}
1442
1443static void do_render(const char *body_json, const char *qs)
1444{
1445 char *text = NULL;
1446 buf_t out;
1447
1448 if (body_json && *body_json) {
1449 const char *p = strstr(body_json, "\"body\"");
1450 if (p) {
1451 const char *q = p + 6;
1452 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
1453 if (*q == ':') {
1454 q++;
1455 while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++;
1456 if (*q == '"') text = json_dup_string(&q);
1457 }
1458 }
1459 }
1460 if (!text && qs) {
1461 /* Convenience for GET callers; capped so a URL cannot allocate much. */
1462 char tmp[8192];
1463 if (get_query_val(qs, "text", tmp, sizeof tmp)) {
1464 text = (char *)malloc(strlen(tmp) + 1);
1465 if (text) str_copy(text, strlen(tmp) + 1, tmp);
1466 }
1467 }
1468 if (!text) {
1469 json_err(400, "Bad Request", "missing body field");
1470 return;
1471 }
1472 if (strlen(text) > (size_t)BODY_MAX) {
1473 free(text);
1474 json_err(413, "Payload Too Large", "note body exceeds 512 KiB");
1475 return;
1476 }
1477
1478 buf_init(&out);
1479 render_markdown(&out, text);
1480
1481 json_header();
1482 {
1483 buf_t b;
1484 buf_init(&b);
1485 buf_puts(&b, "{\"ok\":true,\"html\":");
1486 json_str(&b, buf_str(&out));
1487 buf_puts(&b, "}\n");
1488 fwrite(buf_str(&b), 1, b.n, stdout);
1489 buf_free(&b);
1490 }
1491 buf_free(&out);
1492 free(text);
1493}
1494
1495/* ------------------------------------------------------------------ */
1496/* HTML mode */
1497/* ------------------------------------------------------------------ */
1498
1499/* Split UI_HTML on the two control-byte placeholders and expand them into
1500 * the theme macros, so the page and the bot palette can never drift. */
1501static void emit_ui(int embed)
1502{
1503 const char *p = UI_HTML;
1504
1505 while (*p) {
1506 if (*p == '\001') {
1507 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
1508 ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}"
1509 "</style>", stdout);
1510 p++;
1511 } else if (*p == '\002') {
1512 fputs(SX_BOT_THEME_HANDOFF, stdout);
1513 p++;
1514 } else {
1515 putchar(*p++);
1516 }
1517 }
1518 (void)embed;
1519}
1520
1521static void mode_html(int embed)
1522{
1523 fputs("Content-Type: text/html; charset=utf-8\r\n"
1524 "Cache-Control: no-store\r\n"
1525 "X-Content-Type-Options: nosniff\r\n"
1526 "X-Frame-Options: SAMEORIGIN\r\n"
1527 "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1528 "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1529 "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
1530 emit_ui(embed);
1531}
1532
1533/* ------------------------------------------------------------------ */
1534/* Entry */
1535/* ------------------------------------------------------------------ */
1536
1537static const char *method(void)
1538{
1539 const char *m = getenv("REQUEST_METHOD");
1540 return (m && *m) ? m : "GET";
1541}
1542
1543int main(int argc, char **argv)
1544{
1545 const char *qs;
1546 const char *req_method;
1547 char action[64];
1548 char id[64];
1549 char val[256];
1550 static char body[REQ_MAX];
1551 int got;
1552
1553 /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */
1554 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1555 printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC);
1556 return 0;
1557 }
1558 if (argc > 1 && strcmp(argv[1], "--version") == 0) {
1559 printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
1560 return 0;
1561 }
1562
1563 require_node_auth();
1564
1565 qs = getenv("QUERY_STRING");
1566 if (!qs) qs = "";
1567 req_method = method();
1568
1569 action[0] = '\0';
1570 id[0] = '\0';
1571 get_query_val(qs, "action", action, sizeof action);
1572 get_query_val(qs, "id", id, sizeof id);
1573
1574 /* 2. Anything that names an action, asks for JSON, or POSTs is API. */
1575 if (action[0] || strstr(qs, "format=json") || strcmp(req_method, "POST") == 0) {
1576 int action_present = action[0] != '\0';
1577 char act[64];
1578
1579 if (!action_present) {
1580 char fmt[32];
1581 if (get_query_val(qs, "format", fmt, sizeof fmt) && strcmp(fmt, "json") == 0)
1582 str_copy(action, sizeof action, "list");
1583 else
1584 str_copy(action, sizeof action, "list");
1585 }
1586 /* Keep two buffers: reading `format` into `action` would clobber the
1587 * action we just parsed (lesson (l) in the market tracker). */
1588 str_copy(act, sizeof act, action);
1589
1590 if (!ensure_notes_dir()) { json_err(500, "Internal Server Error", "notes dir unavailable"); return 0; }
1591 load_index();
1592
1593 got = read_request_body(body, sizeof body);
1594 if (got < 0) { json_err(413, "Payload Too Large", "request body too large"); return 0; }
1595
1596 if (strcmp(act, "list") == 0) {
1597 do_list();
1598 } else if (strcmp(act, "get") == 0) {
1599 do_get(id);
1600 } else if (strcmp(act, "search") == 0) {
1601 val[0] = '\0';
1602 get_query_val(qs, "q", val, sizeof val);
1603 do_search(val);
1604 } else if (strcmp(act, "save") == 0) {
1605 do_save(body);
1606 } else if (strcmp(act, "delete") == 0) {
1607 do_delete(id);
1608 } else if (strcmp(act, "pin") == 0) {
1609 do_pin(id, body, qs);
1610 } else if (strcmp(act, "render") == 0) {
1611 do_render(body, qs);
1612 } else {
1613 json_err(400, "Bad Request", "unknown action");
1614 }
1615 return 0;
1616 }
1617
1618 /* 3. Everything else is the page. */
1619 {
1620 int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL;
1621 mode_html(embed);
1622 }
1623 return 0;
1624}