feat: external session API + magic login (merge from open-refboard 02750ba)
Publish container image / build-and-push (push) Canceled after 0s

- POST /api/external/session: bridge auth via X-API-Key, JIT user provisioning
- GET /api/external/health: capability report
- /magic frontend route: consumes ?token= JWT, redirects
- docs/EXTERNAL-API.md: bridge contract spec
This commit is contained in:
Hermes committed 2026-10-14 10:13:54 +00:00
1 parent 4cda9c8c0a
commit 0504df49b0
7 files changed
+428 -43

No files matched your search

+40 -39
View File
@@ -9,15 +9,15 @@
"version": "1.0.0",
"dependencies": {
"bcryptjs": "^2.4.3",
"better-sqlite3": "^11.7.0",
"better-sqlite3": "^11.10.0",
"cors": "^2.8.5",
"express": "^4.21.1",
"jsonwebtoken": "^9.0.2",
"express": "^4.22.3",
"jsonwebtoken": "^9.0.3",
"minio": "^8.0.2",
"multer": "^1.4.5-lts.1",
"sharp": "^0.33.2",
"socket.io": "^4.8.1",
"uuid": "^11.0.3"
"uuid": "^11.1.1"
}
},
"node_modules/@emnapi/runtime": {
@@ -522,9 +522,9 @@
}
},
"node_modules/body-parser": {
"version": "1.20.4",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz",
"integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==",
"version": "1.20.8",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz",
"integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
@@ -535,7 +535,7 @@
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.14.0",
"qs": "~6.16.0",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
@@ -984,9 +984,9 @@
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
@@ -1026,14 +1026,14 @@
}
},
"node_modules/express": {
"version": "4.22.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",
"integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
"version": "4.22.3",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz",
"integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "~1.20.3",
"body-parser": "~1.20.5",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
@@ -1050,9 +1050,9 @@
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"path-to-regexp": "~0.1.13",
"proxy-addr": "~2.0.7",
"qs": "~6.14.0",
"qs": "~6.16.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
@@ -1236,9 +1236,9 @@
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
@@ -1665,9 +1665,9 @@
}
},
"node_modules/path-to-regexp": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
"integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==",
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
"license": "MIT"
},
"node_modules/prebuild-install": {
@@ -1736,12 +1736,13 @@
}
},
"node_modules/qs": {
"version": "6.14.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz",
"integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==",
"version": "6.16.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
"integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
@@ -1959,14 +1960,14 @@
}
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3",
"side-channel-list": "^1.0.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
@@ -1978,13 +1979,13 @@
}
},
"node_modules/side-channel-list": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3"
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
@@ -2389,9 +2390,9 @@
}
},
"node_modules/uuid": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz",
"integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
+4 -4
View File
@@ -8,14 +8,14 @@
},
"dependencies": {
"bcryptjs": "^2.4.3",
"better-sqlite3": "^11.7.0",
"better-sqlite3": "^11.10.0",
"cors": "^2.8.5",
"express": "^4.21.1",
"jsonwebtoken": "^9.0.2",
"express": "^4.22.3",
"jsonwebtoken": "^9.0.3",
"minio": "^8.0.2",
"multer": "^1.4.5-lts.1",
"sharp": "^0.33.2",
"socket.io": "^4.8.1",
"uuid": "^11.0.3"
"uuid": "^11.1.1"
}
}
+204
View File
@@ -0,0 +1,204 @@
/**
* Open RefBoard — External Session API
*
* Generic integration endpoint for external systems ("bridges": AYON,
* Nextcloud, scripts, ...). A bridge authenticates with the shared
* REFBOARD_API_KEY (X-API-Key header), identifies a user, and receives
* a JWT it can embed in a magic-login URL.
*
* Contract:
* POST /api/external/session
* Headers: X-API-Key: <REFBOARD_API_KEY>
* Body: { user_name: string (required, source of username+display_name),
* user_email?: string (defaults to <user_name>@bridges.local),
* board_id?: string (board to land on; or board_name+collection_id / collection_name)
* role?: 'member' | 'admin' for NEW users (default 'member') }
* Returns: { user: {...}, token, expires_in, board?: {id, name, url} }
*
* Auto-provisioning: users are created on first use (user_name is mandatory),
* matching existing users by username. Provisioned accounts get a random
* unusable password — they can only log in via bridge sessions or admin
* password reset.
*/
const { Router } = require('express');
const { v4: uuidv4 } = require('uuid');
const crypto = require('crypto');
const { apiKeyMiddleware } = require('../auth');
const {
getUserByUsername,
getUserByEmail,
getUserById,
createUser,
getBoard,
getCollection,
getCollectionMember,
addCollectionMember,
createCollection,
createBoard,
} = require('../db');
const { generateToken } = require('../auth');
const router = Router();
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';
const BRIDGE_EMAIL_DOMAIN = process.env.EXTERNAL_BRIDGE_EMAIL_DOMAIN || 'bridges.local';
function expiresInSeconds() {
// Mirror common jwt lib shorthand strings we care about; default 7d.
const m = /^(\d+)([smhdwy])$/.exec(JWT_EXPIRES_IN.trim());
if (!m) return 7 * 24 * 3600;
const mult = { s: 1, m: 60, h: 3600, d: 86400, w: 604800, y: 31536000 };
return parseInt(m[1], 10) * (mult[m[2]] || 1);
}
function boardUrl(req, board) {
const proto = req.headers['x-forwarded-proto'] || req.protocol || 'http';
const host = req.headers['x-forwarded-host'] || req.headers.host || '';
const base = process.env.PUBLIC_URL || `${proto}://${host}`;
return `${base}/board/${board.id}`;
}
function sanitizeUsername(raw) {
let name = String(raw).trim().toLowerCase().replace(/[^a-z0-9_-]/g, '-');
if (!name) name = 'bridge-user';
return name.slice(0, 40);
}
router.use(apiKeyMiddleware);
/**
* POST /api/external/session
* Ensure user exists (auto-provision) and mint a login JWT.
*/
router.post('/session', async (req, res) => {
try {
const { user_name, user_email, board_id, board_name, collection_id, collection_name, role } = req.body || {};
if (!user_name || typeof user_name !== 'string') {
return res.status(400).json({ error: 'user_name is required' });
}
const username = sanitizeUsername(user_name);
// --- resolve or provision user ---
let user = getUserByUsername(username);
if (!user) {
const email = (user_email && typeof user_email === 'string' && user_email.includes('@'))
? user_email.trim().toLowerCase()
: `${username}@${BRIDGE_EMAIL_DOMAIN}`;
if (getUserByEmail(email)) {
return res.status(409).json({
error: `Email conflict: ${email} already registered but username "${username}" does not match a user`,
});
}
// Random unusable password — provisioned users authenticate via bridges only
const randomPassword = crypto.randomBytes(24).toString('hex');
const bcrypt = require('bcryptjs');
const passwordHash = await bcrypt.hash(randomPassword, 12);
user = createUser({
id: uuidv4(),
email,
username,
passwordHash,
displayName: String(user_name).trim().slice(0, 80),
role: role === 'admin' ? 'admin' : 'member',
});
console.log(`[external] provisioned user: ${username} (${email})`);
} else if (!user.is_active) {
return res.status(403).json({ error: `User ${username} is deactivated` });
}
// --- resolve or create target board (optional) ---
let board = null;
if (board_id) {
board = getBoard(board_id);
if (!board) return res.status(404).json({ error: 'Board not found' });
}
if (!board && (collection_id || collection_name)) {
let collection = collection_id
? getCollection(collection_id)
: require('../db').db
.prepare('SELECT * FROM collections WHERE name = ? ORDER BY created_at LIMIT 1')
.get(String(collection_name).trim());
if (!collection) {
if (collection_id) return res.status(404).json({ error: 'Collection not found' });
// create-on-demand for collection_name
collection = createCollection({
id: uuidv4(),
name: String(collection_name).trim(),
description: `Created via external bridge (${req.headers['x-bridge'] || 'unknown'})`,
createdBy: user.id,
});
addCollectionMember(collection.id, user.id, 'owner');
}
if (!getCollectionMember(collection.id, user.id)) {
addCollectionMember(collection.id, user.id, 'editor');
}
const boardName = board_name ? String(board_name).trim() : 'Main';
const existing = require('../db').db
.prepare('SELECT * FROM boards WHERE collection_id = ? AND name = ? ORDER BY created_at LIMIT 1')
.get(collection.id, boardName);
board = existing || createBoard({
id: uuidv4(),
collectionId: collection.id,
name: boardName,
description: '',
createdBy: user.id,
});
}
const token = generateToken({
id: user.id,
email: user.email,
role: user.role,
username: user.username,
display_name: user.display_name,
});
return res.json({
user: {
id: user.id,
username: user.username,
display_name: user.display_name,
email: user.email,
role: user.role,
},
token,
token_type: 'Bearer',
expires_in: expiresInSeconds(),
board: board ? { id: board.id, name: board.name, collection_id: board.collection_id, url: boardUrl(req, board) } : null,
});
} catch (err) {
console.error('[external] session error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
});
/**
* GET /api/external/health
* Bridge-facing liveness + capability report.
*/
router.get('/health', (_req, res) => {
try {
const { getUserCount } = require('../db');
return res.json({
status: 'ok',
service: 'refboard',
open_refboard: true,
api_version: 1,
users: getUserCount(),
});
} catch (err) {
console.error('[external] health error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;
+2
View File
@@ -99,6 +99,7 @@ const collectionRoutes = require('./routes/collections');
const boardRoutes = require('./routes/boards');
const uploadRoutes = require('./routes/upload');
const adminRoutes = require('./routes/admin');
const externalRoutes = require('./routes/external');
const threadRoutes = require('./routes/threads');
const pdfRoutes = require('./routes/pdf');
const activityRoutes = require('./routes/activity');
@@ -108,6 +109,7 @@ app.use('/api/collections', collectionRoutes);
app.use('/api/boards', boardRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/external', externalRoutes);
app.use('/api/boards', threadRoutes);
app.use('/api/boards', pdfRoutes);
app.use('/api/boards', activityRoutes);