all repos — snow-editor @ 13d855e25e8510a57608b0ce77f62cbeed372d0e

small and cozy markdown, and orgmode editor

backend/test/api.test.js (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
import assert from 'node:assert';
import { after, before, describe, test } from 'node:test';
import { createApp } from '../src/app.js';
import { getDb, initDb, purgeExpiredDocuments } from '../src/db.js';
import { APP_VERSION } from '../src/messages.js';
const ALLOWED_ORIGIN = 'http://localhost:41737';

let server;
let baseUrl;

function api(path, { method = 'GET', headers = {}, body } = {}) {
  return fetch(`${baseUrl}${path}`, {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
}

async function readJson(res) {
  const text = await res.text();
  return text ? JSON.parse(text) : null;
}

async function createDocument(overrides = {}) {
  const res = await api('/api/documents', {
    method: 'POST',
    headers: { Origin: ALLOWED_ORIGIN },
    body: {
      title: 'Test doc',
      mode: 'markdown',
      content: '# Hello',
      expiresIn: '7d',
      ...overrides,
    },
  });
  assert.equal(res.status, 201);
  return readJson(res);
}

before(() => {
  initDb(':memory:');
  const app = createApp({
    shareAllowedOrigins: ALLOWED_ORIGIN,
  });
  server = app.listen(0);
  const { port } = server.address();
  baseUrl = `http://127.0.0.1:${port}`;
});

after(() => {
  server.close();
});

describe('Snow Editor API', () => {
  test('GET /api/health returns ok with db check', async () => {
    const res = await api('/api/health');
    const data = await readJson(res);

    assert.equal(res.status, 200);
    assert.equal(data.ok, true);
    assert.equal(data.db, 'ok');
    assert.equal(typeof data.uptime, 'number');
    assert.equal(data.version, APP_VERSION);
    assert.match(data.version, /^\d+\.\d+\.\d+$/);
  });

  test('POST /documents without Origin is rejected', async () => {
    const res = await api('/api/documents', {
      method: 'POST',
      body: {
        title: 'Blocked',
        mode: 'markdown',
        content: 'nope',
        expiresIn: '7d',
      },
    });
    const data = await readJson(res);

    assert.equal(res.status, 403);
    assert.equal(data.error, 'ORIGIN_NOT_ALLOWED');
  });

  test('POST /documents with allowed Origin succeeds', async () => {
    const data = await createDocument({ title: 'Allowed' });
    assert.ok(data.viewToken);
    assert.ok(data.editToken);
  });

  test('GET /view/:token returns document', async () => {
    const doc = await createDocument({ content: '# View me' });
    const res = await api(`/api/documents/view/${doc.viewToken}`);
    const data = await readJson(res);

    assert.equal(res.status, 200);
    assert.equal(data.content, '# View me');
  });

  test('POST lock acquires edit lock', async () => {
    const doc = await createDocument();
    const res = await api(`/api/documents/edit/${doc.editToken}/lock`, {
      method: 'POST',
      body: { clientId: 'client-a' },
    });
    const data = await readJson(res);

    assert.equal(res.status, 200);
    assert.equal(data.locked, true);
    assert.ok(data.lockToken);
  });

  test('second clientId on lock returns 423', async () => {
    const doc = await createDocument();
    await api(`/api/documents/edit/${doc.editToken}/lock`, {
      method: 'POST',
      body: { clientId: 'client-a' },
    });

    const res = await api(`/api/documents/edit/${doc.editToken}/lock`, {
      method: 'POST',
      body: { clientId: 'client-b' },
    });
    const data = await readJson(res);

    assert.equal(res.status, 423);
    assert.equal(data.error, 'DOCUMENT_LOCKED');
  });

  test('PUT without lock returns 403', async () => {
    const doc = await createDocument();
    const res = await api(`/api/documents/edit/${doc.editToken}`, {
      method: 'PUT',
      body: {
        clientId: 'ghost',
        lockToken: 'missing',
        title: 'Nope',
        mode: 'markdown',
        content: 'fail',
      },
    });
    const data = await readJson(res);

    assert.equal(res.status, 403);
    assert.equal(data.error, 'LOCK_REQUIRED');
  });

  test('expired document returns 410', async () => {
    const doc = await createDocument();
    const past = new Date(Date.now() - 60_000).toISOString();
    getDb()
      .prepare('UPDATE documents SET expires_at = ? WHERE edit_token = ?')
      .run(past, doc.editToken);

    const res = await api(`/api/documents/edit/${doc.editToken}`);
    const data = await readJson(res);

    assert.equal(res.status, 410);
    assert.equal(data.error, 'EXPIRED');
  });

  test('body larger than 1 MB returns 413', async () => {
    const doc = await createDocument();
    const lockRes = await api(`/api/documents/edit/${doc.editToken}/lock`, {
      method: 'POST',
      body: { clientId: 'big-body' },
    });
    const lock = await readJson(lockRes);

    const huge = 'x'.repeat(1024 * 1024 + 1);
    const res = await api(`/api/documents/edit/${doc.editToken}`, {
      method: 'PUT',
      body: {
        clientId: 'big-body',
        lockToken: lock.lockToken,
        title: 'Huge',
        mode: 'markdown',
        content: huge,
      },
    });
    const data = await readJson(res);

    assert.equal(res.status, 413);
    assert.equal(data.error, 'CONTENT_TOO_LARGE');
  });

  test('version list and restore require active lock', async () => {
    const doc = await createDocument({ content: 'v1' });
    const lockRes = await api(`/api/documents/edit/${doc.editToken}/lock`, {
      method: 'POST',
      body: { clientId: 'version-client' },
    });
    const lock = await readJson(lockRes);

    await api(`/api/documents/edit/${doc.editToken}`, {
      method: 'PUT',
      body: {
        clientId: 'version-client',
        lockToken: lock.lockToken,
        title: doc.title,
        mode: 'markdown',
        content: 'v2',
      },
    });

    const versionsRes = await api(
      `/api/documents/edit/${doc.editToken}/versions?clientId=version-client&lockToken=${lock.lockToken}`,
    );
    const versionsData = await readJson(versionsRes);

    assert.equal(versionsRes.status, 200);
    assert.ok(versionsData.versions.length >= 1);

    const versionId = versionsData.versions[0].id;
    const restoreRes = await api(
      `/api/documents/edit/${doc.editToken}/versions/${versionId}/restore`,
      {
        method: 'POST',
        body: {
          clientId: 'version-client',
          lockToken: lock.lockToken,
        },
      },
    );
    const restored = await readJson(restoreRes);

    assert.equal(restoreRes.status, 200);
    assert.equal(restored.content, 'v1');
  });

  test('rapid consecutive PUTs coalesce into a single version', async () => {
    const doc = await createDocument({ content: 'first' });
    const lockRes = await api(`/api/documents/edit/${doc.editToken}/lock`, {
      method: 'POST',
      body: { clientId: 'coalesce-client' },
    });
    const lock = await readJson(lockRes);

    for (const content of ['second', 'third', 'fourth']) {
      const res = await api(`/api/documents/edit/${doc.editToken}`, {
        method: 'PUT',
        body: {
          clientId: 'coalesce-client',
          lockToken: lock.lockToken,
          title: doc.title,
          mode: 'markdown',
          content,
        },
      });
      assert.equal(res.status, 200);
    }

    const count = getDb()
      .prepare(
        'SELECT COUNT(*) AS n FROM document_versions WHERE document_id = ?',
      )
      .get(doc.id);

    assert.equal(count.n, 1);
  });

  test('purgeExpiredDocuments removes expired rows and cascades', () => {
    // Inserted directly to avoid the 10 req/min create limiter shared by tests.
    const db = getDb();
    const docId = 'purge-doc';
    const past = new Date(Date.now() - 60_000).toISOString();
    db.prepare(
      `INSERT INTO documents (id, title, mode, content, view_token, edit_token, expires_at, created_at, updated_at)
       VALUES (?, 'Purge me', 'markdown', 'bye', 'purge-view', 'purge-edit', ?, ?, ?)`,
    ).run(docId, past, past, past);
    db.prepare(
      `INSERT INTO edit_locks (id, document_id, lock_token, client_id, expires_at, created_at, updated_at)
       VALUES ('purge-lock', ?, 'purge-lock-token', 'purge-client', ?, ?, ?)`,
    ).run(docId, past, past, past);
    db.prepare(
      `INSERT INTO document_versions (id, document_id, title, mode, content, created_at)
       VALUES ('purge-version', ?, 'Purge me', 'markdown', 'v0', ?)`,
    ).run(docId, past);

    const removed = purgeExpiredDocuments(db);
    assert.ok(removed >= 1);

    const row = db.prepare('SELECT id FROM documents WHERE id = ?').get(docId);
    assert.equal(row, undefined);

    const locks = db
      .prepare('SELECT COUNT(*) AS n FROM edit_locks WHERE document_id = ?')
      .get(docId);
    assert.equal(locks.n, 0);

    const versions = db
      .prepare('SELECT COUNT(*) AS n FROM document_versions WHERE document_id = ?')
      .get(docId);
    assert.equal(versions.n, 0);
  });
});