Elffuss BraidHub

kikocis/clonagent public

main · 7.7 KiBRawPermalink
1// Pluggable authentication for ClonAgent.
2// Modes (configurable from /api/settings → Settings UI):
3// - 'none' : open (dev / local)
4// - 'basic' : username + password against the multi-user store (data/users.json)
5// - 'oidc' : OpenID Connect (Keycloak, Google, Auth0, etc.)
6const { Issuer, generators } = require('openid-client');
7const crypto = require('crypto');
8const settings = require('../routes/settings');
9const users = require('./users');
10const mailer = require('./mailer');
11const magicAuth = require('./magic-auth');
12
13let oidcClient;
14let oidcReady = false;
15
16async function getOidcClient() {
17 const s = settings.read().auth?.oidc;
18 if (!s?.issuerUrl || !s?.clientId) throw new Error('OIDC not configured');
19 if (oidcClient && oidcReady && oidcClient.metadata.client_id === s.clientId) return oidcClient;
20 const issuer = await Issuer.discover(s.issuerUrl);
21 oidcClient = new issuer.Client({
22 client_id: s.clientId,
23 client_secret: s.clientSecret,
24 redirect_uris: [s.redirectUri],
25 response_types: ['code'],
26 });
27 oidcReady = true;
28 return oidcClient;
29}
30
31function resetOidc() { oidcReady = false; oidcClient = undefined; }
32
33const PUBLIC_PATHS = [
34 /^\/api\/health$/,
35 /^\/api\/auth\/(login|logout|whoami|register|oidc\/(start|callback)|forgot-password|reset-password|magic\/(send|verify))$/,
36 /^\/api\/billing\/(plans|webhook)$/,
37 /^\/api\/activity\/sessions(\/.*)?$/,
38 /^\/api\/threads\/[^/]+\/events$/,
39 /^\/api\/tasks\/[^/]+\/events$/,
40];
41
42function requireAuth(req, res, next) {
43 const mode = settings.read().auth?.mode || 'none';
44 if (mode === 'none') return next();
45 if (!req.path.startsWith('/api/')) return next();
46 if (PUBLIC_PATHS.some(re => re.test(req.path))) return next();
47 if (req.session?.user) return next();
48 return res.status(401).json({ error: 'authentication required', mode });
49}
50
51async function loginBasic(req, res) {
52 const { username, password } = req.body || {};
53 if (!username || !password) return res.status(400).json({ error: 'username and password required' });
54 const u = await users.verifyPassword(username, password);
55 if (!u) return res.status(401).json({ error: 'invalid credentials' });
56 req.session.user = { sub: u.username, name: u.name, email: u.email, mode: 'basic', isAdmin: u.isAdmin };
57 res.json({ ok: true, user: req.session.user });
58}
59
60async function register(req, res) {
61 const auth = settings.read().auth || {};
62 if (!auth.allowRegistration) return res.status(403).json({ error: 'registration is disabled' });
63 const { username, password, name, email } = req.body || {};
64 try {
65 const isAdmin = users.userCount() === 0;
66 const created = await users.createUser({ username, password, name, email, isAdmin });
67 req.session.user = { sub: created.username, name: created.name, email: created.email, mode: 'basic', isAdmin: created.isAdmin };
68 if (email) mailer.sendWelcome({ to: email, name: name || username }).catch(() => {});
69 res.json({ ok: true, user: req.session.user });
70 } catch (e) {
71 res.status(400).json({ error: e.message });
72 }
73}
74
75async function forgotPassword(req, res) {
76 const { email } = req.body || {};
77 if (!email) return res.status(400).json({ error: 'email required' });
78 const all = require('./users').findUserByEmail(email);
79 if (!all) return res.json({ ok: true }); // don't reveal if email exists
80 const token = crypto.randomBytes(32).toString('hex');
81 require('./users').setResetToken(all.username, token);
82 await mailer.sendPasswordReset({ to: email, name: all.name, token }).catch(() => {});
83 res.json({ ok: true });
84}
85
86async function resetPassword(req, res) {
87 const { token, password } = req.body || {};
88 if (!token || !password) return res.status(400).json({ error: 'token and password required' });
89 const u = require('./users').findUserByResetToken(token);
90 if (!u) return res.status(400).json({ error: 'invalid or expired token' });
91 await require('./users').changePassword(u.username, password);
92 require('./users').clearResetToken(u.username);
93 res.json({ ok: true });
94}
95
96async function oidcStart(req, res) {
97 try {
98 const client = await getOidcClient();
99 const codeVerifier = generators.codeVerifier();
100 const state = generators.state();
101 req.session.oidc = { codeVerifier, state };
102 const url = client.authorizationUrl({
103 scope: 'openid email profile',
104 code_challenge: generators.codeChallenge(codeVerifier),
105 code_challenge_method: 'S256',
106 state,
107 });
108 res.redirect(url);
109 } catch (e) {
110 res.status(500).json({ error: e.message });
111 }
112}
113
114async function oidcCallback(req, res) {
115 try {
116 const client = await getOidcClient();
117 const params = client.callbackParams(req);
118 const { codeVerifier, state } = req.session.oidc || {};
119 const tokenSet = await client.callback(
120 settings.read().auth.oidc.redirectUri,
121 params,
122 { code_verifier: codeVerifier, state },
123 );
124 const claims = tokenSet.claims();
125 req.session.user = {
126 sub: claims.sub,
127 name: claims.name || claims.preferred_username || claims.email,
128 email: claims.email,
129 mode: 'oidc',
130 isAdmin: false,
131 };
132 delete req.session.oidc;
133 res.redirect('/');
134 } catch (e) {
135 res.status(500).send(`OIDC callback error: ${e.message}`);
136 }
137}
138
139function logout(req, res) {
140 req.session.destroy(() => res.json({ ok: true }));
141}
142
143function whoami(req, res) {
144 const s = settings.read().auth || {};
145 const mode = s.mode || 'none';
146 res.json({
147 mode,
148 allowRegistration: !!s.allowRegistration || users.userCount() === 0,
149 user: req.session?.user || null,
150 });
151}
152
153async function magicSend(req, res) {
154 const { email } = req.body || {};
155 if (!email || !email.includes('@')) return res.status(400).json({ error: 'valid email required' });
156
157 // Create account if it doesn't exist yet
158 let u = users.findUserByEmail(email);
159 if (!u) {
160 const username = email.split('@')[0].toLowerCase().replace(/[^a-z0-9._-]/g, '') + '_' + Date.now().toString(36);
161 const tempPw = crypto.randomBytes(16).toString('hex');
162 const isAdmin = users.userCount() === 0;
163 u = await users.createUser({ username, password: tempPw, email, name: email.split('@')[0], isAdmin });
164 }
165
166 const token = magicAuth.createToken(email);
167 const link = `${process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com'}/api/auth/magic/verify?token=${token}`;
168
169 await mailer.send({
170 to: email,
171 subject: 'Your ClonAgent sign-in link',
172 html: `
173 <div style="font-family:sans-serif;max-width:480px;margin:auto;color:#e2e8f0;background:#0f1117;padding:32px;border-radius:12px">
174 <h1 style="color:#a78bfa;margin:0 0 8px">Sign in to ClonAgent</h1>
175 <p style="margin:0 0 20px;color:#94a3b8">Click the button below — this link expires in 15 minutes.</p>
176 <a href="${link}" style="display:inline-block;background:#7c5cff;color:#fff;padding:12px 24px;border-radius:8px;text-decoration:none;font-weight:600">
177 Sign in →
178 </a>
179 <p style="color:#475569;font-size:12px;margin-top:24px">If you didn't request this, ignore this email.</p>
180 </div>`,
181 }).catch(() => {});
182
183 res.json({ ok: true });
184}
185
186async function magicVerify(req, res) {
187 const { token } = req.query;
188 if (!token) return res.redirect('/?error=missing-token');
189
190 const email = magicAuth.consumeToken(token);
191 if (!email) return res.redirect('/?error=expired');
192
193 const u = users.findUserByEmail(email);
194 if (!u) return res.redirect('/?error=user-not-found');
195
196 req.session.user = { sub: u.username, name: u.name, email: u.email, mode: 'basic', isAdmin: u.isAdmin };
197 res.redirect('/chat');
198}
199
200module.exports = {
201 requireAuth, loginBasic, register, forgotPassword, resetPassword,
202 magicSend, magicVerify,
203 oidcStart, oidcCallback, logout, whoami, resetOidc,
204};