ShtukbaseStandard
package file→ .shtukbase/packages/live/test/live.test.ts

test/live.test.ts

297 lines, 15.8 KB.

  1. // The live server on a small temporary project: the address, the token, the schema and the contour, the front
  2. // matter kept in place, the allow list of actions, the events. Run: `bun test` in the package (or `shtuk run live selftest`).
  3. import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
  4. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
  5. import { tmpdir } from 'node:os';
  6. import { dirname, join } from 'node:path';
  7. import { Project, Result } from '../../collections/checks/lib/speclib.ts';
  8. import { check as checkHost } from '../checks/l01_host.ts';
  9. import { check as checkToken } from '../checks/l02_token.ts';
  10. import { check as checkRun } from '../checks/l03_run.ts';
  11. import { setFields, split, join as joinPage } from '../server/fm.ts';
  12. import { slug } from '../server/records.ts';
  13. import { type Live, start } from '../server/server.ts';
  14. import { readSettings } from '../server/settings.ts';
  15. const TASK_A = `---
  16. type: Task
  17. # a comment that must stay
  18. title: "First: task"
  19. status: todo
  20. priority: P1
  21. tags:
  22. - one
  23. - two
  24. ---
  25. Task text.
  26. `;
  27. const files: Record<string, string> = {
  28. 'index.md': '---\ntitle: Test project\n---\n',
  29. 'base/live.md': '---\ntype: Page\ntitle: Live server\nport: 4322\nrun: [demo hello, shtuk check]\n---\n',
  30. '.shtukbase/packages.lock': 'lockVersion: 1\npackages:\n demo: {version: 0.1.0}\n',
  31. '.shtukbase/packages/demo/package.md': '---\ntype: Package\nid: demo\nversion: 0.1.0\nactions:\n - {name: hello, run: hello.ts}\n - {name: secret, run: secret.ts}\n - {name: ok, run: ok.ts, check: true}\n---\n',
  32. '.shtukbase/packages/demo/hello.ts': 'console.log("hello " + process.argv.slice(2).join(" "));\n',
  33. '.shtukbase/packages/demo/secret.ts': 'console.log("must not run");\n',
  34. '.shtukbase/packages/demo/ok.ts': 'console.log("all good");\n',
  35. 'work/tasks.md': `---
  36. type: Collection
  37. title: Tasks
  38. itemType: Task
  39. properties:
  40. status: {kind: phase, contour: /work/contours/tasks, label: "State"}
  41. priority:
  42. kind: select
  43. label: "Priority"
  44. options: [{name: P0}, {name: P1}, {name: P2}]
  45. due: {kind: date, label: "Due"}
  46. points: {kind: number}
  47. holdReason: {kind: text, label: "Why on hold"}
  48. owner: {kind: relation, collection: /work/people}
  49. ---
  50. `,
  51. 'work/people.md': '---\ntype: Collection\ntitle: People\nitemType: Person\n---\n',
  52. 'work/people/ann.md': '---\ntype: Person\ntitle: Ann\n---\n',
  53. 'work/contours/tasks.md': '---\ntype: Contour\ntitle: Tasks\ncollection: /work/tasks\nphases: [/work/contours/tasks/todo, /work/contours/tasks/doing, /work/contours/tasks/done, /work/contours/tasks/hold]\nentry: /work/contours/tasks/todo\n---\n',
  54. 'work/contours/tasks/todo.md': '---\ntype: Phase\ntitle: Queued\nnext:\n - /work/contours/tasks/doing\n - {to: /work/contours/tasks/hold, needs: holdReason}\n---\n',
  55. 'work/contours/tasks/doing.md': '---\ntype: Phase\ntitle: In progress\nnext: [/work/contours/tasks/done]\n---\n',
  56. 'work/contours/tasks/done.md': '---\ntype: Phase\ntitle: Done\n---\n',
  57. 'work/contours/tasks/hold.md': '---\ntype: Phase\ntitle: On hold\nnext: [/work/contours/tasks/todo]\n---\n',
  58. 'work/tasks/a.md': TASK_A,
  59. };
  60. let root = '';
  61. let live: Live;
  62. let base = '';
  63. const auth = () => ({ authorization: `Bearer ${live.token}`, 'content-type': 'application/json' });
  64. const call = (method: string, path: string, body?: unknown, headers: Record<string, string> = auth()) =>
  65. fetch(base + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'manual' });
  66. const read = (rel: string) => readFileSync(join(root, rel), 'utf8');
  67. beforeAll(() => {
  68. root = mkdtempSync(join(tmpdir(), 'live-test-'));
  69. for (const [rel, text] of Object.entries(files)) {
  70. mkdirSync(dirname(join(root, rel)), { recursive: true });
  71. writeFileSync(join(root, rel), text);
  72. }
  73. live = start({ root, port: 0, build: false, quiet: true });
  74. base = `http://127.0.0.1:${live.port}`;
  75. });
  76. afterAll(() => {
  77. live?.stop();
  78. if (root) rmSync(root, { recursive: true, force: true });
  79. });
  80. describe('LIVE-R01: only this computer', () => {
  81. test('listens on 127.0.0.1', async () => {
  82. expect(live.host).toBe('127.0.0.1');
  83. expect(live.url.startsWith('http://127.0.0.1:')).toBe(true);
  84. expect((await fetch(base + '/api/hello')).status).toBe(200);
  85. });
  86. test('refuses another address', () => {
  87. expect(() => start({ root, port: 0, host: '0.0.0.0', build: false, quiet: true })).toThrow(/only on this computer/);
  88. });
  89. test('refuses a settings page with another host, and the check says so', () => {
  90. const other = mkdtempSync(join(tmpdir(), 'live-host-'));
  91. mkdirSync(join(other, 'base'));
  92. writeFileSync(join(other, 'base/live.md'), '---\nhost: 0.0.0.0\nrun: ["*"]\ntoken: false\n---\n');
  93. try {
  94. expect(() => start({ root: other, port: 0, build: false, quiet: true })).toThrow(/LIVE-R01/);
  95. const p = new Project(other);
  96. for (const [fn, id] of [[checkHost, 'live01'], [checkToken, 'live02'], [checkRun, 'live03']] as const) {
  97. const res = new Result({ id, title: id });
  98. fn(p, res);
  99. expect(res.holes.length).toBe(1);
  100. }
  101. } finally {
  102. rmSync(other, { recursive: true, force: true });
  103. }
  104. });
  105. test('a foreign host name is refused (DNS rebinding)', async () => {
  106. const r = await fetch(base + '/api/hello', { headers: { host: `evil.example:${live.port}` } });
  107. expect(r.status).toBe(403);
  108. });
  109. });
  110. describe('LIVE-R02: writing needs the token', () => {
  111. test('reads without the token', async () => {
  112. const r = await call('GET', '/api/records?collection=/work/tasks', undefined, {});
  113. expect(r.status).toBe(200);
  114. const j = await r.json();
  115. expect(j.records.map((x: any) => x.path)).toEqual(['/work/tasks/a.md']);
  116. expect(j.collection.phases.status.map((p: any) => p.name)).toEqual(['todo', 'doing', 'done', 'hold']);
  117. expect((await (await call('GET', '/api/hello', undefined, {})).json()).write).toBe(false);
  118. });
  119. test('every write without the token is 401', async () => {
  120. const h = { 'content-type': 'application/json' };
  121. expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P0' } }, h)).status).toBe(401);
  122. expect((await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'x' } }, h)).status).toBe(401);
  123. expect((await call('DELETE', '/api/record?path=/work/tasks/a.md', undefined, {})).status).toBe(401);
  124. expect((await call('POST', '/api/run', { package: 'demo', action: 'hello' }, h)).status).toBe(401);
  125. expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P0' } }, { ...h, authorization: 'Bearer wrong' })).status).toBe(401);
  126. expect(read('work/tasks/a.md')).toBe(TASK_A);
  127. });
  128. test('the link puts the token into a cookie and drops it from the address', async () => {
  129. const r = await fetch(`${base}/work/?token=${live.token}`, { redirect: 'manual' });
  130. expect(r.status).toBe(302);
  131. expect(r.headers.get('location')).toBe('/work/');
  132. const cookie = r.headers.get('set-cookie') ?? '';
  133. expect(cookie).toContain('HttpOnly');
  134. expect(cookie).toContain('SameSite=Strict');
  135. const hello = await (await fetch(base + '/api/hello', { headers: { cookie: cookie.split(';')[0] } })).json();
  136. expect(hello.write).toBe(true);
  137. });
  138. test('a write from a foreign page is 403 even with the token', async () => {
  139. const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P0' } }, { ...auth(), origin: 'http://evil.example' });
  140. expect(r.status).toBe(403);
  141. });
  142. });
  143. describe('records', () => {
  144. test('a field changes in place: order, quotes, comments and lists stay', async () => {
  145. const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'doing', points: 3 } });
  146. expect(r.status).toBe(200);
  147. expect(read('work/tasks/a.md')).toBe(TASK_A.replace('status: todo', 'status: doing').replace(' - two\n', ' - two\npoints: 3\n'));
  148. });
  149. test('the body changes, the header stays', async () => {
  150. const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', body: 'New text.\n' });
  151. expect(r.status).toBe(200);
  152. expect(read('work/tasks/a.md').endsWith('---\n\nNew text.\n')).toBe(true);
  153. expect(read('work/tasks/a.md')).toContain('# a comment that must stay');
  154. });
  155. test('a stale etag is 409', async () => {
  156. expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P2' }, etag: 'old' })).status).toBe(409);
  157. });
  158. test('schema errors are 422 at the field, in English, and nothing is written', async () => {
  159. const before = read('work/tasks/a.md');
  160. for (const [set, field, text] of [
  161. [{ priority: 'P9' }, 'priority', 'is not an option'],
  162. [{ due: '28.11.2026' }, 'due', 'is not a date'],
  163. [{ points: 'many' }, 'points', 'is not a number'],
  164. [{ owner: '/work/people/bob.md' }, 'owner', 'is not a record of the collection'],
  165. [{ title: '' }, 'title', 'title is required'],
  166. ] as const) {
  167. const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set });
  168. expect(r.status).toBe(422);
  169. const j = await r.json();
  170. expect(j.field).toBe(field);
  171. expect(j.error).toContain(text);
  172. }
  173. expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { owner: '/work/people/ann.md' } })).status).toBe(200);
  174. expect(read('work/tasks/a.md')).toBe(before.replace('points: 3\n', 'points: 3\nowner: /work/people/ann.md\n'));
  175. });
  176. test('a phase moves only along the contour', async () => {
  177. let r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'todo' } });
  178. expect(r.status).toBe(422);
  179. expect((await r.json()).error).toContain('There is no transition "In progress" (doing) → "Queued" (todo)');
  180. r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'nope' } });
  181. expect(r.status).toBe(422);
  182. expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'done' } })).status).toBe(200);
  183. });
  184. test('a gate of a move needs its field', async () => {
  185. const c = await (await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'Put on hold' } })).json();
  186. let r = await call('PATCH', '/api/record', { path: c.path, set: { status: 'hold' } });
  187. expect(r.status).toBe(422);
  188. expect((await r.json()).field).toBe('holdReason');
  189. r = await call('PATCH', '/api/record', { path: c.path, set: { status: 'hold', holdReason: 'waiting' } });
  190. expect(r.status).toBe(200);
  191. });
  192. test('create: type, title, the entry phase; a name from the title; a new record starts at the entry', async () => {
  193. const r = await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'New task', priority: 'P0' }, body: 'What to do.' });
  194. expect(r.status).toBe(201);
  195. const j = await r.json();
  196. expect(j.path).toBe('/work/tasks/new-task.md');
  197. expect(read('work/tasks/new-task.md')).toBe('---\ntype: Task\ntitle: New task\npriority: P0\nstatus: todo\n---\n\nWhat to do.\n');
  198. const again = await (await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'New task' } })).json();
  199. expect(again.path).toBe('/work/tasks/new-task-2.md');
  200. expect((await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'Right away', status: 'doing' } })).status).toBe(422);
  201. expect((await call('POST', '/api/records', { collection: '/work/tasks', fields: {} })).status).toBe(422);
  202. });
  203. test('a Russian title gets a latin file name', () => {
  204. // the Russian words for "new task", written as code points: this source stays English
  205. expect(slug('\u041d\u043e\u0432\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430')).toBe('novaya-zadacha');
  206. });
  207. test('delete moves the record to deleted/', async () => {
  208. const r = await call('DELETE', '/api/record?path=/work/tasks/new-task-2.md');
  209. expect(r.status).toBe(200);
  210. expect((await r.json()).deletedTo).toBe('/deleted/work/tasks/new-task-2.md');
  211. expect(existsSync(join(root, 'work/tasks/new-task-2.md'))).toBe(false);
  212. expect(existsSync(join(root, 'deleted/work/tasks/new-task-2.md'))).toBe(true);
  213. });
  214. test('only records of collections are written; no way out of the project', async () => {
  215. expect((await call('PATCH', '/api/record', { path: '/base/live.md', set: { run: ['demo secret'] } })).status).toBe(403);
  216. expect((await call('PATCH', '/api/record', { path: '/../x.md', set: { a: 1 } })).status).toBe(403);
  217. expect((await call('PATCH', '/api/record', { path: '/.shtukbase/packages.lock', set: { a: 1 } })).status).toBe(403);
  218. expect((await fetch(base + '/.shtukbase/packages.lock')).status).toBe(404);
  219. expect((await fetch(base + '/%2e%2e/etc/passwd')).status).toBe(404);
  220. });
  221. test('search finds by title and text', async () => {
  222. const j = await (await call('GET', '/api/search?q=' + encodeURIComponent('what to do'))).json();
  223. expect(j.results.map((x: any) => x.path)).toEqual(['/work/tasks/new-task.md']);
  224. });
  225. });
  226. describe('LIVE-R03: actions only from the allow list', () => {
  227. test('an allowed action runs, with its arguments', async () => {
  228. const j = await (await call('POST', '/api/run', { package: 'demo', action: 'hello', args: ['world'] })).json();
  229. expect(j.ok).toBe(true);
  230. expect(j.output).toBe('hello world');
  231. });
  232. test('an action not in the list is 403 and does not run', async () => {
  233. const r = await call('POST', '/api/run', { package: 'demo', action: 'secret' });
  234. expect(r.status).toBe(403);
  235. expect((await r.json()).error).toContain('is not allowed');
  236. });
  237. test('the list is empty by default', () => {
  238. const page = readFileSync(join(import.meta.dir, '..', 'pages', 'base', 'live.md'), 'utf8');
  239. const other = mkdtempSync(join(tmpdir(), 'live-default-'));
  240. mkdirSync(join(other, 'base'));
  241. writeFileSync(join(other, 'base/live.md'), page);
  242. try {
  243. expect(readSettings(other)).toEqual({ host: '127.0.0.1', port: 4322, run: [], problems: [] });
  244. } finally {
  245. rmSync(other, { recursive: true, force: true });
  246. }
  247. });
  248. test('shtuk check runs every check, streamed as NDJSON', async () => {
  249. const r = await call('POST', '/api/run', { package: 'shtuk', action: 'check', stream: true });
  250. expect(r.headers.get('content-type')).toContain('ndjson');
  251. const events = (await r.text()).trim().split('\n').map((l) => JSON.parse(l));
  252. expect(events).toEqual([{ type: 'start', step: 'demo/ok' }, { type: 'out', text: 'all good' }, { type: 'end', step: 'demo/ok', code: 0 }, { type: 'exit', code: 0 }]);
  253. });
  254. });
  255. describe('events', () => {
  256. test('a changed file is announced on /api/events', async () => {
  257. const ctl = new AbortController();
  258. const r = await fetch(base + '/api/events', { signal: ctl.signal });
  259. const reader = r.body!.getReader();
  260. const dec = new TextDecoder();
  261. let text = '';
  262. const got = (async () => {
  263. while (!text.includes('/work/tasks/b.md')) {
  264. const { value, done } = await reader.read();
  265. if (done) break;
  266. text += dec.decode(value);
  267. }
  268. })();
  269. await Bun.sleep(150);
  270. writeFileSync(join(root, 'work/tasks/b.md'), '---\ntype: Task\ntitle: B\n---\n');
  271. await Promise.race([got, Bun.sleep(4000)]);
  272. ctl.abort();
  273. expect(text).toContain('event: change');
  274. expect(text).toContain('/work/tasks/b.md');
  275. });
  276. });
  277. describe('front matter', () => {
  278. test('a block value is replaced as a whole; a new field goes last; removing works', () => {
  279. const s = setFields(split(TASK_A), { tags: ['x', 'y z'], due: '2026-11-28', priority: null });
  280. expect(joinPage(s)).toBe('---\ntype: Task\n# a comment that must stay\ntitle: "First: task"\nstatus: todo\ntags: [x, "y z"]\ndue: "2026-11-28"\n---\n\nTask text.\n');
  281. });
  282. test('values that YAML would read otherwise are quoted', () => {
  283. const s = setFields(split('---\na: 1\n---\n'), { b: 'true', c: '12', d: 'a: b', e: '#x', f: 'café' });
  284. expect(s.lines).toEqual(['a: 1', 'b: "true"', 'c: "12"', 'd: "a: b"', 'e: "#x"', 'f: café']);
  285. });
  286. });