blob: 2f5f8379227c57cbea790af95a8dabec5fe29678 [file] [log] [blame]
simon26e79f72022-10-05 22:16:08 -04001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
simond47ef9e2022-09-28 22:24:28 -040018'use strict';
Larbi Gharibe9af9732021-03-31 15:08:01 +010019
simon7e00d612022-10-01 20:06:53 -040020import dotenv from 'dotenv';
simon6c2a63d2022-10-11 13:51:29 -040021const nodeEnv = process.env.NODE_ENV || 'development';
22dotenv.config({ path: `.env.${nodeEnv}` });
simon7e00d612022-10-01 20:06:53 -040023
simon07b4eb02022-09-29 17:50:26 -040024import cors from 'cors';
25import express, { NextFunction, Request, Response } from 'express';
26import session from 'express-session';
simond47ef9e2022-09-28 22:24:28 -040027import { promises as fs } from 'fs';
28import http from 'http';
simon20076982022-10-11 15:04:13 -040029import { Account } from 'jami-web-common';
simond47ef9e2022-09-28 22:24:28 -040030import passport from 'passport';
simon06527b02022-10-01 15:01:47 -040031import { IVerifyOptions, Strategy as LocalStrategy } from 'passport-local';
simon07b4eb02022-09-29 17:50:26 -040032import path from 'path';
33import { Server, Socket } from 'socket.io';
34import { ExtendedError } from 'socket.io/dist/namespace';
35
simon06527b02022-10-01 15:01:47 -040036import JamiDaemon from './JamiDaemon';
Adrien Béraude74741b2021-04-19 13:22:54 -040037//import { createRequire } from 'module';
38//const require = createRequire(import.meta.url);
Adrien Béraud947e8792021-04-15 18:32:44 -040039//const redis = require('redis-url').connect()
40//const RedisStore = require('connect-redis')(session)
Adrien Béraud6ecaa402021-04-06 17:37:25 -040041/*const passportSocketIo = require('passport.socketio')*/
simond47ef9e2022-09-28 22:24:28 -040042import indexRouter from './routes/index.js';
simond47ef9e2022-09-28 22:24:28 -040043import JamiRestApi from './routes/jami.js';
idillon8e6c0062022-09-16 13:34:43 -040044// import { sentrySetUp } from './sentry.js'
Adrien Béraude74741b2021-04-19 13:22:54 -040045
simond47ef9e2022-09-28 22:24:28 -040046const configPath = 'jamiServerConfig.json';
Larbi Gharibe9af9732021-03-31 15:08:01 +010047
Adrien Béraud6ecaa402021-04-06 17:37:25 -040048//const sessionStore = new RedisStore({ client: redis })
simond47ef9e2022-09-28 22:24:28 -040049const sessionStore = new session.MemoryStore();
Larbi Gharibe9af9732021-03-31 15:08:01 +010050
simon06527b02022-10-01 15:01:47 -040051interface User {
52 id: string;
53 config: UserConfig;
54 username: string;
55 accountFilter?: (account: any) => boolean;
56}
57
simon7a7b4d52022-09-23 02:09:42 -040058interface UserConfig {
simon06527b02022-10-01 15:01:47 -040059 accountId?: string;
simon7a7b4d52022-09-23 02:09:42 -040060 accounts: string;
61 password?: string;
62 username?: string;
simond47ef9e2022-09-28 22:24:28 -040063 type?: string;
simon7a7b4d52022-09-23 02:09:42 -040064}
65
66interface AppConfig {
simond47ef9e2022-09-28 22:24:28 -040067 users: Record<string, UserConfig>;
simon06527b02022-10-01 15:01:47 -040068 authMethods: unknown[];
simon7a7b4d52022-09-23 02:09:42 -040069}
70
71const loadConfig = async (filePath: string): Promise<AppConfig> => {
simond47ef9e2022-09-28 22:24:28 -040072 const config = { users: {}, authMethods: [] };
73 try {
74 return Object.assign(config, JSON.parse((await fs.readFile(filePath)).toString()));
75 } catch (e) {
76 console.log(e);
77 return config;
78 }
79};
Adrien Béraud824a7132021-04-17 17:25:27 -040080
simon7a7b4d52022-09-23 02:09:42 -040081const saveConfig = (filePath: string, config: AppConfig) => {
simond47ef9e2022-09-28 22:24:28 -040082 return fs.writeFile(filePath, JSON.stringify(config));
83};
Adrien Béraude74741b2021-04-19 13:22:54 -040084
Larbi Gharibe9af9732021-03-31 15:08:01 +010085/*
Adrien Béraud3b5d9a62021-04-17 18:40:27 -040086Share sessions between Passport.js and Socket.io
Larbi Gharibe9af9732021-03-31 15:08:01 +010087*/
88
89function logSuccess() {
simond47ef9e2022-09-28 22:24:28 -040090 console.log('passportSocketIo authorized user with Success 😁');
Larbi Gharibe9af9732021-03-31 15:08:01 +010091}
92
93function logFail() {
simond47ef9e2022-09-28 22:24:28 -040094 console.log('passportSocketIo failed to authorized user 👺');
Larbi Gharibe9af9732021-03-31 15:08:01 +010095}
96
97/*
Larbi Gharibe9af9732021-03-31 15:08:01 +010098
Adrien Béraud3b5d9a62021-04-17 18:40:27 -040099tempAccounts holds users accounts while tempting to authenticate them on Jams.
100connectedUsers holds users accounts after they got authenticated by Jams.
Larbi Gharibe9af9732021-03-31 15:08:01 +0100101
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400102Users should be removed from connectedUsers when receiving a disconnect
103web socket call
Larbi Gharibe9af9732021-03-31 15:08:01 +0100104
105*/
simon06527b02022-10-01 15:01:47 -0400106const tempAccounts: Record<
107 string,
108 {
109 newUser: Express.User;
110 done: (error: any, user?: any, options?: IVerifyOptions) => void;
111 }
112> = {};
113const connectedUsers: Record<string, UserConfig> = {};
Larbi Gharibe9af9732021-03-31 15:08:01 +0100114
simon7a7b4d52022-09-23 02:09:42 -0400115const createServer = async (appConfig: AppConfig) => {
simond47ef9e2022-09-28 22:24:28 -0400116 const app = express();
simon6c2a63d2022-10-11 13:51:29 -0400117 console.log(`Loading server for ${nodeEnv} with config:`);
simond47ef9e2022-09-28 22:24:28 -0400118 console.log(appConfig);
Larbi Gharibe9af9732021-03-31 15:08:01 +0100119
simond47ef9e2022-09-28 22:24:28 -0400120 const corsOptions = {
121 origin: 'http://127.0.0.1:3000',
122 };
Adrien Béraud4e287b92021-04-24 16:15:56 -0400123
simon6c2a63d2022-10-11 13:51:29 -0400124 if (nodeEnv === 'development') {
simond47ef9e2022-09-28 22:24:28 -0400125 const webpack = await import('webpack');
126 const webpackDev = await import('webpack-dev-middleware');
127 const webpackHot = await import('webpack-hot-middleware');
128 const { default: webpackConfig } = await import('jami-web-client/webpack.config.js');
simonc7d52452022-09-23 02:09:42 -0400129
simond47ef9e2022-09-28 22:24:28 -0400130 const compiler = webpack.default(webpackConfig);
131 app.use(
132 webpackDev.default(compiler, {
133 publicPath: webpackConfig.output?.publicPath,
134 })
135 );
136 app.use(webpackHot.default(compiler));
137 }
Larbi Gharibe9af9732021-03-31 15:08:01 +0100138
simond47ef9e2022-09-28 22:24:28 -0400139 /*
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400140 Configuation for Passeport Js
141 */
simond47ef9e2022-09-28 22:24:28 -0400142 app.disable('x-powered-by');
Adrien Béraud6ecaa402021-04-06 17:37:25 -0400143
simon6c2a63d2022-10-11 13:51:29 -0400144 const secretKey = process.env.SECRET_KEY_BASE;
simon7a7b4d52022-09-23 02:09:42 -0400145
simon6c2a63d2022-10-11 13:51:29 -0400146 if (!secretKey) {
simond47ef9e2022-09-28 22:24:28 -0400147 throw new Error('SECRET_KEY_BASE undefined');
148 }
149
150 const sessionMiddleware = session({
151 store: sessionStore,
152 resave: false,
153 saveUninitialized: true,
154 cookie: {
155 secure: false, //!development,
156 maxAge: 2419200000,
157 },
simon6c2a63d2022-10-11 13:51:29 -0400158 secret: secretKey,
simond47ef9e2022-09-28 22:24:28 -0400159 });
160
161 app.use(sessionMiddleware);
162 app.use(passport.initialize());
163 app.use(passport.session());
164 // app.use(app.router)
165 app.use(cors(corsOptions));
166
167 const jami = new JamiDaemon((account: Account, conversation: any, message: any) => {
168 console.log('JamiDaemon onMessage');
169
170 if (conversation.listeners) {
171 Object.values(conversation.listeners).forEach((listener: any) => {
172 listener.socket.emit('newMessage', message);
173 });
simon7a7b4d52022-09-23 02:09:42 -0400174 }
simond47ef9e2022-09-28 22:24:28 -0400175 });
176 const apiRouter = new JamiRestApi(jami).getRouter();
simon7a7b4d52022-09-23 02:09:42 -0400177
simond47ef9e2022-09-28 22:24:28 -0400178 /*
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400179 io.use(passportSocketIo.authorize({
180 key: 'connect.sid',
181 secret: process.env.SECRET_KEY_BASE,
182 store: sessionStore,
183 passport: passport,
184 cookieParser: cookieParser,
185 //success: logSuccess(),
186 // fail: logFail(),
Adrien Béraude74741b2021-04-19 13:22:54 -0400187 }))
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400188 */
Adrien Béraud6ecaa402021-04-06 17:37:25 -0400189
simond47ef9e2022-09-28 22:24:28 -0400190 const isSetupComplete = () => {
191 return 'admin' in appConfig.users;
192 };
193
simon06527b02022-10-01 15:01:47 -0400194 const accountFilter = (filter: string | string[]) => {
simond47ef9e2022-09-28 22:24:28 -0400195 if (typeof filter === 'string') {
196 if (filter === '*') return undefined;
197 else return (account: Account) => account.getId() === filter;
198 } else if (Array.isArray(filter)) {
199 return (account: Account) => filter.includes(account.getId());
200 } else {
201 throw new Error('Invalid account filter string');
Adrien Béraude74741b2021-04-19 13:22:54 -0400202 }
simond47ef9e2022-09-28 22:24:28 -0400203 };
Adrien Béraude74741b2021-04-19 13:22:54 -0400204
simond47ef9e2022-09-28 22:24:28 -0400205 const user = (id: string, config: UserConfig) => {
206 return {
207 id,
208 config,
209 username: config.username || id,
210 accountFilter: accountFilter(config.accounts),
211 };
212 };
213
214 passport.serializeUser((user: any, done) => {
simon06527b02022-10-01 15:01:47 -0400215 user = user as User;
simond47ef9e2022-09-28 22:24:28 -0400216 connectedUsers[user.id] = user.config;
217 console.log('=============================SerializeUser called ' + user.id);
218 console.log(user);
219 done(null, user.id);
220 });
221
222 const deserializeUser = (id: string, done: (err: any, user?: Express.User | false | null) => void) => {
223 console.log('=============================DeserializeUser called on: ' + id);
224 const userConfig = connectedUsers[id];
225 console.log(userConfig);
226 if (userConfig) {
227 done(null, user(id, userConfig));
228 } else done(404, null);
229 };
230 passport.deserializeUser(deserializeUser);
231
232 const jamsStrategy = new LocalStrategy(async (username, password, done) => {
233 const accountId = await jami.addAccount({
234 managerUri: 'https://jams.savoirfairelinux.com',
235 managerUsername: username,
236 archivePassword: password,
237 });
238 const id = `jams_${username}`;
239 const userConfig = { username, type: 'jams', accounts: accountId };
240 const newUser = user(id, userConfig);
241 console.log('AccountId: ' + accountId);
242 tempAccounts[accountId] = { done, newUser };
243 });
244 jamsStrategy.name = 'jams';
245
246 const localStrategy = new LocalStrategy((username, password, done) => {
247 console.log('localStrategy: ' + username + ' ' + password);
248
249 const id = username;
250 const userConfig = appConfig.users[username];
251 if (!userConfig) {
252 return done(null, false, { message: 'Incorrect username.' });
Adrien Béraude74741b2021-04-19 13:22:54 -0400253 }
simond47ef9e2022-09-28 22:24:28 -0400254 if (userConfig.password !== password) {
255 return done(null, false, { message: 'Incorrect password.' });
Adrien Béraude74741b2021-04-19 13:22:54 -0400256 }
simond47ef9e2022-09-28 22:24:28 -0400257 userConfig.type = 'local';
Adrien Béraude74741b2021-04-19 13:22:54 -0400258
simond47ef9e2022-09-28 22:24:28 -0400259 done(null, user(id, userConfig));
260 });
Adrien Béraud6ecaa402021-04-06 17:37:25 -0400261
simond47ef9e2022-09-28 22:24:28 -0400262 passport.use(jamsStrategy);
263 passport.use(localStrategy);
264
265 const secured = (req: Request, res: Response, next: NextFunction) => {
266 if (req.user) {
267 return next();
Adrien Béraude74741b2021-04-19 13:22:54 -0400268 }
simond47ef9e2022-09-28 22:24:28 -0400269 res.status(401).end();
270 };
271 const securedRedirect = (req: Request, res: Response, next: NextFunction) => {
simon06527b02022-10-01 15:01:47 -0400272 const user = req.user as UserConfig | undefined;
273 if (user?.accountId) {
simond47ef9e2022-09-28 22:24:28 -0400274 return next();
Adrien Béraude74741b2021-04-19 13:22:54 -0400275 }
simond47ef9e2022-09-28 22:24:28 -0400276 (req.session as any).returnTo = req.originalUrl;
277 res.redirect('/login');
278 };
279
280 app.use(express.json());
281 app.post('/setup', (req, res) => {
282 if (isSetupComplete()) {
283 return res.status(404).end();
Adrien Béraude74741b2021-04-19 13:22:54 -0400284 }
simond47ef9e2022-09-28 22:24:28 -0400285 if (!req.body.password) {
286 return res.status(400).end();
Adrien Béraude5cad982021-06-07 10:05:50 -0400287 }
simond47ef9e2022-09-28 22:24:28 -0400288 console.log(req.body);
289 appConfig.users.admin = {
290 accounts: '*',
291 password: req.body.password,
292 };
293 res.status(200).end();
294 saveConfig(configPath, appConfig);
295 });
296 app.post('/auth/jams', passport.authenticate('jams'), (req, res) => {
297 res.json({ loggedin: true });
298 });
299 app.post('/auth/local', passport.authenticate('local'), (req, res) => {
simon06527b02022-10-01 15:01:47 -0400300 res.json({ loggedin: true, user: (req.user as User | undefined)?.id });
simond47ef9e2022-09-28 22:24:28 -0400301 });
Adrien Béraude5cad982021-06-07 10:05:50 -0400302
simond47ef9e2022-09-28 22:24:28 -0400303 const getState = (req: Request) => {
304 if (req.user) {
simon06527b02022-10-01 15:01:47 -0400305 const user = req.user as UserConfig;
simond47ef9e2022-09-28 22:24:28 -0400306 return { loggedin: true, username: user.username, type: user.type };
307 } else if (isSetupComplete()) {
308 return {};
309 } else {
310 return { setupComplete: false };
311 }
312 };
idillon452e2102022-09-16 13:23:28 -0400313
simond47ef9e2022-09-28 22:24:28 -0400314 // sentrySetUp(app);
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400315
simond47ef9e2022-09-28 22:24:28 -0400316 app.get('/auth', (req, res) => {
317 const state = getState(req);
318 if (req.user) {
319 res.json(state);
320 } else {
321 res.status(401).json(state);
322 }
323 });
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400324
simond47ef9e2022-09-28 22:24:28 -0400325 app.use('/api', secured, apiRouter);
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400326
simond47ef9e2022-09-28 22:24:28 -0400327 app.use('/', indexRouter);
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400328
simond47ef9e2022-09-28 22:24:28 -0400329 /* GET React App */
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400330
simond47ef9e2022-09-28 22:24:28 -0400331 const cwd = process.cwd();
332 app.use(express.static(path.join(cwd, 'client/dist')));
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400333
simond47ef9e2022-09-28 22:24:28 -0400334 app.use((req, res) => {
335 res.render(path.join(cwd, 'client/dist/index.ejs'), {
336 initdata: JSON.stringify(getState(req)),
337 });
338 });
idillon452e2102022-09-16 13:23:28 -0400339
simond47ef9e2022-09-28 22:24:28 -0400340 // @ts-ignore TODO: Fix the typescript error
341 const server = http.Server(app);
Adrien Béraud4e287b92021-04-24 16:15:56 -0400342
simond47ef9e2022-09-28 22:24:28 -0400343 const io = new Server(server, { cors: corsOptions });
344 const wrap = (middleware: any) => (socket: Socket, next: (err?: ExtendedError) => void) =>
345 middleware(socket.request, {}, next);
346 io.use(wrap(sessionMiddleware));
347 io.use(wrap(passport.initialize()));
348 io.use(wrap(passport.session()));
349 io.use((socket, next) => {
350 if ((socket.request as any).user) {
351 next();
352 } else {
353 next(new Error('unauthorized'));
354 }
355 });
356 io.on('connect', (socket) => {
357 console.log(`new connection ${socket.id}`);
simon20076982022-10-11 15:04:13 -0400358 const session = (socket.request as any).session;
simond47ef9e2022-09-28 22:24:28 -0400359 console.log(`saving sid ${socket.id} in session ${session.id}`);
360 session.socketId = socket.id;
361 session.save();
Adrien Béraudabba2e52021-04-24 21:39:56 -0400362
simond47ef9e2022-09-28 22:24:28 -0400363 socket.on('conversation', (data) => {
364 console.log('io conversation');
365 console.log(data);
366 if (session.conversation) {
367 console.log(`disconnect from old conversation ${session.conversation.conversationId}`);
368 const conversation = jami.getConversation(session.conversation.accountId, session.conversation.conversationId);
simon06527b02022-10-01 15:01:47 -0400369 if (conversation) {
370 delete conversation.listeners[socket.id];
371 }
simond47ef9e2022-09-28 22:24:28 -0400372 }
373 session.conversation = { accountId: data.accountId, conversationId: data.conversationId };
374 const conversation = jami.getConversation(data.accountId, data.conversationId);
simon06527b02022-10-01 15:01:47 -0400375 if (conversation) {
376 if (!conversation.listeners) {
377 conversation.listeners = {};
378 }
379 conversation.listeners[socket.id] = {
380 socket,
381 session,
382 };
383 }
simond47ef9e2022-09-28 22:24:28 -0400384 session.save();
385 });
386 });
Adrien Béraud4e287b92021-04-24 16:15:56 -0400387
simond47ef9e2022-09-28 22:24:28 -0400388 return server;
389};
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400390
Adrien Béraude74741b2021-04-19 13:22:54 -0400391loadConfig(configPath)
simond47ef9e2022-09-28 22:24:28 -0400392 .then(createServer)
393 .then((server) => {
394 server.listen(3000);
395 });