openvibers/openvibe.live Commits
JSON times carry their zone (ISO 8601 Z) on the API edge (#854)
Changes
@@@ -146,6 +146,8 @@ const whipHandler = require('./streaming/whip-handler');// ── Express App ──────────────────────────────────────────────const app = express();++// Times leave with their zone (openvibe.design rule 148): the SQLite-era text columns are UTC.++app.use(require('./iso-times').isoJsonTimes);// GET /openapi.json (SEO-3): this service's public API as OpenAPI 3.1, generated from the contracts// (openvibe-contracts); the operations they mark internal-only are left out.app.get('/openapi.json', (_req, res) => {nnew file mode 100644@@@ -0,0 +1,46 @@++'use strict';++/**++ * Times leave with their zone (openvibe.design rule 148).++ *++ * The tables created from SQLite (migrations/0001_initial.sql) keep timestamps as text in the++ * SQLite shape `YYYY-MM-DD HH:MM:SS`, which ov_now() writes in UTC. A browser reads that string as++ * local time, so west of UTC every event looked hours in the future. This is the edge: JSON fields++ * whose name says they are a time are rendered as ISO 8601 with Z, and nothing else changes — the++ * stored text, cursors built from it and every query that compares it stay exactly as they are.++ *++ * Already-ISO values (with Z or an offset), dates (`YYYY-MM-DD`) and non-strings pass through.++ * `POST /api/v1/...` cursors echo their own stored text, not one of these fields, so pagination is++ * unaffected.++ */++const SQL_TEXT_TIME = /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d(?::\d\d(?:\.\d+)?)?$/;++// created_at, updated_at, started_at, ended_at, expires_at, last_message_at, timestamp, …++// and the bare `created` / `updated` / `started` / `ended` / `expires` some responses use.++const TIME_KEY = /(^|_)(at|created|updated|started|ended|expires|timestamp)$|^last_|^(since|until)$/;++++/** One stored time as ISO 8601 with Z; anything not in the SQLite shape is returned untouched. */++function isoTime(value) {++ return typeof value === 'string' && SQL_TEXT_TIME.test(value) ? `${value.replace(' ', 'T')}Z` : value;++}++++/** Copy `value`, rendering time-named fields; arrays and plain objects are walked, a Date is not. */++function normalizeTimes(value, depth = 0) {++ if (depth > 8 || value === null || typeof value !== 'object') return value;++ if (Array.isArray(value)) return value.map((item) => normalizeTimes(item, depth + 1));++ const proto = Object.getPrototypeOf(value);++ if (proto !== Object.prototype && proto !== null) return value;++ const out = {};++ for (const [key, item] of Object.entries(value)) {++ out[key] = TIME_KEY.test(key) ? isoTime(item) : normalizeTimes(item, depth + 1);++ }++ return out;++}++++/** Express middleware: JSON answers carry ISO times. Internal service routes keep their SQL shape. */++function isoJsonTimes(req, res, next) {++ if (req.path.startsWith('/internal/')) return next();++ const json = res.json.bind(res);++ res.json = (body) => json(normalizeTimes(body));++ next();++}++++module.exports = { TIME_KEY, SQL_TEXT_TIME, isoTime, normalizeTimes, isoJsonTimes };nnew file mode 100644@@@ -0,0 +1,60 @@++'use strict';++/**++ * Times leave with their zone (openvibe.design rule 148): Live's SQLite-era text timestamps are UTC++ * but a browser reads `YYYY-MM-DD HH:MM:SS` as local time. The JSON edge renders time fields as ISO++ * 8601 with Z; stored text, cursors and every query that compares it stay unchanged.++ *++ * node --import ./test/helpers/pg-preload.mjs test/iso-times.test.js++ */++const assert = require('assert');++const http = require('http');++++process.env.NODE_ENV = 'test';++const quiet = console.log;++console.log = (...a) => { if (!/^\[/.test(String(a[0]))) quiet(...a); };++console.warn = () => {};++++const { isoTime, normalizeTimes, isoJsonTimes } = require('../server/iso-times');++assert.strictEqual(isoTime('2026-11-12 05:01:02'), '2026-11-12T05:01:02Z');++assert.strictEqual(isoTime('2026-11-12T05:01:02.123Z'), '2026-11-12T05:01:02.123Z', 'ISO with Z is left alone');++assert.strictEqual(isoTime('2026-11-12T05:01:02+02:00'), '2026-11-12T05:01:02+02:00', 'ISO with an offset is left alone');++assert.strictEqual(isoTime('2026-11-12'), '2026-11-12', 'a date is not a time');++assert.strictEqual(isoTime(null), null);++assert.deepStrictEqual(++ normalizeTimes({ id: 1, created_at: '2026-11-12 05:01:02', updated_at: null, when: '2026-11-12 05:01:02', meta: { last_seen: '2026-11-12 05:01:02' }, tags: [{ expires_at: '2026-11-12 05:01:02' }] }),++ { id: 1, created_at: '2026-11-12T05:01:02Z', updated_at: null, when: '2026-11-12 05:01:02', meta: { last_seen: '2026-11-12T05:01:02Z' }, tags: [{ expires_at: '2026-11-12T05:01:02Z' }] },++ 'time-named fields are rendered; body text that looks like a time is not',++);++++(async () => {++ const db = require('../server/db/database');++ await db.initDb();++ const created = await db.createUser({ username: 'zoner', display_name: 'Zoner', stream_key: 'z'.repeat(32) });++ const userId = created.id || created.lastInsertRowid;++ const raw = db.getDb();++ await raw.prepare(`INSERT INTO streams (id, user_id, title, is_live, started_at, created_at) OVERRIDING SYSTEM VALUE++ VALUES (91, ?, 'Zoned', 1, '2026-10-01 10:00:00', '2026-10-01 10:00:00')`).run(userId);++++ const express = require('express');++ const app = express();++ app.use(isoJsonTimes);++ app.use('/api/streams', require('../server/streaming/routes'));++ const server = http.createServer(app).listen(0, '127.0.0.1');++ await new Promise((r) => server.once('listening', r));++ const get = async (p) => { const r = await fetch(`http://127.0.0.1:${server.address().port}${p}`); return { status: r.status, json: await r.json() }; };++++ const r = await get('/api/streams');++ assert.strictEqual(r.status, 200);++ const stream = (r.json.streams || []).find((s) => s.id === 91);++ assert.ok(stream, 'the live stream is listed');++ assert.strictEqual(stream.started_at, '2026-10-01T10:00:00Z', 'started_at is ISO with Z');++ assert.match(stream.started_at, /Z$/);++ const stored = await raw.prepare('SELECT started_at FROM streams WHERE id = 91').get();++ assert.strictEqual(stored.started_at, '2026-10-01 10:00:00', 'the stored text is untouched');++++ server.close();++ try { await globalThis.__ovLiveTestDbClose(); } catch { /* */ }++ console.log = quiet;++ console.log('iso times: helper and GET /api/streams checked');++ process.exit(0);++})().catch((e) => { console.error(e); process.exit(1); });
@@ -146,6 +146,8 @@ const whipHandler = require('./streaming/whip-handler');
@@ -146,6 +146,8 @@ const whipHandler = require('./streaming/whip-handler');
// ── Express App ──────────────────────────────────────────────
// ── Express App ──────────────────────────────────────────────
const app = express();
const app = express();
+// Times leave with their zone (openvibe.design rule 148): the SQLite-era text columns are UTC.
+app.use(require('./iso-times').isoJsonTimes);
// GET /openapi.json (SEO-3): this service's public API as OpenAPI 3.1, generated from the contracts
// GET /openapi.json (SEO-3): this service's public API as OpenAPI 3.1, generated from the contracts
// (openvibe-contracts); the operations they mark internal-only are left out.
// (openvibe-contracts); the operations they mark internal-only are left out.
app.get('/openapi.json', (_req, res) => {
app.get('/openapi.json', (_req, res) => {
new file mode 100644
new file mode 100644
@@ -0,0 +1,46 @@
@@ -0,0 +1,46 @@
+'use strict';
+/**
+ * Times leave with their zone (openvibe.design rule 148).
+ *
+ * The tables created from SQLite (migrations/0001_initial.sql) keep timestamps as text in the
+ * SQLite shape `YYYY-MM-DD HH:MM:SS`, which ov_now() writes in UTC. A browser reads that string as
+ * local time, so west of UTC every event looked hours in the future. This is the edge: JSON fields
+ * whose name says they are a time are rendered as ISO 8601 with Z, and nothing else changes — the
+ * stored text, cursors built from it and every query that compares it stay exactly as they are.
+ *
+ * Already-ISO values (with Z or an offset), dates (`YYYY-MM-DD`) and non-strings pass through.
+ * `POST /api/v1/...` cursors echo their own stored text, not one of these fields, so pagination is
+ * unaffected.
+ */
+const SQL_TEXT_TIME = /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d(?::\d\d(?:\.\d+)?)?$/;
+// created_at, updated_at, started_at, ended_at, expires_at, last_message_at, timestamp, …
+// and the bare `created` / `updated` / `started` / `ended` / `expires` some responses use.
+const TIME_KEY = /(^|_)(at|created|updated|started|ended|expires|timestamp)$|^last_|^(since|until)$/;
+
+/** One stored time as ISO 8601 with Z; anything not in the SQLite shape is returned untouched. */
+function isoTime(value) {
+ return typeof value === 'string' && SQL_TEXT_TIME.test(value) ? `${value.replace(' ', 'T')}Z` : value;
+}
+
+/** Copy `value`, rendering time-named fields; arrays and plain objects are walked, a Date is not. */
+function normalizeTimes(value, depth = 0) {
+ if (depth > 8 || value === null || typeof value !== 'object') return value;
+ if (Array.isArray(value)) return value.map((item) => normalizeTimes(item, depth + 1));
+ const proto = Object.getPrototypeOf(value);
+ if (proto !== Object.prototype && proto !== null) return value;
+ const out = {};
+ for (const [key, item] of Object.entries(value)) {
+ out[key] = TIME_KEY.test(key) ? isoTime(item) : normalizeTimes(item, depth + 1);
+ }
+ return out;
+}
+
+/** Express middleware: JSON answers carry ISO times. Internal service routes keep their SQL shape. */
+function isoJsonTimes(req, res, next) {
+ if (req.path.startsWith('/internal/')) return next();
+ const json = res.json.bind(res);
+ res.json = (body) => json(normalizeTimes(body));
+ next();
+}
+
+module.exports = { TIME_KEY, SQL_TEXT_TIME, isoTime, normalizeTimes, isoJsonTimes };
new file mode 100644
new file mode 100644
@@ -0,0 +1,60 @@
@@ -0,0 +1,60 @@
+'use strict';
+/**
+ * Times leave with their zone (openvibe.design rule 148): Live's SQLite-era text timestamps are UTC
+ * but a browser reads `YYYY-MM-DD HH:MM:SS` as local time. The JSON edge renders time fields as ISO
+ * 8601 with Z; stored text, cursors and every query that compares it stay unchanged.
+ *
+ * node --import ./test/helpers/pg-preload.mjs test/iso-times.test.js
+ */
+const assert = require('assert');
+const http = require('http');
+
+process.env.NODE_ENV = 'test';
+const quiet = console.log;
+console.log = (...a) => { if (!/^\[/.test(String(a[0]))) quiet(...a); };
+console.warn = () => {};
+
+const { isoTime, normalizeTimes, isoJsonTimes } = require('../server/iso-times');
+assert.strictEqual(isoTime('2026-11-12 05:01:02'), '2026-11-12T05:01:02Z');
+assert.strictEqual(isoTime('2026-11-12T05:01:02.123Z'), '2026-11-12T05:01:02.123Z', 'ISO with Z is left alone');
+assert.strictEqual(isoTime('2026-11-12T05:01:02+02:00'), '2026-11-12T05:01:02+02:00', 'ISO with an offset is left alone');
+assert.strictEqual(isoTime('2026-11-12'), '2026-11-12', 'a date is not a time');
+assert.strictEqual(isoTime(null), null);
+assert.deepStrictEqual(
+ normalizeTimes({ id: 1, created_at: '2026-11-12 05:01:02', updated_at: null, when: '2026-11-12 05:01:02', meta: { last_seen: '2026-11-12 05:01:02' }, tags: [{ expires_at: '2026-11-12 05:01:02' }] }),
+ { id: 1, created_at: '2026-11-12T05:01:02Z', updated_at: null, when: '2026-11-12 05:01:02', meta: { last_seen: '2026-11-12T05:01:02Z' }, tags: [{ expires_at: '2026-11-12T05:01:02Z' }] },
+ 'time-named fields are rendered; body text that looks like a time is not',
+);
+
+(async () => {
+ const db = require('../server/db/database');
+ await db.initDb();
+ const created = await db.createUser({ username: 'zoner', display_name: 'Zoner', stream_key: 'z'.repeat(32) });
+ const userId = created.id || created.lastInsertRowid;
+ const raw = db.getDb();
+ await raw.prepare(`INSERT INTO streams (id, user_id, title, is_live, started_at, created_at) OVERRIDING SYSTEM VALUE
+ VALUES (91, ?, 'Zoned', 1, '2026-10-01 10:00:00', '2026-10-01 10:00:00')`).run(userId);
+
+ const express = require('express');
+ const app = express();
+ app.use(isoJsonTimes);
+ app.use('/api/streams', require('../server/streaming/routes'));
+ const server = http.createServer(app).listen(0, '127.0.0.1');
+ await new Promise((r) => server.once('listening', r));
+ const get = async (p) => { const r = await fetch(`http://127.0.0.1:${server.address().port}${p}`); return { status: r.status, json: await r.json() }; };
+
+ const r = await get('/api/streams');
+ assert.strictEqual(r.status, 200);
+ const stream = (r.json.streams || []).find((s) => s.id === 91);
+ assert.ok(stream, 'the live stream is listed');
+ assert.strictEqual(stream.started_at, '2026-10-01T10:00:00Z', 'started_at is ISO with Z');
+ assert.match(stream.started_at, /Z$/);
+ const stored = await raw.prepare('SELECT started_at FROM streams WHERE id = 91').get();
+ assert.strictEqual(stored.started_at, '2026-10-01 10:00:00', 'the stored text is untouched');
+
+ server.close();
+ try { await globalThis.__ovLiveTestDbClose(); } catch { /* */ }
+ console.log = quiet;
+ console.log('iso times: helper and GET /api/streams checked');
+ process.exit(0);
+})().catch((e) => { console.error(e); process.exit(1); });