forked from valette/desk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesk.js
More file actions
310 lines (207 loc) · 7.74 KB
/
desk.js
File metadata and controls
310 lines (207 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
'use strict';
const actions = require( 'desk-base' ),
auth = require( 'basic-auth' ),
compress = require( 'compression' ),
crypto = require( 'crypto' ),
directory = require( 'serve-index' ),
express = require( 'express' ),
formidable = require( 'formidable' ),
fs = require( 'fs-extra' ),
http = require( 'http' ),
https = require( 'https' ),
path = require( 'path' ),
pty = require( 'node-pty' ),
socketIO = require( 'socket.io' );
const { test } = require('shelljs');
const certificateFile = path.join( __dirname, "certificate.pem" ),
deskDir = actions.getRootDir(),
homeURL = process.env.DESK_PREFIX ? ( "/" + process.env.DESK_PREFIX + "/" ) : '/',
port = process.env.PORT || 8080,
passwordFile = path.join( deskDir, "password.json" ),
privateKeyFile = path.join( __dirname, "privatekey.pem" ),
uploadDir = path.join( deskDir, 'upload' ) + '/';
process.title = "desk";
let id = { username : process.env.USER, password : "password" };
fs.mkdirsSync( deskDir );
fs.mkdirsSync( uploadDir );
actions.include( __dirname + '/extensions' );
function authenticate ( user, pass ) {
if ( id.username === undefined ) return true;
const pass256 = pass;
const shasum256 = crypto.createHash( 'sha256' );
shasum256.update(pass256);
const sha256 = shasum256.digest( 'hex' );
//If the hash of the password is calculated with SHA-1 then we change it
if ( id.sha) {
const pass1 = pass;
const shasum1 = crypto.createHash( 'sha1' );
shasum1.update( pass1 );
const sha1 = shasum1.digest( 'hex' );
if ( !user || !pass || user !== id.username || sha1 !== id.sha ) { throw new Error( 'bad auth' );}
// We verify that the logins are correct before deleting and addind the hash 256
else if (user && pass && user == id.username && sha1 == id.sha) {
delete id.sha;
id.sha256 = sha256;
fs.writeFileSync( passwordFile, JSON.stringify( id ) );
};
//
} else {
if ( !user || !pass || user !== id.username || sha256 !== id.sha256 ) { throw new Error( 'bad auth' )};
}
}
const app = express()
.use( ( req, res, next ) => {
if ( publicDirs[ req.path.slice( homeURL.length ).split( '/' )[ 0 ] ] ) {
return next();
}
try {
const user = auth( req ) || {};
authenticate( user.name, user.pass );
res.cookie( 'homeURL', homeURL );
return next();
} catch ( e ) {
res.setHeader( 'WWW-Authenticate', 'Basic realm="Identity?"' );
res.sendStatus( 401 );
}
} )
.use( compress() )
.set( 'trust proxy', true )
.use( express.urlencoded( { limit : '10mb', extended : true } ) )
.post( path.join( homeURL, '/upload' ), ( req, res ) => {
if ( !actions.getSettings().permissions ) return;
let outputDir;
const files = [];
const form = new formidable.IncomingForm( {
uploadDir, maxFileSize : 200 * 1024 * 1024 * 1024 } );
form.parse( req, function( err, fields, files ) {
outputDir = path.join(deskDir, unescape(fields.uploadDir));
} );
form.on( 'file', ( name, file ) => files.push( file ) );
form.on( 'error', ( err ) => log( "upload error : " + err ) );
form.on( 'end', async () => {
const length = files.length;
while ( files.length ) {
const file = files.pop();
log( "file : " + file.filepath.toString() );
const fullName = path.join( outputDir, file.originalFilename );
let newFile, index = 0;
do {
newFile = fullName + ( index > 0 ? "." + index : "" );
index++
} while ( await fs.exists( newFile ) )
await fs.move( file.filepath.toString(), newFile );
log( "uploaded to " + newFile );
}
if ( length ) res.send( 'file(s) uploaded successfully' );
} );
} )
.use( homeURL, express.static( __dirname + '/node_modules/desk-ui/compiled/dist' ),
express.static( deskDir ), directory( deskDir ) );
let server, baseURL = "http://";
if ( fs.existsSync( privateKeyFile ) && fs.existsSync( certificateFile ) ) {
server = https.createServer( {
key: fs.readFileSync( privateKeyFile ),
cert: fs.readFileSync( certificateFile )
}, app );
baseURL = "https://";
} else {
server = http.createServer( app );
}
const io = socketIO( server, { path : path.join( homeURL, 'socket.io' ),
maxHttpBufferSize : 1e8 } );
function log ( message ) {
console.log( message );
if ( io ) io.emit( "log", message );
}
log( "Start : " + new Date().toLocaleString() );
let publicDirs = {};
function updatePublicDirs () {
const dirs = actions.getSettings().dataDirs;
publicDirs = {};
for ( let [ dir, props ] of Object.entries( dirs ) ) {
if ( props.public ) publicDirs[ dir ] = true;
}
if ( Object.keys ( publicDirs ).length ) {
log( "public data : " + Object.keys( publicDirs ).join(', ') );
}
}
actions.on( 'actions updated', updatePublicDirs );
updatePublicDirs();
function updatePassword() {
try { id = JSON.parse( fs.readFileSync( passwordFile ) ); }
catch ( e ) {
log( "error while reading password file : " );
log( e );
}
if ( id.password ) {
// convert to secure format
const shasum = crypto.createHash( 'sha256' );
shasum.update( id.password );
id.sha256 = shasum.digest( 'hex' );
delete id.password;
fs.writeFileSync( passwordFile, JSON.stringify( id ) );
}
}
updatePassword();
fs.watchFile( passwordFile, updatePassword );
actions.oldEmit = actions.emit;
actions.emit = ( e, d ) => { io.emit( e, d ); return actions.oldEmit( e, d ) };
io.on( 'connection', socket => {
try {
const auth = ( socket.request.headers.authorization || "" ).slice( 6 );
const id = ( '' + Buffer.from( auth, 'base64' ) ).split( ':' );
authenticate( ...id );
} catch ( e ) { return socket.disconnect(); }
const ip = ( socket.client.conn.request.headers[ 'x-forwarded-for' ]
|| socket.handshake.address ).split( ":" ).pop();
log( new Date().toString() + ': connect : ' + ip );
socket.emit( "actions updated", actions.getSettings() );
socket.on( 'disconnect', () => log( new Date().toString() + ': disconnect : ' + ip ) )
.on( 'action', action => actions.execute( action ) )
.on( 'setEmitLog', log => actions.setEmitLog( log ) )
.on( 'password', password => {
const shasum = crypto.createHash( 'sha256' );
shasum.update( password );
id.sha256 = shasum.digest( 'hex' );
fs.writeFileSync( passwordFile, JSON.stringify( id ) );
} );
} );
const terms = {};
if ( actions.getSettings().permissions ) io.of( '/xterm' ).on( 'connection', socket => {
try {
const auth = ( socket.request.headers.authorization || "" ).slice( 6 );
const id = ( '' + Buffer.from( auth, 'base64' ) ).split( ':' );
authenticate( ...id );
} catch ( e ) { return socket.disconnect(); }
socket.on( 'newTerminal', function( options, cb ) {
if ( terms[ options.name ] ) return;
log( "new terminal : " + options.name );
io.of( '/xterm' + options.name ).on( 'connection', socket => {
const term = pty.spawn(process.platform === 'win32' ? 'cmd.exe' : 'bash', [], {
name: 'xterm-color',
cols: 80,
rows: 24,
cwd: process.env.HOME,
env: process.env
} );
term.on('data', data => {
try { socket.send( data ); }
catch ( ex ) { console.warn( ex ); }
} );
terms[ options.name ] = true;
socket.on( 'resize', size => term.resize( size.nCols, size.nRows ) )
.on( 'message', msg => term.write(msg) )
.on( 'disconnect', async () => {
term.kill();
const name = '/xterm' + options.name;
io.of( name ).removeAllListeners();
io._nsps.delete( name );// Remove from the server namespaces
log( "namespaces : " + Array.from( io._nsps.keys() ).join( ',' ) );
delete terms[ options.name ];
} );
} );
if ( cb ) cb();
} );
} );
server.listen( port );
log ( "server running : " + baseURL + "localhost:" + port + homeURL );