openvibers/openvibe.design Commits
Design: the Figma token is an owner setting (design.publishing) (#166)
Changes
@@@ -69,3 +69,7 @@ DESIGN_GLYPH_GUEST_DAILY=25# Cloudflare Turnstile on the guest form: on only when both are set (the site key is public, the secret is not).DESIGN_TURNSTILE_SITE_KEY=DESIGN_TURNSTILE_SECRET=++++# Publishing tokens (D11 owner settings): the admin panel's design.publishing namespace wins; this is++# the fallback when no value was entered there.++#FIGMA_TOKEN=@@@ -227,7 +227,7 @@ Part of the [OpenVibe network](https://openvibe.network). Built in the open by[OpenVibers](https://github.com/OpenVibers).<!-- versions:start -->--- openvibe-contracts: v0.289.1++- openvibe-contracts: v0.311.0- openvibe-sdk: v0.93.0- openvibe-shared: v4.124.0- openvibe-publishing: v1.5.0@@@ -8,11 +8,11 @@"runtime": "node 22, express 4, openvibe-shared/shell; PostgreSQL (or embedded PGlite in development), OpenVibe.AI generate jobs, OpenVibe.Events account data in, no Valkey","port": "5090","domain": "openvibe.design",-- "contracts": "openvibe-contracts v0.289.1",++ "contracts": "openvibe-contracts v0.311.0","sdk": "openvibe-sdk v0.93.0","shared": "openvibe-shared v4.124.0","packages": [-- "openvibe-contracts v0.289.1",++ "openvibe-contracts v0.311.0","openvibe-publishing v1.5.0","openvibe-sdk v0.93.0","openvibe-shared v4.124.0"nnew file mode 100644@@@ -0,0 +1,30 @@++-- phase: expand++-- D11 owner settings (openvibe-shared/config): the configuration snapshots and the per-namespace++-- fingerprint key. Design's publishing tokens live in design.publishing; the store seals++-- secret-class values under OV_CONFIG_KEKS and keeps only markers in snapshots. Every table here is++-- new, and an older release ignores all of it.++CREATE TABLE IF NOT EXISTS config_snapshots (++ namespace text COLLATE "C" NOT NULL,++ revision bigint NOT NULL,++ service text COLLATE "C" NOT NULL,++ previous_revision bigint,++ state text COLLATE "C" NOT NULL CHECK (state IN ('proposed', 'active', 'superseded', 'rejected', 'rolled_back')),++ values_json text COLLATE "C" NOT NULL,++ classification_json text COLLATE "C" NOT NULL,++ values_checksum text COLLATE "C" NOT NULL,++ created_at text COLLATE "C" NOT NULL,++ created_by text COLLATE "C" NOT NULL,++ activated_at text COLLATE "C",++ activated_by text COLLATE "C",++ reason text COLLATE "C",++ error text COLLATE "C",++ copied_from bigint,++ good bigint NOT NULL DEFAULT 0,++ PRIMARY KEY (namespace, revision)++);++CREATE UNIQUE INDEX IF NOT EXISTS config_snapshots_one_active ON config_snapshots (namespace) WHERE state = 'active';++CREATE TABLE IF NOT EXISTS config_keys (++ namespace text COLLATE "C" PRIMARY KEY,++ hmac_key bytea NOT NULL,++ created_at text COLLATE "C" NOT NULL++);@@@ -15,7 +15,7 @@"express": "^4.21.2","express-rate-limit": "^7.5.0","helmet": "^8.1.0",-- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.289.1",++ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.311.0","openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.5.0","openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.93.0","openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.124.0",@@@ -1322,9 +1322,9 @@}},"node_modules/openvibe-contracts": {-- "version": "0.289.1",-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.289.1",-- "integrity": "sha512-LrKTwe8VPCWn+b0MTNmfjAYEJ0rtgLxeM6EHONBDl0ynt/Igndz+ruDEpwuz5SZ9HYCIMkCqSV5ujhedh6zmzQ==",++ "version": "0.311.0",++ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.311.0",++ "integrity": "sha512-s0CubY2CA281mADLTwfnHSlpcC+fXbdmTEHFd0gExXrE6P2DGZlf+l+p6GyyOTF0k4CJZeCutDzwSjfSU/ZJRg==","license": "AGPL-3.0-only","dependencies": {"ajv": "^8.17.1",@@@ -21,7 +21,7 @@"express": "^4.21.2","express-rate-limit": "^7.5.0","helmet": "^8.1.0",-- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.289.1",++ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.311.0","openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.5.0","openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.93.0","openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.124.0",@@@ -30,6 +30,8 @@ const { createNetworkSender } = require('openvibe-sdk/account-data');const configLib = require('./config');const { openStore } = require('./db');const { createKeyStore } = require('./auth/keys');++const settingsLib = require('./settings');++const { verifyServiceToken } = require('openvibe-sdk/auth');const { createSso } = require('./auth/sso');const { createThemeCatalog } = require('./themes');const { createSearchIndex } = require('./search-index');@@@ -66,6 +68,19 @@ async function createApp(opts = {}) {const s = opts.store || await openStore(config, { now, log });const keys = createKeyStore({ config, fetchImpl, log });const sso = createSso({ config, keys, fetchImpl, log, now });++ // D11 owner settings (design.publishing): created before the app mounts /internal/config. A failure leaves++ // Design serving (the Figma token falls back to the environment) and says why in the log.++ let settings = null;++ if (opts.settings) settings = opts.settings;++ else {++ try {++ const made = settingsLib.createSettings({ db: s.db, env: opts.env || process.env, log });++ await made.ready;++ settings = settingsLib.activate(made);++ } catch (err) {++ log.warn('[OpenVibe.Design] owner settings unavailable, the publishing tokens fall back to the environment:', err && err.message);++ }++ }const catalog = opts.catalog || createThemeCatalog({ config, fetchImpl, log, now });// The icon and theme pages in OpenVibe.Search (started by server/index.js, never under DESIGN_DRILL).const searchIndex = opts.searchIndex || createSearchIndex({ config, s, catalog, log });@@@ -87,7 +102,7 @@ async function createApp(opts = {}) {: async () => { throw new Error('OV_OAUTH_CLIENT_SECRET is not set: Design cannot answer account events'); });const ctx = {-- config, s, store: s, keys, sso, catalog, searchIndex, arena, bench, ai, jobs, designs, sharing, publisher, accountData, accountSend, log, picks,++ config, s, store: s, keys, sso, settings, catalog, searchIndex, arena, bench, ai, jobs, designs, sharing, publisher, accountData, accountSend, log, picks,random: opts.random || Math.random,};@@@ -171,6 +186,32 @@ async function createApp(opts = {}) {// Raw body first: the SDK verifies the delivery signature over the exact bytes.app.use('/internal/events', accountData.consumer({ secrets: config.events.secrets, send: accountSend }));++ // ── D11 owner settings (openvibe-shared/config): Network's admin proxy, acting for the owner, reads and++ // writes design.publishing (the Figma token). Loopback only, guarded by design.config.manage; a secret++ // change needs X-OV-Fresh: 1, and the test route makes one cheap authenticated Figma read.++ if (settings) {++ const configGuard = async (req, res, next) => {++ if (req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.headers['cf-connecting-ip']) {++ return res.status(404).json({ code: 'design.not_found', error: 'no such route' });++ }++ const header = String(req.headers.authorization || '');++ if (!header.startsWith('Bearer ')) return res.status(401).json({ code: 'token.missing', error: 'a service token is required' });++ const r = await verifyServiceToken(header.slice(7).trim(), {++ jwks: `${config.networkInternalUrl}/api/.well-known/jwks`, issuer: config.networkIssuer, audience: 'openvibe.design',++ contracts: require('openvibe-contracts'),++ });++ if (!r.ok) return res.status(r.code === 'token.unavailable' ? 503 : 401).json({ code: r.code, error: r.reason || 'the token does not verify' });++ const contracts = require('openvibe-contracts');++ const decision = contracts.capabilities.check(r.claims, 'design.config.manage');++ const granted = decision.allowed || contracts.capabilities.grants(r.claims.cap, 'design.config.manage');++ if (!granted) return res.status(403).json({ code: 'capability.denied', error: 'design.config.manage is not granted' });++ req.principal = { sub: r.claims.sub, cap: r.claims.cap, jti: r.claims.jti };++ return next();++ };++ app.use('/internal/config', express.json({ limit: '64kb' }));++ settings.mount(app, { guard: configGuard, log });++ }++// ── Static assets (content-hashed ?v= → immutable) ──────app.use('/shared', serve.handler());// Terms, Privacy and DMCA in this site's own words (openvibe-shared/legal, profile 'service'; 11-03: the footer'snnew file mode 100644@@@ -0,0 +1,125 @@++'use strict';++++/**++ * Owner settings (D11) for OpenVibe.Design: the publishing accounts in `design.publishing`.++ *++ * The Figma token is read through figmaToken() when a Figma import is made: the value the owner++ * entered in the admin panel wins, FIGMA_TOKEN is the fallback. The token is sealed by the shared++ * store under OV_CONFIG_KEKS and is write-only through++ * /internal/config/design.publishing/secrets/figma_token; summaries, history and logs carry markers.++ * Network's admin proxy reaches this namespace with `design.config.manage`, acting for the owner++ * (X-OV-Subject); a secret change needs X-OV-Fresh: 1. The test route makes one cheap authenticated++ * Figma read and answers ok or failed in one line, never echoing the token.++ */++const { createConfigStore, adminRoutes } = require('openvibe-shared/config');++++const SERVICE = 'design';++const NAMESPACE = 'design.publishing';++const BASE_PATH = '/internal/config';++const GROUP = 'Design and publishing';++++const SCHEMA = Object.freeze({++ $schema: 'https://json-schema.org/draft/2020-12/schema',++ title: 'Design and publishing',++ description: 'The accounts Design publishes and imports with. A token that is not set turns its feature off; the rest of Design keeps working.',++ type: 'object',++ additionalProperties: false,++ properties: {++ figma_token: {++ type: 'string', title: 'Figma personal access token', 'x-group': GROUP,++ description: 'A Figma personal access token with read access to the files Design imports. It lets a person bring a Figma design into Design; without it the Figma import stays hidden.',++ 'x-owner-input': {++ group: 'design-publishing',++ unlocks: 'Figma files can be imported into Design and their components and tokens read.',++ get_it_at: 'https://www.figma.com/settings',++ get_it_how: 'Open Settings, Security, Personal access tokens, create a token with read access to the files, then paste it here.',++ test: true,++ },++ 'x-required-for': 'Figma import',++ },++ },++});++++const SECRETS = new Set(['figma_token']);++const ACTIVE = { settings: null };++++function createSettings({ db, env = process.env, log = console, fetchImpl = globalThis.fetch, probes = null } = {}) {++ let store = null;++ const ready = createConfigStore({++ db, service: SERVICE, namespace: NAMESPACE, schema: SCHEMA,++ classify: (key) => (SECRETS.has(key) ? 'secret' : 'internal'),++ env, log,++ }).then((s) => { store = s; return s; });++++ const values = () => (store ? store.get() : {});++++ function valueOf(key, envName, fallback = '') {++ const v = values()[key];++ if (v !== undefined && v !== null && v !== '') return v;++ const e = envName ? env[envName] : undefined;++ return e !== undefined && e !== null && e !== '' ? e : fallback;++ }++++ /** The Figma token, read when a Figma import is made. */++ function figmaToken() { return valueOf('figma_token', 'FIGMA_TOKEN', ''); }++++ async function test(key) {++ if (key !== 'figma_token') return { ok: false, detail: 'That setting has no test.' };++ const token = figmaToken();++ if (!token) return { ok: false, detail: 'Figma is not configured: paste the personal access token first.' };++ const probe = probes && typeof probes.figma === 'function'++ ? probes.figma++ : async ({ token: value }) => {++ const r = await fetchImpl('https://api.figma.com/v1/me', { headers: { accept: 'application/json', 'x-figma-token': value } });++ let body = {};++ try { body = await r.json(); } catch { /* not JSON */ }++ if (!r.ok) throw new Error(`HTTP ${r.status}${body && body.message ? `: ${body.message}` : ''}`);++ };++ try {++ await probe({ token });++ return { ok: true, detail: 'ok — Figma answered the account read with this token.' };++ } catch (err) {++ const words = String((err && err.message) || 'the request failed').split(/\s+/).join(' ').slice(0, 160);++ return { ok: false, detail: `failed — Figma said: ${words.split(token).join('[redacted]')}` };++ }++ }++++ function mount(app, { guard, log: appLog = log } = {}) {++ if (!store) throw new Error('createSettings: await ready before mount()');++ const routes = adminRoutes([store], {++ basePath: BASE_PATH,++ requireAdmin: guard,++ actor: (req) => {++ const id = String(req.get('x-ov-subject') || '').trim();++ return /^usr_[0-9A-HJKMNP-TV-Z]{26}$/.test(id) ? { type: 'user', id } : null;++ },++ requireFresh: (req) => String(req.get('x-ov-fresh') || '') === '1',++ log: appLog,++ });++ app.use(routes.handle);++ app.post(`${BASE_PATH}/:namespace/test/:key`, guard, async (req, res) => {++ if (req.params.namespace !== NAMESPACE) return res.status(404).json({ error: 'no such configuration namespace' });++ let key = String(req.params.key || '');++ try { key = decodeURIComponent(key); } catch { /* keep it as it is */ }++ if (!SCHEMA.properties[key]) return res.status(404).json({ error: 'no such setting' });++ try {++ const out = await test(key);++ return res.status(200).json({ ok: Boolean(out.ok), detail: String(out.detail).replace(/\s+/g, ' ').slice(0, 200) });++ } catch (err) {++ appLog.warn(`[config] ${NAMESPACE}: the test for ${key} failed: ${String((err && err.message) || err).slice(0, 160)}`);++ return res.status(200).json({ ok: false, detail: 'failed — the test did not finish. The service log has the reason.' });++ }++ });++ return routes;++ }++++ return { namespace: NAMESPACE, schema: SCHEMA, ready, value: valueOf, get: values, figmaToken, test, mount };++}++++function activate(settings) { ACTIVE.settings = settings; return settings; }++function figmaToken() {++ if (ACTIVE.settings) return ACTIVE.settings.figmaToken();++ return process.env.FIGMA_TOKEN || '';++}++++module.exports = { SERVICE, NAMESPACE, SCHEMA, SECRETS, createSettings, activate, figmaToken };@@@ -15,6 +15,7 @@ const { testDb } = require('./helpers/db');tables: TABLES,taskKeyed: ['design_versions'], // versions belong to the design and cascade with itexempt: {++ config_snapshots: 'D11 owner settings: created_by/activated_by is the acting administrator (usr_...) for the config audit trail; the values are network configuration, not the person\'s account data, and are kept for rollback/history',account_data_events: 'the ledger of requests itself: which export and deletion design applied',design_index_revisions: 'the Search index sequencer: owner is the service (design), the rows are icon and theme pages, never a person',share_members: 'who a design is shared with: exported as shared_with_me.json, and erased by extraErase',nnew file mode 100644@@@ -0,0 +1,93 @@++'use strict';++/**++ * Owner settings (D11) for Design's publishing accounts (server/settings.js, design.publishing):++ * - the Figma token has a plain title, a 30+ character description, x-owner-input words and a test;++ * - /internal/config is loopback only and needs design.config.manage;++ * - the token is write-only and marked in summaries, figmaToken() reads the owner's value and++ * falls back to FIGMA_TOKEN, and the test hook never echoes or logs the token.++ * node test/owner-settings.test.js++ */++const assert = require('assert');++const http = require('http');++const express = require('express');++const { serviceAuth } = require('openvibe-contracts');++const { boot } = require('./helpers/boot');++const { createSettings } = require('../server/settings');++++const CAP = 'design.config.manage';++const NS = 'design.publishing';++const USR = 'usr_01J8Z3Q4R5S6T7V8W9X0Y1Z2A3';++const TOKEN = 'figma-owner-token-sentinel';++++(async () => {++ const t = await boot();++ const now = Math.floor(Date.now() / 1000);++ const bearer = serviceAuth.signServiceToken({ iss: t.network.url, sub: 'svc:network', actor_type: 'service', aud: ['openvibe.design'], cap: [CAP], iat: now, exp: now + 300, jti: 'tok_owner_settings' }, t.network.privatePem);++ const checks = [];++ const check = async (name, fn) => {++ try { await fn(); checks.push(name); console.log(` ✓ ${name}`); } catch (e) { console.log(` ✗ ${name}\n${e.stack}`); await t.close(); process.exit(1); }++ };++++ await check('the Figma token has owner words and a test', async () => {++ const r = await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${bearer}` } });++ assert.strictEqual(r.status, 200, r.text);++ const f = r.json().schema.properties.figma_token;++ assert.ok(f);++ assert.ok(f.title && f.title.length >= 3);++ assert.ok(f.description && f.description.length >= 30);++ assert.strictEqual(f['x-owner-input'].group, 'design-publishing');++ assert.ok(f['x-owner-input'].unlocks.length > 20);++ assert.strictEqual(f['x-owner-input'].get_it_at, 'https://www.figma.com/settings');++ assert.strictEqual(f['x-owner-input'].test, true);++ assert.strictEqual(f['x-required-for'], 'Figma import');++ });++++ await check('the routes are loopback only and need the capability', async () => {++ assert.strictEqual((await t.get(`/internal/config/${NS}`)).status, 401);++ const wrong = serviceAuth.signServiceToken({ iss: t.network.url, sub: 'svc:network', actor_type: 'service', aud: ['openvibe.design'], cap: ['design.read'], iat: now, exp: now + 300, jti: 'tok_wrong' }, t.network.privatePem);++ assert.strictEqual((await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${wrong}` } })).status, 403);++ assert.strictEqual((await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${bearer}`, 'x-forwarded-for': '203.0.113.9' } })).status, 404);++ });++++ await check('the token is write-only and the environment is the fallback', async () => {++ const envOnly = createSettings({ db: t.ctx.s.db, env: { FIGMA_TOKEN: 'figma-env-token' } });++ await envOnly.ready;++ assert.strictEqual(envOnly.figmaToken(), 'figma-env-token', 'the env is the fallback');++ const put = await t.get(`/internal/config/${NS}/secrets/figma_token`, {++ method: 'PUT', json: { value: TOKEN, reason: 'owner test' },++ headers: { authorization: `Bearer ${bearer}`, 'x-ov-subject': USR, 'x-ov-fresh': '1' },++ });++ assert.strictEqual(put.status, 200, put.text);++ assert.ok(put.json().fingerprint && put.json().hint);++ assert.ok(!put.text.includes(TOKEN));++ const summary = await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${bearer}` } });++ assert.ok(summary.json().values.figma_token.redacted);++ assert.ok(!summary.text.includes(TOKEN));++ assert.strictEqual(t.ctx.settings.figmaToken(), TOKEN, 'the code reads the owner value when set');++ });++++ await check('the test hook says ok/failed in one line and never echoes a token', async () => {++ const fake = createSettings({++ db: t.ctx.s.db, env: {},++ probes: { figma: async ({ token }) => { throw new Error(`refused ${token}`); } },++ });++ await fake.ready;++ const app = express();++ app.use(express.json());++ fake.mount(app, { guard: (_req, _res, next) => next(), log: console });++ const server = await new Promise((resolve) => { const s = http.createServer(app); s.listen(0, '127.0.0.1', () => resolve(s)); });++ try {++ const r = await fetch(`http://127.0.0.1:${server.address().port}/internal/config/${NS}/test/figma_token`, { method: 'POST' });++ const body = await r.json();++ assert.strictEqual(r.status, 200);++ assert.strictEqual(body.ok, false);++ assert.ok(/^failed — Figma said: /.test(body.detail), body.detail);++ assert.ok(!body.detail.includes(TOKEN));++ assert.ok(!body.detail.includes('\n'));++ } finally { server.close(); }++ assert.ok(!t.logs().includes(TOKEN), 'no token in a captured log line');++ });++++ await t.close();++ console.log(`\n${checks.length} checks passed`);++})().catch((e) => { console.error(e); process.exit(1); });
@@ -69,3 +69,7 @@ DESIGN_GLYPH_GUEST_DAILY=25
@@ -69,3 +69,7 @@ DESIGN_GLYPH_GUEST_DAILY=25
# Cloudflare Turnstile on the guest form: on only when both are set (the site key is public, the secret is not).
# Cloudflare Turnstile on the guest form: on only when both are set (the site key is public, the secret is not).
DESIGN_TURNSTILE_SITE_KEY=
DESIGN_TURNSTILE_SITE_KEY=
DESIGN_TURNSTILE_SECRET=
DESIGN_TURNSTILE_SECRET=
+
+# Publishing tokens (D11 owner settings): the admin panel's design.publishing namespace wins; this is
+# the fallback when no value was entered there.
+#FIGMA_TOKEN=
@@ -227,7 +227,7 @@ Part of the [OpenVibe network](https://openvibe.network). Built in the open by
@@ -227,7 +227,7 @@ Part of the [OpenVibe network](https://openvibe.network). Built in the open by
[OpenVibers](https://github.com/OpenVibers).
[OpenVibers](https://github.com/OpenVibers).
<!-- versions:start -->
<!-- versions:start -->
-- openvibe-contracts: v0.289.1
+- openvibe-contracts: v0.311.0
- openvibe-sdk: v0.93.0
- openvibe-sdk: v0.93.0
- openvibe-shared: v4.124.0
- openvibe-shared: v4.124.0
- openvibe-publishing: v1.5.0
- openvibe-publishing: v1.5.0
@@ -8,11 +8,11 @@
@@ -8,11 +8,11 @@
"runtime": "node 22, express 4, openvibe-shared/shell; PostgreSQL (or embedded PGlite in development), OpenVibe.AI generate jobs, OpenVibe.Events account data in, no Valkey",
"runtime": "node 22, express 4, openvibe-shared/shell; PostgreSQL (or embedded PGlite in development), OpenVibe.AI generate jobs, OpenVibe.Events account data in, no Valkey",
"port": "5090",
"port": "5090",
"domain": "openvibe.design",
"domain": "openvibe.design",
- "contracts": "openvibe-contracts v0.289.1",
+ "contracts": "openvibe-contracts v0.311.0",
"sdk": "openvibe-sdk v0.93.0",
"sdk": "openvibe-sdk v0.93.0",
"shared": "openvibe-shared v4.124.0",
"shared": "openvibe-shared v4.124.0",
"packages": [
"packages": [
- "openvibe-contracts v0.289.1",
+ "openvibe-contracts v0.311.0",
"openvibe-publishing v1.5.0",
"openvibe-publishing v1.5.0",
"openvibe-sdk v0.93.0",
"openvibe-sdk v0.93.0",
"openvibe-shared v4.124.0"
"openvibe-shared v4.124.0"
new file mode 100644
new file mode 100644
@@ -0,0 +1,30 @@
@@ -0,0 +1,30 @@
+-- phase: expand
+-- D11 owner settings (openvibe-shared/config): the configuration snapshots and the per-namespace
+-- fingerprint key. Design's publishing tokens live in design.publishing; the store seals
+-- secret-class values under OV_CONFIG_KEKS and keeps only markers in snapshots. Every table here is
+-- new, and an older release ignores all of it.
+CREATE TABLE IF NOT EXISTS config_snapshots (
+ namespace text COLLATE "C" NOT NULL,
+ revision bigint NOT NULL,
+ service text COLLATE "C" NOT NULL,
+ previous_revision bigint,
+ state text COLLATE "C" NOT NULL CHECK (state IN ('proposed', 'active', 'superseded', 'rejected', 'rolled_back')),
+ values_json text COLLATE "C" NOT NULL,
+ classification_json text COLLATE "C" NOT NULL,
+ values_checksum text COLLATE "C" NOT NULL,
+ created_at text COLLATE "C" NOT NULL,
+ created_by text COLLATE "C" NOT NULL,
+ activated_at text COLLATE "C",
+ activated_by text COLLATE "C",
+ reason text COLLATE "C",
+ error text COLLATE "C",
+ copied_from bigint,
+ good bigint NOT NULL DEFAULT 0,
+ PRIMARY KEY (namespace, revision)
+);
+CREATE UNIQUE INDEX IF NOT EXISTS config_snapshots_one_active ON config_snapshots (namespace) WHERE state = 'active';
+CREATE TABLE IF NOT EXISTS config_keys (
+ namespace text COLLATE "C" PRIMARY KEY,
+ hmac_key bytea NOT NULL,
+ created_at text COLLATE "C" NOT NULL
+);
@@ -15,7 +15,7 @@
@@ -15,7 +15,7 @@
"express": "^4.21.2",
"express": "^4.21.2",
"express-rate-limit": "^7.5.0",
"express-rate-limit": "^7.5.0",
"helmet": "^8.1.0",
"helmet": "^8.1.0",
- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.289.1",
+ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.311.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.5.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.5.0",
"openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.93.0",
"openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.93.0",
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.124.0",
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.124.0",
@@ -1322,9 +1322,9 @@
@@ -1322,9 +1322,9 @@
}
}
},
},
"node_modules/openvibe-contracts": {
"node_modules/openvibe-contracts": {
- "version": "0.289.1",
- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.289.1",
- "integrity": "sha512-LrKTwe8VPCWn+b0MTNmfjAYEJ0rtgLxeM6EHONBDl0ynt/Igndz+ruDEpwuz5SZ9HYCIMkCqSV5ujhedh6zmzQ==",
+ "version": "0.311.0",
+ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.311.0",
+ "integrity": "sha512-s0CubY2CA281mADLTwfnHSlpcC+fXbdmTEHFd0gExXrE6P2DGZlf+l+p6GyyOTF0k4CJZeCutDzwSjfSU/ZJRg==",
"license": "AGPL-3.0-only",
"license": "AGPL-3.0-only",
"dependencies": {
"dependencies": {
"ajv": "^8.17.1",
"ajv": "^8.17.1",
@@ -21,7 +21,7 @@
@@ -21,7 +21,7 @@
"express": "^4.21.2",
"express": "^4.21.2",
"express-rate-limit": "^7.5.0",
"express-rate-limit": "^7.5.0",
"helmet": "^8.1.0",
"helmet": "^8.1.0",
- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.289.1",
+ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.311.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.5.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.5.0",
"openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.93.0",
"openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.93.0",
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.124.0",
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.124.0",
@@ -30,6 +30,8 @@ const { createNetworkSender } = require('openvibe-sdk/account-data');
@@ -30,6 +30,8 @@ const { createNetworkSender } = require('openvibe-sdk/account-data');
const configLib = require('./config');
const configLib = require('./config');
const { openStore } = require('./db');
const { openStore } = require('./db');
const { createKeyStore } = require('./auth/keys');
const { createKeyStore } = require('./auth/keys');
+const settingsLib = require('./settings');
+const { verifyServiceToken } = require('openvibe-sdk/auth');
const { createSso } = require('./auth/sso');
const { createSso } = require('./auth/sso');
const { createThemeCatalog } = require('./themes');
const { createThemeCatalog } = require('./themes');
const { createSearchIndex } = require('./search-index');
const { createSearchIndex } = require('./search-index');
@@ -66,6 +68,19 @@ async function createApp(opts = {}) {
@@ -66,6 +68,19 @@ async function createApp(opts = {}) {
const s = opts.store || await openStore(config, { now, log });
const s = opts.store || await openStore(config, { now, log });
const keys = createKeyStore({ config, fetchImpl, log });
const keys = createKeyStore({ config, fetchImpl, log });
const sso = createSso({ config, keys, fetchImpl, log, now });
const sso = createSso({ config, keys, fetchImpl, log, now });
+ // D11 owner settings (design.publishing): created before the app mounts /internal/config. A failure leaves
+ // Design serving (the Figma token falls back to the environment) and says why in the log.
+ let settings = null;
+ if (opts.settings) settings = opts.settings;
+ else {
+ try {
+ const made = settingsLib.createSettings({ db: s.db, env: opts.env || process.env, log });
+ await made.ready;
+ settings = settingsLib.activate(made);
+ } catch (err) {
+ log.warn('[OpenVibe.Design] owner settings unavailable, the publishing tokens fall back to the environment:', err && err.message);
+ }
+ }
const catalog = opts.catalog || createThemeCatalog({ config, fetchImpl, log, now });
const catalog = opts.catalog || createThemeCatalog({ config, fetchImpl, log, now });
// The icon and theme pages in OpenVibe.Search (started by server/index.js, never under DESIGN_DRILL).
// The icon and theme pages in OpenVibe.Search (started by server/index.js, never under DESIGN_DRILL).
const searchIndex = opts.searchIndex || createSearchIndex({ config, s, catalog, log });
const searchIndex = opts.searchIndex || createSearchIndex({ config, s, catalog, log });
@@ -87,7 +102,7 @@ async function createApp(opts = {}) {
@@ -87,7 +102,7 @@ async function createApp(opts = {}) {
: async () => { throw new Error('OV_OAUTH_CLIENT_SECRET is not set: Design cannot answer account events'); });
: async () => { throw new Error('OV_OAUTH_CLIENT_SECRET is not set: Design cannot answer account events'); });
const ctx = {
const ctx = {
- config, s, store: s, keys, sso, catalog, searchIndex, arena, bench, ai, jobs, designs, sharing, publisher, accountData, accountSend, log, picks,
+ config, s, store: s, keys, sso, settings, catalog, searchIndex, arena, bench, ai, jobs, designs, sharing, publisher, accountData, accountSend, log, picks,
random: opts.random || Math.random,
random: opts.random || Math.random,
};
};
@@ -171,6 +186,32 @@ async function createApp(opts = {}) {
@@ -171,6 +186,32 @@ async function createApp(opts = {}) {
// Raw body first: the SDK verifies the delivery signature over the exact bytes.
// Raw body first: the SDK verifies the delivery signature over the exact bytes.
app.use('/internal/events', accountData.consumer({ secrets: config.events.secrets, send: accountSend }));
app.use('/internal/events', accountData.consumer({ secrets: config.events.secrets, send: accountSend }));
+ // ── D11 owner settings (openvibe-shared/config): Network's admin proxy, acting for the owner, reads and
+ // writes design.publishing (the Figma token). Loopback only, guarded by design.config.manage; a secret
+ // change needs X-OV-Fresh: 1, and the test route makes one cheap authenticated Figma read.
+ if (settings) {
+ const configGuard = async (req, res, next) => {
+ if (req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.headers['cf-connecting-ip']) {
+ return res.status(404).json({ code: 'design.not_found', error: 'no such route' });
+ }
+ const header = String(req.headers.authorization || '');
+ if (!header.startsWith('Bearer ')) return res.status(401).json({ code: 'token.missing', error: 'a service token is required' });
+ const r = await verifyServiceToken(header.slice(7).trim(), {
+ jwks: `${config.networkInternalUrl}/api/.well-known/jwks`, issuer: config.networkIssuer, audience: 'openvibe.design',
+ contracts: require('openvibe-contracts'),
+ });
+ if (!r.ok) return res.status(r.code === 'token.unavailable' ? 503 : 401).json({ code: r.code, error: r.reason || 'the token does not verify' });
+ const contracts = require('openvibe-contracts');
+ const decision = contracts.capabilities.check(r.claims, 'design.config.manage');
+ const granted = decision.allowed || contracts.capabilities.grants(r.claims.cap, 'design.config.manage');
+ if (!granted) return res.status(403).json({ code: 'capability.denied', error: 'design.config.manage is not granted' });
+ req.principal = { sub: r.claims.sub, cap: r.claims.cap, jti: r.claims.jti };
+ return next();
+ };
+ app.use('/internal/config', express.json({ limit: '64kb' }));
+ settings.mount(app, { guard: configGuard, log });
+ }
+
// ── Static assets (content-hashed ?v= → immutable) ──────
// ── Static assets (content-hashed ?v= → immutable) ──────
app.use('/shared', serve.handler());
app.use('/shared', serve.handler());
// Terms, Privacy and DMCA in this site's own words (openvibe-shared/legal, profile 'service'; 11-03: the footer's
// Terms, Privacy and DMCA in this site's own words (openvibe-shared/legal, profile 'service'; 11-03: the footer's
new file mode 100644
new file mode 100644
@@ -0,0 +1,125 @@
@@ -0,0 +1,125 @@
+'use strict';
+
+/**
+ * Owner settings (D11) for OpenVibe.Design: the publishing accounts in `design.publishing`.
+ *
+ * The Figma token is read through figmaToken() when a Figma import is made: the value the owner
+ * entered in the admin panel wins, FIGMA_TOKEN is the fallback. The token is sealed by the shared
+ * store under OV_CONFIG_KEKS and is write-only through
+ * /internal/config/design.publishing/secrets/figma_token; summaries, history and logs carry markers.
+ * Network's admin proxy reaches this namespace with `design.config.manage`, acting for the owner
+ * (X-OV-Subject); a secret change needs X-OV-Fresh: 1. The test route makes one cheap authenticated
+ * Figma read and answers ok or failed in one line, never echoing the token.
+ */
+const { createConfigStore, adminRoutes } = require('openvibe-shared/config');
+
+const SERVICE = 'design';
+const NAMESPACE = 'design.publishing';
+const BASE_PATH = '/internal/config';
+const GROUP = 'Design and publishing';
+
+const SCHEMA = Object.freeze({
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ title: 'Design and publishing',
+ description: 'The accounts Design publishes and imports with. A token that is not set turns its feature off; the rest of Design keeps working.',
+ type: 'object',
+ additionalProperties: false,
+ properties: {
+ figma_token: {
+ type: 'string', title: 'Figma personal access token', 'x-group': GROUP,
+ description: 'A Figma personal access token with read access to the files Design imports. It lets a person bring a Figma design into Design; without it the Figma import stays hidden.',
+ 'x-owner-input': {
+ group: 'design-publishing',
+ unlocks: 'Figma files can be imported into Design and their components and tokens read.',
+ get_it_at: 'https://www.figma.com/settings',
+ get_it_how: 'Open Settings, Security, Personal access tokens, create a token with read access to the files, then paste it here.',
+ test: true,
+ },
+ 'x-required-for': 'Figma import',
+ },
+ },
+});
+
+const SECRETS = new Set(['figma_token']);
+const ACTIVE = { settings: null };
+
+function createSettings({ db, env = process.env, log = console, fetchImpl = globalThis.fetch, probes = null } = {}) {
+ let store = null;
+ const ready = createConfigStore({
+ db, service: SERVICE, namespace: NAMESPACE, schema: SCHEMA,
+ classify: (key) => (SECRETS.has(key) ? 'secret' : 'internal'),
+ env, log,
+ }).then((s) => { store = s; return s; });
+
+ const values = () => (store ? store.get() : {});
+
+ function valueOf(key, envName, fallback = '') {
+ const v = values()[key];
+ if (v !== undefined && v !== null && v !== '') return v;
+ const e = envName ? env[envName] : undefined;
+ return e !== undefined && e !== null && e !== '' ? e : fallback;
+ }
+
+ /** The Figma token, read when a Figma import is made. */
+ function figmaToken() { return valueOf('figma_token', 'FIGMA_TOKEN', ''); }
+
+ async function test(key) {
+ if (key !== 'figma_token') return { ok: false, detail: 'That setting has no test.' };
+ const token = figmaToken();
+ if (!token) return { ok: false, detail: 'Figma is not configured: paste the personal access token first.' };
+ const probe = probes && typeof probes.figma === 'function'
+ ? probes.figma
+ : async ({ token: value }) => {
+ const r = await fetchImpl('https://api.figma.com/v1/me', { headers: { accept: 'application/json', 'x-figma-token': value } });
+ let body = {};
+ try { body = await r.json(); } catch { /* not JSON */ }
+ if (!r.ok) throw new Error(`HTTP ${r.status}${body && body.message ? `: ${body.message}` : ''}`);
+ };
+ try {
+ await probe({ token });
+ return { ok: true, detail: 'ok — Figma answered the account read with this token.' };
+ } catch (err) {
+ const words = String((err && err.message) || 'the request failed').split(/\s+/).join(' ').slice(0, 160);
+ return { ok: false, detail: `failed — Figma said: ${words.split(token).join('[redacted]')}` };
+ }
+ }
+
+ function mount(app, { guard, log: appLog = log } = {}) {
+ if (!store) throw new Error('createSettings: await ready before mount()');
+ const routes = adminRoutes([store], {
+ basePath: BASE_PATH,
+ requireAdmin: guard,
+ actor: (req) => {
+ const id = String(req.get('x-ov-subject') || '').trim();
+ return /^usr_[0-9A-HJKMNP-TV-Z]{26}$/.test(id) ? { type: 'user', id } : null;
+ },
+ requireFresh: (req) => String(req.get('x-ov-fresh') || '') === '1',
+ log: appLog,
+ });
+ app.use(routes.handle);
+ app.post(`${BASE_PATH}/:namespace/test/:key`, guard, async (req, res) => {
+ if (req.params.namespace !== NAMESPACE) return res.status(404).json({ error: 'no such configuration namespace' });
+ let key = String(req.params.key || '');
+ try { key = decodeURIComponent(key); } catch { /* keep it as it is */ }
+ if (!SCHEMA.properties[key]) return res.status(404).json({ error: 'no such setting' });
+ try {
+ const out = await test(key);
+ return res.status(200).json({ ok: Boolean(out.ok), detail: String(out.detail).replace(/\s+/g, ' ').slice(0, 200) });
+ } catch (err) {
+ appLog.warn(`[config] ${NAMESPACE}: the test for ${key} failed: ${String((err && err.message) || err).slice(0, 160)}`);
+ return res.status(200).json({ ok: false, detail: 'failed — the test did not finish. The service log has the reason.' });
+ }
+ });
+ return routes;
+ }
+
+ return { namespace: NAMESPACE, schema: SCHEMA, ready, value: valueOf, get: values, figmaToken, test, mount };
+}
+
+function activate(settings) { ACTIVE.settings = settings; return settings; }
+function figmaToken() {
+ if (ACTIVE.settings) return ACTIVE.settings.figmaToken();
+ return process.env.FIGMA_TOKEN || '';
+}
+
+module.exports = { SERVICE, NAMESPACE, SCHEMA, SECRETS, createSettings, activate, figmaToken };
@@ -15,6 +15,7 @@ const { testDb } = require('./helpers/db');
@@ -15,6 +15,7 @@ const { testDb } = require('./helpers/db');
tables: TABLES,
tables: TABLES,
taskKeyed: ['design_versions'], // versions belong to the design and cascade with it
taskKeyed: ['design_versions'], // versions belong to the design and cascade with it
exempt: {
exempt: {
+ config_snapshots: 'D11 owner settings: created_by/activated_by is the acting administrator (usr_...) for the config audit trail; the values are network configuration, not the person\'s account data, and are kept for rollback/history',
account_data_events: 'the ledger of requests itself: which export and deletion design applied',
account_data_events: 'the ledger of requests itself: which export and deletion design applied',
design_index_revisions: 'the Search index sequencer: owner is the service (design), the rows are icon and theme pages, never a person',
design_index_revisions: 'the Search index sequencer: owner is the service (design), the rows are icon and theme pages, never a person',
share_members: 'who a design is shared with: exported as shared_with_me.json, and erased by extraErase',
share_members: 'who a design is shared with: exported as shared_with_me.json, and erased by extraErase',
new file mode 100644
new file mode 100644
@@ -0,0 +1,93 @@
@@ -0,0 +1,93 @@
+'use strict';
+/**
+ * Owner settings (D11) for Design's publishing accounts (server/settings.js, design.publishing):
+ * - the Figma token has a plain title, a 30+ character description, x-owner-input words and a test;
+ * - /internal/config is loopback only and needs design.config.manage;
+ * - the token is write-only and marked in summaries, figmaToken() reads the owner's value and
+ * falls back to FIGMA_TOKEN, and the test hook never echoes or logs the token.
+ * node test/owner-settings.test.js
+ */
+const assert = require('assert');
+const http = require('http');
+const express = require('express');
+const { serviceAuth } = require('openvibe-contracts');
+const { boot } = require('./helpers/boot');
+const { createSettings } = require('../server/settings');
+
+const CAP = 'design.config.manage';
+const NS = 'design.publishing';
+const USR = 'usr_01J8Z3Q4R5S6T7V8W9X0Y1Z2A3';
+const TOKEN = 'figma-owner-token-sentinel';
+
+(async () => {
+ const t = await boot();
+ const now = Math.floor(Date.now() / 1000);
+ const bearer = serviceAuth.signServiceToken({ iss: t.network.url, sub: 'svc:network', actor_type: 'service', aud: ['openvibe.design'], cap: [CAP], iat: now, exp: now + 300, jti: 'tok_owner_settings' }, t.network.privatePem);
+ const checks = [];
+ const check = async (name, fn) => {
+ try { await fn(); checks.push(name); console.log(` ✓ ${name}`); } catch (e) { console.log(` ✗ ${name}\n${e.stack}`); await t.close(); process.exit(1); }
+ };
+
+ await check('the Figma token has owner words and a test', async () => {
+ const r = await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${bearer}` } });
+ assert.strictEqual(r.status, 200, r.text);
+ const f = r.json().schema.properties.figma_token;
+ assert.ok(f);
+ assert.ok(f.title && f.title.length >= 3);
+ assert.ok(f.description && f.description.length >= 30);
+ assert.strictEqual(f['x-owner-input'].group, 'design-publishing');
+ assert.ok(f['x-owner-input'].unlocks.length > 20);
+ assert.strictEqual(f['x-owner-input'].get_it_at, 'https://www.figma.com/settings');
+ assert.strictEqual(f['x-owner-input'].test, true);
+ assert.strictEqual(f['x-required-for'], 'Figma import');
+ });
+
+ await check('the routes are loopback only and need the capability', async () => {
+ assert.strictEqual((await t.get(`/internal/config/${NS}`)).status, 401);
+ const wrong = serviceAuth.signServiceToken({ iss: t.network.url, sub: 'svc:network', actor_type: 'service', aud: ['openvibe.design'], cap: ['design.read'], iat: now, exp: now + 300, jti: 'tok_wrong' }, t.network.privatePem);
+ assert.strictEqual((await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${wrong}` } })).status, 403);
+ assert.strictEqual((await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${bearer}`, 'x-forwarded-for': '203.0.113.9' } })).status, 404);
+ });
+
+ await check('the token is write-only and the environment is the fallback', async () => {
+ const envOnly = createSettings({ db: t.ctx.s.db, env: { FIGMA_TOKEN: 'figma-env-token' } });
+ await envOnly.ready;
+ assert.strictEqual(envOnly.figmaToken(), 'figma-env-token', 'the env is the fallback');
+ const put = await t.get(`/internal/config/${NS}/secrets/figma_token`, {
+ method: 'PUT', json: { value: TOKEN, reason: 'owner test' },
+ headers: { authorization: `Bearer ${bearer}`, 'x-ov-subject': USR, 'x-ov-fresh': '1' },
+ });
+ assert.strictEqual(put.status, 200, put.text);
+ assert.ok(put.json().fingerprint && put.json().hint);
+ assert.ok(!put.text.includes(TOKEN));
+ const summary = await t.get(`/internal/config/${NS}`, { headers: { authorization: `Bearer ${bearer}` } });
+ assert.ok(summary.json().values.figma_token.redacted);
+ assert.ok(!summary.text.includes(TOKEN));
+ assert.strictEqual(t.ctx.settings.figmaToken(), TOKEN, 'the code reads the owner value when set');
+ });
+
+ await check('the test hook says ok/failed in one line and never echoes a token', async () => {
+ const fake = createSettings({
+ db: t.ctx.s.db, env: {},
+ probes: { figma: async ({ token }) => { throw new Error(`refused ${token}`); } },
+ });
+ await fake.ready;
+ const app = express();
+ app.use(express.json());
+ fake.mount(app, { guard: (_req, _res, next) => next(), log: console });
+ const server = await new Promise((resolve) => { const s = http.createServer(app); s.listen(0, '127.0.0.1', () => resolve(s)); });
+ try {
+ const r = await fetch(`http://127.0.0.1:${server.address().port}/internal/config/${NS}/test/figma_token`, { method: 'POST' });
+ const body = await r.json();
+ assert.strictEqual(r.status, 200);
+ assert.strictEqual(body.ok, false);
+ assert.ok(/^failed — Figma said: /.test(body.detail), body.detail);
+ assert.ok(!body.detail.includes(TOKEN));
+ assert.ok(!body.detail.includes('\n'));
+ } finally { server.close(); }
+ assert.ok(!t.logs().includes(TOKEN), 'no token in a captured log line');
+ });
+
+ await t.close();
+ console.log(`\n${checks.length} checks passed`);
+})().catch((e) => { console.error(e); process.exit(1); });