archivo del paquete→ .shtukbase/packages/live/test/live.test.ts
test/live.test.ts
297 líneas, 15.8 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // The live server on a small temporary project: the address, the token, the schema and the contour, the front
- // matter kept in place, the allow list of actions, the events. Run: `bun test` in the package (or `shtuk run live selftest`).
- import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
- import { tmpdir } from 'node:os';
- import { dirname, join } from 'node:path';
- import { Project, Result } from '../../collections/checks/lib/speclib.ts';
- import { check as checkHost } from '../checks/l01_host.ts';
- import { check as checkToken } from '../checks/l02_token.ts';
- import { check as checkRun } from '../checks/l03_run.ts';
- import { setFields, split, join as joinPage } from '../server/fm.ts';
- import { slug } from '../server/records.ts';
- import { type Live, start } from '../server/server.ts';
- import { readSettings } from '../server/settings.ts';
- const TASK_A = `---
- type: Task
- # a comment that must stay
- title: "First: task"
- status: todo
- priority: P1
- tags:
- - one
- - two
- ---
- Task text.
- `;
- const files: Record<string, string> = {
- 'index.md': '---\ntitle: Test project\n---\n',
- 'base/live.md': '---\ntype: Page\ntitle: Live server\nport: 4322\nrun: [demo hello, shtuk check]\n---\n',
- '.shtukbase/packages.lock': 'lockVersion: 1\npackages:\n demo: {version: 0.1.0}\n',
- '.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',
- '.shtukbase/packages/demo/hello.ts': 'console.log("hello " + process.argv.slice(2).join(" "));\n',
- '.shtukbase/packages/demo/secret.ts': 'console.log("must not run");\n',
- '.shtukbase/packages/demo/ok.ts': 'console.log("all good");\n',
- 'work/tasks.md': `---
- type: Collection
- title: Tasks
- itemType: Task
- properties:
- status: {kind: phase, contour: /work/contours/tasks, label: "State"}
- priority:
- kind: select
- label: "Priority"
- options: [{name: P0}, {name: P1}, {name: P2}]
- due: {kind: date, label: "Due"}
- points: {kind: number}
- holdReason: {kind: text, label: "Why on hold"}
- owner: {kind: relation, collection: /work/people}
- ---
- `,
- 'work/people.md': '---\ntype: Collection\ntitle: People\nitemType: Person\n---\n',
- 'work/people/ann.md': '---\ntype: Person\ntitle: Ann\n---\n',
- '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',
- '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',
- 'work/contours/tasks/doing.md': '---\ntype: Phase\ntitle: In progress\nnext: [/work/contours/tasks/done]\n---\n',
- 'work/contours/tasks/done.md': '---\ntype: Phase\ntitle: Done\n---\n',
- 'work/contours/tasks/hold.md': '---\ntype: Phase\ntitle: On hold\nnext: [/work/contours/tasks/todo]\n---\n',
- 'work/tasks/a.md': TASK_A,
- };
- let root = '';
- let live: Live;
- let base = '';
- const auth = () => ({ authorization: `Bearer ${live.token}`, 'content-type': 'application/json' });
- const call = (method: string, path: string, body?: unknown, headers: Record<string, string> = auth()) =>
- fetch(base + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'manual' });
- const read = (rel: string) => readFileSync(join(root, rel), 'utf8');
- beforeAll(() => {
- root = mkdtempSync(join(tmpdir(), 'live-test-'));
- for (const [rel, text] of Object.entries(files)) {
- mkdirSync(dirname(join(root, rel)), { recursive: true });
- writeFileSync(join(root, rel), text);
- }
- live = start({ root, port: 0, build: false, quiet: true });
- base = `http://127.0.0.1:${live.port}`;
- });
- afterAll(() => {
- live?.stop();
- if (root) rmSync(root, { recursive: true, force: true });
- });
- describe('LIVE-R01: only this computer', () => {
- test('listens on 127.0.0.1', async () => {
- expect(live.host).toBe('127.0.0.1');
- expect(live.url.startsWith('http://127.0.0.1:')).toBe(true);
- expect((await fetch(base + '/api/hello')).status).toBe(200);
- });
- test('refuses another address', () => {
- expect(() => start({ root, port: 0, host: '0.0.0.0', build: false, quiet: true })).toThrow(/only on this computer/);
- });
- test('refuses a settings page with another host, and the check says so', () => {
- const other = mkdtempSync(join(tmpdir(), 'live-host-'));
- mkdirSync(join(other, 'base'));
- writeFileSync(join(other, 'base/live.md'), '---\nhost: 0.0.0.0\nrun: ["*"]\ntoken: false\n---\n');
- try {
- expect(() => start({ root: other, port: 0, build: false, quiet: true })).toThrow(/LIVE-R01/);
- const p = new Project(other);
- for (const [fn, id] of [[checkHost, 'live01'], [checkToken, 'live02'], [checkRun, 'live03']] as const) {
- const res = new Result({ id, title: id });
- fn(p, res);
- expect(res.holes.length).toBe(1);
- }
- } finally {
- rmSync(other, { recursive: true, force: true });
- }
- });
- test('a foreign host name is refused (DNS rebinding)', async () => {
- const r = await fetch(base + '/api/hello', { headers: { host: `evil.example:${live.port}` } });
- expect(r.status).toBe(403);
- });
- });
- describe('LIVE-R02: writing needs the token', () => {
- test('reads without the token', async () => {
- const r = await call('GET', '/api/records?collection=/work/tasks', undefined, {});
- expect(r.status).toBe(200);
- const j = await r.json();
- expect(j.records.map((x: any) => x.path)).toEqual(['/work/tasks/a.md']);
- expect(j.collection.phases.status.map((p: any) => p.name)).toEqual(['todo', 'doing', 'done', 'hold']);
- expect((await (await call('GET', '/api/hello', undefined, {})).json()).write).toBe(false);
- });
- test('every write without the token is 401', async () => {
- const h = { 'content-type': 'application/json' };
- expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P0' } }, h)).status).toBe(401);
- expect((await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'x' } }, h)).status).toBe(401);
- expect((await call('DELETE', '/api/record?path=/work/tasks/a.md', undefined, {})).status).toBe(401);
- expect((await call('POST', '/api/run', { package: 'demo', action: 'hello' }, h)).status).toBe(401);
- expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P0' } }, { ...h, authorization: 'Bearer wrong' })).status).toBe(401);
- expect(read('work/tasks/a.md')).toBe(TASK_A);
- });
- test('the link puts the token into a cookie and drops it from the address', async () => {
- const r = await fetch(`${base}/work/?token=${live.token}`, { redirect: 'manual' });
- expect(r.status).toBe(302);
- expect(r.headers.get('location')).toBe('/work/');
- const cookie = r.headers.get('set-cookie') ?? '';
- expect(cookie).toContain('HttpOnly');
- expect(cookie).toContain('SameSite=Strict');
- const hello = await (await fetch(base + '/api/hello', { headers: { cookie: cookie.split(';')[0] } })).json();
- expect(hello.write).toBe(true);
- });
- test('a write from a foreign page is 403 even with the token', async () => {
- const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P0' } }, { ...auth(), origin: 'http://evil.example' });
- expect(r.status).toBe(403);
- });
- });
- describe('records', () => {
- test('a field changes in place: order, quotes, comments and lists stay', async () => {
- const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'doing', points: 3 } });
- expect(r.status).toBe(200);
- expect(read('work/tasks/a.md')).toBe(TASK_A.replace('status: todo', 'status: doing').replace(' - two\n', ' - two\npoints: 3\n'));
- });
- test('the body changes, the header stays', async () => {
- const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', body: 'New text.\n' });
- expect(r.status).toBe(200);
- expect(read('work/tasks/a.md').endsWith('---\n\nNew text.\n')).toBe(true);
- expect(read('work/tasks/a.md')).toContain('# a comment that must stay');
- });
- test('a stale etag is 409', async () => {
- expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { priority: 'P2' }, etag: 'old' })).status).toBe(409);
- });
- test('schema errors are 422 at the field, in English, and nothing is written', async () => {
- const before = read('work/tasks/a.md');
- for (const [set, field, text] of [
- [{ priority: 'P9' }, 'priority', 'is not an option'],
- [{ due: '28.11.2026' }, 'due', 'is not a date'],
- [{ points: 'many' }, 'points', 'is not a number'],
- [{ owner: '/work/people/bob.md' }, 'owner', 'is not a record of the collection'],
- [{ title: '' }, 'title', 'title is required'],
- ] as const) {
- const r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set });
- expect(r.status).toBe(422);
- const j = await r.json();
- expect(j.field).toBe(field);
- expect(j.error).toContain(text);
- }
- expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { owner: '/work/people/ann.md' } })).status).toBe(200);
- expect(read('work/tasks/a.md')).toBe(before.replace('points: 3\n', 'points: 3\nowner: /work/people/ann.md\n'));
- });
- test('a phase moves only along the contour', async () => {
- let r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'todo' } });
- expect(r.status).toBe(422);
- expect((await r.json()).error).toContain('There is no transition "In progress" (doing) → "Queued" (todo)');
- r = await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'nope' } });
- expect(r.status).toBe(422);
- expect((await call('PATCH', '/api/record', { path: '/work/tasks/a.md', set: { status: 'done' } })).status).toBe(200);
- });
- test('a gate of a move needs its field', async () => {
- const c = await (await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'Put on hold' } })).json();
- let r = await call('PATCH', '/api/record', { path: c.path, set: { status: 'hold' } });
- expect(r.status).toBe(422);
- expect((await r.json()).field).toBe('holdReason');
- r = await call('PATCH', '/api/record', { path: c.path, set: { status: 'hold', holdReason: 'waiting' } });
- expect(r.status).toBe(200);
- });
- test('create: type, title, the entry phase; a name from the title; a new record starts at the entry', async () => {
- const r = await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'New task', priority: 'P0' }, body: 'What to do.' });
- expect(r.status).toBe(201);
- const j = await r.json();
- expect(j.path).toBe('/work/tasks/new-task.md');
- expect(read('work/tasks/new-task.md')).toBe('---\ntype: Task\ntitle: New task\npriority: P0\nstatus: todo\n---\n\nWhat to do.\n');
- const again = await (await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'New task' } })).json();
- expect(again.path).toBe('/work/tasks/new-task-2.md');
- expect((await call('POST', '/api/records', { collection: '/work/tasks', fields: { title: 'Right away', status: 'doing' } })).status).toBe(422);
- expect((await call('POST', '/api/records', { collection: '/work/tasks', fields: {} })).status).toBe(422);
- });
- test('a Russian title gets a latin file name', () => {
- // the Russian words for "new task", written as code points: this source stays English
- expect(slug('\u041d\u043e\u0432\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430')).toBe('novaya-zadacha');
- });
- test('delete moves the record to deleted/', async () => {
- const r = await call('DELETE', '/api/record?path=/work/tasks/new-task-2.md');
- expect(r.status).toBe(200);
- expect((await r.json()).deletedTo).toBe('/deleted/work/tasks/new-task-2.md');
- expect(existsSync(join(root, 'work/tasks/new-task-2.md'))).toBe(false);
- expect(existsSync(join(root, 'deleted/work/tasks/new-task-2.md'))).toBe(true);
- });
- test('only records of collections are written; no way out of the project', async () => {
- expect((await call('PATCH', '/api/record', { path: '/base/live.md', set: { run: ['demo secret'] } })).status).toBe(403);
- expect((await call('PATCH', '/api/record', { path: '/../x.md', set: { a: 1 } })).status).toBe(403);
- expect((await call('PATCH', '/api/record', { path: '/.shtukbase/packages.lock', set: { a: 1 } })).status).toBe(403);
- expect((await fetch(base + '/.shtukbase/packages.lock')).status).toBe(404);
- expect((await fetch(base + '/%2e%2e/etc/passwd')).status).toBe(404);
- });
- test('search finds by title and text', async () => {
- const j = await (await call('GET', '/api/search?q=' + encodeURIComponent('what to do'))).json();
- expect(j.results.map((x: any) => x.path)).toEqual(['/work/tasks/new-task.md']);
- });
- });
- describe('LIVE-R03: actions only from the allow list', () => {
- test('an allowed action runs, with its arguments', async () => {
- const j = await (await call('POST', '/api/run', { package: 'demo', action: 'hello', args: ['world'] })).json();
- expect(j.ok).toBe(true);
- expect(j.output).toBe('hello world');
- });
- test('an action not in the list is 403 and does not run', async () => {
- const r = await call('POST', '/api/run', { package: 'demo', action: 'secret' });
- expect(r.status).toBe(403);
- expect((await r.json()).error).toContain('is not allowed');
- });
- test('the list is empty by default', () => {
- const page = readFileSync(join(import.meta.dir, '..', 'pages', 'base', 'live.md'), 'utf8');
- const other = mkdtempSync(join(tmpdir(), 'live-default-'));
- mkdirSync(join(other, 'base'));
- writeFileSync(join(other, 'base/live.md'), page);
- try {
- expect(readSettings(other)).toEqual({ host: '127.0.0.1', port: 4322, run: [], problems: [] });
- } finally {
- rmSync(other, { recursive: true, force: true });
- }
- });
- test('shtuk check runs every check, streamed as NDJSON', async () => {
- const r = await call('POST', '/api/run', { package: 'shtuk', action: 'check', stream: true });
- expect(r.headers.get('content-type')).toContain('ndjson');
- const events = (await r.text()).trim().split('\n').map((l) => JSON.parse(l));
- expect(events).toEqual([{ type: 'start', step: 'demo/ok' }, { type: 'out', text: 'all good' }, { type: 'end', step: 'demo/ok', code: 0 }, { type: 'exit', code: 0 }]);
- });
- });
- describe('events', () => {
- test('a changed file is announced on /api/events', async () => {
- const ctl = new AbortController();
- const r = await fetch(base + '/api/events', { signal: ctl.signal });
- const reader = r.body!.getReader();
- const dec = new TextDecoder();
- let text = '';
- const got = (async () => {
- while (!text.includes('/work/tasks/b.md')) {
- const { value, done } = await reader.read();
- if (done) break;
- text += dec.decode(value);
- }
- })();
- await Bun.sleep(150);
- writeFileSync(join(root, 'work/tasks/b.md'), '---\ntype: Task\ntitle: B\n---\n');
- await Promise.race([got, Bun.sleep(4000)]);
- ctl.abort();
- expect(text).toContain('event: change');
- expect(text).toContain('/work/tasks/b.md');
- });
- });
- describe('front matter', () => {
- test('a block value is replaced as a whole; a new field goes last; removing works', () => {
- const s = setFields(split(TASK_A), { tags: ['x', 'y z'], due: '2026-11-28', priority: null });
- 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');
- });
- test('values that YAML would read otherwise are quoted', () => {
- const s = setFields(split('---\na: 1\n---\n'), { b: 'true', c: '12', d: 'a: b', e: '#x', f: 'café' });
- expect(s.lines).toEqual(['a: 1', 'b: "true"', 'c: "12"', 'd: "a: b"', 'e: "#x"', 'f: café']);
- });
- });