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

+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;