@everneed/worker 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/worker/rabbitmq.js +143 -263
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@everneed/worker",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -235,7 +235,6 @@ export default {
235
235
  channel.consume(`req/${pseudoEnv.process.env.SVC_NAME}/${moduleSpace}/${endpoint}`, async (message)=>{
236
236
  const mqHeader = message.properties.headers
237
237
  const mqReq = await this.decryptMessage({
238
- mode: mqHeader.mode,
239
238
  message: message.content.toString(),
240
239
  ...(mqHeader.auth && { token: mqHeader.auth.token }),
241
240
  ...(mqHeader.auth && { userAgent: mqHeader.auth.userAgent })
@@ -258,60 +257,28 @@ export default {
258
257
  const response = new ResponseCode()
259
258
  response.pushCode("INVALID_ENDPOINT")
260
259
  prep["message"] = await this.encryptMessage({
261
- mode: mqHeader.mode,
262
260
  message: response.result
263
261
  })
264
262
  throw "invalid_endpoint"
265
263
  }
266
264
  /* API enforce Auth */
267
265
  if(main.default[endpoint].authentication){
268
- if(!mqHeader.auth && mqHeader.mode != "auth"){
266
+ if(!mqHeader.auth){
269
267
  const response = new ResponseCode()
270
268
  response.pushCode("NOT_AUTHENTICATED")
271
269
  prep["message"] = await this.encryptMessage({
272
- mode: mqHeader.mode,
273
270
  message: response.result
274
271
  })
275
272
  throw "not_authenticated"
276
273
  }
277
274
  }
278
-
279
- /* With Auth */
280
- if(mqHeader.auth && mqHeader.mode == "auth"){
281
- const { token, userAgent } = mqHeader.auth
282
- const auth = await this.verifyToken({
283
- token: token,
284
- userAgent: userAgent
285
- })
286
-
287
- if(auth.checkError()){ // NOT_AUTHENTICATED || SESSION_EXPIRED
288
- prep["message"] = await this.encryptMessage({
289
- mode: mqHeader.mode,
290
- message: auth.result
291
- })
292
- }
293
- else{ // AUTHENTICATED || REFRESH_SESSION
294
- const result = await main.default[endpoint].function[`v${trueVersion}`](mqHeader.auth, mqReq.payload)
295
- const response = new ResponseCode(result)
296
- if(auth.hasCode("REFRESH_SESSION")) response.pushRefresh(auth.result.data)
297
- prep["message"] = await this.encryptMessage({
298
- mode: mqHeader.mode,
299
- message: response.result,
300
- token: token,
301
- userAgent: userAgent
302
- })
303
- }
304
- }
305
- /* Without Auth */
306
- else{
307
- const result = await main.default[endpoint].function[`v${trueVersion}`](false, mqReq.payload)
308
- prep["message"] = await this.encryptMessage({
309
- mode: mqHeader.mode,
310
- message: result,
311
- ...(mqHeader.auth && { token: mqHeader.auth.token }),
312
- ...(mqHeader.auth && { userAgent: mqHeader.auth.userAgent })
313
- })
314
- }
275
+ /* Main Process */
276
+ const result = await main.default[endpoint].function[`v${trueVersion}`](mqHeader.auth || false, mqReq.payload)
277
+ prep["message"] = await this.encryptMessage({
278
+ message: result,
279
+ ...(mqHeader.auth && { token: mqHeader.auth.token }),
280
+ ...(mqHeader.auth && { userAgent: mqHeader.auth.userAgent })
281
+ })
315
282
 
316
283
  throw "finish"
317
284
  }
@@ -320,7 +287,6 @@ export default {
320
287
  channel.sendToQueue(message.properties.replyTo, Buffer.from(prep.message), {
321
288
  correlationId: message.properties.correlationId,
322
289
  headers:{
323
- mode: mqHeader.mode,
324
290
  ...(mqHeader.version && { version: mqHeader.version }),
325
291
  ...(mqHeader.auth && { auth: mqHeader.auth })
326
292
  },
@@ -337,11 +303,10 @@ export default {
337
303
  // connection.close()
338
304
  })
339
305
  },
340
- publish: function({topic, version, mode="auth", auth=null, trip="passby", data}){
306
+ publish: function({topic, version, auth=null, trip="passby", data}){
341
307
  /* Usage */
342
308
  // publish({
343
309
  // topic: <topic start at svc :String>,
344
- // mode: <"auth"|"no auth" :String>
345
310
  // auth:{
346
311
  // token: <auth token :String>,
347
312
  // userAgent: <ua string :String>,
@@ -354,246 +319,161 @@ export default {
354
319
  // ex: req/cd6f01UjkB7E/rolling-tempat-duduk/class/getAll
355
320
  // ex: res/cd6f01UjkB7E/rolling-tempat-duduk/class/getAll
356
321
 
322
+ const response = new ResponseCode()
357
323
  return new Promise(async (resolve, reject)=>{
358
324
  /* RabbitMQ Engine */
359
325
  amqp.connect(pseudoEnv.process.env.RABBIT_HOST, async (error0, connection)=>{
360
326
  if(error0){ throw error0 }
361
327
 
362
- /* Creates connection & channel */
363
- const channel = connection.createChannel((error1, channel)=>{
364
- if (error1){ throw error1 }
365
- return channel
366
- })
367
-
368
- /* Build payload structure */
369
- // like topic, address, etc.
370
- const userName = auth ? this.getUserInfo({tokenBody: auth.token.split(".")[0]}).userName : `guest${randomStr({length: 12})}`
371
- const prep = {
372
- topic: `req/${topic}`,
373
- message:{
374
- trip: trip,
375
- senderAddress: `${createHmac("sha256", userName).digest("hex").slice(0, 12)}${moment().utc().format("HHmmssSSS")}`,
376
- payload: data
377
- }
378
- }
379
- /* Main publisher */
380
- const mqReq = await this.encryptMessage({
381
- mode: mode,
382
- message: prep.message,
383
- ...(auth && { token: auth.token }),
384
- ...(auth && { userAgent: auth.userAgent })
385
- })
386
-
387
- channel.assertQueue(prep.topic, { durable: true })
388
- channel.sendToQueue(prep.topic, Buffer.from(mqReq), {
389
- headers:{
390
- ...(version && { version: version }),
391
- mode: mode,
392
- ...(auth && { auth: auth })
393
- },
394
- ...(trip == "returning" && { correlationId: prep.message.senderAddress }),
395
- ...(trip == "returning" && { replyTo: `res/${topic}` }),
396
- })
397
-
398
- /* Resolvation According to Trip */
399
- if(trip == "returning"){
400
- /* Creates consumer for returning messages */
401
- channel.assertQueue(`res/${topic}`, { durable: true })
402
- channel.consume(`res/${topic}`, async (message)=>{
403
- /* Differentiate normal flow with refresh session flow */
404
- const sessionRefresh = ()=>{
405
- const response = new ResponseCode(message.content.toString())
406
- if(response.hasCode("REFRESH_SESSION")) return true
407
- else return false
328
+ try{
329
+ /* Creates connection & channel */
330
+ const channel = connection.createChannel((error1, channel)=>{
331
+ if (error1){ throw error1 }
332
+ return channel
333
+ })
334
+
335
+ /* Build payload structure */
336
+ // like topic, address, etc.
337
+ const userName = auth ? this.getUserInfo({tokenBody: auth.token.split(".")[0]}).userName : `guest${randomStr({length: 12})}`
338
+ const prep = {
339
+ topic: `req/${topic}`,
340
+ message:{
341
+ trip: trip,
342
+ senderAddress: `${createHmac("sha256", userName).digest("hex").slice(0, 12)}${moment().utc().format("HHmmssSSS")}`,
343
+ payload: data
408
344
  }
409
- const mqRes = await this.decryptMessage({
410
- mode: mode,
411
- message: message.content.toString(),
412
- ...((auth && !sessionRefresh()) && { token: auth.token }),
413
- ...((auth && sessionRefresh()) && { token: message.content.toString().data.token }),
414
- ...(auth && { userAgent: auth.userAgent })
345
+ }
346
+ /* Validate Auth */
347
+ if(auth){
348
+ const validate = await this.publish({
349
+ topic: "authenthor/session/svVerifyToken",
350
+ trip: "returning",
351
+ data:{
352
+ token: auth.token,
353
+ userAgent: auth.userAgent,
354
+ noRefresh: true
355
+ }
415
356
  })
416
357
 
417
- if(message.properties.correlationId == prep.message.senderAddress){
418
- resolve(mqRes)
419
- channel.ack(message)
420
- setTimeout(()=>{
421
- connection.close()
422
- }, 500)
423
- }
424
- }, {
425
- noAck: false
358
+ response.createNew(validate)
359
+ if(response.checkError()) throw "abort"
360
+ else response.reset()
361
+ }
362
+ /* Main publisher */
363
+ const mqReq = await this.encryptMessage({
364
+ message: prep.message,
365
+ ...(auth && { token: auth.token }),
366
+ ...(auth && { userAgent: auth.userAgent })
426
367
  })
427
- }
428
- else if(trip == "passby"){
429
- resolve("sent")
430
-
431
- setTimeout(()=>{
432
- connection.close()
433
- }, 500)
434
- }
368
+
369
+ channel.assertQueue(prep.topic, { durable: true })
370
+ channel.sendToQueue(prep.topic, Buffer.from(mqReq), {
371
+ headers:{
372
+ ...(version && { version: version }),
373
+ ...(auth && { auth: auth })
374
+ },
375
+ ...(trip == "returning" && { correlationId: prep.message.senderAddress }),
376
+ ...(trip == "returning" && { replyTo: `res/${topic}` }),
377
+ })
378
+
379
+ /* Resolvation According to Trip */
380
+ if(trip == "returning"){
381
+ /* Creates consumer for returning messages */
382
+ channel.assertQueue(`res/${topic}`, { durable: true })
383
+ channel.consume(`res/${topic}`, async (message)=>{
384
+ const mqRes = await this.decryptMessage({
385
+ message: message.content.toString(),
386
+ ...(auth && { token: auth.token }),
387
+ ...(auth && { userAgent: auth.userAgent })
388
+ })
389
+
390
+ if(message.properties.correlationId == prep.message.senderAddress){
391
+ response.createNew(mqRes)
392
+ channel.ack(message)
393
+ setTimeout(()=>{
394
+ connection.close()
395
+ }, 500)
396
+
397
+ resolve(response)
398
+ }
399
+ }, {
400
+ noAck: false
401
+ })
402
+ }
403
+ else if(trip == "passby"){
404
+ response.pushCode("GENERAL_OK")
405
+
406
+ setTimeout(()=>{
407
+ connection.close()
408
+ }, 500)
435
409
 
410
+ resolve(response)
411
+ }
412
+ }
413
+ catch(something){
414
+ response.createNew(response.result)
415
+ if(something != "abort"){
416
+ // err: other error
417
+ response.pushCode("LOGIC_ERROR")
418
+ response.pushTrace({code: "LOGIC_ERROR", trace: `Unexpected error on queue publisher`})
419
+ }
420
+
421
+ resolve(response)
422
+ }
436
423
  // connection.close()
437
424
  })
438
425
  })
439
426
  },
440
- encryptMessage: function({mode="auth", message, token=null, userAgent=null}){
427
+ encryptMessage: function({message, token=null, userAgent=null}){
441
428
  return new Promise(async (resolve, reject)=>{
442
- if(mode == "auth"){
443
- /* Active Auth Session */
444
- if(token && userAgent){
445
- const { userId } = this.getUserInfo({ tokenBody: token.split(".")[0] })
446
- const uaHash = crypto.hash("sha256", switchPourStr(userAgent, pseudoEnv.process.env.TOKEN_UA_SALT))
447
- await redis.connect().catch(error => {})
448
- const authKey = await redis.get(`auth:session:long:${userId}:${uaHash}`)
449
- const hash = crypto.hash("sha256", switchPourStr(authKey, pseudoEnv.process.env.RABBIT_MESSAGE_SALT))
450
- const key = hash.substring(0, 16)
451
- const iv = hash.substring(48)
452
-
453
- const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(iv))
454
- let encrypted = cipher.update(JSON.stringify(message), "utf-8", "base64")
455
- encrypted += cipher.final("base64")
456
- return resolve(encrypted)
457
- }
458
- /* No Auth */
459
- else{
460
- const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_KEY), Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_IV))
461
- let encrypted = cipher.update(JSON.stringify(message), "utf-8", "base64")
462
- encrypted += cipher.final("base64")
463
- return resolve(encrypted)
464
- }
465
- }
466
- else if(mode == "no auth"){
467
- /* Unchecked Token (Illegal/Refresh) */
468
- if(token){
469
- const {key, iv} = pipe(token)
470
- .then(token=> token.split(".")[0])
471
- .then(tokenBody=> this.getUserInfo({tokenBody: tokenBody}))
472
- .then(({userName, userId, displayName})=>{
473
- return switchPourStr(
474
- userName,
475
- pseudoEnv.process.env.RABBIT_MESSAGE_KEY,
476
- userId,
477
- pseudoEnv.process.env.RABBIT_MESSAGE_IV,
478
- displayName,
479
- )
480
- })
481
- .then(mixWord=> crypto.hash("sha256", mixWord))
482
- .then(hash=>{
483
- return {
484
- key: hash.substring(0, 16),
485
- iv: hash.substring(48)
486
- }
487
- })
488
- .result
429
+ /* Active Auth Session */
430
+ if(token && userAgent){
431
+ const { userId } = this.getUserInfo({ tokenBody: token.split(".")[0] })
432
+ const uaHash = crypto.hash("sha256", switchPourStr(userAgent, pseudoEnv.process.env.TOKEN_UA_SALT))
433
+ await redis.connect().catch(error => {})
434
+ const authKey = await redis.get(`auth:session:long:${userId}:${uaHash}`)
435
+ const hash = crypto.hash("sha256", switchPourStr(authKey || "kontol", pseudoEnv.process.env.RABBIT_MESSAGE_SALT))
436
+ const key = hash.substring(0, 16)
437
+ const iv = hash.substring(48)
489
438
 
490
- const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(iv))
491
- let encrypted = cipher.update(JSON.stringify(message), "utf-8", "base64")
492
- encrypted += cipher.final("base64")
493
- return resolve(encrypted)
494
- }
495
- /* No Auth */
496
- else{
497
- const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_KEY), Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_IV))
498
- let encrypted = cipher.update(JSON.stringify(message), "utf-8", "base64")
499
- encrypted += cipher.final("base64")
500
- return resolve(encrypted)
501
- }
502
- }
439
+ const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(iv))
440
+ let encrypted = cipher.update(JSON.stringify(message), "utf-8", "base64")
441
+ encrypted += cipher.final("base64")
442
+ return resolve(encrypted)
443
+ }
444
+ /* No Auth */
445
+ else{
446
+ const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_KEY), Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_IV))
447
+ let encrypted = cipher.update(JSON.stringify(message), "utf-8", "base64")
448
+ encrypted += cipher.final("base64")
449
+ return resolve(encrypted)
450
+ }
503
451
  })
504
452
  },
505
- decryptMessage: function({mode="auth", message, token=null, userAgent=null}){
453
+ decryptMessage: function({message, token=null, userAgent=null}){
506
454
  return new Promise(async (resolve, reject)=>{
507
- if(mode == "auth"){
508
- /* Active Auth Session */
509
- if(token && userAgent){
510
- const { userId } = this.getUserInfo({ tokenBody: token.split(".")[0] })
511
- const uaHash = crypto.hash("sha256", switchPourStr(userAgent, pseudoEnv.process.env.TOKEN_UA_SALT))
512
- await redis.connect().catch(error => {})
513
- const authKey = await redis.get(`auth:session:long:${userId}:${uaHash}`)
514
- const hash = crypto.hash("sha256", switchPourStr(authKey, pseudoEnv.process.env.RABBIT_MESSAGE_SALT))
515
- const key = hash.substring(0, 16)
516
- const iv = hash.substring(48)
517
-
518
- const decipher = crypto.createDecipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(iv))
519
- let decrypted = decipher.update(message, "base64", "utf-8")
520
- decrypted += decipher.final("utf-8")
521
- return resolve(JSON.parse(decrypted))
522
- }
523
- /* No Auth */
524
- else{
525
- const decipher = crypto.createDecipheriv("aes-128-cbc", Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_KEY), Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_IV))
526
- let decrypted = decipher.update(message, "base64", "utf-8")
527
- decrypted += decipher.final("utf-8")
528
- return resolve(JSON.parse(decrypted))
529
- }
530
- }
531
- else if(mode == "no auth"){
532
- /* Unchecked Token (Illegal/Refresh) */
533
- if(token){
534
- const {key, iv} = pipe(token)
535
- .then(token=> token.split(".")[0])
536
- .then(tokenBody=> this.getUserInfo({tokenBody: tokenBody}))
537
- .then(({userName, userId, displayName})=>{
538
- return switchPourStr(
539
- userName,
540
- pseudoEnv.process.env.RABBIT_MESSAGE_KEY,
541
- userId,
542
- pseudoEnv.process.env.RABBIT_MESSAGE_IV,
543
- displayName,
544
- )
545
- })
546
- .then(mixWord=> crypto.hash("sha256", mixWord))
547
- .then(hash=>{
548
- return {
549
- key: hash.substring(0, 16),
550
- iv: hash.substring(48)
551
- }
552
- })
553
- .result
455
+ /* Active Auth Session */
456
+ if(token && userAgent){
457
+ const { userId } = this.getUserInfo({ tokenBody: token.split(".")[0] })
458
+ const uaHash = crypto.hash("sha256", switchPourStr(userAgent, pseudoEnv.process.env.TOKEN_UA_SALT))
459
+ await redis.connect().catch(error => {})
460
+ const authKey = await redis.get(`auth:session:long:${userId}:${uaHash}`)
461
+ const hash = crypto.hash("sha256", switchPourStr(authKey || "kontol", pseudoEnv.process.env.RABBIT_MESSAGE_SALT))
462
+ const key = hash.substring(0, 16)
463
+ const iv = hash.substring(48)
554
464
 
555
- const decipher = crypto.createDecipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(iv))
556
- let decrypted = decipher.update(message, "base64", "utf-8")
557
- decrypted += decipher.final("utf-8")
558
- return resolve(JSON.parse(decrypted))
559
- }
560
- /* No Auth */
561
- else{
562
- const decipher = crypto.createDecipheriv("aes-128-cbc", Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_KEY), Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_IV))
563
- let decrypted = decipher.update(message, "base64", "utf-8")
564
- decrypted += decipher.final("utf-8")
565
- return resolve(JSON.parse(decrypted))
566
- }
567
- }
568
- })
569
- },
570
- verifyToken: function({token, userAgent}){
571
- const response = new ResponseCode()
572
- return new Promise(async (resolve, reject)=>{
573
- try{
574
- await this.publish({
575
- topic: "authenthor/session/svVerifyToken",
576
- mode: "no auth",
577
- trip: "returning",
578
- data:{
579
- token: token,
580
- userAgent: userAgent
465
+ const decipher = crypto.createDecipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(iv))
466
+ let decrypted = decipher.update(message, "base64", "utf-8")
467
+ decrypted += decipher.final("utf-8")
468
+ return resolve(JSON.parse(decrypted))
469
+ }
470
+ /* No Auth */
471
+ else{
472
+ const decipher = crypto.createDecipheriv("aes-128-cbc", Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_KEY), Buffer.from(pseudoEnv.process.env.RABBIT_MESSAGE_IV))
473
+ let decrypted = decipher.update(message, "base64", "utf-8")
474
+ decrypted += decipher.final("utf-8")
475
+ return resolve(JSON.parse(decrypted))
581
476
  }
582
- })
583
- .then(apiRes=>{
584
- response.createNew(apiRes)
585
- throw "abort"
586
- })
587
- }
588
- catch(something){
589
- if(something != "abort"){
590
- // err: other error
591
- response.pushCode("LOGIC_ERROR")
592
- response.pushTrace({code: "LOGIC_ERROR", trace: `Unexpected error on ${pseudoEnv.process.env.SVC_DISPLAY} svCreateToken() function`})
593
- }
594
-
595
- resolve(response)
596
- }
597
477
  })
598
478
  },
599
479
  getUserInfo: function({tokenBody}){