blob: 793453c57a42c1569e7dd244e4b31d0c353b1da3 [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 { Server, Socket } from 'socket.io';
33import { ExtendedError } from 'socket.io/dist/namespace';
34
simon06527b02022-10-01 15:01:47 -040035import JamiDaemon from './JamiDaemon';
Adrien Béraude74741b2021-04-19 13:22:54 -040036//import { createRequire } from 'module';
37//const require = createRequire(import.meta.url);
Adrien Béraud947e8792021-04-15 18:32:44 -040038//const redis = require('redis-url').connect()
39//const RedisStore = require('connect-redis')(session)
Adrien Béraud6ecaa402021-04-06 17:37:25 -040040/*const passportSocketIo = require('passport.socketio')*/
simond47ef9e2022-09-28 22:24:28 -040041import indexRouter from './routes/index.js';
simond47ef9e2022-09-28 22:24:28 -040042import JamiRestApi from './routes/jami.js';
idillon8e6c0062022-09-16 13:34:43 -040043// import { sentrySetUp } from './sentry.js'
Adrien Béraude74741b2021-04-19 13:22:54 -040044
simond47ef9e2022-09-28 22:24:28 -040045const configPath = 'jamiServerConfig.json';
Larbi Gharibe9af9732021-03-31 15:08:01 +010046
Adrien Béraud6ecaa402021-04-06 17:37:25 -040047//const sessionStore = new RedisStore({ client: redis })
simond47ef9e2022-09-28 22:24:28 -040048const sessionStore = new session.MemoryStore();
Larbi Gharibe9af9732021-03-31 15:08:01 +010049
simon06527b02022-10-01 15:01:47 -040050interface User {
51 id: string;
52 config: UserConfig;
53 username: string;
54 accountFilter?: (account: any) => boolean;
55}
56
simon7a7b4d52022-09-23 02:09:42 -040057interface UserConfig {
simon06527b02022-10-01 15:01:47 -040058 accountId?: string;
simon7a7b4d52022-09-23 02:09:42 -040059 accounts: string;
60 password?: string;
61 username?: string;
simond47ef9e2022-09-28 22:24:28 -040062 type?: string;
simon7a7b4d52022-09-23 02:09:42 -040063}
64
65interface AppConfig {
simond47ef9e2022-09-28 22:24:28 -040066 users: Record<string, UserConfig>;
simon06527b02022-10-01 15:01:47 -040067 authMethods: unknown[];
simon7a7b4d52022-09-23 02:09:42 -040068}
69
70const loadConfig = async (filePath: string): Promise<AppConfig> => {
simond47ef9e2022-09-28 22:24:28 -040071 const config = { users: {}, authMethods: [] };
72 try {
73 return Object.assign(config, JSON.parse((await fs.readFile(filePath)).toString()));
74 } catch (e) {
75 console.log(e);
76 return config;
77 }
78};
Adrien Béraud824a7132021-04-17 17:25:27 -040079
simon7a7b4d52022-09-23 02:09:42 -040080const saveConfig = (filePath: string, config: AppConfig) => {
simond47ef9e2022-09-28 22:24:28 -040081 return fs.writeFile(filePath, JSON.stringify(config));
82};
Adrien Béraude74741b2021-04-19 13:22:54 -040083
Larbi Gharibe9af9732021-03-31 15:08:01 +010084/*
Adrien Béraud3b5d9a62021-04-17 18:40:27 -040085Share sessions between Passport.js and Socket.io
Larbi Gharibe9af9732021-03-31 15:08:01 +010086*/
87
88function logSuccess() {
simond47ef9e2022-09-28 22:24:28 -040089 console.log('passportSocketIo authorized user with Success 😁');
Larbi Gharibe9af9732021-03-31 15:08:01 +010090}
91
92function logFail() {
simond47ef9e2022-09-28 22:24:28 -040093 console.log('passportSocketIo failed to authorized user 👺');
Larbi Gharibe9af9732021-03-31 15:08:01 +010094}
95
96/*
Larbi Gharibe9af9732021-03-31 15:08:01 +010097
Adrien Béraud3b5d9a62021-04-17 18:40:27 -040098tempAccounts holds users accounts while tempting to authenticate them on Jams.
99connectedUsers holds users accounts after they got authenticated by Jams.
Larbi Gharibe9af9732021-03-31 15:08:01 +0100100
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400101Users should be removed from connectedUsers when receiving a disconnect
102web socket call
Larbi Gharibe9af9732021-03-31 15:08:01 +0100103
104*/
simon06527b02022-10-01 15:01:47 -0400105const tempAccounts: Record<
106 string,
107 {
108 newUser: Express.User;
109 done: (error: any, user?: any, options?: IVerifyOptions) => void;
110 }
111> = {};
112const connectedUsers: Record<string, UserConfig> = {};
Larbi Gharibe9af9732021-03-31 15:08:01 +0100113
simon7a7b4d52022-09-23 02:09:42 -0400114const createServer = async (appConfig: AppConfig) => {
simond47ef9e2022-09-28 22:24:28 -0400115 const app = express();
simon6c2a63d2022-10-11 13:51:29 -0400116 console.log(`Loading server for ${nodeEnv} with config:`);
simond47ef9e2022-09-28 22:24:28 -0400117 console.log(appConfig);
Larbi Gharibe9af9732021-03-31 15:08:01 +0100118
simond47ef9e2022-09-28 22:24:28 -0400119 const corsOptions = {
120 origin: 'http://127.0.0.1:3000',
121 };
Adrien Béraud4e287b92021-04-24 16:15:56 -0400122
simond47ef9e2022-09-28 22:24:28 -0400123 /*
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400124 Configuation for Passeport Js
125 */
simond47ef9e2022-09-28 22:24:28 -0400126 app.disable('x-powered-by');
Adrien Béraud6ecaa402021-04-06 17:37:25 -0400127
simon6c2a63d2022-10-11 13:51:29 -0400128 const secretKey = process.env.SECRET_KEY_BASE;
simon7a7b4d52022-09-23 02:09:42 -0400129
simon6c2a63d2022-10-11 13:51:29 -0400130 if (!secretKey) {
simond47ef9e2022-09-28 22:24:28 -0400131 throw new Error('SECRET_KEY_BASE undefined');
132 }
133
134 const sessionMiddleware = session({
135 store: sessionStore,
136 resave: false,
137 saveUninitialized: true,
138 cookie: {
139 secure: false, //!development,
140 maxAge: 2419200000,
141 },
simon6c2a63d2022-10-11 13:51:29 -0400142 secret: secretKey,
simond47ef9e2022-09-28 22:24:28 -0400143 });
144
145 app.use(sessionMiddleware);
146 app.use(passport.initialize());
147 app.use(passport.session());
148 // app.use(app.router)
149 app.use(cors(corsOptions));
150
151 const jami = new JamiDaemon((account: Account, conversation: any, message: any) => {
152 console.log('JamiDaemon onMessage');
153
154 if (conversation.listeners) {
155 Object.values(conversation.listeners).forEach((listener: any) => {
156 listener.socket.emit('newMessage', message);
157 });
simon7a7b4d52022-09-23 02:09:42 -0400158 }
simond47ef9e2022-09-28 22:24:28 -0400159 });
160 const apiRouter = new JamiRestApi(jami).getRouter();
simon7a7b4d52022-09-23 02:09:42 -0400161
simond47ef9e2022-09-28 22:24:28 -0400162 /*
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400163 io.use(passportSocketIo.authorize({
164 key: 'connect.sid',
165 secret: process.env.SECRET_KEY_BASE,
166 store: sessionStore,
167 passport: passport,
168 cookieParser: cookieParser,
169 //success: logSuccess(),
170 // fail: logFail(),
Adrien Béraude74741b2021-04-19 13:22:54 -0400171 }))
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400172 */
Adrien Béraud6ecaa402021-04-06 17:37:25 -0400173
simond47ef9e2022-09-28 22:24:28 -0400174 const isSetupComplete = () => {
175 return 'admin' in appConfig.users;
176 };
177
simon06527b02022-10-01 15:01:47 -0400178 const accountFilter = (filter: string | string[]) => {
simond47ef9e2022-09-28 22:24:28 -0400179 if (typeof filter === 'string') {
180 if (filter === '*') return undefined;
181 else return (account: Account) => account.getId() === filter;
182 } else if (Array.isArray(filter)) {
183 return (account: Account) => filter.includes(account.getId());
184 } else {
185 throw new Error('Invalid account filter string');
Adrien Béraude74741b2021-04-19 13:22:54 -0400186 }
simond47ef9e2022-09-28 22:24:28 -0400187 };
Adrien Béraude74741b2021-04-19 13:22:54 -0400188
simond47ef9e2022-09-28 22:24:28 -0400189 const user = (id: string, config: UserConfig) => {
190 return {
191 id,
192 config,
193 username: config.username || id,
194 accountFilter: accountFilter(config.accounts),
195 };
196 };
197
198 passport.serializeUser((user: any, done) => {
simon06527b02022-10-01 15:01:47 -0400199 user = user as User;
simond47ef9e2022-09-28 22:24:28 -0400200 connectedUsers[user.id] = user.config;
201 console.log('=============================SerializeUser called ' + user.id);
202 console.log(user);
203 done(null, user.id);
204 });
205
206 const deserializeUser = (id: string, done: (err: any, user?: Express.User | false | null) => void) => {
207 console.log('=============================DeserializeUser called on: ' + id);
208 const userConfig = connectedUsers[id];
209 console.log(userConfig);
210 if (userConfig) {
211 done(null, user(id, userConfig));
212 } else done(404, null);
213 };
214 passport.deserializeUser(deserializeUser);
215
216 const jamsStrategy = new LocalStrategy(async (username, password, done) => {
217 const accountId = await jami.addAccount({
218 managerUri: 'https://jams.savoirfairelinux.com',
219 managerUsername: username,
220 archivePassword: password,
221 });
222 const id = `jams_${username}`;
223 const userConfig = { username, type: 'jams', accounts: accountId };
224 const newUser = user(id, userConfig);
225 console.log('AccountId: ' + accountId);
226 tempAccounts[accountId] = { done, newUser };
227 });
228 jamsStrategy.name = 'jams';
229
230 const localStrategy = new LocalStrategy((username, password, done) => {
231 console.log('localStrategy: ' + username + ' ' + password);
232
233 const id = username;
234 const userConfig = appConfig.users[username];
235 if (!userConfig) {
236 return done(null, false, { message: 'Incorrect username.' });
Adrien Béraude74741b2021-04-19 13:22:54 -0400237 }
simond47ef9e2022-09-28 22:24:28 -0400238 if (userConfig.password !== password) {
239 return done(null, false, { message: 'Incorrect password.' });
Adrien Béraude74741b2021-04-19 13:22:54 -0400240 }
simond47ef9e2022-09-28 22:24:28 -0400241 userConfig.type = 'local';
Adrien Béraude74741b2021-04-19 13:22:54 -0400242
simond47ef9e2022-09-28 22:24:28 -0400243 done(null, user(id, userConfig));
244 });
Adrien Béraud6ecaa402021-04-06 17:37:25 -0400245
simond47ef9e2022-09-28 22:24:28 -0400246 passport.use(jamsStrategy);
247 passport.use(localStrategy);
248
249 const secured = (req: Request, res: Response, next: NextFunction) => {
250 if (req.user) {
251 return next();
Adrien Béraude74741b2021-04-19 13:22:54 -0400252 }
simond47ef9e2022-09-28 22:24:28 -0400253 res.status(401).end();
254 };
255 const securedRedirect = (req: Request, res: Response, next: NextFunction) => {
simon06527b02022-10-01 15:01:47 -0400256 const user = req.user as UserConfig | undefined;
257 if (user?.accountId) {
simond47ef9e2022-09-28 22:24:28 -0400258 return next();
Adrien Béraude74741b2021-04-19 13:22:54 -0400259 }
simond47ef9e2022-09-28 22:24:28 -0400260 (req.session as any).returnTo = req.originalUrl;
261 res.redirect('/login');
262 };
263
264 app.use(express.json());
265 app.post('/setup', (req, res) => {
266 if (isSetupComplete()) {
267 return res.status(404).end();
Adrien Béraude74741b2021-04-19 13:22:54 -0400268 }
simond47ef9e2022-09-28 22:24:28 -0400269 if (!req.body.password) {
270 return res.status(400).end();
Adrien Béraude5cad982021-06-07 10:05:50 -0400271 }
simond47ef9e2022-09-28 22:24:28 -0400272 console.log(req.body);
273 appConfig.users.admin = {
274 accounts: '*',
275 password: req.body.password,
276 };
277 res.status(200).end();
278 saveConfig(configPath, appConfig);
279 });
280 app.post('/auth/jams', passport.authenticate('jams'), (req, res) => {
281 res.json({ loggedin: true });
282 });
283 app.post('/auth/local', passport.authenticate('local'), (req, res) => {
simon06527b02022-10-01 15:01:47 -0400284 res.json({ loggedin: true, user: (req.user as User | undefined)?.id });
simond47ef9e2022-09-28 22:24:28 -0400285 });
Adrien Béraude5cad982021-06-07 10:05:50 -0400286
simond47ef9e2022-09-28 22:24:28 -0400287 const getState = (req: Request) => {
288 if (req.user) {
simon06527b02022-10-01 15:01:47 -0400289 const user = req.user as UserConfig;
simond47ef9e2022-09-28 22:24:28 -0400290 return { loggedin: true, username: user.username, type: user.type };
291 } else if (isSetupComplete()) {
292 return {};
293 } else {
294 return { setupComplete: false };
295 }
296 };
idillon452e2102022-09-16 13:23:28 -0400297
simond47ef9e2022-09-28 22:24:28 -0400298 // sentrySetUp(app);
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400299
simond47ef9e2022-09-28 22:24:28 -0400300 app.get('/auth', (req, res) => {
301 const state = getState(req);
302 if (req.user) {
303 res.json(state);
304 } else {
305 res.status(401).json(state);
306 }
307 });
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400308
simond47ef9e2022-09-28 22:24:28 -0400309 app.use('/api', secured, apiRouter);
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400310
simond47ef9e2022-09-28 22:24:28 -0400311 app.use('/', indexRouter);
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400312
simond47ef9e2022-09-28 22:24:28 -0400313 // @ts-ignore TODO: Fix the typescript error
314 const server = http.Server(app);
Adrien Béraud4e287b92021-04-24 16:15:56 -0400315
simond47ef9e2022-09-28 22:24:28 -0400316 const io = new Server(server, { cors: corsOptions });
317 const wrap = (middleware: any) => (socket: Socket, next: (err?: ExtendedError) => void) =>
318 middleware(socket.request, {}, next);
319 io.use(wrap(sessionMiddleware));
320 io.use(wrap(passport.initialize()));
321 io.use(wrap(passport.session()));
322 io.use((socket, next) => {
323 if ((socket.request as any).user) {
324 next();
325 } else {
326 next(new Error('unauthorized'));
327 }
328 });
329 io.on('connect', (socket) => {
330 console.log(`new connection ${socket.id}`);
simon20076982022-10-11 15:04:13 -0400331 const session = (socket.request as any).session;
simond47ef9e2022-09-28 22:24:28 -0400332 console.log(`saving sid ${socket.id} in session ${session.id}`);
333 session.socketId = socket.id;
334 session.save();
Adrien Béraudabba2e52021-04-24 21:39:56 -0400335
simond47ef9e2022-09-28 22:24:28 -0400336 socket.on('conversation', (data) => {
337 console.log('io conversation');
338 console.log(data);
339 if (session.conversation) {
340 console.log(`disconnect from old conversation ${session.conversation.conversationId}`);
341 const conversation = jami.getConversation(session.conversation.accountId, session.conversation.conversationId);
simon06527b02022-10-01 15:01:47 -0400342 if (conversation) {
343 delete conversation.listeners[socket.id];
344 }
simond47ef9e2022-09-28 22:24:28 -0400345 }
346 session.conversation = { accountId: data.accountId, conversationId: data.conversationId };
347 const conversation = jami.getConversation(data.accountId, data.conversationId);
simon06527b02022-10-01 15:01:47 -0400348 if (conversation) {
349 if (!conversation.listeners) {
350 conversation.listeners = {};
351 }
352 conversation.listeners[socket.id] = {
353 socket,
354 session,
355 };
356 }
simond47ef9e2022-09-28 22:24:28 -0400357 session.save();
358 });
359 });
Adrien Béraud4e287b92021-04-24 16:15:56 -0400360
simond47ef9e2022-09-28 22:24:28 -0400361 return server;
362};
Adrien Béraud3b5d9a62021-04-17 18:40:27 -0400363
Adrien Béraude74741b2021-04-19 13:22:54 -0400364loadConfig(configPath)
simond47ef9e2022-09-28 22:24:28 -0400365 .then(createServer)
366 .then((server) => {
simond8ca2f22022-10-11 23:30:55 -0400367 server.listen(3001);
simond47ef9e2022-09-28 22:24:28 -0400368 });